@entro314labs/iso-engine 0.0.0-stage → 0.5.1

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +165 -2
  3. package/THIRD_PARTY_NOTICES.md +39 -0
  4. package/dist/engine/anim.js +225 -0
  5. package/dist/engine/behaviors.js +105 -0
  6. package/dist/engine/diagram.js +80 -0
  7. package/dist/engine/draw.js +117 -0
  8. package/dist/engine/export.js +81 -0
  9. package/dist/engine/figure.js +35 -0
  10. package/dist/engine/global.js +4 -0
  11. package/dist/engine/index.d.ts +278 -0
  12. package/dist/engine/index.js +164 -0
  13. package/dist/engine/math.js +190 -0
  14. package/dist/engine/node.js +290 -0
  15. package/dist/engine/paths.js +76 -0
  16. package/dist/engine/prefabs/architecture.js +136 -0
  17. package/dist/engine/prefabs/basics.js +131 -0
  18. package/dist/engine/prefabs/devices.js +295 -0
  19. package/dist/engine/prefabs/icons.js +49 -0
  20. package/dist/engine/prefabs/index.js +12 -0
  21. package/dist/engine/prefabs/logistics.js +156 -0
  22. package/dist/engine/scene.js +466 -0
  23. package/dist/engine/shapes.js +781 -0
  24. package/dist/engine/sort.js +153 -0
  25. package/dist/engine/spec.js +81 -0
  26. package/dist/engine/style.js +87 -0
  27. package/dist/engine.css +1 -0
  28. package/dist/figure.css +93 -0
  29. package/dist/figure.d.ts +22 -0
  30. package/dist/figure.js +73 -0
  31. package/dist/filters.d.ts +9 -0
  32. package/dist/filters.js +22 -0
  33. package/dist/index.d.ts +9 -0
  34. package/dist/index.js +8 -0
  35. package/dist/iso.global.js +7990 -0
  36. package/dist/kernel.d.ts +102 -0
  37. package/dist/kernel.js +172 -0
  38. package/dist/loops.d.ts +49 -0
  39. package/dist/loops.js +64 -0
  40. package/dist/patterns.d.ts +44 -0
  41. package/dist/patterns.js +97 -0
  42. package/dist/theme.css +19 -0
  43. package/dist/types.d.ts +86 -0
  44. package/dist/types.js +1 -0
  45. package/package.json +50 -4
  46. package/skills/iso-engine/SKILL.md +143 -0
  47. package/skills/iso-engine/examples/engine.html +42 -0
  48. package/skills/iso-engine/examples/figure.html +51 -0
  49. package/skills/iso-engine/examples/loop.html +68 -0
  50. package/skills/iso-engine/examples/loop.js +36 -0
  51. package/skills/iso-engine/examples/matcher.js +134 -0
  52. package/skills/iso-engine/examples/spec.html +42 -0
  53. package/skills/iso-engine/references/animation.md +116 -0
  54. package/skills/iso-engine/references/api.md +207 -0
  55. package/skills/iso-engine/references/composition.md +66 -0
  56. package/skills/iso-engine/references/diagrams.md +68 -0
  57. package/skills/iso-engine/references/figures.md +359 -0
  58. package/skills/iso-engine/references/loops.md +126 -0
  59. package/skills/iso-engine/references/prefabs.md +103 -0
  60. package/skills/iso-engine/references/spec.md +66 -0
  61. package/skills/iso-engine/references/style.md +76 -0
  62. package/skills/iso-engine/references/troubleshooting.md +49 -0
  63. package/skills/iso-engine/scripts/build.mjs +35 -0
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Isometric projection kernel shared by every figure (skills/iso-engine/references/figures.md, "The kernel" and "Camera tilt").
3
+ *
4
+ * Axes: +x runs down-right, +y runs down-left, +z is up. Everything is drawn as flat SVG inside a
5
+ * `matrix()` that places a face's local 2D coordinates onto a 3D plane, so text, rounded corners and
6
+ * glyphs come out in correct perspective without hand-computed polygons.
7
+ */
8
+ export type Pt = [number, number];
9
+ export type Vec3 = [number, number, number];
10
+ export interface Rect {
11
+ x: number;
12
+ y: number;
13
+ w: number;
14
+ h: number;
15
+ }
16
+ export declare const C: number;
17
+ export declare const S: number;
18
+ export interface Kernel {
19
+ /** Point: 3D -> screen. */
20
+ P(x: number, y: number, z: number): Pt;
21
+ /** Direction only (no origin offset). */
22
+ D(x: number, y: number, z: number): Pt;
23
+ /** Transform placing a group's local (u, v) coordinates on the plane through O spanned by U and V. */
24
+ plane(O: Vec3, U: Vec3, V: Vec3): string;
25
+ /** z = const plane. */
26
+ TOP(x: number, y: number, z: number): string;
27
+ /** y = const plane (faces lower-left); pass its top-left corner. */
28
+ FRONT(x: number, y: number, z: number): string;
29
+ /** x = const plane (faces lower-right); pass its front top corner (x_max, y_max, z_top). */
30
+ SIDE(x: number, y: number, z: number): string;
31
+ rect(t: string, w: number, h: number, r?: number, cls?: string): string;
32
+ /** Box at (x,y,z), size w along x, d along y, h along z: its three visible faces. Records its corners in `pts`. */
33
+ box(x: number, y: number, z: number, w: number, d: number, h: number, r?: number): string;
34
+ /** Short upright cylinder (a platter, a can, a knob) centred at (cx,cy), base at z, radius r, height h. */
35
+ disc(cx: number, cy: number, z: number, r: number, h: number, cls?: string): string;
36
+ /** Every projected corner drawn so far; `frame()` fits the viewBox to them. Reset with `pts.length = 0`. */
37
+ pts: Pt[];
38
+ /**
39
+ * Camera tilt: 0 = isometric, 1 = plan (a true top-down plan rotated 45°). FRONT and SIDE planes collapse
40
+ * to zero height at 1, which is what a plan should show. Back-to-front order stays valid at every tilt.
41
+ */
42
+ setTilt(t: number): void;
43
+ }
44
+ export declare function createKernel(): Kernel;
45
+ /** Axis-aligned bounds of projected points. */
46
+ export declare function bbox(q: readonly Pt[]): Rect;
47
+ /** Fit the svg's viewBox to the points plus a margin (fraction of the larger side). Returns the viewBox. */
48
+ export declare function frame(svg: SVGSVGElement, q: readonly Pt[], margin?: number): Rect;
49
+ export declare function setViewBox(svg: SVGSVGElement, vb: Rect): void;
50
+ /** Escape text for interpolation into SVG markup. */
51
+ export declare const esc: (s: string) => string;
52
+ /** `n` copies of `f(i)` joined: texture from repetition (vents, ribs, rails). */
53
+ export declare const rep: (n: number, f: (i: number) => string) => string;
54
+ export declare const ln: (x1: number, y1: number, x2: number, y2: number, cls?: string) => string;
55
+ export declare const rc: (x: number, y: number, w: number, h: number, r?: number, cls?: string) => string;
56
+ export declare const ci: (x: number, y: number, r: number, cls?: string) => string;
57
+ /** Text in face-local units. Pass `max` (the room on its surface, in the same units) to shrink or truncate it to fit. */
58
+ export declare const tx: (x: number, y: number, s: string, size: number, anchor?: 'start' | 'middle' | 'end', cls?: string, max?: number) => string;
59
+ /** Extent of a unit: [x0, y0, z0, x1, y1, z1]. */
60
+ export type B6 = [number, number, number, number, number, number];
61
+ export interface Unit {
62
+ bb: B6;
63
+ svg: string;
64
+ part?: string;
65
+ cls: string;
66
+ }
67
+ /**
68
+ * Back-to-front order for non-intersecting boxes: an edge a→b whenever a is behind b and not the reverse
69
+ * (when both hold their projections can't overlap, so order doesn't matter), then a topological sort
70
+ * that prefers authoring order and falls back to it for any cycle.
71
+ */
72
+ export declare function depthSort<T extends {
73
+ bb: B6;
74
+ }>(list: readonly T[]): T[];
75
+ export interface Units {
76
+ /** Start a unit; `part` makes it a pressable `.part` (several units may share one part id), else `cls` groups decoration. */
77
+ begin(part?: string, cls?: string): void;
78
+ /** Add a box to the current unit (extends its extent). */
79
+ bx(x: number, y: number, z: number, w: number, d: number, h: number, r?: number): void;
80
+ onTop(x: number, y: number, z: number, s: string): void;
81
+ onFront(x: number, y: number, z: number, s: string): void;
82
+ onSide(x: number, y: number, z: number, s: string): void;
83
+ /** Append already-projected svg (a path, a tent) to the current unit; pair with `extend` so it sorts. */
84
+ raw(svg: string): void;
85
+ /** Grow the current unit's extent without drawing a box. */
86
+ extend(x: number, y: number, z: number, w: number, d: number, h: number): void;
87
+ /**
88
+ * All units, depth-sorted, each wrapped in its group. `extra` items (already-wrapped svg with an extent,
89
+ * e.g. parts that need their own CSS-transform wrapper) are sorted in with them.
90
+ */
91
+ emit(extra?: ReadonlyArray<{
92
+ bb: B6;
93
+ html: string;
94
+ }>): string;
95
+ /** Units in authoring order (e.g. to bound a part's units for zoom or callouts). */
96
+ list(): readonly Unit[];
97
+ }
98
+ /**
99
+ * Collect a scene as units (a box or a few boxes plus the flat detail on their faces) and let
100
+ * `depthSort` work out the paint order, instead of hand-ordering hundreds of small parts.
101
+ */
102
+ export declare function createUnits(k: Kernel): Units;
package/dist/kernel.js ADDED
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Isometric projection kernel shared by every figure (skills/iso-engine/references/figures.md, "The kernel" and "Camera tilt").
3
+ *
4
+ * Axes: +x runs down-right, +y runs down-left, +z is up. Everything is drawn as flat SVG inside a
5
+ * `matrix()` that places a face's local 2D coordinates onto a 3D plane, so text, rounded corners and
6
+ * glyphs come out in correct perspective without hand-computed polygons.
7
+ */
8
+ import { fitText } from './engine/index.js';
9
+ export const C = Math.cos(Math.PI / 6);
10
+ export const S = Math.sin(Math.PI / 6);
11
+ export function createKernel() {
12
+ let A = S, B = 1;
13
+ const pts = [];
14
+ const P = (x, y, z) => [(x - y) * C, (x + y) * A - z * B];
15
+ const D = (x, y, z) => [(x - y) * C, (x + y) * A - z * B];
16
+ const plane = (O, U, V) => {
17
+ const o = P(...O), u = D(...U), v = D(...V);
18
+ return `matrix(${u[0]} ${u[1]} ${v[0]} ${v[1]} ${o[0]} ${o[1]})`;
19
+ };
20
+ const TOP = (x, y, z) => plane([x, y, z], [1, 0, 0], [0, 1, 0]);
21
+ const FRONT = (x, y, z) => plane([x, y, z], [1, 0, 0], [0, 0, -1]);
22
+ const SIDE = (x, y, z) => plane([x, y, z], [0, -1, 0], [0, 0, -1]);
23
+ const rect = (t, w, h, r = 0, cls = 'face') => `<rect class="${cls}" transform="${t}" width="${w}" height="${h}" rx="${r}"/>`;
24
+ /*
25
+ * A box rounded in plan: one continuous wall along the visible rounded outline plus a rounded top, so the corners
26
+ * line up (rounding the FRONT and SIDE faces separately leaves notched corners). r = 0 keeps the three flat faces.
27
+ */
28
+ const box = (x, y, z, w, d, h, r = 0) => {
29
+ for (const X of [x, x + w])
30
+ for (const Y of [y, y + d])
31
+ for (const Z of [z, z + h])
32
+ pts.push(P(X, Y, Z));
33
+ if (r <= 0)
34
+ return rect(SIDE(x + w, y + d, z + h), d, h) + rect(FRONT(x, y + d, z + h), w, h) + rect(TOP(x, y, z + h), w, d, 0, 'face top');
35
+ r = Math.min(r, w / 2, d / 2);
36
+ const n = 8, z1 = z + h, q = Math.PI / 4, H = Math.PI / 2;
37
+ const arc = (cx, cy, a0, a1) => Array.from({ length: n + 1 }, (_, i) => { const a = a0 + ((a1 - a0) * i) / n; return [cx + r * Math.cos(a), cy + r * Math.sin(a)]; });
38
+ const ring = [...arc(x + w - r, y + r, -H, 0), ...arc(x + w - r, y + d - r, 0, H), ...arc(x + r, y + d - r, H, 2 * H), ...arc(x + r, y + r, 2 * H, 3 * H)];
39
+ const seen = [...arc(x + w - r, y + r, -q, 0), ...arc(x + w - r, y + d - r, 0, H), ...arc(x + r, y + d - r, H, 3 * q)]; // the outline the viewer sees
40
+ const d3 = (p3) => 'M' + p3.map(p => P(p[0], p[1], p[2]).map(v => +v.toFixed(2)).join(' ')).join('L') + 'Z';
41
+ const wall = [...seen.map(([a, b]) => [a, b, z]), ...[...seen].reverse().map(([a, b]) => [a, b, z1])];
42
+ return `<path class="face" d="${d3(wall)}"/><path class="face top" d="${d3(ring.map(([a, b]) => [a, b, z1]))}"/>`;
43
+ };
44
+ // bottom ellipse, a side band between the ellipse's left and right screen extremes, then the top ellipse
45
+ const disc = (cx, cy, z, r, h, cls = 'face') => {
46
+ const k = r / Math.SQRT2;
47
+ const L0 = P(cx - k, cy + k, z), R0 = P(cx + k, cy - k, z), L1 = P(cx - k, cy + k, z + h), R1 = P(cx + k, cy - k, z + h);
48
+ for (const Z of [z, z + h])
49
+ pts.push(P(cx + r, cy + r, Z), P(cx - r, cy - r, Z), P(cx - k, cy + k, Z), P(cx + k, cy - k, Z));
50
+ return `<g transform="${TOP(cx, cy, z)}"><circle class="${cls}" r="${r}"/></g>` +
51
+ `<path class="${cls} band" d="M${L0} L${L1} L${R1} L${R0} Z"/>` +
52
+ `<line class="edge" x1="${L0[0]}" y1="${L0[1]}" x2="${L1[0]}" y2="${L1[1]}"/>` +
53
+ `<line class="edge" x1="${R0[0]}" y1="${R0[1]}" x2="${R1[0]}" y2="${R1[1]}"/>` +
54
+ `<g transform="${TOP(cx, cy, z + h)}"><circle class="${cls} top" r="${r}"/></g>`;
55
+ };
56
+ const setTilt = (t) => { A = S + (C - S) * t; B = 1 - t; };
57
+ return { P, D, plane, TOP, FRONT, SIDE, rect, box, disc, pts, setTilt };
58
+ }
59
+ /** Axis-aligned bounds of projected points. */
60
+ export function bbox(q) {
61
+ if (!q.length)
62
+ throw new Error('bbox: no points to bound');
63
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
64
+ for (const [x, y] of q) {
65
+ x0 = Math.min(x0, x);
66
+ y0 = Math.min(y0, y);
67
+ x1 = Math.max(x1, x);
68
+ y1 = Math.max(y1, y);
69
+ }
70
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
71
+ }
72
+ /** Fit the svg's viewBox to the points plus a margin (fraction of the larger side). Returns the viewBox. */
73
+ export function frame(svg, q, margin = 0.1) {
74
+ const b = bbox(q), m = margin * Math.max(b.w, b.h);
75
+ const vb = { x: b.x - m, y: b.y - m, w: b.w + 2 * m, h: b.h + 2 * m };
76
+ setViewBox(svg, vb);
77
+ return vb;
78
+ }
79
+ export function setViewBox(svg, vb) {
80
+ svg.setAttribute('viewBox', `${vb.x} ${vb.y} ${vb.w} ${vb.h}`);
81
+ }
82
+ /** Escape text for interpolation into SVG markup. */
83
+ export const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
84
+ /** `n` copies of `f(i)` joined: texture from repetition (vents, ribs, rails). */
85
+ export const rep = (n, f) => Array.from({ length: n }, (_, i) => f(i)).join('');
86
+ // ---- flat detail primitives (face-local units, drawn inside an onTop/onFront/onSide group) ----
87
+ export const ln = (x1, y1, x2, y2, cls = 'detail') => `<line class="${cls}" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}"/>`;
88
+ export const rc = (x, y, w, h, r = 0.6, cls = 'detail') => `<rect class="${cls}" x="${x}" y="${y}" width="${w}" height="${h}" rx="${r}"/>`;
89
+ export const ci = (x, y, r, cls = 'detail') => `<circle class="${cls}" cx="${x}" cy="${y}" r="${r}"/>`;
90
+ /** Text in face-local units. Pass `max` (the room on its surface, in the same units) to shrink or truncate it to fit. */
91
+ export const tx = (x, y, s, size, anchor = 'start', cls = '', max) => {
92
+ // figure text is tracked (.stage text: letter-spacing .08em), so estimate it like a tracked label
93
+ const f = max ? fitText(s, size, 'tx-label', undefined, max) : { str: s, size };
94
+ return `<text${cls ? ` class="${cls}"` : ''} x="${x}" y="${y}" font-size="${+f.size.toFixed(2)}" text-anchor="${anchor}">${esc(f.str)}</text>`;
95
+ };
96
+ /** `a` can't cover `b`: it lies entirely on the low side of `b` along some axis. */
97
+ const behind = (a, b) => a[3] <= b[0] + 1e-6 || a[4] <= b[1] + 1e-6 || a[5] <= b[2] + 1e-6;
98
+ /**
99
+ * Back-to-front order for non-intersecting boxes: an edge a→b whenever a is behind b and not the reverse
100
+ * (when both hold their projections can't overlap, so order doesn't matter), then a topological sort
101
+ * that prefers authoring order and falls back to it for any cycle.
102
+ */
103
+ export function depthSort(list) {
104
+ const n = list.length, indeg = new Array(n).fill(0), out = list.map(() => []);
105
+ for (let i = 0; i < n; i++)
106
+ for (let j = i + 1; j < n; j++) {
107
+ const ab = behind(list[i].bb, list[j].bb), ba = behind(list[j].bb, list[i].bb);
108
+ if (ab && !ba) {
109
+ out[i].push(j);
110
+ indeg[j]++;
111
+ }
112
+ else if (ba && !ab) {
113
+ out[j].push(i);
114
+ indeg[i]++;
115
+ }
116
+ }
117
+ const ready = indeg.flatMap((d, i) => (d === 0 ? [i] : [])), done = [], seen = new Set();
118
+ while (ready.length) {
119
+ ready.sort((a, b) => a - b);
120
+ const i = ready.shift();
121
+ done.push(i);
122
+ seen.add(i);
123
+ for (const k of out[i])
124
+ if (--indeg[k] === 0)
125
+ ready.push(k);
126
+ }
127
+ for (let i = 0; i < n; i++)
128
+ if (!seen.has(i))
129
+ done.push(i);
130
+ return done.map(i => list[i]);
131
+ }
132
+ /**
133
+ * Collect a scene as units (a box or a few boxes plus the flat detail on their faces) and let
134
+ * `depthSort` work out the paint order, instead of hand-ordering hundreds of small parts.
135
+ */
136
+ export function createUnits(k) {
137
+ const units = [];
138
+ let u;
139
+ const cur = () => { if (!u)
140
+ throw new Error('units: call begin() before drawing'); return u; };
141
+ const extend = (x, y, z, w, d, h) => {
142
+ const b = cur().bb;
143
+ b[0] = Math.min(b[0], x);
144
+ b[1] = Math.min(b[1], y);
145
+ b[2] = Math.min(b[2], z);
146
+ b[3] = Math.max(b[3], x + w);
147
+ b[4] = Math.max(b[4], y + d);
148
+ b[5] = Math.max(b[5], z + h);
149
+ };
150
+ return {
151
+ begin(part, cls = part ? '' : 'deco') {
152
+ u = { bb: [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity], svg: '', part, cls };
153
+ units.push(u);
154
+ },
155
+ bx(x, y, z, w, d, h, r = 0) {
156
+ extend(x, y, z, w, d, h);
157
+ cur().svg += k.box(x, y, z, w, d, h, r);
158
+ },
159
+ extend,
160
+ raw(svg) { cur().svg += svg; },
161
+ onTop(x, y, z, s) { cur().svg += `<g transform="${k.TOP(x, y, z)}">${s}</g>`; },
162
+ onFront(x, y, z, s) { cur().svg += `<g transform="${k.FRONT(x, y, z)}">${s}</g>`; },
163
+ onSide(x, y, z, s) { cur().svg += `<g transform="${k.SIDE(x, y, z)}">${s}</g>`; },
164
+ emit(extra = []) {
165
+ const items = units.map(x => ({ bb: x.bb, html: x.part
166
+ ? `<g class="part press${x.cls ? ` ${x.cls}` : ''}" data-id="${x.part}">${x.svg}</g>`
167
+ : `<g class="${x.cls}">${x.svg}</g>` }));
168
+ return depthSort([...items, ...extra]).map(x => x.html).join('');
169
+ },
170
+ list() { return units; },
171
+ };
172
+ }
@@ -0,0 +1,49 @@
1
+ import { type IsoNode, type IsoPath, type Opts, type Scene, type Timeline, type Vec3 } from './engine/index.js';
2
+ import type { LoopContext } from './types.js';
3
+ /**
4
+ * A scene with the standard loop options: colours inherited from the page (`theme.css` tokens, so a page accent
5
+ * recolours it), no autoplay (the host decides when it plays), the poster as the reduced-motion rest pose. Installs
6
+ * the glow filters that `.glow-halo` blooms use.
7
+ */
8
+ export declare function loopScene(host: HTMLElement, aria: string, posterTime: number, opts?: Opts): Scene;
9
+ /** Seconds before a loop's story starts (the entrance plays first); cycle time 0 is this moment. */
10
+ export declare const DELAY = 1.2;
11
+ /** Ease in and out (cubic), the default for moves within a beat. */
12
+ export declare const smooth: (k: number) => number;
13
+ export interface Beat {
14
+ name: string;
15
+ start: number;
16
+ len: number;
17
+ }
18
+ /** Lay beats end to end: `[name, seconds]` pairs → each beat's start, plus the cycle length. */
19
+ export declare function beats(spec: readonly (readonly [string, number])[]): {
20
+ list: Beat[];
21
+ cycle: number;
22
+ };
23
+ /** Narrate every beat from the timeline, so captions follow seek, loop and pause exactly. */
24
+ export declare function narrate(tl: Timeline, ctx: LoopContext, list: readonly {
25
+ name: string;
26
+ start: number;
27
+ }[], says: readonly string[]): void;
28
+ /** One move of a ride: along `path` between cycle times `t0` and `t1`, resting at its end until `until`. */
29
+ export interface Leg {
30
+ path: IsoPath;
31
+ t0: number;
32
+ t1: number;
33
+ until: number;
34
+ back?: boolean;
35
+ }
36
+ /**
37
+ * Carry a node along world paths at set moments of the cycle, resting between legs (`s.travel` loops without rests).
38
+ * `ease` shapes each move (default `smooth`; a product whose motion rules ask for linear progress passes `k => k`).
39
+ */
40
+ export declare function ride(s: Scene, id: string, home: Vec3, cycle: number, legs: readonly Leg[], ease?: (k: number) => number): void;
41
+ /**
42
+ * A soft bloom of accent light behind a lit object (`figure.css` `.glow-halo`), flat on its plane, hidden until a beat
43
+ * shows it. Add it just before the object it lights so it sorts behind it. Two forms:
44
+ * `halo(s, id, at, size, r?)` adds it to scene `s`; `halo(id, at, size, r?)` returns a detached node for `s.add` or
45
+ * a group. Default radius 8.
46
+ */
47
+ export declare function halo(s: Scene, id: string, at: Vec3, size: readonly [number, number], r?: number): IsoNode;
48
+ export declare function halo(id: string, at: Vec3, size: readonly [number, number], r?: number): IsoNode;
49
+ export type { Loop, LoopContext, LoopHandle } from './types.js';
package/dist/loops.js ADDED
@@ -0,0 +1,64 @@
1
+ import Iso, {} from './engine/index.js';
2
+ import { installFilters } from './filters.js';
3
+ /**
4
+ * A scene with the standard loop options: colours inherited from the page (`theme.css` tokens, so a page accent
5
+ * recolours it), no autoplay (the host decides when it plays), the poster as the reduced-motion rest pose. Installs
6
+ * the glow filters that `.glow-halo` blooms use.
7
+ */
8
+ export function loopScene(host, aria, posterTime, opts = {}) {
9
+ installFilters(host.ownerDocument);
10
+ return Iso.scene(host, {
11
+ theme: 'inherit', label: aria, autoplay: false, reducedMotion: 'static', restTime: posterTime, padding: 10, ...opts,
12
+ });
13
+ }
14
+ /** Seconds before a loop's story starts (the entrance plays first); cycle time 0 is this moment. */
15
+ export const DELAY = 1.2;
16
+ /** Ease in and out (cubic), the default for moves within a beat. */
17
+ export const smooth = (k) => (k < 0.5 ? 4 * k * k * k : 1 - (-2 * k + 2) ** 3 / 2);
18
+ /** Lay beats end to end: `[name, seconds]` pairs → each beat's start, plus the cycle length. */
19
+ export function beats(spec) {
20
+ let t = 0;
21
+ const list = spec.map(([name, len]) => { const start = t; t += len; return { name, start, len }; });
22
+ return { list, cycle: t };
23
+ }
24
+ /** Narrate every beat from the timeline, so captions follow seek, loop and pause exactly. */
25
+ export function narrate(tl, ctx, list, says) {
26
+ list.forEach((b, i) => tl.call(() => { ctx.beat(i, list.length, b.name); ctx.say(says[i]); }, b.start + 0.001));
27
+ }
28
+ /**
29
+ * Carry a node along world paths at set moments of the cycle, resting between legs (`s.travel` loops without rests).
30
+ * `ease` shapes each move (default `smooth`; a product whose motion rules ask for linear progress passes `k => k`).
31
+ */
32
+ export function ride(s, id, home, cycle, legs, ease = smooth) {
33
+ const node = s.get(id);
34
+ if (!node)
35
+ throw new Error(`ride: no node "${id}"`);
36
+ let last = '';
37
+ s.loop(time => {
38
+ let p = home;
39
+ if (time >= DELAY) {
40
+ const c = (((time - DELAY) % cycle) + cycle) % cycle;
41
+ for (const L of legs) {
42
+ if (c < L.t0 || c >= L.until)
43
+ continue;
44
+ const e = ease(Math.min(1, (c - L.t0) / (L.t1 - L.t0)));
45
+ p = L.path.at(L.back ? 1 - e : e);
46
+ break;
47
+ }
48
+ }
49
+ const key = `${p[0]},${p[1]},${p[2]}`;
50
+ if (key === last)
51
+ return; // resting: don't force a re-sort every frame
52
+ last = key;
53
+ node.set({ x: p[0] - home[0], y: p[1] - home[1], z: p[2] - home[2] });
54
+ });
55
+ }
56
+ export function halo(...a) {
57
+ if (typeof a[0] === 'string') {
58
+ const [id, at, size, r = 8] = a;
59
+ return haloNode(id, at, size, r);
60
+ }
61
+ const [scene, id, at, size, r = 8] = a;
62
+ return scene.add(haloNode(id, at, size, r));
63
+ }
64
+ const haloNode = (id, at, size, r) => Iso.make('rect', { id, at, size: [size[0], size[1]], r, fill: 'f-accent', line: null, class: 'glow-halo', opacity: 0 });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Shared interaction patterns from the "Layers & links" section of skills/iso-engine/references/figures.md: tweens (zoom, tilt),
3
+ * signal sequences and callouts. Figures compose these; each returns a `cancel` so the host can unmount
4
+ * a figure mid-animation without stray frames or timers writing into a detached stage.
5
+ */
6
+ import { type Pt, type Rect } from './kernel.js';
7
+ /** True when the viewer asked for reduced motion: animations jump to their end state. */
8
+ export declare const reduced: () => boolean;
9
+ export declare const ease: (k: number) => number;
10
+ export interface Tween {
11
+ /** Run `step(e)` each frame with eased progress 0..1; a new run cancels the previous one. */
12
+ run(ms: number, step: (e: number) => void): void;
13
+ cancel(): void;
14
+ }
15
+ export declare function createTween(): Tween;
16
+ export interface Sequence {
17
+ /** Apply steps one after another, calling `render()` after each; a new run cancels the previous one. */
18
+ run(steps: Array<() => void>, ms?: number): Promise<void>;
19
+ cancel(): void;
20
+ }
21
+ export declare function createSequence(render: () => void): Sequence;
22
+ export interface Zoom {
23
+ /** Current viewBox (mutated in place while tweening). */
24
+ readonly vb: Rect;
25
+ /** ViewBox around bounds `b`, same aspect as the base frame, never wider than it. */
26
+ fit(b: Rect, pad?: number): Rect;
27
+ to(target: Rect, ms?: number): void;
28
+ /** Back to the base frame. */
29
+ reset(ms?: number): void;
30
+ cancel(): void;
31
+ }
32
+ /** Tween the svg's viewBox; `onFrame` runs after each update (reposition callouts there). */
33
+ export declare function createZoom(svg: SVGSVGElement, base: Rect, onFrame?: () => void): Zoom;
34
+ export interface Callout {
35
+ at: Pt;
36
+ lines: string[];
37
+ }
38
+ /**
39
+ * Draw leader-line labels into `hud` (a `<g>` drawn last, no plane transform) for the current viewBox.
40
+ * Sizes are in screen pixels, so labels keep their size under zoom. Lines stack upward, clear of the leader.
41
+ */
42
+ export declare function placeCallouts(svg: SVGSVGElement, hud: SVGGElement, vb: Rect, list: readonly Callout[]): void;
43
+ /** Call `fn` when the element's rendered size changes (callouts are sized in screen pixels). Returns a disconnect. */
44
+ export declare function onResize(el: Element, fn: () => void): () => void;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Shared interaction patterns from the "Layers & links" section of skills/iso-engine/references/figures.md: tweens (zoom, tilt),
3
+ * signal sequences and callouts. Figures compose these; each returns a `cancel` so the host can unmount
4
+ * a figure mid-animation without stray frames or timers writing into a detached stage.
5
+ */
6
+ import { esc, setViewBox } from './kernel.js';
7
+ /** True when the viewer asked for reduced motion: animations jump to their end state. */
8
+ export const reduced = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
9
+ export const ease = (k) => (k < 0.5 ? 2 * k * k : 1 - (-2 * k + 2) ** 2 / 2);
10
+ export function createTween() {
11
+ let gen = 0;
12
+ return {
13
+ run(ms, step) {
14
+ const g = ++gen, t0 = performance.now();
15
+ if (reduced() || ms <= 0) {
16
+ step(1);
17
+ return;
18
+ }
19
+ const frame = (now) => {
20
+ if (g !== gen)
21
+ return;
22
+ const k = Math.min(1, (now - t0) / ms);
23
+ step(ease(k));
24
+ if (k < 1)
25
+ requestAnimationFrame(frame);
26
+ };
27
+ requestAnimationFrame(frame);
28
+ },
29
+ cancel() { gen++; },
30
+ };
31
+ }
32
+ export function createSequence(render) {
33
+ let gen = 0;
34
+ return {
35
+ async run(steps, ms = 180) {
36
+ const g = ++gen;
37
+ for (const step of steps) {
38
+ if (g !== gen)
39
+ return;
40
+ step();
41
+ render();
42
+ if (!reduced())
43
+ await new Promise(r => setTimeout(r, ms));
44
+ }
45
+ },
46
+ cancel() { gen++; },
47
+ };
48
+ }
49
+ /** Tween the svg's viewBox; `onFrame` runs after each update (reposition callouts there). */
50
+ export function createZoom(svg, base, onFrame = () => { }) {
51
+ const vb = { ...base }, tween = createTween();
52
+ const to = (target, ms = 420) => {
53
+ const from = { ...vb };
54
+ tween.run(ms, e => {
55
+ vb.x = from.x + (target.x - from.x) * e;
56
+ vb.y = from.y + (target.y - from.y) * e;
57
+ vb.w = from.w + (target.w - from.w) * e;
58
+ vb.h = from.h + (target.h - from.h) * e;
59
+ setViewBox(svg, vb);
60
+ onFrame();
61
+ });
62
+ };
63
+ return {
64
+ vb,
65
+ fit(b, pad = 1.8) {
66
+ const s = Math.min(1, Math.max(b.w / base.w, b.h / base.h) * pad), w = base.w * s, h = base.h * s;
67
+ return { x: b.x + b.w / 2 - w / 2, y: b.y + b.h / 2 - h / 2, w, h };
68
+ },
69
+ to,
70
+ reset(ms) { to(base, ms); },
71
+ cancel: tween.cancel,
72
+ };
73
+ }
74
+ /**
75
+ * Draw leader-line labels into `hud` (a `<g>` drawn last, no plane transform) for the current viewBox.
76
+ * Sizes are in screen pixels, so labels keep their size under zoom. Lines stack upward, clear of the leader.
77
+ */
78
+ export function placeCallouts(svg, hud, vb, list) {
79
+ const r = svg.getBoundingClientRect();
80
+ const k = r.width && r.height ? Math.max(vb.w / r.width, vb.h / r.height) : vb.w / 600;
81
+ hud.innerHTML = list.map(({ at: [ax, ay], lines }) => {
82
+ const left = ax < vb.x + vb.w / 2;
83
+ const lx = left ? vb.x + 14 * k : vb.x + vb.w - 14 * k, ly = ay - 26 * k, ex = ax + (left ? -18 : 18) * k;
84
+ return `<circle class="dot" cx="${ax}" cy="${ay}" r="${2.4 * k}"/>
85
+ <polyline class="leader" points="${ax},${ay} ${ex},${ly} ${lx},${ly}"/>
86
+ ${lines.map((t, j) => `<text class="lcd" x="${lx}" y="${ly - 5 * k - (lines.length - 1 - j) * 13 * k}"
87
+ font-size="${11 * k}" stroke-width="${3 * k}" text-anchor="${left ? 'start' : 'end'}">${esc(t)}</text>`).join('')}`;
88
+ }).join('');
89
+ }
90
+ /** Call `fn` when the element's rendered size changes (callouts are sized in screen pixels). Returns a disconnect. */
91
+ export function onResize(el, fn) {
92
+ if (typeof ResizeObserver !== 'function')
93
+ return () => { };
94
+ const ro = new ResizeObserver(() => fn());
95
+ ro.observe(el);
96
+ return () => ro.disconnect();
97
+ }
package/dist/theme.css ADDED
@@ -0,0 +1,19 @@
1
+ /* Default tokens for figures and loops: grey hairlines on near-background fills, light and dark, plus one accent
2
+ (sodium) for what is lit. Load it before figure.css, or define these properties yourself. Dark follows the system
3
+ unless <html data-theme="light|dark"> pins it. Override --accent / --accent-hi on any ancestor of a figure or loop
4
+ to recolour just that one. */
5
+ :root {
6
+ --page:#e9eaea; --panel:#f6f6f5; --edge:#d6d8d8; --body:#f6f6f5; --deck:#fbfbfa; --glass:#ececea;
7
+ --line:#7a7d80; --detail:#b9bbbd; --live:#111213; --ink:#6a6d70;
8
+ --accent:#d97706; --accent-hi:#f59e0b;
9
+ --mono:"IBM Plex Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace;
10
+ color-scheme:light;
11
+ }
12
+ @media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) {
13
+ --page:#0c0d0e; --panel:#141516; --edge:#222426; --body:#141516; --deck:#18191a; --glass:#0e0f10;
14
+ --line:#6d7073; --detail:#393c3f; --live:#f1f1ee; --ink:#8a8d90;
15
+ --accent:#ff9a2e; --accent-hi:#ffc77a; color-scheme:dark; } }
16
+ :root[data-theme="dark"] {
17
+ --page:#0c0d0e; --panel:#141516; --edge:#222426; --body:#141516; --deck:#18191a; --glass:#0e0f10;
18
+ --line:#6d7073; --detail:#393c3f; --live:#f1f1ee; --ink:#8a8d90;
19
+ --accent:#ff9a2e; --accent-hi:#ffc77a; color-scheme:dark; }
@@ -0,0 +1,86 @@
1
+ /** What `mountFigure` (or a host app's own shell) hands a figure when it mounts. */
2
+ export interface FigureContext {
3
+ /** The figure's `<svg>`, already in the document with role, tabindex and aria-label set. Empty. */
4
+ stage: SVGSVGElement;
5
+ /** Write the live readout (the figure's state caption). Call it on every interaction. */
6
+ readout(text: string): void;
7
+ /** The element holding `stage`. Engine-built figures create their scene here (and may remove `stage`). */
8
+ host: HTMLElement;
9
+ /** setTimeout, cleared automatically when the figure is left. */
10
+ after(ms: number, fn: () => void): void;
11
+ /** setInterval, cleared automatically when the figure is left. */
12
+ every(ms: number, fn: () => void): void;
13
+ /** Call `fn(timestampMs)` every animation frame until the returned stop() or the figure is left; time from the timestamp. */
14
+ loop(fn: (now: number) => void): () => void;
15
+ /** Press feedback: sink the part and light it (glow kit `.flash`), then let it fade. */
16
+ flash(el: Element | null, ms?: number): void;
17
+ /** Restart a one-shot CSS animation, e.g. a `.pulse` travelling along a wire (`replay(el)` toggles `go`). */
18
+ replay(el: Element | null, cls?: string): void;
19
+ /** Warm accent haze behind the figure while it is on. */
20
+ power(on: boolean): void;
21
+ }
22
+ /** What a mounted figure gives back to its host. */
23
+ export interface FigureHandle {
24
+ /**
25
+ * Page-level keys (digits, letters) while this figure is shown; return true if consumed. Modified keys
26
+ * (meta/ctrl/alt) should be filtered out by the host. Arrow keys and Escape belong on `stage` listeners so
27
+ * they only act while the drawing has focus.
28
+ */
29
+ key?(e: KeyboardEvent): boolean;
30
+ /** Cancel timers, tweens and sequences. Listeners on `stage` go away with the element. */
31
+ destroy?(): void;
32
+ /**
33
+ * A short scripted sequence that uses the same functions as real input and leaves the figure lit. `mountFigure`
34
+ * runs it on arrival with `{ demo: true }`; it is how a figure opens already alive on a landing page. Schedule it
35
+ * with `ctx.after`.
36
+ */
37
+ demo?(): void;
38
+ }
39
+ /**
40
+ * An interactive isometric figure drawn with the kernel. `css` is figure-specific styling and must be scoped under
41
+ * `[data-fig="<id>"]`; the shared classes (.face, .detail, .press, .part, .flow, .cut, .hud …) live in
42
+ * `@entro314labs/iso-engine/figure.css`.
43
+ */
44
+ export interface Figure {
45
+ /** Unique id and css scope, kebab-case. */
46
+ id: string;
47
+ /** Display name (the figure's title caption). */
48
+ name: string;
49
+ /** The project the figure was made for (a host may group figures by it). */
50
+ project?: string;
51
+ /** How to operate it, for a caption. */
52
+ hint: string;
53
+ /** What it is and how to operate it, for screen readers. */
54
+ aria: string;
55
+ css?: string;
56
+ mount(ctx: FigureContext): FigureHandle;
57
+ }
58
+ /** What a host hands a loop when it mounts it. */
59
+ export interface LoopContext {
60
+ /** Narrate the current beat (a caption). */
61
+ say(text: string): void;
62
+ /** Mark beat `index` of `total` as current (e.g. a counter: `02 / 05 · idle`). */
63
+ beat(index: number, total: number, name: string): void;
64
+ }
65
+ /** What a mounted loop gives back: its engine scene (the host plays, pauses and seeks it) and its poster time. */
66
+ export interface LoopHandle {
67
+ scene: import('./engine/index.js').Scene;
68
+ /** Seconds into the timeline of the poster frame: shown before play, under reduced motion and in thumbnails. */
69
+ posterTime: number;
70
+ destroy?(): void;
71
+ }
72
+ /**
73
+ * One autoplaying animation built on the Iso engine (`@entro314labs/iso-engine/engine`). `css` is scoped under
74
+ * `[data-loop="<id>"]`.
75
+ */
76
+ export interface Loop {
77
+ id: string;
78
+ project: string;
79
+ /** Short label for what the loop shows, e.g. "flow", "how it works". */
80
+ kind: string;
81
+ name: string;
82
+ /** The whole story in one or two sentences, for screen readers. */
83
+ aria: string;
84
+ css?: string;
85
+ mount(host: HTMLElement, ctx: LoopContext): LoopHandle;
86
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};