@johnoscott/isometric-engine 0.14.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +1 -1
  2. package/iso-editor.js +249 -203
  3. package/iso-render.js +200 -154
  4. package/iso-systems.js +210 -162
  5. package/isometric-diagram.js +389 -0
  6. package/js/iso-core/index.js +5 -0
  7. package/js/iso-core/mono.js +242 -0
  8. package/js/iso-editor/ui/canvas.js +23 -1
  9. package/js/iso-objects/ants.js +36 -0
  10. package/js/iso-objects/index.js +55 -1
  11. package/js/iso-objects/looks.js +25 -0
  12. package/js/iso-objects/mono-paint.js +96 -0
  13. package/js/iso-objects/motion-builder.js +130 -0
  14. package/js/iso-objects/motion-doc.js +421 -0
  15. package/js/iso-objects/motion-entry.js +34 -0
  16. package/js/iso-objects/motion-schema.js +83 -0
  17. package/js/iso-objects/motion.js +640 -0
  18. package/js/iso-objects/resolve.js +238 -0
  19. package/js/iso-objects/scene.js +15 -13
  20. package/js/iso-objects/timeline.js +593 -0
  21. package/js/iso-systems/compile.js +83 -1
  22. package/js/iso-systems/index.js +4 -1
  23. package/js/iso-systems/render.js +20 -0
  24. package/js/iso-systems/schema.json +40 -0
  25. package/js/iso-viewer/index.js +6 -0
  26. package/js/iso-viewer/page.js +40 -16
  27. package/js/iso-viewer/play.js +340 -0
  28. package/js/iso-viewer/player.js +149 -175
  29. package/js/iso-viewer/transport.js +289 -0
  30. package/package.json +84 -2
  31. package/src/iso-core/index.ts +1 -0
  32. package/src/iso-core/mono.ts +306 -0
  33. package/src/iso-core/theme.ts +2 -1
  34. package/src/iso-editor/ui/canvas.ts +14 -1
  35. package/src/iso-objects/ants.ts +53 -0
  36. package/src/iso-objects/compile.ts +4 -1
  37. package/src/iso-objects/index.ts +16 -1
  38. package/src/iso-objects/looks.ts +21 -0
  39. package/src/iso-objects/mono-paint.ts +97 -0
  40. package/src/iso-objects/motion-builder.ts +79 -0
  41. package/src/iso-objects/motion-doc.ts +309 -0
  42. package/src/iso-objects/motion-entry.ts +13 -0
  43. package/src/iso-objects/motion-schema.ts +55 -0
  44. package/src/iso-objects/motion.ts +617 -0
  45. package/src/iso-objects/resolve.ts +196 -0
  46. package/src/iso-objects/scene.ts +32 -13
  47. package/src/iso-objects/timeline.ts +493 -0
  48. package/src/iso-objects/types.ts +22 -2
  49. package/src/iso-systems/compile.ts +86 -4
  50. package/src/iso-systems/index.ts +4 -1
  51. package/src/iso-systems/render.ts +45 -0
  52. package/src/iso-systems/schema.json +40 -0
  53. package/src/iso-viewer/index.ts +4 -0
  54. package/src/iso-viewer/page.ts +28 -11
  55. package/src/iso-viewer/play.ts +280 -0
  56. package/src/iso-viewer/player.ts +132 -150
  57. package/src/iso-viewer/transport.ts +272 -0
  58. package/types/iso-core/index.d.ts +1 -0
  59. package/types/iso-core/mono.d.ts +61 -0
  60. package/types/iso-core/theme.d.ts +2 -0
  61. package/types/iso-objects/ants.d.ts +34 -0
  62. package/types/iso-objects/compile.d.ts +3 -0
  63. package/types/iso-objects/index.d.ts +16 -1
  64. package/types/iso-objects/looks.d.ts +4 -0
  65. package/types/iso-objects/mono-paint.d.ts +20 -0
  66. package/types/iso-objects/motion-builder.d.ts +105 -0
  67. package/types/iso-objects/motion-doc.d.ts +193 -0
  68. package/types/iso-objects/motion-entry.d.ts +11 -0
  69. package/types/iso-objects/motion-schema.d.ts +594 -0
  70. package/types/iso-objects/motion.d.ts +202 -0
  71. package/types/iso-objects/resolve.d.ts +20 -0
  72. package/types/iso-objects/scene.d.ts +14 -0
  73. package/types/iso-objects/timeline.d.ts +66 -0
  74. package/types/iso-objects/types.d.ts +34 -0
  75. package/types/iso-systems/compile.d.ts +25 -3
  76. package/types/iso-systems/index.d.ts +4 -1
  77. package/types/iso-systems/render.d.ts +25 -0
  78. package/types/iso-viewer/index.d.ts +4 -0
  79. package/types/iso-viewer/play.d.ts +37 -0
  80. package/types/iso-viewer/transport.d.ts +73 -0
  81. package/types/player/isometric-diagram.d.ts +24 -0
@@ -0,0 +1,306 @@
1
+ // Black-and-white (monochrome) palettes, patterns and connector line rhythms, plus
2
+ // deterministic mapping from any Theme to a print-ready light or dark MonoLook.
3
+
4
+ import type { Theme } from './theme.ts';
5
+
6
+ export type MonoPattern = 'none' | 'hatch' | 'hatch-wide' | 'dots';
7
+ export type MonoStep = 0 | 1 | 2 | 3;
8
+
9
+ export interface MonoFace {
10
+ top: string;
11
+ left: string;
12
+ right: string;
13
+ edge: string;
14
+ }
15
+
16
+ export interface MonoRhythm {
17
+ dash: number[];
18
+ width: number;
19
+ }
20
+
21
+ export interface MonoRoleLook extends MonoFace {
22
+ step: MonoStep;
23
+ pattern: MonoPattern;
24
+ }
25
+
26
+ export interface MonoLook {
27
+ mode: 'light' | 'dark';
28
+ paper: string;
29
+ ink: string;
30
+ roles: Record<string, MonoRoleLook>;
31
+ kinds: Record<string, MonoRhythm>;
32
+ warnings: string[];
33
+ }
34
+
35
+ export interface MonoTable {
36
+ roles?: Record<string, { step?: MonoStep; pattern?: MonoPattern }>;
37
+ kinds?: Record<string, { dash?: number[]; width?: number }>;
38
+ }
39
+
40
+ const deepFreeze = <T>(v: T): T => {
41
+ if (v && typeof v === 'object') {
42
+ Object.freeze(v);
43
+ for (const child of Object.values(v as Record<string, unknown>)) deepFreeze(child);
44
+ }
45
+ return v;
46
+ };
47
+
48
+ /** Fixed L* cutoffs separating steps 0/1, 1/2 and 2/3 from a role's light top face. */
49
+ const STEP_THRESHOLDS = [86, 81, 76] as const;
50
+
51
+ const KIND_ORDER = ['send', 'reply', 'token', 'blocked', 'user', 'event', 'control', 'planned'] as const;
52
+
53
+ export const MONO = deepFreeze({
54
+ light: {
55
+ paper: '#ffffff',
56
+ ink: '#141414',
57
+ steps: [
58
+ { top: '#f4f4f4', left: '#dcdcdc', right: '#c4c4c4', edge: '#3a3a3a' },
59
+ { top: '#dedede', left: '#bfbfbf', right: '#a2a2a2', edge: '#2e2e2e' },
60
+ { top: '#bcbcbc', left: '#9a9a9a', right: '#7e7e7e', edge: '#222222' },
61
+ { top: '#8f8f8f', left: '#707070', right: '#565656', edge: '#141414' },
62
+ ] as readonly [MonoFace, MonoFace, MonoFace, MonoFace],
63
+ },
64
+ dark: {
65
+ paper: '#161616',
66
+ ink: '#f2f2f2',
67
+ steps: [
68
+ { top: '#2a2a2a', left: '#222222', right: '#1b1b1b', edge: '#b8b8b8' },
69
+ { top: '#454545', left: '#383838', right: '#2c2c2c', edge: '#c8c8c8' },
70
+ { top: '#6a6a6a', left: '#565656', right: '#444444', edge: '#dadada' },
71
+ { top: '#9c9c9c', left: '#808080', right: '#686868', edge: '#141414' },
72
+ ] as readonly [MonoFace, MonoFace, MonoFace, MonoFace],
73
+ },
74
+ patterns: ['none', 'hatch', 'hatch-wide', 'dots'] as readonly MonoPattern[],
75
+ rhythms: [
76
+ { dash: [], width: 2.6 },
77
+ { dash: [9, 4], width: 2.4 },
78
+ { dash: [7, 6], width: 2.4 },
79
+ { dash: [3, 6], width: 2.4 },
80
+ { dash: [1.5, 3.5], width: 2.6 },
81
+ { dash: [10, 3, 2, 3], width: 2.4 },
82
+ { dash: [], width: 1.4 },
83
+ { dash: [7, 6], width: 1.4 },
84
+ { dash: [3, 3], width: 1.6 },
85
+ { dash: [14, 4], width: 1.8 },
86
+ ] as readonly MonoRhythm[],
87
+ kindOrder: KIND_ORDER,
88
+ thresholds: STEP_THRESHOLDS,
89
+ darkWidthAdd: 0.4,
90
+ });
91
+
92
+ const HEX_RE = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
93
+ const HSL_RE = /^hsl\(\s*([+-]?(?:\d+\.?\d*|\.\d+))\s+([+-]?(?:\d+\.?\d*|\.\d+))%\s+([+-]?(?:\d+\.?\d*|\.\d+))%\s*\)$/i;
94
+
95
+ function parseColor(color: string): [number, number, number] {
96
+ if (typeof color !== 'string') throw new Error(`mono: invalid colour "${String(color)}"`);
97
+ const s = color.trim();
98
+ const hex = HEX_RE.exec(s);
99
+ if (hex) {
100
+ const h = hex[1];
101
+ if (h.length === 3) {
102
+ return [
103
+ parseInt(h[0] + h[0], 16) / 255,
104
+ parseInt(h[1] + h[1], 16) / 255,
105
+ parseInt(h[2] + h[2], 16) / 255,
106
+ ];
107
+ }
108
+ return [
109
+ parseInt(h.slice(0, 2), 16) / 255,
110
+ parseInt(h.slice(2, 4), 16) / 255,
111
+ parseInt(h.slice(4, 6), 16) / 255,
112
+ ];
113
+ }
114
+ const hsl = HSL_RE.exec(s);
115
+ if (hsl) {
116
+ const h = Number(hsl[1]);
117
+ const sat = Number(hsl[2]);
118
+ const lig = Number(hsl[3]);
119
+ if (!Number.isFinite(h) || sat < 0 || sat > 100 || lig < 0 || lig > 100) {
120
+ throw new Error(`mono: invalid colour "${color}"`);
121
+ }
122
+ const hue = ((h % 360) + 360) % 360;
123
+ const S = sat / 100;
124
+ const L = lig / 100;
125
+ const a = S * Math.min(L, 1 - L);
126
+ const f = (n: number) => {
127
+ const k = (n + hue / 30) % 12;
128
+ return L - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
129
+ };
130
+ return [f(0), f(8), f(4)];
131
+ }
132
+ throw new Error(`mono: invalid colour "${color}"`);
133
+ }
134
+
135
+ function luminance(color: string): number {
136
+ const [r, g, b] = parseColor(color);
137
+ // IEC 61966-2-1 / WCAG 2.1 sRGB transfer function
138
+ const lin = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
139
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
140
+ }
141
+
142
+ /** CIE lightness L* (0 to 100) of a #rgb, #rrggbb or hsl(h s% l%) colour. */
143
+ export function greyOf(color: string): number {
144
+ const y = luminance(color);
145
+ return y > 216 / 24389 ? 116 * Math.cbrt(y) - 16 : (24389 / 27) * y;
146
+ }
147
+
148
+ /** WCAG 2.1 contrast ratio between two colours (1 to 21). */
149
+ export function contrast(a: string, b: string): number {
150
+ const la = luminance(a);
151
+ const lb = luminance(b);
152
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
153
+ }
154
+
155
+ const VALID_PATTERNS = new Set<string>(MONO.patterns);
156
+ const FIXED_KIND_INDEX = new Map<string, number>(MONO.kindOrder.map((k, i) => [k, i]));
157
+
158
+ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
159
+ const uniqueSorted = (names: readonly string[]) => [...new Set(names)].sort(cmp);
160
+ const round2 = (n: number) => Math.round(n * 100) / 100;
161
+
162
+ function stepFromLightness(lStar: number): MonoStep {
163
+ if (lStar >= STEP_THRESHOLDS[0]) return 0;
164
+ if (lStar >= STEP_THRESHOLDS[1]) return 1;
165
+ if (lStar >= STEP_THRESHOLDS[2]) return 2;
166
+ return 3;
167
+ }
168
+
169
+ function validateOwn(own: MonoTable): void {
170
+ if (own.roles) {
171
+ for (const [name, ov] of Object.entries(own.roles)) {
172
+ if (ov.step !== undefined) {
173
+ if (typeof ov.step !== 'number' || !Number.isInteger(ov.step) || ov.step < 0 || ov.step > 3) {
174
+ throw new Error(`mono: invalid step "${String(ov.step)}" for role "${name}"`);
175
+ }
176
+ }
177
+ if (ov.pattern !== undefined) {
178
+ if (typeof ov.pattern !== 'string' || !VALID_PATTERNS.has(ov.pattern)) {
179
+ throw new Error(`mono: invalid pattern "${String(ov.pattern)}" for role "${name}"`);
180
+ }
181
+ }
182
+ }
183
+ }
184
+ if (own.kinds) {
185
+ for (const [name, ov] of Object.entries(own.kinds)) {
186
+ if (ov.dash !== undefined) {
187
+ if (!Array.isArray(ov.dash) || !ov.dash.every(n => typeof n === 'number' && Number.isFinite(n) && n >= 0)) {
188
+ throw new Error(`mono: invalid dash "${String(ov.dash)}" for kind "${name}"`);
189
+ }
190
+ }
191
+ if (ov.width !== undefined) {
192
+ if (typeof ov.width !== 'number' || !Number.isFinite(ov.width) || ov.width <= 0) {
193
+ throw new Error(`mono: invalid width "${String(ov.width)}" for kind "${name}"`);
194
+ }
195
+ }
196
+ }
197
+ }
198
+ }
199
+
200
+ /** Map a theme's roles and kinds into deterministic monochrome steps, patterns and line rhythms. */
201
+ export function monoOf(
202
+ theme: Theme,
203
+ mode: 'light' | 'dark',
204
+ use?: { roles?: string[]; kinds?: string[] },
205
+ own?: MonoTable,
206
+ ): MonoLook {
207
+ if (mode !== 'light' && mode !== 'dark') throw new Error(`mono: invalid mode "${String(mode)}"`);
208
+ if (own) validateOwn(own);
209
+
210
+ const palette = MONO[mode];
211
+ const warnings: string[] = [];
212
+ const lTop = theme.light['l-top'];
213
+
214
+ const roleNames = uniqueSorted(use?.roles ?? Object.keys(theme.roles));
215
+ const stepByRole = new Map<string, MonoStep>();
216
+ const byStep: string[][] = [[], [], [], []];
217
+
218
+ for (const name of roleNames) {
219
+ const ovStep = own?.roles?.[name]?.step;
220
+ let step: MonoStep;
221
+ if (ovStep !== undefined) {
222
+ step = ovStep;
223
+ } else {
224
+ const def = theme.roles[name];
225
+ if (!def) throw new Error(`mono: unknown role "${name}"`);
226
+ if (typeof lTop !== 'string') throw new Error('mono: theme.light is missing "l-top"');
227
+ step = stepFromLightness(greyOf(`hsl(${def.h} ${def.s}% ${lTop})`));
228
+ }
229
+ stepByRole.set(name, step);
230
+ byStep[step].push(name);
231
+ }
232
+
233
+ const patternByRole = new Map<string, MonoPattern>();
234
+ for (let step = 0; step < byStep.length; step++) {
235
+ const group = byStep[step];
236
+ for (let i = 0; i < group.length; i++) {
237
+ const name = group[i];
238
+ const ovPattern = own?.roles?.[name]?.pattern;
239
+ if (ovPattern !== undefined) {
240
+ patternByRole.set(name, ovPattern);
241
+ } else {
242
+ const idx = i % MONO.patterns.length;
243
+ const pattern = MONO.patterns[idx];
244
+ patternByRole.set(name, pattern);
245
+ if (i >= MONO.patterns.length) {
246
+ const alike = group.slice(0, i).find(r => patternByRole.get(r) === pattern);
247
+ if (alike !== undefined) {
248
+ warnings.push(`role "${name}" wraps on step ${step} to pattern "${pattern}", matching "${alike}"`);
249
+ }
250
+ }
251
+ }
252
+ }
253
+ }
254
+
255
+ const roles: Record<string, MonoRoleLook> = {};
256
+ for (const name of roleNames) {
257
+ const step = stepByRole.get(name)!;
258
+ const pattern = patternByRole.get(name)!;
259
+ const face = palette.steps[step];
260
+ roles[name] = {
261
+ step,
262
+ pattern,
263
+ top: face.top,
264
+ left: face.left,
265
+ right: face.right,
266
+ edge: face.edge,
267
+ };
268
+ }
269
+
270
+ const kindNames = uniqueSorted(use?.kinds ?? Object.keys(theme.kinds));
271
+ const widthBump = mode === 'dark' ? MONO.darkWidthAdd : 0;
272
+ const kinds: Record<string, MonoRhythm> = {};
273
+ let extraIndex = 0;
274
+
275
+ for (const name of kindNames) {
276
+ const ov = own?.kinds?.[name];
277
+ const fixedIdx = FIXED_KIND_INDEX.get(name);
278
+ let rhythmIdx: number;
279
+ if (fixedIdx !== undefined) {
280
+ rhythmIdx = fixedIdx;
281
+ } else {
282
+ rhythmIdx = MONO.kindOrder.length + extraIndex;
283
+ extraIndex++;
284
+ if (rhythmIdx >= MONO.rhythms.length) {
285
+ const wrapped = rhythmIdx % MONO.rhythms.length;
286
+ if (!ov || ov.dash === undefined || ov.width === undefined) {
287
+ warnings.push(`kind "${name}" exceeds the ${MONO.rhythms.length} line rhythms; reusing rhythm ${wrapped}`);
288
+ }
289
+ rhythmIdx = wrapped;
290
+ }
291
+ }
292
+ const base = MONO.rhythms[rhythmIdx];
293
+ const dash = ov?.dash !== undefined ? [...ov.dash] : [...base.dash];
294
+ const width = ov?.width !== undefined ? ov.width : round2(base.width + widthBump);
295
+ kinds[name] = { dash, width };
296
+ }
297
+
298
+ return {
299
+ mode,
300
+ paper: palette.paper,
301
+ ink: palette.ink,
302
+ roles,
303
+ kinds,
304
+ warnings,
305
+ };
306
+ }
@@ -12,7 +12,8 @@ export interface Theme {
12
12
  name: string;
13
13
  light: Record<string, string>;
14
14
  dark: Record<string, string>;
15
- kinds: Record<string, { color: string; dash: 'solid' | 'dashed' | 'dotted'; legend: string }>;
15
+ /** ants: the dash its connectors march with, where it isn't its dash's own */
16
+ kinds: Record<string, { color: string; dash: 'solid' | 'dashed' | 'dotted'; legend: string; ants?: [number, number] }>;
16
17
  roles: Record<string, RawRole>;
17
18
  }
18
19
 
@@ -328,6 +328,8 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
328
328
  empty.hidden = true;
329
329
  layer?.drawn?.();
330
330
  if (pendingReveal && reveal(pendingReveal)) pendingReveal = undefined;
331
+ // once, on the first drawing after its own drop; another drag forgets it (its drawings are trials, and the pointer is on them)
332
+ if (pendingNudge) { if (!drag) nudge(pendingNudge); pendingNudge = undefined; }
331
333
  paintNav();
332
334
  paintOverlay();
333
335
  if (from && from.svg !== s) {
@@ -1162,7 +1164,8 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1162
1164
  const cmd = pins.length ? seqCmd(`${f.plan.label} at [${m.at.join(', ')}]${wayWords(g, keep)}`, [f.plan.add, pinsCmd(pins, '')]) : f.plan.add;
1163
1165
  if (g.invalid) unshift(g);
1164
1166
  if (!run(doc, { ...cmd, select: [f.path] }, 'canvas', opts.note)) { lastKey = ''; unshift(g); await draw(g.origCd!); return; }
1165
- if (g.invalid) opts.note(`${f.name} added; that spot is taken, so the layout placed it`);
1167
+ // the layout may have placed it out of view: shown, once it is drawn there, so that its name is asked above it
1168
+ if (g.invalid) { opts.note(`${f.name} added; that spot is taken, so the layout placed it`); pendingNudge = f.path; }
1166
1169
  doc.select([f.path], 'canvas');
1167
1170
  // its name, in the inline field above it; the drop and the name are one undo step
1168
1171
  rename(f.path, { joins: doc.undoId, at: lastPin });
@@ -1609,6 +1612,16 @@ export function canvasView<M, D extends CanvasDrawing, A extends object = object
1609
1612
  return true;
1610
1613
  }
1611
1614
  let pendingReveal: Path[] | undefined;
1615
+ /** what is cut off by the canvas's edge, just into view: as far as it takes, and nothing when none of it is cut off */
1616
+ function nudge(p: Path) {
1617
+ const b = boxFor(p), v = V.view;
1618
+ if (!v || !b) return;
1619
+ if (b.w > v.w || b.h > v.h) { reveal([p]); return; }
1620
+ const m = 12 / scale(), by = (a: number, n: number, va: number, vn: number) => (a < va ? a - va - m : a + n > va + vn ? a + n - va - vn + m : 0);
1621
+ const dx = by(b.x, b.w, v.x, v.w), dy = by(b.y, b.h, v.y, v.h);
1622
+ if (dx || dy) { V.view = { ...v, x: v.x + dx, y: v.y + dy }; applyView(); }
1623
+ }
1624
+ let pendingNudge: Path | undefined;
1612
1625
  ifEvents();
1613
1626
  doc.onSelect(c => {
1614
1627
  paintOverlay();
@@ -0,0 +1,53 @@
1
+ // Marching dashes on a still drawing (docs/design/MOTION.md, 5a): a loop of the drawing's own, for a page or an image that plays
2
+ // nothing else. Two ways: 'css' (a class on each connector and ANTS_CSS once on the page, which a switch can stop) and 'smil' (an
3
+ // animation inside each connector, for an SVG that goes out alone, where a page's stylesheet doesn't reach). In motion (a
4
+ // timeline's `ants`) there is no loop: a frame has the offset of its moment.
5
+
6
+ import type { CompiledScene } from './compile.ts';
7
+
8
+ export const ANT_SPEED = 32 / 1.1;
9
+ export const ANT_DASH: Record<string, [number, number]> = { solid: [9, 7], dashed: [7, 6], dotted: [3, 6] };
10
+ export const ANT_STILL = ['blocked', 'planned'];
11
+ export interface AntsOptions {
12
+ /** how it moves (default: smil); 'none': the dashes, standing still */
13
+ by?: 'css' | 'smil' | 'none';
14
+ /** the connectors that march (default: every one that may) */
15
+ ids?: string[];
16
+ /** units a second, in the drawing's units (default: 32 in 1.1 s) */
17
+ speed?: number;
18
+ dash?: [number, number];
19
+ /** the connectors' dashes, by kind: the theme's `kinds` (a dashed kind marches with its own dash) */
20
+ kinds?: Record<string, { dash?: 'solid' | 'dashed' | 'dotted'; ants?: [number, number] }>;
21
+ /** kinds whose connectors stand still (default: blocked, planned) */
22
+ still?: string[];
23
+ }
24
+ /** for 'css': one rule and its keyframes. A page stops them, where they are, with --ants: paused. */
25
+ export const ANTS_CSS = `
26
+ .flow.iso-ants{stroke-dasharray:var(--ant-on) var(--ant-off);animation:iso-ants var(--ant-turn) linear infinite;animation-play-state:var(--ants,running)}
27
+ @keyframes iso-ants{to{stroke-dashoffset:var(--ant-to)}}
28
+ `;
29
+ /** the dash a connector marches with, or undefined when it stands still */
30
+ export function antDash(kind: string, o: Pick<AntsOptions, 'dash' | 'kinds' | 'still'> = {}): [number, number] | undefined {
31
+ return (o.still ?? ANT_STILL).includes(kind) ? undefined : o.dash ?? o.kinds?.[kind]?.ants ?? ANT_DASH[o.kinds?.[kind]?.dash ?? 'solid'];
32
+ }
33
+
34
+ /** what a scene's `ants:` in the file asks for, as options; undefined: none */
35
+ export function antsOf(raw: { ants?: boolean | string[] | { ids?: string[]; speed?: number; dash?: [number, number] } } | undefined): Pick<AntsOptions, 'ids' | 'speed' | 'dash'> | undefined {
36
+ const a = raw?.ants;
37
+ return !a ? undefined : a === true ? {} : Array.isArray(a) ? { ids: a } : a;
38
+ }
39
+
40
+ /** The scene's still, as SVG text, with its connectors marching. */
41
+ export function withAnts(scene: Pick<CompiledScene, 'rendered' | 'routes'>, o: AntsOptions = {}): string {
42
+ const kindOf = new Map(scene.routes.map(r => [r.id, r.kind])), wanted = o.ids && new Set(o.ids), speed = o.speed ?? ANT_SPEED;
43
+ const n = (v: number) => String(Number(v.toFixed(3)));
44
+ return scene.rendered.svg.replace(/(<g data-route="([^"]*)" data-part="line">(?:<g[^>]*>)*)<path ([^>]*?)\s*\/>/g, (m, before: string, id: string, attrs: string) => {
45
+ const route = id.replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
46
+ const dash = wanted && !wanted.has(route) ? undefined : antDash(kindOf.get(route) ?? '', o);
47
+ if (!dash || !/class="flow\b/.test(attrs)) return m;
48
+ const period = dash[0] + dash[1], turn = n(period / Math.max(1e-6, Math.abs(speed)) ), to = n(speed < 0 ? period : -period);
49
+ if (o.by === 'css') return `${before}<path ${attrs.replace(/class="flow\b/, 'class="flow iso-ants')} style="--ant-on:${n(dash[0])};--ant-off:${n(dash[1])};--ant-to:${to};--ant-turn:${turn}s"/>`;
50
+ if (o.by === 'none') return `${before}<path ${attrs.replace(/ ?stroke-dasharray="[^"]*"/, '')} style="stroke-dasharray:${n(dash[0])} ${n(dash[1])}"/>`;
51
+ return `${before}<path ${attrs.replace(/ ?stroke-dasharray="[^"]*"/, '')} style="stroke-dasharray:${n(dash[0])} ${n(dash[1])}"><animate attributeName="stroke-dashoffset" from="0" to="${to}" dur="${turn}s" repeatCount="indefinite"/></path>`;
52
+ });
53
+ }
@@ -9,10 +9,13 @@ import { routeAll, type Routed } from './route.ts';
9
9
  import { resolveSteps, type Steps } from './steps.ts';
10
10
  import { extendTheme, loadTheme } from '../iso-core/theme.ts';
11
11
  import { type KindCatalog, nodeKindOr } from './kinds.ts';
12
+ import type { MotionDoc } from './motion-doc.ts';
12
13
  import type { GridDef, RawDiagram, RawNode, RawRegion, RawScene, Theme } from './types.ts';
13
14
  import { facePainter, iconPainter } from './assets.ts';
14
15
 
15
- export interface CompiledScene { id: string; raw: RawDiagram['scenes'][number]; layout: Layout; routes: Routed[]; steps: Steps; rendered: RenderedScene; grid: GridDef; assemble: boolean }
16
+ export interface CompiledScene { id: string; raw: RawDiagram['scenes'][number]; layout: Layout; routes: Routed[]; steps: Steps; rendered: RenderedScene; grid: GridDef; assemble: boolean;
17
+ /** the file's `motion:` on this scene, checked against the drawing (a file with errors in it has none) */
18
+ motion?: MotionDoc }
16
19
  export interface Compiled {
17
20
  ok: boolean;
18
21
  /** the parsed source: positions and spans of every value, for the proof sheet */
@@ -5,7 +5,7 @@
5
5
  // The layer's public API. Importers name the module a name comes from (with code splitting, a barrel puts every file
6
6
  // it reaches into each bundle that imports it); the Node tests may import this index.
7
7
 
8
- export type { Side, StepRef, RawPlacement, RawDeco, RawNode, RawGate, RawRegion, RawNote, RawScene, GridDef, RawDiagram, RegionKindName, Placed, RawRole, RawKind, Theme } from './types.ts';
8
+ export type { Side, StepRef, RawPlacement, RawDeco, RawNode, RawGate, RawRegion, RawNote, RawScene, GridDef, RawDiagram, RegionKindName, Placed, RawRole, RawKind, Theme, RawMotion, RawVariant } from './types.ts';
9
9
  export { regionKind, nodeKind, nodeKindOr, wallHeight, kindsCss } from './kinds.ts';
10
10
  export type { RegionShape, RegionKind, KindCatalog } from './kinds.ts';
11
11
  export { drawDecos, boxAsset, plate, cloudPath, drawCloud, defaultLabel, registerMarks, markCss, iconPainter, facePainter, placeholderIcon } from './assets.ts';
@@ -18,6 +18,21 @@ export { silhouette, polyBounds, polyRectArea, rectArea, lineRectArea, Obstacles
18
18
  export type { Rect, Poly, LabelText, PlacedLabel, CalloutSpot } from './labels.ts';
19
19
  export { offscreen, assembly } from './assemble.ts';
20
20
  export type { Edge, Piece, Assembly } from './assemble.ts';
21
+ export { ASSEMBLE_STYLES, DISASSEMBLE_STYLES, MOTION_ORDERS, MOTION_EASINGS, motionModel, motionOrder, planOf, assemble, disassemble, alongPath, svgAt, paint, introSvg } from './motion.ts';
22
+ export type { AssembleStyle, DisassembleStyle, MotionOrder, MotionEasing, Direction, PieceMotion, AssembleOptions, DisassembleOptions, PlanOptions, MotionPiece, MotionModel, MotionPlan, ScenePlan, SceneState, ItemState, LabelState, RouteState } from './motion.ts';
23
+ export { drawLooks } from './looks.ts';
24
+ export { withAnts, antsOf, antDash, ANTS_CSS, ANT_SPEED, ANT_DASH, ANT_STILL } from './ants.ts';
25
+ export type { AntsOptions } from './ants.ts';
26
+ export { motion, MotionBuilder, SeriesBuilder, NodesBuilder } from './motion-builder.ts';
27
+ export type { SequenceOptions, Timing, CameraVerbs, Ids as MotionIds } from './motion-builder.ts';
28
+ export { bindMotion, motionOfSteps, motionSource } from './timeline.ts';
29
+ export type { Timeline, BindOptions, BeatInfo, Cue, MotionSource } from './timeline.ts';
30
+ export { MOTION_SCHEMA } from './motion-schema.ts';
31
+ export { EASING_NAMES, EXTRAPOLATE, checkMotion, msOf, readMs, easeOf, curveAt, springAt, bezier } from './motion-doc.ts';
32
+ export type { MotionDoc, MotionNode, MotionTime, MotionEase, EasingName, Extrapolate, SpringConfig, Curve, Say as MotionSay, Focus, ReadTime, Sequence, SeriesItem, Transition, MotionDiag } from './motion-doc.ts';
33
+ export { resolveSvg, FONT_STACKS } from './resolve.ts';
34
+ export { monoOfDrawing, monoTheme, monoCss, paintMono, usedIn } from './mono-paint.ts';
35
+ export type { ResolveOptions, ThemeMode } from './resolve.ts';
21
36
  export { durationFor, resolveSteps, midpoint } from './steps.ts';
22
37
  export type { RawStep, Token, StepData, Say, Mark, Badge, Steps } from './steps.ts';
23
38
  export { focusView } from './focus.ts';
@@ -0,0 +1,21 @@
1
+ // The looks things declare (`variants:`): the same drawing with each thing's in it, for a motion to take that thing's parts from. A format
2
+ // that offers looks draws them after it compiles; one that doesn't bundles none of this.
3
+
4
+ import type { CompiledScene } from './compile.ts';
5
+ import { renderScene } from './scene.ts';
6
+ import type { Theme } from './types.ts';
7
+
8
+ /** Draw a scene's looks into its `rendered` (none declared: nothing). */
9
+ export function drawLooks(s: CompiledScene, theme: Theme): void {
10
+ const looks: Record<string, string[]> = {};
11
+ for (const p of s.layout.items) { const v = (p.region ?? p.node)?.variants; if (v) looks[p.id] = Object.keys(v); }
12
+ if (!Object.keys(looks).length) return;
13
+ s.rendered.looks = looks;
14
+ s.rendered.variants = Object.fromEntries([...new Set(Object.values(looks).flat())].map(name => [name, renderScene({
15
+ scene: s.raw, routes: s.routes, steps: s.steps, theme, id: s.raw.id, gridStep: s.grid.step ?? s.grid.snap ?? 1,
16
+ layout: { ...s.layout, items: s.layout.items.map(p => {
17
+ const v = (p.region ?? p.node)?.variants?.[name];
18
+ return !v ? p : p.region ? { ...p, region: { ...p.region, ...v, deco: undefined } as typeof p.region } : { ...p, node: { ...p.node!, ...v } };
19
+ }) },
20
+ }).svg]));
21
+ }
@@ -0,0 +1,97 @@
1
+ // The black and white treatment of a self-contained drawing (docs/design/MOTION.md, 5b): a paint, not a drawing. The tables
2
+ // (iso-core/mono.ts) become a theme and rules the resolver works out as it does any theme's; patterns go over a thing's faces, inside
3
+ // its own wrapper, so that motion moves them with it. Geometry, ids and wrappers are the styled drawing's. What has a hue after all of
4
+ // that (a screen's own colours, a brand mark's) becomes the grey of its lightness: nothing has a hue.
5
+
6
+ import { extendTheme, type Theme } from '../iso-core/theme.ts';
7
+ import { contrast, greyOf, MONO, monoOf, type MonoLook, type MonoPattern, type MonoTable } from '../iso-core/mono.ts';
8
+ import type { ThemeMode } from './resolve.ts';
9
+
10
+ const pct = (grey: string) => `${Math.round((parseInt(grey.slice(1, 3), 16) / 255) * 10000) / 100}%`;
11
+ /** a grey between two, by its share of the second */
12
+ const between = (a: string, b: string, f: number) => { const [x, y] = [a, b].map(c => parseInt(c.slice(1, 3), 16)), v = Math.round(x + (y - x) * f).toString(16).padStart(2, '0'); return `#${v}${v}${v}`; };
13
+
14
+ /** the roles and connector kinds a drawing uses */
15
+ export function usedIn(svg: string, theme: Theme, kinds: string[]): { roles: string[]; kinds: string[] } {
16
+ const seen = new Set([...svg.matchAll(/\sclass="([^"]*)"/g)].flatMap(m => m[1].split(/\s+/)).filter(c => c.startsWith('k-')).map(c => c.slice(2)));
17
+ return { roles: Object.keys(theme.roles).filter(r => seen.has(r)), kinds: [...new Set(kinds)].filter(k => k in theme.kinds) };
18
+ }
19
+
20
+ /** the theme in greys, its tokens by the same names, so that everything that names one is grey too */
21
+ export function monoTheme(theme: Theme, look: MonoLook): Theme {
22
+ const steps = MONO[look.mode].steps, face = (role: string, step: 0 | 1) => look.roles[role] ?? steps[step];
23
+ const tokens: Record<string, string> = {};
24
+ // a token is ink, unless it is one of a surface's
25
+ for (const [k, v] of Object.entries(theme.light)) tokens[k] = /%$/.test(v) ? v : look.ink;
26
+ const slab = face('slab', 0), pad = face('pad', 0);
27
+ Object.assign(tokens, {
28
+ bg: look.paper, surface: look.paper, on: look.paper, ink: look.ink, muted: between(look.paper, look.ink, 0.72), line: between(look.paper, look.ink, 0.3), 'code-bg': between(look.paper, look.ink, 0.06),
29
+ 'slab-top': slab.top, 'slab-l': slab.left, 'slab-r': slab.right, 'pad-top': pad.top,
30
+ });
31
+ const roles = Object.fromEntries(Object.entries(theme.roles).map(([k]) => [k, { h: 0, s: 0 }]));
32
+ const kinds = Object.fromEntries(Object.entries(theme.kinds).map(([k, v]) => [k, { ...v, color: look.ink }]));
33
+ return extendTheme({ ...theme, light: tokens, dark: tokens, roles, kinds });
34
+ }
35
+
36
+ /** what is each role's and each kind's own: the faces' lightnesses, the connectors' rhythms */
37
+ export function monoCss(look: MonoLook): string {
38
+ let css = '';
39
+ for (const [name, r] of Object.entries(look.roles)) css += `.k-${name}{--s:0%;--l-top:${pct(r.top)};--l-left:${pct(r.left)};--l-right:${pct(r.right)};--l-edge:${pct(r.edge)}}\n`;
40
+ for (const [name, k] of Object.entries(look.kinds)) css += `.flow.f-${name}{stroke-width:${k.width}${k.dash.length ? `;stroke-dasharray:${k.dash.join(' ')}` : ';stroke-dasharray:none'}}\n`;
41
+ return css;
42
+ }
43
+
44
+ const TILE: Record<Exclude<MonoPattern, 'none'>, { size: number; draw: (ink: string, w: number) => string }> = {
45
+ hatch: { size: 6, draw: (c, w) => `<path d="M0,6L6,0M-1.5,1.5L1.5,-1.5M4.5,7.5L7.5,4.5" stroke="${c}" stroke-width="${w}" fill="none"/>` },
46
+ 'hatch-wide': { size: 12, draw: (c, w) => `<path d="M0,0L12,12M-3,9L3,15M9,-3L15,3" stroke="${c}" stroke-width="${w}" fill="none"/>` },
47
+ dots: { size: 8, draw: (c, w) => `<circle cx="2" cy="2" r="${w + 0.2}" fill="${c}"/><circle cx="6" cy="6" r="${w + 0.2}" fill="${c}"/>` },
48
+ };
49
+ const round = (v: number) => Math.round(v * 100) / 100;
50
+ /** a pattern's ink on a face: the mode's own ink or paper, whichever stands out */
51
+ const patternInk = (face: string, look: MonoLook) => (contrast(face, look.ink) >= contrast(face, look.paper) ? look.ink : look.paper);
52
+
53
+ /** The resolved drawing with its patterns, and no hue in it. `id`: the drawing's own (its patterns' ids begin with it). */
54
+ export function paintMono(svg: string, look: MonoLook, id: string): string {
55
+ const need = new Map<string, string>();
56
+ const use = (pattern: Exclude<MonoPattern, 'none'>, ink: string) => {
57
+ const key = `${id}-mono-${pattern}-${ink.slice(1)}`, t = TILE[pattern], w = look.mode === 'dark' ? 1.2 : 0.9;
58
+ if (!need.has(key)) need.set(key, `<pattern id="${key}" width="${t.size}" height="${t.size}" patternUnits="userSpaceOnUse">${t.draw(ink, round(w))}</pattern>`);
59
+ return key;
60
+ };
61
+ // each face of a patterned role's solids, again, in its pattern, straight after it
62
+ const depth: (string | undefined)[] = [];
63
+ let out = '', layer = '';
64
+ for (const m of svg.matchAll(/<\/[a-zA-Z][\w:-]*>|<([a-zA-Z][\w:-]*)((?:\s+[\w:-]+="[^"]*")*)\s*(\/?)>|[^<]+/g)) {
65
+ out += m[0];
66
+ if (m[0].startsWith('</')) { depth.pop(); continue; }
67
+ if (m[1] === undefined) continue;
68
+ const cls = (/\sclass="([^"]*)"/.exec(m[2])?.[1] ?? '').split(/\s+/);
69
+ if (depth.length === 1) layer = cls.find(c => c.startsWith('g-')) ?? '';
70
+ const role = cls.find(c => c.startsWith('k-'))?.slice(2) ?? depth.at(-1);
71
+ if (!m[3]) depth.push(cls.includes('ghost') ? '' : role);
72
+ if (!m[3] || (m[1] !== 'polygon' && m[1] !== 'path') || !role || !cls.some(c => c === 'top' || c === 'lft' || c === 'rgt')) continue;
73
+ // a ground is drawn on (its top) and has its name on its front: they stay plain, and its other side tells it
74
+ if (layer === 'g-base' && !cls.includes('rgt')) continue;
75
+ const p = Object.hasOwn(look.roles, role) ? look.roles[role].pattern : 'none';
76
+ const fill = /\sfill="(#[0-9a-f]{6})"/.exec(m[2])?.[1], shape = /\s(points|d)="[^"]*"/.exec(m[2])?.[0];
77
+ if (p === 'none' || !fill || !shape) continue;
78
+ const opacity = /\sfill-opacity="[^"]*"/.exec(m[2])?.[0] ?? '';
79
+ out += `<${m[1]}${shape} class="mono-pattern" fill="url(#${use(p, patternInk(fill, look))})" stroke="none"${opacity}/>`;
80
+ }
81
+ // whatever still has a hue, in the grey of its own lightness
82
+ out = out.replace(/#([0-9a-f]{6})\b/g, (h, x: string) => (x.slice(0, 2) === x.slice(2, 4) && x.slice(2, 4) === x.slice(4, 6) ? h : greyHex(h)));
83
+ if (need.size) out = out.replace(/<defs\/>|<defs>/, d => (d === '<defs/>' ? `<defs>${[...need.values()].join('')}</defs>` : d + [...need.values()].join('')));
84
+ return out;
85
+ }
86
+ /** the grey of a colour's own lightness (L*) */
87
+ function greyHex(c: string): string {
88
+ const l = greyOf(c), y = l > 8 ? ((l + 16) / 116) ** 3 : l / (24389 / 27), s = y <= 0.0031308 ? y * 12.92 : 1.055 * y ** (1 / 2.4) - 0.055;
89
+ const v = Math.max(0, Math.min(255, Math.round(s * 255))).toString(16).padStart(2, '0');
90
+ return `#${v}${v}${v}`;
91
+ }
92
+
93
+ /** Everything a compile needs for the treatment: the look, its theme and its rules. */
94
+ export function monoOfDrawing(svg: string, theme: Theme, mode: ThemeMode, kinds: string[], own?: MonoTable): { look: MonoLook; theme: Theme; css: string } {
95
+ const look = monoOf(theme, mode, usedIn(svg, theme, kinds), own);
96
+ return { look, theme: monoTheme(theme, look), css: monoCss(look) };
97
+ }