@johnoscott/isometric-engine 0.14.1 → 0.15.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.
- package/README.md +1 -1
- package/iso-editor.js +199 -190
- package/iso-render.js +157 -148
- package/iso-systems.js +170 -159
- package/js/iso-objects/ants.js +36 -0
- package/js/iso-objects/index.js +47 -1
- package/js/iso-objects/looks.js +25 -0
- package/js/iso-objects/motion-builder.js +130 -0
- package/js/iso-objects/motion-doc.js +500 -0
- package/js/iso-objects/motion-entry.js +32 -0
- package/js/iso-objects/motion.js +635 -0
- package/js/iso-objects/resolve.js +238 -0
- package/js/iso-objects/scene.js +15 -13
- package/js/iso-objects/timeline.js +553 -0
- package/js/iso-systems/compile.js +59 -1
- package/js/iso-systems/index.js +4 -1
- package/js/iso-systems/render.js +20 -0
- package/js/iso-systems/schema.json +39 -0
- package/js/iso-viewer/page.js +2 -1
- package/js/iso-viewer/player.js +23 -34
- package/package.json +46 -1
- package/src/iso-objects/ants.ts +53 -0
- package/src/iso-objects/compile.ts +4 -1
- package/src/iso-objects/index.ts +14 -1
- package/src/iso-objects/looks.ts +21 -0
- package/src/iso-objects/motion-builder.ts +79 -0
- package/src/iso-objects/motion-doc.ts +361 -0
- package/src/iso-objects/motion-entry.ts +12 -0
- package/src/iso-objects/motion.ts +616 -0
- package/src/iso-objects/resolve.ts +196 -0
- package/src/iso-objects/scene.ts +29 -13
- package/src/iso-objects/timeline.ts +443 -0
- package/src/iso-objects/types.ts +20 -2
- package/src/iso-systems/compile.ts +58 -3
- package/src/iso-systems/index.ts +4 -1
- package/src/iso-systems/render.ts +41 -0
- package/src/iso-systems/schema.json +39 -0
- package/src/iso-viewer/page.ts +2 -1
- package/src/iso-viewer/player.ts +24 -41
- package/types/iso-objects/ants.d.ts +33 -0
- package/types/iso-objects/compile.d.ts +3 -0
- package/types/iso-objects/index.d.ts +14 -1
- package/types/iso-objects/looks.d.ts +4 -0
- package/types/iso-objects/motion-builder.d.ts +105 -0
- package/types/iso-objects/motion-doc.d.ts +787 -0
- package/types/iso-objects/motion-entry.d.ts +10 -0
- package/types/iso-objects/motion.d.ts +200 -0
- package/types/iso-objects/resolve.d.ts +20 -0
- package/types/iso-objects/scene.d.ts +11 -0
- package/types/iso-objects/timeline.d.ts +46 -0
- package/types/iso-objects/types.d.ts +32 -0
- package/types/iso-systems/compile.d.ts +20 -3
- package/types/iso-systems/index.d.ts +4 -1
- package/types/iso-systems/render.d.ts +21 -0
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
// Motion as a function of time: a plan is seekable. `at(ms)` gives what the scene looks like then, as plain JSON (a
|
|
2
|
+
// SceneState); svgAt(scene, state) is that as SVG text (no DOM), paint(svg, state) puts it on a live drawing,
|
|
3
|
+
// idempotently; frame(ms) is svgAt of at(ms). No clock, no DOM and no randomness that isn't seeded in what makes a frame:
|
|
4
|
+
// the same scene, options and seed give the same bytes, in any order, anywhere. assemble() ends, and disassemble()
|
|
5
|
+
// starts, on the scene's own still render, byte for byte; the other end is empty.
|
|
6
|
+
//
|
|
7
|
+
// How: motionModel(scene) is what a plan needs of a drawing, as plain data (a page carries it as JSON); planOf(model,
|
|
8
|
+
// options) works out when each piece, connector and label moves. A state touches only the drawing's wrappers (scene.ts:
|
|
9
|
+
// data-item or data-route, with data-part), the connectors' own paths, the overlay's layer and the viewBox.
|
|
10
|
+
|
|
11
|
+
import type { CompiledScene } from './compile.ts';
|
|
12
|
+
import type { Placed, RawMotion } from './types.ts';
|
|
13
|
+
import { iso } from '../iso-core/kernel.ts';
|
|
14
|
+
import { offscreen, type Assembly } from './assemble.ts';
|
|
15
|
+
import { polyBounds, silhouette, type Rect } from './labels.ts';
|
|
16
|
+
|
|
17
|
+
export const ASSEMBLE_STYLES = ['edge', 'drop', 'rise', 'fly', 'pop', 'scatter', 'build', 'fade'] as const;
|
|
18
|
+
export const DISASSEMBLE_STYLES = ['explode', 'lift-off', 'sink', 'scatter', 'fly-out', 'collapse', 'fade', 'reverse'] as const;
|
|
19
|
+
export const MOTION_ORDERS = ['by-depth', 'by-layer', 'by-region', 'by-flow', 'as-listed', 'random'] as const;
|
|
20
|
+
export const MOTION_EASINGS = ['linear', 'ease', 'ease-in', 'ease-out', 'settle', 'spring', 'bounce'] as const;
|
|
21
|
+
export type AssembleStyle = typeof ASSEMBLE_STYLES[number];
|
|
22
|
+
export type DisassembleStyle = typeof DISASSEMBLE_STYLES[number];
|
|
23
|
+
export type MotionOrder = typeof MOTION_ORDERS[number];
|
|
24
|
+
export type MotionEasing = typeof MOTION_EASINGS[number];
|
|
25
|
+
export type Direction = 'left' | 'right' | 'top' | 'bottom';
|
|
26
|
+
|
|
27
|
+
/** what one piece's (or a region's contents') `motion:` in the file may say */
|
|
28
|
+
export type PieceMotion = RawMotion;
|
|
29
|
+
interface CommonOptions {
|
|
30
|
+
order?: MotionOrder;
|
|
31
|
+
/** where by-flow starts: a piece's id (default: the first piece no connector ends at) */
|
|
32
|
+
source?: string;
|
|
33
|
+
connectors?: 'draw' | 'grow' | 'fade';
|
|
34
|
+
/** after the connectors are in (before they go): a token runs along each, once */
|
|
35
|
+
pulses?: boolean;
|
|
36
|
+
labels?: 'fade' | 'type' | 'with-piece';
|
|
37
|
+
/** the whole plan's length, ms: everything is scaled to it (default: as long as it comes to) */
|
|
38
|
+
duration?: number;
|
|
39
|
+
/** ms between one piece's start and the next's */
|
|
40
|
+
stagger?: number;
|
|
41
|
+
/** ms one piece's move takes */
|
|
42
|
+
piece?: number;
|
|
43
|
+
/** how much of the next part (pieces, connectors, labels) runs over the end of the one before, 0 to 1 */
|
|
44
|
+
overlap?: number;
|
|
45
|
+
easing?: MotionEasing;
|
|
46
|
+
/** fly, fly-out: the side it comes from or goes to */
|
|
47
|
+
from?: Direction;
|
|
48
|
+
seed?: number;
|
|
49
|
+
}
|
|
50
|
+
export interface AssembleOptions extends CommonOptions { style?: AssembleStyle }
|
|
51
|
+
export interface DisassembleOptions extends CommonOptions {
|
|
52
|
+
style?: DisassembleStyle;
|
|
53
|
+
/** explode, collapse: the point (in the drawing's units), or a piece's id (default: the drawing's middle; collapse
|
|
54
|
+
* into the region that holds each piece: 'region') */
|
|
55
|
+
point?: [number, number] | string;
|
|
56
|
+
/** reverse: the assemble style it plays backwards */
|
|
57
|
+
of?: AssembleStyle;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ---------- what a plan needs of a drawing ----------
|
|
61
|
+
|
|
62
|
+
export interface MotionPiece {
|
|
63
|
+
id: string; kind: 'region' | 'node'; parent?: string; depth: number; layer: number; key: number;
|
|
64
|
+
bbox: Rect;
|
|
65
|
+
/** the middle of its footprint, and its bottom outline (left, front, right corner), in the drawing's units */
|
|
66
|
+
foot: [number, number]; base: [number, number][];
|
|
67
|
+
motion?: PieceMotion;
|
|
68
|
+
}
|
|
69
|
+
export interface MotionModel {
|
|
70
|
+
viewBox: [number, number, number, number];
|
|
71
|
+
pieces: MotionPiece[];
|
|
72
|
+
routes: { id: string; path: string; from?: string; to?: string }[];
|
|
73
|
+
/** notes' ids and what they are on (a piece or a route) */
|
|
74
|
+
notes: Record<string, string | undefined>;
|
|
75
|
+
/** the build-time intro's own timing (`edge` with no other timing given plays exactly it) */
|
|
76
|
+
intro: Assembly;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const r2 = (v: number) => Math.round(v * 100) / 100 || 0; // (never -0)
|
|
80
|
+
const r4 = (v: number) => Math.round(v * 10000) / 10000 || 0;
|
|
81
|
+
|
|
82
|
+
export function motionModel(s: CompiledScene): MotionModel {
|
|
83
|
+
const depthOf = (p: Placed) => { let d = 0; for (let a = p.parent; a; a = a.parent) d++; return d; };
|
|
84
|
+
const inherited = (p: Placed): PieceMotion | undefined => {
|
|
85
|
+
// a region's motion is its contents' too, each key unless the piece (or a nearer region) says its own
|
|
86
|
+
const chain: PieceMotion[] = [];
|
|
87
|
+
for (let a: Placed | undefined = p; a; a = a.parent) { const m = (a.region ?? a.node)?.motion; if (m) chain.unshift(m); }
|
|
88
|
+
return chain.length ? Object.assign({}, ...chain) as PieceMotion : undefined;
|
|
89
|
+
};
|
|
90
|
+
const AIR = new Set(s.layout.items.filter(p => p.region && s.layout.catalog && s.rendered.svg.includes(`class="tunnel" data-id="${p.id}"`)).map(p => p.id));
|
|
91
|
+
return {
|
|
92
|
+
viewBox: s.rendered.viewBox,
|
|
93
|
+
pieces: s.layout.items.map(p => {
|
|
94
|
+
const b = p.box, c = iso((b.x0 + b.x1) / 2, (b.y0 + b.y1) / 2, b.z0), m = inherited(p);
|
|
95
|
+
return {
|
|
96
|
+
id: p.id, kind: p.type, ...(p.parent ? { parent: p.parent.id } : {}), depth: depthOf(p),
|
|
97
|
+
layer: AIR.has(p.id) ? 2 : p.type === 'region' ? 0 : 1, key: r2(b.x0 + b.y0 + b.z0 * 0.01),
|
|
98
|
+
bbox: polyBounds(silhouette(b)), foot: [r2(c[0]), r2(c[1])],
|
|
99
|
+
base: [iso(b.x0, b.y1, b.z0), iso(b.x1, b.y1, b.z0), iso(b.x1, b.y0, b.z0)].map(q => [r2(q[0]), r2(q[1])] as [number, number]),
|
|
100
|
+
...(m ? { motion: m } : {}),
|
|
101
|
+
};
|
|
102
|
+
}),
|
|
103
|
+
routes: s.routes.filter(r => s.rendered.paths[r.id]).map(r => ({ id: r.id, path: s.rendered.paths[r.id], ...ends(r.raw as { from?: unknown; to?: unknown }) })),
|
|
104
|
+
notes: Object.fromEntries((s.raw.notes ?? []).map((n, i) => [`${s.id}-note-${i}`, n.on])),
|
|
105
|
+
intro: s.rendered.assembly,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
const endId = (v: unknown) => (typeof v === 'string' ? v.split('.')[0] : undefined);
|
|
109
|
+
const ends = (r: { from?: unknown; to?: unknown }) => { const from = endId(r.from), to = endId(r.to); return { ...(from ? { from } : {}), ...(to ? { to } : {}) }; };
|
|
110
|
+
|
|
111
|
+
// ---------- curves, and a seeded stream ----------
|
|
112
|
+
|
|
113
|
+
const bezier = (x1: number, y1: number, x2: number, y2: number) => (x: number) => {
|
|
114
|
+
if (x <= 0) return 0; if (x >= 1) return 1;
|
|
115
|
+
const at = (a: number, b: number, t: number) => 3 * a * t * (1 - t) ** 2 + 3 * b * t * t * (1 - t) + t ** 3;
|
|
116
|
+
let lo = 0, hi = 1;
|
|
117
|
+
for (let i = 0; i < 40; i++) { const m = (lo + hi) / 2; if (at(x1, x2, m) < x) lo = m; else hi = m; }
|
|
118
|
+
return at(y1, y2, (lo + hi) / 2);
|
|
119
|
+
};
|
|
120
|
+
const CURVES: Record<MotionEasing, (f: number) => number> = {
|
|
121
|
+
linear: f => f, ease: bezier(0.42, 0, 0.58, 1), 'ease-in': bezier(0.42, 0, 1, 1), 'ease-out': bezier(0, 0, 0.58, 1),
|
|
122
|
+
// the page player's own: quick in, a long settle
|
|
123
|
+
settle: bezier(0.16, 0.84, 0.3, 1),
|
|
124
|
+
spring: f => (f <= 0 ? 0 : f >= 1 ? 1 : 1 - Math.exp(-6 * f) * Math.cos(9.5 * f) * (1 - f)),
|
|
125
|
+
bounce: f => {
|
|
126
|
+
if (f <= 0) return 0; if (f >= 1) return 1;
|
|
127
|
+
const n = 7.5625, d = 2.75;
|
|
128
|
+
if (f < 1 / d) return n * f * f;
|
|
129
|
+
if (f < 2 / d) return n * (f - 1.5 / d) ** 2 + 0.75;
|
|
130
|
+
if (f < 2.5 / d) return n * (f - 2.25 / d) ** 2 + 0.9375;
|
|
131
|
+
return n * (f - 2.625 / d) ** 2 + 0.984375;
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
/** a seeded stream of numbers in [0, 1) (mulberry32) */
|
|
135
|
+
function stream(seed: number): () => number {
|
|
136
|
+
let a = seed >>> 0;
|
|
137
|
+
return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
|
138
|
+
}
|
|
139
|
+
/** an id's own number, so a piece's random place doesn't depend on the others */
|
|
140
|
+
const hashOf = (s: string) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; };
|
|
141
|
+
const clamp = (f: number) => Math.max(0, Math.min(1, f));
|
|
142
|
+
|
|
143
|
+
// ---------- what a scene looks like at a moment ----------
|
|
144
|
+
|
|
145
|
+
/** a thing's block, walls, gate and name: what is not given is as in the still */
|
|
146
|
+
export interface ItemState {
|
|
147
|
+
opacity?: number;
|
|
148
|
+
/** in the drawing's units */
|
|
149
|
+
dx?: number; dy?: number;
|
|
150
|
+
/** about `about` (default: the drawing's origin) */
|
|
151
|
+
scale?: number; about?: [number, number];
|
|
152
|
+
/** only what is inside this shows (a polygon, before the offset) */
|
|
153
|
+
clip?: [number, number][];
|
|
154
|
+
}
|
|
155
|
+
/** a label or a note: faded, or typed so far (0 to 1) */
|
|
156
|
+
export interface LabelState { opacity?: number; typed?: number; dx?: number; dy?: number }
|
|
157
|
+
/** a connector: how much of it is drawn (0 to 1: its arrowhead shows at 1), stroked in, or growing from its source */
|
|
158
|
+
export interface RouteState {
|
|
159
|
+
opacity?: number; drawn?: number; by?: 'stroke' | 'grow';
|
|
160
|
+
/** (a timeline's) marching dashes: on and off, and how far they have marched, in the drawing's units along it */
|
|
161
|
+
ants?: { dash: [number, number]; offset: number };
|
|
162
|
+
}
|
|
163
|
+
/** Plain JSON. Empty: the still render. What isn't named is as in the still. */
|
|
164
|
+
export interface SceneState {
|
|
165
|
+
items?: Record<string, ItemState>;
|
|
166
|
+
/** by the id of a thing, a connector or a note */
|
|
167
|
+
labels?: Record<string, LabelState>;
|
|
168
|
+
routes?: Record<string, RouteState>;
|
|
169
|
+
/** by the id of a thing: how much of each of its looks is there (the rest is its own), 0 to 1 */
|
|
170
|
+
variants?: Record<string, Record<string, number>>;
|
|
171
|
+
/** the step marks' and badges' layers */
|
|
172
|
+
marks?: { opacity: number };
|
|
173
|
+
/** a token on a connector, a fraction (0 to 1) of the way along it */
|
|
174
|
+
tokens?: { route: string; at: number; color?: string; kind?: string }[];
|
|
175
|
+
/** a ring round a point */
|
|
176
|
+
pulses?: { x: number; y: number; rx: number; ry: number; opacity?: number; color?: string }[];
|
|
177
|
+
/** (a timeline's) an outline round a thing: its silhouette */
|
|
178
|
+
outlines?: { id: string; points: [number, number][]; opacity?: number; color?: string }[];
|
|
179
|
+
/** the view, in the drawing's units */
|
|
180
|
+
camera?: [number, number, number, number];
|
|
181
|
+
/** how far toward the 2D view (0 to 1): a morph's, for a host that draws one; svgAt and paint draw the 3D view */
|
|
182
|
+
morph?: number;
|
|
183
|
+
}
|
|
184
|
+
export interface MotionPlan {
|
|
185
|
+
kind: 'assemble' | 'disassemble';
|
|
186
|
+
/** ms */
|
|
187
|
+
duration: number;
|
|
188
|
+
/** when each piece moves, in the order it does */
|
|
189
|
+
pieces: { id: string; delay: number; dur: number; style: string }[];
|
|
190
|
+
routes: { id: string; delay: number; dur: number }[];
|
|
191
|
+
labels: { delay: number; dur: number };
|
|
192
|
+
/** what the scene looks like at t ms: plain JSON, the same for the same t */
|
|
193
|
+
at(t: number): SceneState;
|
|
194
|
+
}
|
|
195
|
+
export interface ScenePlan extends MotionPlan {
|
|
196
|
+
/** the scene's SVG at t ms, as text: svgAt(scene, at(t)) */
|
|
197
|
+
frame(t: number): string;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
interface Timed { p: MotionPiece; delay: number; dur: number; style: string; curve: (f: number) => number; from: Direction }
|
|
201
|
+
|
|
202
|
+
const MARGIN = 24;
|
|
203
|
+
function side(b: Rect, vb: [number, number, number, number], to: Direction): [number, number] {
|
|
204
|
+
const [x, y, w, h] = vb;
|
|
205
|
+
if (to === 'left') return [-(b.x + b.w - x) - MARGIN, 0];
|
|
206
|
+
if (to === 'right') return [x + w - b.x + MARGIN, 0];
|
|
207
|
+
if (to === 'top') return [0, -(b.y + b.h - y) - MARGIN];
|
|
208
|
+
return [0, y + h - b.y + MARGIN];
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** the order the pieces move in: what they stand on, or are in, never after them (but as-listed and random) */
|
|
212
|
+
export function motionOrder(m: MotionModel, order: MotionOrder, o: { seed?: number; source?: string } = {}): MotionPiece[] {
|
|
213
|
+
const P = m.pieces, byId = new Map(P.map(p => [p.id, p]));
|
|
214
|
+
const back = (a: MotionPiece, b: MotionPiece) => a.depth - b.depth || a.key - b.key;
|
|
215
|
+
if (order === 'as-listed') return [...P];
|
|
216
|
+
if (order === 'random') { const next = stream(o.seed ?? 1); return P.map(p => [next(), p] as const).sort((a, b) => a[0] - b[0]).map(x => x[1]); }
|
|
217
|
+
if (order === 'by-layer') return [...P].sort((a, b) => a.layer - b.layer || back(a, b));
|
|
218
|
+
if (order === 'by-depth') return [...P].sort((a, b) => a.key - b.key || a.depth - b.depth);
|
|
219
|
+
const kids = new Map<string | undefined, MotionPiece[]>();
|
|
220
|
+
for (const p of [...P].sort(back)) { const l = kids.get(p.parent) ?? []; l.push(p); kids.set(p.parent, l); }
|
|
221
|
+
const out: MotionPiece[] = [], seen = new Set<string>();
|
|
222
|
+
const add = (p: MotionPiece) => { if (seen.has(p.id)) return; const up = p.parent ? byId.get(p.parent) : undefined; if (up) add(up); seen.add(p.id); out.push(p); };
|
|
223
|
+
if (order === 'by-region') { const walk = (id?: string) => { for (const p of kids.get(id) ?? []) { add(p); walk(p.id); } }; walk(); return out; }
|
|
224
|
+
// by-flow: from the source along the connectors, breadth first; what no connector reaches comes after, back to front
|
|
225
|
+
const next = new Map<string, string[]>(), into = new Set<string>();
|
|
226
|
+
for (const r of m.routes) if (r.from && r.to) { next.set(r.from, [...(next.get(r.from) ?? []), r.to]); into.add(r.to); }
|
|
227
|
+
const start = o.source ?? m.routes.find(r => r.from && !into.has(r.from))?.from ?? m.routes[0]?.from;
|
|
228
|
+
const queue = start ? [start] : [], queued = new Set(queue);
|
|
229
|
+
while (queue.length) { const id = queue.shift()!, p = byId.get(id); if (p) add(p); for (const n of next.get(id) ?? []) if (!queued.has(n)) { queued.add(n); queue.push(n); } }
|
|
230
|
+
for (const p of [...P].sort(back)) add(p);
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const STYLE_EASE: Record<string, MotionEasing> = { edge: 'settle', drop: 'settle', rise: 'ease-out', fly: 'settle', pop: 'spring', scatter: 'settle', build: 'ease-out', fade: 'linear',
|
|
235
|
+
explode: 'ease-in', 'lift-off': 'ease-in', sink: 'ease-in', 'fly-out': 'ease-in', collapse: 'ease-in' };
|
|
236
|
+
/** the assemble style each disassemble style is, seen backwards: what a piece does is one function of how far in it is */
|
|
237
|
+
const OUT_AS: Record<string, string> = { 'lift-off': 'lift', sink: 'rise', scatter: 'scatter', 'fly-out': 'edge', fade: 'fade', explode: 'explode', collapse: 'collapse' };
|
|
238
|
+
|
|
239
|
+
/** either's options: the style is the plan's own kind's */
|
|
240
|
+
export type PlanOptions = Omit<AssembleOptions & DisassembleOptions, 'style'> & { style?: AssembleStyle | DisassembleStyle };
|
|
241
|
+
type AnyOptions = PlanOptions;
|
|
242
|
+
|
|
243
|
+
export function planOf(m: MotionModel, kind: 'assemble' | 'disassemble', opts: AnyOptions = {}): MotionPlan {
|
|
244
|
+
const seed = opts.seed ?? 1, leaving = kind === 'disassemble';
|
|
245
|
+
const reverse = leaving && opts.style === 'reverse';
|
|
246
|
+
const own = (p: MotionPiece): string => {
|
|
247
|
+
if (!leaving) return p.motion?.style ?? (opts.style as AssembleStyle | undefined) ?? 'edge';
|
|
248
|
+
const out = p.motion?.out ?? (opts.style as DisassembleStyle | undefined) ?? 'fly-out';
|
|
249
|
+
return out === 'reverse' ? p.motion?.style ?? opts.of ?? 'edge' : OUT_AS[out];
|
|
250
|
+
};
|
|
251
|
+
const named = (p: MotionPiece): string => (leaving ? p.motion?.out ?? (opts.style as string | undefined) ?? 'fly-out' : own(p));
|
|
252
|
+
// the build-time intro's own timing: the page's assemble, unless something else is asked
|
|
253
|
+
const asIntro = !leaving && !opts.order && opts.stagger === undefined && opts.piece === undefined && opts.overlap === undefined && (opts.style ?? 'edge') === 'edge';
|
|
254
|
+
const order = opts.order ?? (opts.style === 'build' ? 'by-layer' : 'by-depth');
|
|
255
|
+
const timed: Timed[] = [];
|
|
256
|
+
let routes: { id: string; delay: number; dur: number }[], labels: { delay: number; dur: number };
|
|
257
|
+
const mk = (p: MotionPiece, delay: number, dur: number): Timed => {
|
|
258
|
+
const style = own(p), e = p.motion?.easing ?? opts.easing ?? STYLE_EASE[leaving && named(p) !== 'reverse' ? named(p) : style] ?? 'ease';
|
|
259
|
+
return { p, delay: delay + (p.motion?.delay ?? 0), dur: Math.max(1, p.motion?.duration ?? dur), style, curve: CURVES[e], from: p.motion?.from ?? opts.from ?? 'left' };
|
|
260
|
+
};
|
|
261
|
+
if (asIntro) {
|
|
262
|
+
const by = new Map(m.pieces.map(p => [p.id, p]));
|
|
263
|
+
for (const a of m.intro.pieces) { const p = by.get(a.id); if (p) timed.push(mk(p, a.delay, a.dur)); }
|
|
264
|
+
routes = m.intro.routes.map(r => ({ ...r })); labels = { ...m.intro.labels };
|
|
265
|
+
} else {
|
|
266
|
+
const seq = motionOrder(m, order, { seed, source: opts.source });
|
|
267
|
+
const dur = opts.piece ?? 600, step = opts.stagger ?? Math.min(70, 900 / Math.max(1, seq.length)), over = clamp(opts.overlap ?? 0.5);
|
|
268
|
+
const list = reverse || leaving ? [...seq].reverse() : seq;
|
|
269
|
+
const rStep = Math.min(30, 300 / Math.max(1, m.routes.length)), rDur = 400, lDur = 400;
|
|
270
|
+
if (!leaving) {
|
|
271
|
+
list.forEach((p, i) => timed.push(mk(p, i * step, dur)));
|
|
272
|
+
const pEnd = Math.max(0, ...timed.map(x => x.delay + x.dur));
|
|
273
|
+
const rAt = Math.max(0, pEnd - over * dur);
|
|
274
|
+
routes = m.routes.map((r, i) => ({ id: r.id, delay: rAt + i * rStep, dur: rDur }));
|
|
275
|
+
const rEnd = Math.max(rAt, ...routes.map(r => r.delay + r.dur));
|
|
276
|
+
labels = { delay: Math.max(0, rEnd - over * lDur), dur: lDur };
|
|
277
|
+
} else {
|
|
278
|
+
// labels go first, then the connectors un-draw, then the pieces leave
|
|
279
|
+
labels = { delay: 0, dur: lDur };
|
|
280
|
+
const rAt = lDur * (1 - over);
|
|
281
|
+
routes = [...m.routes].reverse().map((r, i) => ({ id: r.id, delay: rAt + i * rStep, dur: rDur }));
|
|
282
|
+
const rEnd = Math.max(rAt, ...routes.map(r => r.delay + r.dur));
|
|
283
|
+
const pAt = Math.max(0, rEnd - over * rDur);
|
|
284
|
+
list.forEach((p, i) => timed.push(mk(p, pAt + i * step, dur)));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const pulse = opts.pulses && m.routes.length ? 700 : 0;
|
|
288
|
+
if (pulse && leaving) { for (const x of [...timed, ...routes, labels]) x.delay += pulse; }
|
|
289
|
+
let total = Math.max(1, ...timed.map(x => x.delay + x.dur), ...routes.map(r => r.delay + r.dur), labels.delay + labels.dur);
|
|
290
|
+
const pulseAt = leaving ? 0 : total;
|
|
291
|
+
if (pulse && !leaving) total += pulse;
|
|
292
|
+
// scaled to the length asked for
|
|
293
|
+
const k = opts.duration !== undefined ? Math.max(1, opts.duration) / total : 1;
|
|
294
|
+
for (const x of [...timed, ...routes, labels]) { x.delay = r2(x.delay * k); x.dur = Math.max(0.01, r2(x.dur * k)); }
|
|
295
|
+
const duration = opts.duration !== undefined ? Math.max(1, opts.duration) : Math.max(1, r2(total));
|
|
296
|
+
|
|
297
|
+
const byPiece = new Map(timed.map(x => [x.p.id, x])), byRoute = new Map(routes.map(r => [r.id, r]));
|
|
298
|
+
const [vx, vy, vw, vh] = m.viewBox, middle: [number, number] = [vx + vw / 2, vy + vh / 2];
|
|
299
|
+
const middleOf = (b: Rect): [number, number] => [b.x + b.w / 2, b.y + b.h / 2];
|
|
300
|
+
const pointOf = (p: MotionPiece, what: string): [number, number] => {
|
|
301
|
+
const pt = opts.point;
|
|
302
|
+
if (Array.isArray(pt)) return pt;
|
|
303
|
+
if (pt === 'region' || (what === 'collapse' && pt === undefined && p.parent)) { const up = m.pieces.find(x => x.id === p.parent); return up ? up.foot : middle; }
|
|
304
|
+
if (typeof pt === 'string') { const at = m.pieces.find(x => x.id === pt); if (at) return at.foot; }
|
|
305
|
+
return middle;
|
|
306
|
+
};
|
|
307
|
+
/** a piece, `e` of the way in (0: away, 1: in place; a spring may pass 1) */
|
|
308
|
+
function piece(x: Timed, e: number, f: number): ItemState {
|
|
309
|
+
const { p } = x, b = p.bbox, away = 1 - e;
|
|
310
|
+
const move = (dx: number, dy: number): ItemState => ({ dx: r2(dx * away), dy: r2(dy * away) });
|
|
311
|
+
switch (x.style) {
|
|
312
|
+
case 'drop': return move(...side(b, m.viewBox, 'top'));
|
|
313
|
+
case 'lift': return move(...side(b, m.viewBox, 'top'));
|
|
314
|
+
case 'fly': return move(...side(b, m.viewBox, x.from));
|
|
315
|
+
case 'rise': {
|
|
316
|
+
// up through its own floor: what is below its bottom outline doesn't show
|
|
317
|
+
const dy = b.h * away, [l, fr, r] = p.base, top = b.y - b.h - 4;
|
|
318
|
+
return { ...move(0, b.h), clip: [[l[0], l[1] - dy], [fr[0], fr[1] - dy], [r[0], r[1] - dy], [r[0] + 2, top - dy], [l[0] - 2, top - dy]].map(q => [r2(q[0]), r2(q[1])] as [number, number]) };
|
|
319
|
+
}
|
|
320
|
+
case 'pop': return { scale: r4(Math.max(0, e)), about: p.foot, opacity: r4(clamp(f * 4)) };
|
|
321
|
+
case 'scatter': {
|
|
322
|
+
const next = stream((seed ^ hashOf(p.id)) >>> 0), a = next() * Math.PI * 2, d = 0.35 + next() * 0.65;
|
|
323
|
+
return { ...move(Math.cos(a) * vw * d * 0.6, Math.sin(a) * vh * d * 0.6), opacity: r4(clamp(e * 1.6)) };
|
|
324
|
+
}
|
|
325
|
+
case 'build': return { ...move(0, -18), opacity: r4(clamp(e)) };
|
|
326
|
+
case 'fade': return { opacity: r4(clamp(e)) };
|
|
327
|
+
case 'explode': {
|
|
328
|
+
const c = pointOf(p, 'explode'), q = middleOf(b), dx = q[0] - c[0], dy = q[1] - c[1], l = Math.hypot(dx, dy);
|
|
329
|
+
const next = stream((seed ^ hashOf(p.id)) >>> 0), a = next() * Math.PI * 2, u = l > 1 ? [dx / l, dy / l] : [Math.cos(a), Math.sin(a)];
|
|
330
|
+
const far = Math.hypot(vw, vh) + Math.max(b.w, b.h);
|
|
331
|
+
return move(u[0] * far, u[1] * far);
|
|
332
|
+
}
|
|
333
|
+
case 'collapse': {
|
|
334
|
+
const c = pointOf(p, 'collapse');
|
|
335
|
+
return { ...move(c[0] - p.foot[0], c[1] - p.foot[1]), scale: r4(Math.max(0, e)), about: p.foot, opacity: r4(clamp(e * 3)) };
|
|
336
|
+
}
|
|
337
|
+
default: { const o = offscreen(b, m.viewBox); return move(o.dx, o.dy); }
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/** how far in something is at t (0 to 1): an arrival's share done, a leaving's share left */
|
|
341
|
+
const share = (t: number, delay: number, dur: number) => { const f = clamp((t - delay) / dur); return leaving ? 1 - f : f; };
|
|
342
|
+
const HIDDEN = { opacity: 0 };
|
|
343
|
+
const connectors = opts.connectors ?? 'draw', labelling = opts.labels ?? 'fade';
|
|
344
|
+
const labelled = [...m.pieces.map(p => p.id), ...m.routes.map(r => r.id), ...Object.keys(m.notes)];
|
|
345
|
+
function at(t0: number): SceneState {
|
|
346
|
+
const t = Math.max(0, Math.min(duration, Number.isFinite(t0) ? t0 : 0));
|
|
347
|
+
if (leaving ? t <= 0 : t >= duration) return {};
|
|
348
|
+
const empty = leaving ? t >= duration : t <= 0;
|
|
349
|
+
const items: Record<string, ItemState> = {}, routeStates: Record<string, RouteState> = {}, labelStates: Record<string, LabelState> = {};
|
|
350
|
+
for (const x of timed) {
|
|
351
|
+
const f = empty ? 0 : share(t, x.delay, x.dur);
|
|
352
|
+
if (f <= 0) items[x.p.id] = HIDDEN;
|
|
353
|
+
else if (f < 1) items[x.p.id] = piece(x, leaving ? 1 - x.curve(1 - f) : x.curve(f), f);
|
|
354
|
+
}
|
|
355
|
+
for (const r of m.routes) {
|
|
356
|
+
const w = byRoute.get(r.id), f = empty || !w ? 0 : share(t, w.delay, w.dur);
|
|
357
|
+
if (f <= 0) routeStates[r.id] = { opacity: 0, drawn: 0 };
|
|
358
|
+
else if (f < 1) routeStates[r.id] = connectors === 'fade' ? { opacity: r4(f) } : connectors === 'grow' ? { drawn: r4(f), by: 'grow' } : { drawn: r4(CURVES['ease-out'](f)) };
|
|
359
|
+
}
|
|
360
|
+
const lf = empty ? 0 : share(t, labels.delay, labels.dur);
|
|
361
|
+
const all: LabelState | undefined = lf <= 0 ? HIDDEN : lf >= 1 ? undefined : labelling === 'type' ? { typed: r4(lf) } : { opacity: r4(lf) };
|
|
362
|
+
for (const id of labelled) {
|
|
363
|
+
let c = all;
|
|
364
|
+
if (labelling === 'with-piece') {
|
|
365
|
+
const on = Object.hasOwn(m.notes, id) ? m.notes[id] : id, w = on === undefined ? undefined : byPiece.get(on) ?? byRoute.get(on);
|
|
366
|
+
if (w) { const f = empty ? 0 : share(t, w.delay, w.dur); c = f <= 0 ? HIDDEN : f >= 1 ? undefined : { opacity: r4(f) }; }
|
|
367
|
+
}
|
|
368
|
+
if (c) labelStates[id] = c;
|
|
369
|
+
}
|
|
370
|
+
const tokens: { route: string; at: number }[] = [];
|
|
371
|
+
if (pulse && !empty) {
|
|
372
|
+
const f = (t - pulseAt * k) / (pulse * k);
|
|
373
|
+
if (f > 0 && f < 1) for (const r of m.routes) tokens.push({ route: r.id, at: r4(CURVES.ease(f)) });
|
|
374
|
+
}
|
|
375
|
+
const some = (o: object) => Object.keys(o).length > 0;
|
|
376
|
+
return {
|
|
377
|
+
...(some(items) ? { items } : {}), ...(some(labelStates) ? { labels: labelStates } : {}), ...(some(routeStates) ? { routes: routeStates } : {}),
|
|
378
|
+
...(lf < 1 ? { marks: { opacity: r4(Math.max(0, lf)) } } : {}), ...(tokens.length ? { tokens } : {}),
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
return { kind, duration, pieces: timed.map(x => ({ id: x.p.id, delay: x.delay, dur: x.dur, style: named(x.p) })), routes, labels, at };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
const n2 = (v: number) => { const s = v.toFixed(2); return s === '-0.00' ? '0' : String(Number(s)); };
|
|
385
|
+
const scaleAt = (c: [number, number], s: number) => `translate(${n2(c[0])} ${n2(c[1])}) scale(${Number(s.toFixed(4))}) translate(${n2(-c[0])} ${n2(-c[1])})`;
|
|
386
|
+
|
|
387
|
+
// ---------- connectors: their paths are polylines in the drawing's units ----------
|
|
388
|
+
|
|
389
|
+
const pointsOf = (d: string) => [...d.matchAll(/(-?[\d.]+),(-?[\d.]+)/g)].map(m => [Number(m[1]), Number(m[2])] as [number, number]);
|
|
390
|
+
const lengthOf = (pts: [number, number][]) => pts.slice(1).reduce((n, p, i) => n + Math.hypot(p[0] - pts[i][0], p[1] - pts[i][1]), 0);
|
|
391
|
+
/** a point a fraction of the way along an SVG polyline path ("M x,y L x,y …") */
|
|
392
|
+
export function alongPath(d: string, f: number): [number, number] {
|
|
393
|
+
const pts = pointsOf(d);
|
|
394
|
+
let left = lengthOf(pts) * f;
|
|
395
|
+
for (let i = 0; i + 1 < pts.length; i++) {
|
|
396
|
+
const seg = Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]);
|
|
397
|
+
if (left <= seg && seg > 0) { const t = left / seg; return [pts[i][0] + (pts[i + 1][0] - pts[i][0]) * t, pts[i][1] + (pts[i + 1][1] - pts[i][1]) * t]; }
|
|
398
|
+
left -= seg;
|
|
399
|
+
}
|
|
400
|
+
return pts[pts.length - 1] ?? [0, 0];
|
|
401
|
+
}
|
|
402
|
+
/** the first part of a path: it grows from its source, its arrowhead at the tip */
|
|
403
|
+
function partOf(d: string, f: number): string {
|
|
404
|
+
const pts = pointsOf(d), end = alongPath(d, f), out: [number, number][] = [];
|
|
405
|
+
let left = lengthOf(pts) * f;
|
|
406
|
+
for (let i = 0; i < pts.length; i++) {
|
|
407
|
+
out.push(pts[i]);
|
|
408
|
+
const seg = i + 1 < pts.length ? Math.hypot(pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]) : Infinity;
|
|
409
|
+
if (left <= seg) break;
|
|
410
|
+
left -= seg;
|
|
411
|
+
}
|
|
412
|
+
return 'M' + [...out, end].map(q => `${n2(q[0])},${n2(q[1])}`).join(' L');
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// ---------- drawing a state: into the still's text, or onto its elements ----------
|
|
416
|
+
|
|
417
|
+
const num = (v: number) => String(Number(v.toFixed(4)));
|
|
418
|
+
/** the start of a text run: an entity counts as one character */
|
|
419
|
+
export function typed(s: string, f: number): string {
|
|
420
|
+
const ch = s.match(/&[^;\s]+;|[\s\S]/gu) ?? [];
|
|
421
|
+
return ch.slice(0, Math.round(ch.length * f)).join('');
|
|
422
|
+
}
|
|
423
|
+
/** what a wrapper's state is: its attributes, and what is inside it (a connector's path, a label's text) */
|
|
424
|
+
interface Drawn { attrs: Record<string, string>; clip?: [number, number][]; path?: { d?: string; style?: string; head: boolean }; typed?: number }
|
|
425
|
+
function drawnItem(i: ItemState): Drawn {
|
|
426
|
+
const t: string[] = [];
|
|
427
|
+
if (i.dx || i.dy) t.push(`translate(${n2(i.dx ?? 0)} ${n2(i.dy ?? 0)})`);
|
|
428
|
+
if (i.scale !== undefined && i.scale !== 1) t.push(scaleAt(i.about ?? [0, 0], i.scale));
|
|
429
|
+
return { attrs: { ...(i.opacity === undefined || i.opacity === 1 ? {} : { opacity: num(i.opacity) }), ...(t.length ? { transform: t.join(' ') } : {}) }, clip: i.clip };
|
|
430
|
+
}
|
|
431
|
+
function drawnRoute(r: RouteState, d: string | undefined): Drawn {
|
|
432
|
+
const out: Drawn = { attrs: r.opacity === undefined || r.opacity === 1 ? {} : { opacity: num(r.opacity) } };
|
|
433
|
+
if (r.drawn !== undefined && r.drawn < 1 && d !== undefined) {
|
|
434
|
+
const f = clamp(r.drawn), len = lengthOf(pointsOf(d));
|
|
435
|
+
out.path = r.by === 'grow' ? { d: partOf(d, f), head: false } : { style: `stroke-dasharray:${n2(len)} ${n2(len)};stroke-dashoffset:${n2(len * (1 - f))}`, head: false };
|
|
436
|
+
} else if (r.ants) out.path = { style: `stroke-dasharray:${n2(r.ants.dash[0])} ${n2(r.ants.dash[1])};stroke-dashoffset:${n2(-r.ants.offset)}`, head: true };
|
|
437
|
+
return out;
|
|
438
|
+
}
|
|
439
|
+
/** the state of one wrapper, by its id and part (undefined: as in the still) */
|
|
440
|
+
function wrapperState(S: SceneState, what: 'item' | 'route', id: string, part: string, pathOf: (id: string) => string | undefined): Drawn | undefined {
|
|
441
|
+
if (part === 'label' || part === 'note') {
|
|
442
|
+
const l = S.labels && Object.hasOwn(S.labels, id) ? S.labels[id] : undefined;
|
|
443
|
+
return l && { attrs: { ...(l.opacity === undefined || l.opacity === 1 ? {} : { opacity: num(l.opacity) }), ...(l.dx || l.dy ? { transform: `translate(${n2(l.dx ?? 0)} ${n2(l.dy ?? 0)})` } : {}) }, ...(l.typed === undefined || l.typed >= 1 ? {} : { typed: l.typed }) };
|
|
444
|
+
}
|
|
445
|
+
if (what === 'route') { const r = S.routes && Object.hasOwn(S.routes, id) ? S.routes[id] : undefined; return r && drawnRoute(r, pathOf(id)); }
|
|
446
|
+
const i = S.items && Object.hasOwn(S.items, id) ? S.items[id] : undefined;
|
|
447
|
+
return i && drawnItem(i);
|
|
448
|
+
}
|
|
449
|
+
/** what a state adds to the overlay's layer: rings and tokens, as [name, attributes] */
|
|
450
|
+
function overlay(S: SceneState, pathOf: (id: string) => string | undefined, inks?: { surface: string; control: string; kinds?: Record<string, string> }): [string, Record<string, string>][] {
|
|
451
|
+
const out: [string, Record<string, string>][] = [];
|
|
452
|
+
for (const o of S.outlines ?? []) out.push(['polygon', { points: o.points.map(q => q.map(n2).join(',')).join(' '), class: 'ring', fill: 'none', 'stroke-width': '2.5', 'stroke-linejoin': 'round', ...(o.opacity === undefined ? {} : { opacity: num(o.opacity) }), ...(inks ? { stroke: o.color ?? inks.control } : { style: `stroke:${o.color ?? 'var(--ring,var(--control,currentColor))'}` }) }]);
|
|
453
|
+
for (const p of S.pulses ?? []) out.push(['ellipse', { cx: n2(p.x), cy: n2(p.y), rx: n2(p.rx), ry: n2(p.ry), class: 'ring', fill: 'none', 'stroke-width': '2.5', ...(p.opacity === undefined ? {} : { opacity: num(p.opacity) }), ...(inks ? { stroke: p.color ?? inks.control } : { style: `stroke:${p.color ?? 'currentColor'}` }) }]);
|
|
454
|
+
for (const k of S.tokens ?? []) { const d = pathOf(k.route); if (d === undefined) continue; const [x, y] = alongPath(d, clamp(k.at)); out.push(['circle', { cx: n2(x), cy: n2(y), r: '7', class: 'tok', ...(inks ? { fill: k.color ?? (k.kind !== undefined ? inks.kinds?.[k.kind] : undefined) ?? inks.control, stroke: inks.surface, 'stroke-width': '2.5' } : { style: `fill:${k.color ?? (k.kind !== undefined ? `var(--${k.kind},var(--control,currentColor))` : 'var(--control,currentColor)')}` }) }]); }
|
|
455
|
+
return out;
|
|
456
|
+
}
|
|
457
|
+
const isStill = (S: SceneState) => Object.keys(S).every(k => k === 'morph' || S[k as keyof SceneState] === undefined);
|
|
458
|
+
const MARK_LAYERS = new Set(['marks', 'badges']);
|
|
459
|
+
const attrText = (v: string) => v.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
|
|
460
|
+
|
|
461
|
+
/** the insides of a drawing's thing wrappers, by id and part: [where the inside starts, where it ends] */
|
|
462
|
+
function insides(svg: string): Map<string, [number, number]> {
|
|
463
|
+
const out = new Map<string, [number, number]>(), open: { key?: string; from: number }[] = [];
|
|
464
|
+
for (const m of svg.matchAll(/<(\/?)([a-zA-Z]+)((?:\s+[\w:-]+="[^"]*")*)\s*(\/?)>/g)) {
|
|
465
|
+
if (m[1]) { const o = open.pop(); if (o?.key !== undefined) out.set(o.key, [o.from, m.index]); continue; }
|
|
466
|
+
if (m[4]) continue;
|
|
467
|
+
const id = /\sdata-item="([^"]*)"/.exec(m[3])?.[1], part = /\sdata-part="([^"]*)"/.exec(m[3])?.[1];
|
|
468
|
+
open.push({ ...(open.length === 2 && id !== undefined && part !== undefined ? { key: `${unescape(id)}\n${part}` } : {}), from: m.index + m[0].length });
|
|
469
|
+
}
|
|
470
|
+
return out;
|
|
471
|
+
}
|
|
472
|
+
type Looks = Pick<CompiledScene['rendered'], 'svg' | 'variants' | 'looks'>;
|
|
473
|
+
const lookCache = new WeakMap<object, Map<string, Map<string, string>>>();
|
|
474
|
+
/** a look's parts of a thing: id and part → what is inside, where it isn't as in the still */
|
|
475
|
+
function lookParts(r: Looks, name: string): Map<string, string> {
|
|
476
|
+
const all = lookCache.get(r) ?? new Map<string, Map<string, string>>(); lookCache.set(r, all);
|
|
477
|
+
let parts = all.get(name);
|
|
478
|
+
if (!parts) {
|
|
479
|
+
all.set(name, (parts = new Map()));
|
|
480
|
+
const v = r.variants?.[name], own = insides(r.svg);
|
|
481
|
+
if (v !== undefined) for (const [key, [a, b]] of insides(v)) { const o = own.get(key); if (o && r.looks?.[key.split('\n')[0]]?.includes(name) && r.svg.slice(...o) !== v.slice(a, b)) parts.set(key, v.slice(a, b)); }
|
|
482
|
+
}
|
|
483
|
+
return parts;
|
|
484
|
+
}
|
|
485
|
+
/** what a thing's part is made of now: its own (how much), and each look's, in the order the thing declares them */
|
|
486
|
+
function mixOf(r: Looks, id: string, part: string, want: Record<string, number>): { own: number; looks: [string, number][] } | undefined {
|
|
487
|
+
const looks: [string, number][] = [];
|
|
488
|
+
for (const name of r.looks?.[id] ?? []) { const a = clamp(want[name] ?? 0), inside = a > 0 ? lookParts(r, name).get(`${id}\n${part}`) : undefined; if (inside !== undefined) looks.push([inside, a]); }
|
|
489
|
+
return looks.length ? { own: clamp(1 - looks.reduce((n, [, a]) => n + a, 0)), looks } : undefined;
|
|
490
|
+
}
|
|
491
|
+
const layers = (own: string, m: { own: number; looks: [string, number][] }) => (m.own > 0 ? `<g opacity="${num(m.own)}">${own}</g>` : '') + m.looks.map(([x, a]) => `<g opacity="${num(a)}">${x}</g>`).join('');
|
|
492
|
+
function withLooks(r: Looks, want: Record<string, Record<string, number>>): string {
|
|
493
|
+
let out = '', at = 0;
|
|
494
|
+
for (const [key, [a, b]] of [...insides(r.svg)].sort((x, y) => x[1][0] - y[1][0])) {
|
|
495
|
+
const [id, part] = key.split('\n'), m = Object.hasOwn(want, id) ? mixOf(r, id, part, want[id]) : undefined;
|
|
496
|
+
if (!m) continue;
|
|
497
|
+
out += r.svg.slice(at, a) + layers(r.svg.slice(a, b), m); at = b;
|
|
498
|
+
}
|
|
499
|
+
return out + r.svg.slice(at);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** A scene as it looks in a state, as SVG text. An empty state is the still render itself, byte for byte. */
|
|
503
|
+
export function svgAt(scene: Pick<CompiledScene, 'rendered' | 'id'>, S: SceneState): string {
|
|
504
|
+
if (isStill(S)) return scene.rendered.svg;
|
|
505
|
+
const svg = S.variants ? withLooks(scene.rendered, S.variants) : scene.rendered.svg;
|
|
506
|
+
const pathOf = (id: string) => (Object.hasOwn(scene.rendered.paths, id) ? scene.rendered.paths[id] : undefined);
|
|
507
|
+
let depth = 0, layer = '', clips = '', nClips = 0;
|
|
508
|
+
let inside: { at: number; w: Drawn } | undefined;
|
|
509
|
+
let out = svg.replace(/<(\/?)([a-zA-Z]+)((?:\s+[\w:-]+="[^"]*")*)\s*(\/?)>|([^<]+)/g, (m, close: string, name: string | undefined, attrs: string, self: string, text: string | undefined) => {
|
|
510
|
+
if (text !== undefined) return inside?.w.typed === undefined ? m : typed(text, inside.w.typed);
|
|
511
|
+
if (close) { depth--; if (inside && depth === inside.at) inside = undefined; if (depth === 1) layer = ''; return m; }
|
|
512
|
+
const at = depth;
|
|
513
|
+
if (!self) depth++;
|
|
514
|
+
const a: Record<string, string> = {};
|
|
515
|
+
for (const [, k, v] of attrs.matchAll(/([\w:-]+)="([^"]*)"/g)) a[k] = v;
|
|
516
|
+
if (at === 0) { if (!S.camera) return m; a.viewBox = S.camera.map(n2).join(' '); } else if (at === 1) {
|
|
517
|
+
layer = name === 'g' && a.class?.startsWith('g-') ? a.class.slice(2) : '';
|
|
518
|
+
if (MARK_LAYERS.has(layer) && S.marks && S.marks.opacity !== 1) a.opacity = num(S.marks.opacity); else return m;
|
|
519
|
+
} else if (at === 2 && a['data-part'] !== undefined) {
|
|
520
|
+
const what = a['data-route'] === undefined ? 'item' : 'route', id = unescape(a['data-route'] ?? a['data-item'] ?? '');
|
|
521
|
+
const w = wrapperState(S, what, id, a['data-part'], pathOf);
|
|
522
|
+
if (!w) return m;
|
|
523
|
+
for (const [k, v] of Object.entries(w.attrs)) a[k] = attrText(v);
|
|
524
|
+
if (w.clip) { const c = `${scene.id}-mc${nClips++}`; clips += `<clipPath id="${c}"><polygon points="${w.clip.map(q => q.join(',')).join(' ')}"/></clipPath>`; a['clip-path'] = `url(#${c})`; }
|
|
525
|
+
if (!self && (w.path || w.typed !== undefined)) inside = { at, w };
|
|
526
|
+
if (!Object.keys(w.attrs).length && !w.clip) return m;
|
|
527
|
+
} else if (inside?.w.path && name === 'path' && a.class?.split(' ')[0] === 'flow') {
|
|
528
|
+
const p = inside.w.path;
|
|
529
|
+
if (p.d !== undefined) a.d = p.d;
|
|
530
|
+
if (p.style !== undefined) a.style = p.style;
|
|
531
|
+
if (!p.head) delete a['marker-end'];
|
|
532
|
+
} else return m;
|
|
533
|
+
return `<${name}${Object.entries(a).map(([k, v]) => ` ${k}="${v}"`).join('')}${self ? '/' : ''}>`;
|
|
534
|
+
});
|
|
535
|
+
if (clips) out = out.replace(/<defs>|<defs\/>/, d => (d === '<defs/>' ? `<defs>${clips}</defs>` : d + clips));
|
|
536
|
+
const over = overlay(S, pathOf, scene.rendered.inks);
|
|
537
|
+
if (over.length) out = out.replace('<g class="g-anim">', g => g + over.map(([n, at]) => `<${n}${Object.entries(at).map(([k, v]) => ` ${k}="${attrText(v)}"`).join('')}/>`).join(''));
|
|
538
|
+
return out;
|
|
539
|
+
}
|
|
540
|
+
const unescape = (s: string) => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&/g, '&');
|
|
541
|
+
|
|
542
|
+
type Kept = { attrs: Map<Element, Map<string, string | null>>; texts: Map<Text, string>; gone: [Text, Node, Node | null][]; made: Element[]; mixed: [Element, Node[]][] };
|
|
543
|
+
const keptOf = new WeakMap<Element, Kept>();
|
|
544
|
+
/** The same on a live drawing (a scene's own <svg>). Idempotent, in any order: what the last state changed is put back
|
|
545
|
+
* first, so the same state gives the same DOM; an empty state gives the still back. */
|
|
546
|
+
export function paint(svg: SVGSVGElement, S: SceneState, rendered?: Looks): void {
|
|
547
|
+
const was = keptOf.get(svg);
|
|
548
|
+
if (was) {
|
|
549
|
+
for (const [el, kids] of was.mixed) el.replaceChildren(...kids);
|
|
550
|
+
for (const [el, attrs] of was.attrs) for (const [k, v] of attrs) { if (v === null) el.removeAttribute(k); else el.setAttribute(k, v); }
|
|
551
|
+
for (const [n, up, next] of was.gone.reverse()) up.insertBefore(n, next);
|
|
552
|
+
for (const [n, t] of was.texts) n.data = t;
|
|
553
|
+
for (const e of was.made) e.remove();
|
|
554
|
+
keptOf.delete(svg);
|
|
555
|
+
}
|
|
556
|
+
if (isStill(S)) return;
|
|
557
|
+
const kept: Kept = { attrs: new Map(), texts: new Map(), gone: [], made: [], mixed: [] };
|
|
558
|
+
keptOf.set(svg, kept);
|
|
559
|
+
const set = (el: Element, k: string, v: string | null) => {
|
|
560
|
+
const m = kept.attrs.get(el) ?? new Map<string, string | null>();
|
|
561
|
+
if (!m.has(k)) m.set(k, el.getAttribute(k));
|
|
562
|
+
kept.attrs.set(el, m);
|
|
563
|
+
if (v === null) el.removeAttribute(k); else el.setAttribute(k, v);
|
|
564
|
+
};
|
|
565
|
+
const doc = svg.ownerDocument;
|
|
566
|
+
const make = (name: string, attrs: Record<string, string>, into: Element) => { const e = doc.createElementNS('http://www.w3.org/2000/svg', name); for (const [k, v] of Object.entries(attrs)) e.setAttribute(k, v); into.append(e); kept.made.push(e); return e; };
|
|
567
|
+
const layers = Array.from(svg.children), layer = (name: string) => layers.find(g => g.getAttribute('class') === `g-${name}`);
|
|
568
|
+
const paths = new Map<string, string>();
|
|
569
|
+
for (const w of Array.from(layer('flows')?.children ?? [])) { const id = w.getAttribute('data-route'), d = w.querySelector('path.flow')?.getAttribute('d'); if (id !== null && d) paths.set(id, d); }
|
|
570
|
+
const pathOf = (id: string) => paths.get(id);
|
|
571
|
+
if (S.camera) set(svg, 'viewBox', S.camera.map(n2).join(' '));
|
|
572
|
+
for (const name of MARK_LAYERS) { const g = layer(name); if (g && S.marks && S.marks.opacity !== 1) set(g, 'opacity', num(S.marks.opacity)); }
|
|
573
|
+
let nClips = 0;
|
|
574
|
+
const defs = layers.find(e => e.localName === 'defs'), first = defs?.firstChild ?? null, id0 = svg.getAttribute('data-scene') ?? 'scene';
|
|
575
|
+
for (const g of layers) for (const el of Array.from(g.children)) {
|
|
576
|
+
const part = el.getAttribute('data-part');
|
|
577
|
+
if (part === null) continue;
|
|
578
|
+
const rid = el.getAttribute('data-route');
|
|
579
|
+
// its looks (the scene's `rendered` has them): the thing's own inside a layer, and each look's over it
|
|
580
|
+
const iid = rid === null ? el.getAttribute('data-item') ?? '' : '', mix = rendered && S.variants && Object.hasOwn(S.variants, iid) ? mixOf(rendered, iid, part, S.variants[iid]) : undefined;
|
|
581
|
+
if (mix) {
|
|
582
|
+
const own = Array.from(el.childNodes), put = (a: number, kids: Node[]) => { const g = doc.createElementNS('http://www.w3.org/2000/svg', 'g'); g.setAttribute('opacity', num(a)); g.append(...kids); return g; };
|
|
583
|
+
const inside = (text: string) => Array.from(doc.importNode(new DOMParser().parseFromString(`<svg xmlns="http://www.w3.org/2000/svg">${text}</svg>`, 'image/svg+xml').documentElement, true).childNodes);
|
|
584
|
+
kept.mixed.push([el, own]);
|
|
585
|
+
el.replaceChildren(...(mix.own > 0 ? [put(mix.own, own)] : []), ...mix.looks.map(([x, a]) => put(a, inside(x))));
|
|
586
|
+
}
|
|
587
|
+
const w = wrapperState(S, rid === null ? 'item' : 'route', rid ?? el.getAttribute('data-item') ?? '', part, pathOf);
|
|
588
|
+
if (!w) continue;
|
|
589
|
+
for (const [k, v] of Object.entries(w.attrs)) set(el, k, v);
|
|
590
|
+
if (w.clip && defs) { const c = make('clipPath', { id: `${id0}-mc${nClips++}` }, defs); defs.insertBefore(c, first); const p = doc.createElementNS('http://www.w3.org/2000/svg', 'polygon'); p.setAttribute('points', w.clip.map(q => q.join(',')).join(' ')); c.append(p); set(el, 'clip-path', `url(#${c.id})`); }
|
|
591
|
+
if (w.typed !== undefined) {
|
|
592
|
+
const runs: Text[] = [];
|
|
593
|
+
for (const tw = doc.createTreeWalker(el, 4); tw.nextNode();) runs.push(tw.currentNode as Text);
|
|
594
|
+
for (const n of runs) {
|
|
595
|
+
kept.texts.set(n, n.data); n.data = Array.from(n.data).slice(0, Math.round(Array.from(n.data).length * w.typed)).join('');
|
|
596
|
+
// no letter yet: no text at all, as svgAt writes it
|
|
597
|
+
if (!n.data) { kept.gone.push([n, n.parentNode!, n.nextSibling]); n.remove(); }
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
const path = w.path && el.querySelector('path.flow');
|
|
601
|
+
if (path && w.path) { if (w.path.d !== undefined) set(path, 'd', w.path.d); if (w.path.style !== undefined) set(path, 'style', w.path.style); if (!w.path.head) set(path, 'marker-end', null); }
|
|
602
|
+
}
|
|
603
|
+
const anim = layer('anim');
|
|
604
|
+
if (anim) for (const [n, at] of overlay(S, pathOf)) make(n, at, anim);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// ---------- a compiled scene's plans ----------
|
|
608
|
+
|
|
609
|
+
const ofScene = (s: CompiledScene, p: MotionPlan): ScenePlan => ({ ...p, frame: t => svgAt(s, p.at(t)) });
|
|
610
|
+
/** the drawing arrives: frame(0) is empty, frame(duration) is the still render */
|
|
611
|
+
export const assemble = (s: CompiledScene, o: AssembleOptions = {}): ScenePlan => ofScene(s, planOf(motionModel(s), 'assemble', o));
|
|
612
|
+
/** the drawing leaves: frame(0) is the still render, frame(duration) is empty */
|
|
613
|
+
export const disassemble = (s: CompiledScene, o: DisassembleOptions = {}): ScenePlan => ofScene(s, planOf(motionModel(s), 'disassemble', o));
|
|
614
|
+
|
|
615
|
+
/** A frame of the page's intro (the default assemble) at t ms, as SVG text. */
|
|
616
|
+
export const introSvg = (s: CompiledScene, t: number): string => assemble(s).frame(t);
|