@senad-d/drawme 0.1.6 → 0.1.9
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/CHANGELOG.md +45 -1
- package/README.md +34 -18
- package/assets/references/diagram-types.md +1 -1
- package/assets/references/style-presets.md +94 -0
- package/assets/references/xml-authoring.md +101 -8
- package/docs/reference.md +96 -12
- package/example/README.md +37 -0
- package/example/drawme-architecture.drawio +62 -0
- package/example/drawme-how-it-works.drawio +79 -122
- package/example/drawme-installation-guide.drawio +63 -97
- package/example/drawme-validation-decision-tree.drawio +79 -73
- package/example/event-driven-orders.drawio +119 -0
- package/example/git-graph-example.drawio +77 -69
- package/package.json +7 -7
- package/src/animate.ts +177 -0
- package/src/animation.ts +637 -0
- package/src/drawio.ts +130 -34
- package/src/fitcanvas.ts +1 -1
- package/src/geometry.ts +30 -14
- package/src/index.ts +120 -17
- package/src/motion.ts +839 -0
- package/src/storyboard.ts +161 -0
- package/src/svgexport.ts +124 -0
- package/src/validate.ts +448 -6
- package/src/workflow.ts +8 -5
- package/example/drawme-extension-waterfall-overview.drawio +0 -72
package/src/motion.ts
ADDED
|
@@ -0,0 +1,839 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DrawMe motion: a typed animation spec stored on a page's root cell and
|
|
3
|
+
* compiled into standalone SVG CSS keyframes plus SMIL connector dots. It covers
|
|
4
|
+
* effects draw.io's native page sequence cannot export portably: connector
|
|
5
|
+
* draw-in, pop and slide entrances, glow highlights, staggered cascades, and
|
|
6
|
+
* dots travelling along connectors. The same timeline yields storyboard frames
|
|
7
|
+
* so the motion can be reviewed as static images.
|
|
8
|
+
*/
|
|
9
|
+
import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
|
|
10
|
+
import { type DomEl, attr, childrenByTag, elemChildren, firstByTag } from "./dom";
|
|
11
|
+
import { collectCellsWithIds } from "./geometry";
|
|
12
|
+
|
|
13
|
+
/** Attribute on the page root cell (`id="0"`) that stores the motion spec as JSON. */
|
|
14
|
+
export const MOTION_ATTRIBUTE = "drawmeMotion";
|
|
15
|
+
|
|
16
|
+
export const MOTION_EFFECTS = [
|
|
17
|
+
"fadeIn",
|
|
18
|
+
"fadeOut",
|
|
19
|
+
"dim",
|
|
20
|
+
"popIn",
|
|
21
|
+
"slideIn",
|
|
22
|
+
"drawIn",
|
|
23
|
+
"highlight",
|
|
24
|
+
"travel",
|
|
25
|
+
"wait",
|
|
26
|
+
] as const;
|
|
27
|
+
export type MotionEffect = (typeof MOTION_EFFECTS)[number];
|
|
28
|
+
|
|
29
|
+
export const SLIDE_DIRECTIONS = ["up", "down", "left", "right"] as const;
|
|
30
|
+
export type SlideDirection = (typeof SLIDE_DIRECTIONS)[number];
|
|
31
|
+
|
|
32
|
+
export interface MotionStep {
|
|
33
|
+
effect: MotionEffect;
|
|
34
|
+
/** Vertex or edge ids. Not used by `wait`. */
|
|
35
|
+
cells?: string[];
|
|
36
|
+
/** Effect duration in ms; required for `wait`. */
|
|
37
|
+
duration?: number;
|
|
38
|
+
/** Extra start offset in ms between consecutive cells of this step (cascade). */
|
|
39
|
+
stagger?: number;
|
|
40
|
+
/** Start together with the previous step instead of after it. */
|
|
41
|
+
parallel?: boolean;
|
|
42
|
+
/** `slideIn` travel direction (default `up`). */
|
|
43
|
+
direction?: SlideDirection;
|
|
44
|
+
/** Hex color for `highlight` glow and `travel` dots. */
|
|
45
|
+
color?: string;
|
|
46
|
+
/** Target opacity for `dim` (default 0.25). */
|
|
47
|
+
value?: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface MotionSpec {
|
|
51
|
+
/** Repeat the sequence (default true). */
|
|
52
|
+
loop?: boolean;
|
|
53
|
+
/** Pause in ms on the final state before a loop restarts (default 1600). */
|
|
54
|
+
hold?: number;
|
|
55
|
+
steps: MotionStep[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const DEFAULT_DURATION: Record<Exclude<MotionEffect, "wait">, number> = {
|
|
59
|
+
fadeIn: 600,
|
|
60
|
+
fadeOut: 500,
|
|
61
|
+
dim: 500,
|
|
62
|
+
popIn: 550,
|
|
63
|
+
slideIn: 650,
|
|
64
|
+
drawIn: 900,
|
|
65
|
+
highlight: 1000,
|
|
66
|
+
travel: 1400,
|
|
67
|
+
};
|
|
68
|
+
const ENTRANCES = new Set<MotionEffect>(["fadeIn", "popIn", "slideIn", "drawIn"]);
|
|
69
|
+
const EDGE_ONLY = new Set<MotionEffect>(["drawIn", "travel"]);
|
|
70
|
+
export const DEFAULT_HOLD_MS = 1600;
|
|
71
|
+
export const DEFAULT_ACCENT = "#2563eb";
|
|
72
|
+
/** Accent for highlight and travel on a dark page (the Dark preset's accent). */
|
|
73
|
+
export const DEFAULT_DARK_ACCENT = "#60a5fa";
|
|
74
|
+
const DEFAULT_DIM = 0.25;
|
|
75
|
+
const SLIDE_DISTANCE = 32;
|
|
76
|
+
const MAX_STEPS = 200;
|
|
77
|
+
const MAX_DURATION_MS = 60_000;
|
|
78
|
+
const MAX_TOTAL_MS = 300_000;
|
|
79
|
+
const EPSILON_MS = 0.05;
|
|
80
|
+
const COLOR = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
|
81
|
+
const EASE = {
|
|
82
|
+
out: "cubic-bezier(0.22, 1, 0.36, 1)",
|
|
83
|
+
in: "cubic-bezier(0.55, 0, 1, 0.45)",
|
|
84
|
+
inOut: "cubic-bezier(0.65, 0, 0.35, 1)",
|
|
85
|
+
back: "cubic-bezier(0.34, 1.56, 0.64, 1)",
|
|
86
|
+
};
|
|
87
|
+
const IDENTITY = transformValue(0, 0, 1);
|
|
88
|
+
const NO_GLOW = "drop-shadow(0px 0px 0px rgba(0, 0, 0, 0))";
|
|
89
|
+
const SVG_NS = "http://www.w3.org/2000/svg";
|
|
90
|
+
|
|
91
|
+
type XmlDocument = ReturnType<DOMParser["parseFromString"]>;
|
|
92
|
+
|
|
93
|
+
type JsonObject = Record<string, unknown>;
|
|
94
|
+
type Value = number | string;
|
|
95
|
+
|
|
96
|
+
interface KeyPoint {
|
|
97
|
+
t: number;
|
|
98
|
+
v: Value;
|
|
99
|
+
ease?: string;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Facts about the page's cells that motion validation needs. */
|
|
103
|
+
export interface MotionCell {
|
|
104
|
+
kind: "vertex" | "edge";
|
|
105
|
+
style: string;
|
|
106
|
+
parent: string | null;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface MotionDot {
|
|
110
|
+
cellId: string;
|
|
111
|
+
start: number;
|
|
112
|
+
duration: number;
|
|
113
|
+
color: string;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** End state of one sequential batch, for storyboard rendering. */
|
|
117
|
+
export interface MotionFrame {
|
|
118
|
+
time: number;
|
|
119
|
+
label: string;
|
|
120
|
+
/** Opacity of every cell the timeline touches (untouched cells are fully visible). */
|
|
121
|
+
opacity: Map<string, number>;
|
|
122
|
+
/** Cells emphasized during this batch (highlight or travel) and their accent color. */
|
|
123
|
+
accent: Map<string, string>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface CompiledMotion {
|
|
127
|
+
loop: boolean;
|
|
128
|
+
/** Length of the step sequence, without the loop hold. */
|
|
129
|
+
sequenceMs: number;
|
|
130
|
+
/** Length of one animation iteration (sequence plus hold when looping). */
|
|
131
|
+
durationMs: number;
|
|
132
|
+
css: string;
|
|
133
|
+
dots: MotionDot[];
|
|
134
|
+
/** Cells whose SVG group must exist. */
|
|
135
|
+
targetCellIds: string[];
|
|
136
|
+
/** Edges whose line path is drawn in. */
|
|
137
|
+
drawInEdgeIds: string[];
|
|
138
|
+
frames: MotionFrame[];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export interface MotionAnalysis {
|
|
142
|
+
spec: MotionSpec | null;
|
|
143
|
+
compiled: CompiledMotion | null;
|
|
144
|
+
errors: string[];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function isObject(value: unknown): value is JsonObject {
|
|
148
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function finite(value: unknown): number | null {
|
|
152
|
+
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function styleValue(style: string, key: string): string | undefined {
|
|
156
|
+
for (const item of style.split(";")) {
|
|
157
|
+
const separator = item.indexOf("=");
|
|
158
|
+
if (separator > 0 && item.slice(0, separator).trim() === key) return item.slice(separator + 1).trim();
|
|
159
|
+
}
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function transformValue(dx: number, dy: number, scale: number): string {
|
|
164
|
+
return `translate(${dx}px, ${dy}px) scale(${scale})`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function round(value: number): number {
|
|
168
|
+
return Math.round(value * 10_000) / 10_000;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Quote an arbitrary draw.io cell id as a CSS attribute-selector string. */
|
|
172
|
+
function cssString(value: string): string {
|
|
173
|
+
let escaped = '"';
|
|
174
|
+
for (const char of value) {
|
|
175
|
+
const code = char.codePointAt(0)!;
|
|
176
|
+
if (char === '"' || char === "\\") escaped += `\\${char}`;
|
|
177
|
+
else if (code <= 0x1f || code === 0x7f) escaped += `\\${code.toString(16)} `;
|
|
178
|
+
else escaped += char;
|
|
179
|
+
}
|
|
180
|
+
return `${escaped}"`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function groupSelector(id: string): string {
|
|
184
|
+
return `g[data-cell-id=${cssString(id)}]`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Cells of one page model, keyed by id (wrapper ids resolved, DOM untouched). */
|
|
188
|
+
export function motionCells(model: DomEl): Map<string, MotionCell> {
|
|
189
|
+
const { ids } = collectCellsWithIds(firstByTag(model, "root"));
|
|
190
|
+
const result = new Map<string, MotionCell>();
|
|
191
|
+
for (const [id, cell] of ids) {
|
|
192
|
+
let kind: MotionCell["kind"] | null = null;
|
|
193
|
+
if (cell.getAttribute("vertex") === "1") kind = "vertex";
|
|
194
|
+
else if (cell.getAttribute("edge") === "1") kind = "edge";
|
|
195
|
+
if (kind) result.set(id, { kind, style: attr(cell, "style") ?? "", parent: attr(cell, "parent") });
|
|
196
|
+
}
|
|
197
|
+
return result;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Shape-check raw JSON (from a tool call or the stored attribute) into a spec. */
|
|
201
|
+
export function parseMotionSpec(raw: unknown, errors: string[]): MotionSpec | null {
|
|
202
|
+
const value = isObject(raw) && isObject(raw.motion) ? raw.motion : raw;
|
|
203
|
+
if (!isObject(value)) {
|
|
204
|
+
errors.push("motion spec must be an object with a steps array");
|
|
205
|
+
return null;
|
|
206
|
+
}
|
|
207
|
+
if (!Array.isArray(value.steps) || value.steps.length === 0) {
|
|
208
|
+
errors.push("motion spec must contain a non-empty steps array");
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
if (value.steps.length > MAX_STEPS) errors.push(`motion spec has ${value.steps.length} steps (maximum ${MAX_STEPS})`);
|
|
212
|
+
if (value.loop !== undefined && typeof value.loop !== "boolean") errors.push("motion loop must be a boolean");
|
|
213
|
+
const hold = value.hold === undefined ? null : finite(value.hold);
|
|
214
|
+
if (value.hold !== undefined && (hold === null || hold < 0 || hold > MAX_DURATION_MS)) {
|
|
215
|
+
errors.push(`motion hold must be between 0 and ${MAX_DURATION_MS} ms`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const steps: MotionStep[] = [];
|
|
219
|
+
value.steps.forEach((raw: unknown, index: number) => {
|
|
220
|
+
const n = index + 1;
|
|
221
|
+
if (!isObject(raw)) {
|
|
222
|
+
errors.push(`motion step ${n} must be an object`);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const effect = raw.effect;
|
|
226
|
+
if (typeof effect !== "string" || !(MOTION_EFFECTS as readonly string[]).includes(effect)) {
|
|
227
|
+
errors.push(`motion step ${n} has unknown effect '${String(effect)}' (expected ${MOTION_EFFECTS.join(", ")})`);
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const step: MotionStep = { effect: effect as MotionEffect };
|
|
231
|
+
parseStepTiming(raw, step, n, errors);
|
|
232
|
+
if (raw.direction !== undefined) {
|
|
233
|
+
if (typeof raw.direction !== "string" || !(SLIDE_DIRECTIONS as readonly string[]).includes(raw.direction)) {
|
|
234
|
+
errors.push(`motion step ${n} direction must be one of ${SLIDE_DIRECTIONS.join(", ")}`);
|
|
235
|
+
} else {
|
|
236
|
+
step.direction = raw.direction as SlideDirection;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (raw.color !== undefined) {
|
|
240
|
+
if (typeof raw.color !== "string" || !COLOR.test(raw.color)) {
|
|
241
|
+
errors.push(`motion step ${n} color must be a hex color such as #2563eb`);
|
|
242
|
+
} else {
|
|
243
|
+
step.color = raw.color;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
steps.push(step);
|
|
247
|
+
});
|
|
248
|
+
return {
|
|
249
|
+
...(value.loop === undefined ? {} : { loop: value.loop === true }),
|
|
250
|
+
...(hold === null ? {} : { hold }),
|
|
251
|
+
steps,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function parseStepTiming(raw: Record<string, unknown>, step: MotionStep, n: number, errors: string[]): void {
|
|
256
|
+
if (raw.cells !== undefined) {
|
|
257
|
+
if (!Array.isArray(raw.cells) || raw.cells.some((id) => typeof id !== "string")) {
|
|
258
|
+
errors.push(`motion step ${n} cells must be an array of cell ids`);
|
|
259
|
+
} else {
|
|
260
|
+
step.cells = raw.cells as string[];
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
for (const key of ["duration", "stagger", "value"] as const) {
|
|
264
|
+
if (raw[key] === undefined) continue;
|
|
265
|
+
const number = finite(raw[key]);
|
|
266
|
+
if (number === null) errors.push(`motion step ${n} ${key} must be a number`);
|
|
267
|
+
else step[key] = number;
|
|
268
|
+
}
|
|
269
|
+
if (raw.parallel !== undefined) {
|
|
270
|
+
if (typeof raw.parallel !== "boolean") errors.push(`motion step ${n} parallel must be a boolean`);
|
|
271
|
+
else step.parallel = raw.parallel;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
class Track {
|
|
276
|
+
readonly points: KeyPoint[];
|
|
277
|
+
current: Value;
|
|
278
|
+
|
|
279
|
+
constructor(initial: Value) {
|
|
280
|
+
this.points = [{ t: 0, v: initial }];
|
|
281
|
+
this.current = initial;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private put(t: number, v: Value, ease?: string): void {
|
|
285
|
+
const existing = this.points.find((point) => Math.abs(point.t - t) < 1e-9);
|
|
286
|
+
if (existing) {
|
|
287
|
+
existing.v = v;
|
|
288
|
+
if (ease) existing.ease = ease;
|
|
289
|
+
} else {
|
|
290
|
+
this.points.push({ t, v, ...(ease ? { ease } : {}) });
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
jump(t: number, v: Value): void {
|
|
295
|
+
if (v === this.current) return;
|
|
296
|
+
if (t > 0) this.put(Math.max(0, t - EPSILON_MS), this.current);
|
|
297
|
+
this.put(t, v);
|
|
298
|
+
this.current = v;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
tween(t0: number, t1: number, from: Value, to: Value, ease: string): void {
|
|
302
|
+
this.jump(t0, from);
|
|
303
|
+
this.put(t0, from, ease);
|
|
304
|
+
this.put(t1, to);
|
|
305
|
+
this.current = to;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
finish(t: number): void {
|
|
309
|
+
this.put(t, this.current);
|
|
310
|
+
this.points.sort((a, b) => a.t - b.t);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
get animated(): boolean {
|
|
314
|
+
return new Set(this.points.map((point) => point.v)).size > 1;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
interface CellTracks {
|
|
319
|
+
opacity: Track;
|
|
320
|
+
transform?: Track;
|
|
321
|
+
filter?: Track;
|
|
322
|
+
line?: Track;
|
|
323
|
+
decor?: Track;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
interface ResolvedStep {
|
|
327
|
+
number: number;
|
|
328
|
+
effect: MotionEffect;
|
|
329
|
+
cells: string[];
|
|
330
|
+
duration: number;
|
|
331
|
+
stagger: number;
|
|
332
|
+
parallel: boolean;
|
|
333
|
+
direction: SlideDirection;
|
|
334
|
+
color: string;
|
|
335
|
+
value: number;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function resolveSteps(
|
|
339
|
+
spec: MotionSpec,
|
|
340
|
+
cells: Map<string, MotionCell>,
|
|
341
|
+
errors: string[],
|
|
342
|
+
accent: string,
|
|
343
|
+
): ResolvedStep[] {
|
|
344
|
+
const resolved: ResolvedStep[] = [];
|
|
345
|
+
spec.steps.forEach((step, index) => {
|
|
346
|
+
const number = index + 1;
|
|
347
|
+
const where = `motion step ${number} (${step.effect})`;
|
|
348
|
+
const duration = step.duration ?? (step.effect === "wait" ? null : DEFAULT_DURATION[step.effect]);
|
|
349
|
+
if (duration === null) errors.push(`${where} needs a duration in ms`);
|
|
350
|
+
else if (duration < 0 || duration > MAX_DURATION_MS || (step.effect !== "wait" && duration === 0)) {
|
|
351
|
+
errors.push(`${where} duration must be between ${step.effect === "wait" ? 0 : 1} and ${MAX_DURATION_MS} ms`);
|
|
352
|
+
}
|
|
353
|
+
const stagger = step.stagger ?? 0;
|
|
354
|
+
if (stagger < 0 || stagger > MAX_DURATION_MS) errors.push(`${where} stagger must be between 0 and ${MAX_DURATION_MS} ms`);
|
|
355
|
+
if (step.parallel && index === 0) errors.push(`${where} cannot be parallel: there is no previous step`);
|
|
356
|
+
const ids = step.cells ?? [];
|
|
357
|
+
validateStepOptions(step, ids, where, errors);
|
|
358
|
+
validateStepCells(step, ids, cells, where, errors);
|
|
359
|
+
resolved.push({
|
|
360
|
+
number,
|
|
361
|
+
effect: step.effect,
|
|
362
|
+
cells: ids,
|
|
363
|
+
duration: duration ?? 0,
|
|
364
|
+
stagger,
|
|
365
|
+
parallel: step.parallel === true,
|
|
366
|
+
direction: step.direction ?? "up",
|
|
367
|
+
color: step.color ?? accent,
|
|
368
|
+
value: step.value ?? DEFAULT_DIM,
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
return resolved;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function validateStepOptions(step: MotionStep, ids: string[], where: string, errors: string[]): void {
|
|
375
|
+
if (step.value !== undefined && (step.effect !== "dim" || step.value < 0 || step.value > 1)) {
|
|
376
|
+
errors.push(`${where} value is only valid for dim and must be between 0 and 1`);
|
|
377
|
+
}
|
|
378
|
+
if (step.direction !== undefined && step.effect !== "slideIn") errors.push(`${where} direction is only valid for slideIn`);
|
|
379
|
+
if (step.color !== undefined && step.effect !== "highlight" && step.effect !== "travel") {
|
|
380
|
+
errors.push(`${where} color is only valid for highlight and travel`);
|
|
381
|
+
}
|
|
382
|
+
if (step.effect === "wait") {
|
|
383
|
+
if (ids.length > 0) errors.push(`${where} must not list cells`);
|
|
384
|
+
} else if (ids.length === 0) {
|
|
385
|
+
errors.push(`${where} must list at least one cell id`);
|
|
386
|
+
}
|
|
387
|
+
if (new Set(ids).size !== ids.length) errors.push(`${where} lists a cell more than once`);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function validateStepCells(
|
|
391
|
+
step: MotionStep, ids: string[], cells: Map<string, MotionCell>, where: string, errors: string[],
|
|
392
|
+
): void {
|
|
393
|
+
for (const id of ids) {
|
|
394
|
+
const cell = cells.get(id);
|
|
395
|
+
if (!cell) {
|
|
396
|
+
errors.push(`${where} references missing cell '${id}'`);
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
if (EDGE_ONLY.has(step.effect) && cell.kind !== "edge") errors.push(`${where} needs a connector, but '${id}' is a shape`);
|
|
400
|
+
if (step.effect !== "drawIn" || cell.kind !== "edge") continue;
|
|
401
|
+
if (styleValue(cell.style, "dashed") === "1") {
|
|
402
|
+
errors.push(`${where} cannot draw dashed connector '${id}'; use fadeIn or make it solid`);
|
|
403
|
+
}
|
|
404
|
+
if (styleValue(cell.style, "flowAnimation") === "1") {
|
|
405
|
+
errors.push(`${where} cannot draw connector '${id}' because it uses flowAnimation=1; use fadeIn`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function batches(steps: ResolvedStep[]): ResolvedStep[][] {
|
|
411
|
+
const result: ResolvedStep[][] = [];
|
|
412
|
+
for (const step of steps) {
|
|
413
|
+
if (step.parallel && result.length > 0) result.at(-1)!.push(step);
|
|
414
|
+
else result.push([step]);
|
|
415
|
+
}
|
|
416
|
+
return result;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function slideOffset(direction: SlideDirection): [number, number] {
|
|
420
|
+
if (direction === "up") return [0, SLIDE_DISTANCE];
|
|
421
|
+
if (direction === "down") return [0, -SLIDE_DISTANCE];
|
|
422
|
+
if (direction === "left") return [SLIDE_DISTANCE, 0];
|
|
423
|
+
return [-SLIDE_DISTANCE, 0];
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function frameLabel(batch: ResolvedStep[]): string {
|
|
427
|
+
return batch
|
|
428
|
+
.filter((step) => step.effect !== "wait")
|
|
429
|
+
.map((step) => {
|
|
430
|
+
const shown = step.cells.slice(0, 3).join(", ");
|
|
431
|
+
const more = step.cells.length > 3 ? ` +${step.cells.length - 3}` : "";
|
|
432
|
+
return `${step.effect} ${shown}${more}`;
|
|
433
|
+
})
|
|
434
|
+
.join(" · ");
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function pct(t: number, total: number): string {
|
|
438
|
+
return `${((t / total) * 100).toFixed(6)}%`;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function formatValue(value: Value): string {
|
|
442
|
+
return typeof value === "number" ? String(round(value)) : value;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function keyframes(name: string, property: string, track: Track, total: number): string {
|
|
446
|
+
const lines = track.points.map((point) => {
|
|
447
|
+
const ease = point.ease ? ` animation-timing-function: ${point.ease};` : "";
|
|
448
|
+
return ` ${pct(point.t, total)} { ${property}: ${formatValue(point.v)};${ease} }`;
|
|
449
|
+
});
|
|
450
|
+
return `@keyframes ${name} {\n${lines.join("\n")}\n}`;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Validate a spec against the page and compile it to CSS, SMIL dots, and storyboard frames. */
|
|
454
|
+
export function compileMotion(
|
|
455
|
+
spec: MotionSpec,
|
|
456
|
+
cells: Map<string, MotionCell>,
|
|
457
|
+
accent: string = DEFAULT_ACCENT,
|
|
458
|
+
): MotionAnalysis {
|
|
459
|
+
const errors: string[] = [];
|
|
460
|
+
const steps = resolveSteps(spec, cells, errors, accent);
|
|
461
|
+
if (errors.length > 0) return { spec, compiled: null, errors };
|
|
462
|
+
|
|
463
|
+
// A cell whose first effect is an entrance starts hidden; everything else starts visible.
|
|
464
|
+
const firstEffect = firstCellEffects(steps);
|
|
465
|
+
|
|
466
|
+
const tracks = new Map<string, CellTracks>();
|
|
467
|
+
const ensure = (id: string): CellTracks => {
|
|
468
|
+
let entry = tracks.get(id);
|
|
469
|
+
if (!entry) {
|
|
470
|
+
entry = { opacity: new Track(ENTRANCES.has(firstEffect.get(id)!) ? 0 : 1) };
|
|
471
|
+
tracks.set(id, entry);
|
|
472
|
+
}
|
|
473
|
+
return entry;
|
|
474
|
+
};
|
|
475
|
+
for (const id of firstEffect.keys()) ensure(id);
|
|
476
|
+
|
|
477
|
+
const dots: MotionDot[] = [];
|
|
478
|
+
const frames: MotionFrame[] = [];
|
|
479
|
+
const drawInEdges = new Set<string>();
|
|
480
|
+
let time = 0;
|
|
481
|
+
for (const batch of batches(steps)) {
|
|
482
|
+
const touched = new Set<string>();
|
|
483
|
+
const accent = new Map<string, string>();
|
|
484
|
+
let span = 0;
|
|
485
|
+
for (const step of batch) {
|
|
486
|
+
const where = `motion step ${step.number} (${step.effect})`;
|
|
487
|
+
span = Math.max(span, step.duration + step.stagger * Math.max(0, step.cells.length - 1));
|
|
488
|
+
step.cells.forEach((id, order) => {
|
|
489
|
+
if (touched.has(id)) {
|
|
490
|
+
errors.push(`${where} targets '${id}' again in the same parallel group`);
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
touched.add(id);
|
|
494
|
+
const cell = tracks.get(id)!;
|
|
495
|
+
const s = time + step.stagger * order;
|
|
496
|
+
const d = step.duration;
|
|
497
|
+
const visible = (cell.opacity.current as number) > 0;
|
|
498
|
+
if (ENTRANCES.has(step.effect) && step.effect !== "fadeIn" && visible) {
|
|
499
|
+
errors.push(`${where} targets '${id}', which is already visible; fade it out first or use highlight`);
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
if ((step.effect === "highlight" || step.effect === "travel") && !visible) {
|
|
503
|
+
errors.push(`${where} targets '${id}', which is hidden at that point; reveal it first`);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
switch (step.effect) {
|
|
507
|
+
case "fadeIn":
|
|
508
|
+
cell.opacity.tween(s, s + d, cell.opacity.current, 1, EASE.out);
|
|
509
|
+
break;
|
|
510
|
+
case "fadeOut":
|
|
511
|
+
cell.opacity.tween(s, s + d, cell.opacity.current, 0, EASE.in);
|
|
512
|
+
break;
|
|
513
|
+
case "dim":
|
|
514
|
+
cell.opacity.tween(s, s + d, cell.opacity.current, step.value, EASE.inOut);
|
|
515
|
+
break;
|
|
516
|
+
case "popIn":
|
|
517
|
+
cell.transform ??= new Track(IDENTITY);
|
|
518
|
+
cell.opacity.tween(s, s + d * 0.6, 0, 1, EASE.out);
|
|
519
|
+
cell.transform.tween(s, s + d, transformValue(0, 0, 0.6), IDENTITY, EASE.back);
|
|
520
|
+
break;
|
|
521
|
+
case "slideIn": {
|
|
522
|
+
const [dx, dy] = slideOffset(step.direction);
|
|
523
|
+
cell.transform ??= new Track(IDENTITY);
|
|
524
|
+
cell.opacity.tween(s, s + d, 0, 1, EASE.out);
|
|
525
|
+
cell.transform.tween(s, s + d, transformValue(dx, dy, 1), IDENTITY, EASE.out);
|
|
526
|
+
break;
|
|
527
|
+
}
|
|
528
|
+
case "drawIn":
|
|
529
|
+
cell.line ??= new Track(1);
|
|
530
|
+
cell.decor ??= new Track(0);
|
|
531
|
+
drawInEdges.add(id);
|
|
532
|
+
cell.opacity.jump(s, 1);
|
|
533
|
+
cell.line.tween(s, s + d * 0.8, 1, 0, EASE.inOut);
|
|
534
|
+
cell.decor.tween(s + d * 0.7, s + d, 0, 1, EASE.out);
|
|
535
|
+
break;
|
|
536
|
+
case "highlight": {
|
|
537
|
+
const glow = `drop-shadow(0px 0px 12px ${step.color})`;
|
|
538
|
+
cell.filter ??= new Track(NO_GLOW);
|
|
539
|
+
cell.filter.tween(s, s + d * 0.4, NO_GLOW, glow, EASE.out);
|
|
540
|
+
cell.filter.tween(s + d * 0.4, s + d, glow, NO_GLOW, EASE.inOut);
|
|
541
|
+
if (cells.get(id)!.kind === "vertex") {
|
|
542
|
+
cell.transform ??= new Track(IDENTITY);
|
|
543
|
+
cell.transform.tween(s, s + d * 0.4, IDENTITY, transformValue(0, 0, 1.04), EASE.out);
|
|
544
|
+
cell.transform.tween(s + d * 0.4, s + d, transformValue(0, 0, 1.04), IDENTITY, EASE.inOut);
|
|
545
|
+
}
|
|
546
|
+
accent.set(id, step.color);
|
|
547
|
+
break;
|
|
548
|
+
}
|
|
549
|
+
case "travel":
|
|
550
|
+
dots.push({ cellId: id, start: s, duration: d, color: step.color });
|
|
551
|
+
accent.set(id, step.color);
|
|
552
|
+
break;
|
|
553
|
+
case "wait":
|
|
554
|
+
break;
|
|
555
|
+
}
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
time += span;
|
|
559
|
+
if (batch.some((step) => step.effect !== "wait")) {
|
|
560
|
+
const opacity = new Map<string, number>();
|
|
561
|
+
for (const [id, cell] of tracks) opacity.set(id, cell.opacity.current as number);
|
|
562
|
+
frames.push({ time, label: frameLabel(batch), opacity, accent });
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
if (time > MAX_TOTAL_MS) errors.push(`motion sequence lasts ${Math.round(time)} ms (maximum ${MAX_TOTAL_MS} ms)`);
|
|
566
|
+
if (errors.length > 0) return { spec, compiled: null, errors };
|
|
567
|
+
|
|
568
|
+
const loop = spec.loop ?? true;
|
|
569
|
+
const sequenceMs = Math.max(1, time);
|
|
570
|
+
const durationMs = loop ? sequenceMs + (spec.hold ?? DEFAULT_HOLD_MS) : sequenceMs;
|
|
571
|
+
const css = compileTrackCss(tracks, durationMs, loop);
|
|
572
|
+
return {
|
|
573
|
+
spec,
|
|
574
|
+
errors,
|
|
575
|
+
compiled: {
|
|
576
|
+
loop,
|
|
577
|
+
sequenceMs,
|
|
578
|
+
durationMs,
|
|
579
|
+
css,
|
|
580
|
+
dots,
|
|
581
|
+
targetCellIds: [...tracks.keys()],
|
|
582
|
+
drawInEdgeIds: [...drawInEdges],
|
|
583
|
+
frames,
|
|
584
|
+
},
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function firstCellEffects(steps: ResolvedStep[]): Map<string, MotionEffect> {
|
|
589
|
+
const effects = new Map<string, MotionEffect>();
|
|
590
|
+
for (const step of steps) {
|
|
591
|
+
for (const id of step.cells) {
|
|
592
|
+
if (!effects.has(id)) effects.set(id, step.effect);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return effects;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
function compileTrackCss(tracks: Map<string, CellTracks>, durationMs: number, loop: boolean): string {
|
|
599
|
+
const iteration = loop ? "infinite" : "1";
|
|
600
|
+
const rules: string[] = [];
|
|
601
|
+
const reduced: string[] = [];
|
|
602
|
+
let counter = 0;
|
|
603
|
+
const animate = (selector: string, entries: [string, Track][], extra = ""): void => {
|
|
604
|
+
const live = entries.filter(([, track]) => track.animated);
|
|
605
|
+
if (live.length === 0) return;
|
|
606
|
+
const names: string[] = [];
|
|
607
|
+
const finals: string[] = [];
|
|
608
|
+
for (const [property, track] of live) {
|
|
609
|
+
track.finish(durationMs);
|
|
610
|
+
const name = `drawme-motion-${++counter}`;
|
|
611
|
+
rules.push(keyframes(name, property, track, durationMs));
|
|
612
|
+
names.push(`${name} ${durationMs}ms linear 0ms ${iteration} normal both`);
|
|
613
|
+
finals.push(`${property}: ${formatValue(track.current)} !important;`);
|
|
614
|
+
}
|
|
615
|
+
rules.push(`${selector} { animation: ${names.join(", ")};${extra} }`);
|
|
616
|
+
reduced.push(` ${selector} { animation: none !important; ${finals.join(" ")} }`);
|
|
617
|
+
};
|
|
618
|
+
for (const [id, cell] of tracks) {
|
|
619
|
+
const group = groupSelector(id);
|
|
620
|
+
const groupTracks: [string, Track][] = [["opacity", cell.opacity]];
|
|
621
|
+
if (cell.transform) groupTracks.push(["transform", cell.transform]);
|
|
622
|
+
if (cell.filter) groupTracks.push(["filter", cell.filter]);
|
|
623
|
+
animate(group, groupTracks, cell.transform ? " transform-box: fill-box; transform-origin: center;" : "");
|
|
624
|
+
if (cell.line) animate(`${group} [data-drawme-line]`, [["stroke-dashoffset", cell.line]], " stroke-dasharray: 1 1;");
|
|
625
|
+
if (cell.decor) animate(`${group} [data-drawme-decor]`, [["opacity", cell.decor]]);
|
|
626
|
+
}
|
|
627
|
+
reduced.push(" [data-drawme-dot] { display: none !important; }");
|
|
628
|
+
rules.push(`@media (prefers-reduced-motion: reduce) {\n${reduced.join("\n")}\n}`);
|
|
629
|
+
|
|
630
|
+
return rules.join("\n");
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// --- Storage on the page root cell ---
|
|
634
|
+
|
|
635
|
+
function rootCellElement(model: DomEl): DomEl | null {
|
|
636
|
+
const root = firstByTag(model, "root");
|
|
637
|
+
if (!root) return null;
|
|
638
|
+
return elemChildren(root).find((child) => attr(child, "id") === "0") ?? null;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/** The stored motion JSON of a page, or null. */
|
|
642
|
+
export function readStoredMotion(model: DomEl): string | null {
|
|
643
|
+
const cell = rootCellElement(model);
|
|
644
|
+
return cell ? attr(cell, MOTION_ATTRIBUTE) : null;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Store motion JSON on the page root cell, wrapping a plain `<mxCell id="0"/>`
|
|
649
|
+
* in a `UserObject` (draw.io's form for a root cell with custom properties).
|
|
650
|
+
*/
|
|
651
|
+
export function storeMotion(model: DomEl, json: string): void {
|
|
652
|
+
const cell = rootCellElement(model);
|
|
653
|
+
if (!cell) throw new Error("page has no root cell id=\"0\"");
|
|
654
|
+
if (cell.tagName === "UserObject" || cell.tagName === "object") {
|
|
655
|
+
cell.setAttribute(MOTION_ATTRIBUTE, json);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const node = cell as unknown as {
|
|
659
|
+
ownerDocument: { createElement(tag: string): DomEl };
|
|
660
|
+
parentNode: { replaceChild(next: unknown, old: unknown): void };
|
|
661
|
+
attributes: { length: number; [i: number]: { name: string; value: string } };
|
|
662
|
+
};
|
|
663
|
+
const doc = node.ownerDocument;
|
|
664
|
+
const wrapper = doc.createElement("UserObject");
|
|
665
|
+
wrapper.setAttribute("label", "");
|
|
666
|
+
wrapper.setAttribute(MOTION_ATTRIBUTE, json);
|
|
667
|
+
wrapper.setAttribute("id", "0");
|
|
668
|
+
const inner = doc.createElement("mxCell");
|
|
669
|
+
for (const { name, value } of Array.from(node.attributes)) {
|
|
670
|
+
if (name !== "id") inner.setAttribute(name, value);
|
|
671
|
+
}
|
|
672
|
+
(wrapper as unknown as { appendChild(child: unknown): void }).appendChild(inner);
|
|
673
|
+
node.parentNode.replaceChild(wrapper, cell);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** True when a page background color is dark (a Dark theme page). */
|
|
677
|
+
export function isDarkBackground(color: string | null): boolean {
|
|
678
|
+
const match = /^#([0-9a-fA-F]{6})$/.exec(color ?? "");
|
|
679
|
+
if (!match) return false;
|
|
680
|
+
const value = Number.parseInt(match[1], 16);
|
|
681
|
+
const channel = (shift: number): number => ((value >> shift) & 0xff) / 255;
|
|
682
|
+
return 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0) < 0.4;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** Pick a 1-based page from a parsed `.drawio` document. */
|
|
686
|
+
export function selectPage(root: DomEl, pageIndex = 1): { diagram: DomEl; model: DomEl; name: string } {
|
|
687
|
+
if (!Number.isInteger(pageIndex) || pageIndex < 1) throw new Error("pageIndex must be a positive 1-based integer");
|
|
688
|
+
const pageList = childrenByTag(root, "diagram");
|
|
689
|
+
const pages = pageList.length > 0 ? pageList : [root];
|
|
690
|
+
const diagram = pages[pageIndex - 1];
|
|
691
|
+
if (!diagram) throw new Error(`pageIndex ${pageIndex} is out of range (diagram has ${pages.length} page(s))`);
|
|
692
|
+
const model = diagram.tagName === "mxGraphModel" ? diagram : firstByTag(diagram, "mxGraphModel");
|
|
693
|
+
if (!model) throw new Error("compressed or missing page model cannot be animated; save the diagram uncompressed");
|
|
694
|
+
return { diagram, model, name: attr(diagram, "name") ?? "?" };
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
/** Parse and compile the motion stored on a page; null when none is stored. */
|
|
698
|
+
export function analyzeStoredMotion(model: DomEl): MotionAnalysis | null {
|
|
699
|
+
const raw = readStoredMotion(model);
|
|
700
|
+
if (raw === null || raw.trim() === "") return null;
|
|
701
|
+
const errors: string[] = [];
|
|
702
|
+
let parsed: unknown;
|
|
703
|
+
try {
|
|
704
|
+
parsed = JSON.parse(raw);
|
|
705
|
+
} catch (error) {
|
|
706
|
+
return { spec: null, compiled: null, errors: [`stored motion contains malformed JSON: ${(error as Error).message}`] };
|
|
707
|
+
}
|
|
708
|
+
const spec = parseMotionSpec(parsed, errors);
|
|
709
|
+
if (!spec || errors.length > 0) return { spec, compiled: null, errors };
|
|
710
|
+
return compileMotion(spec, motionCells(model), themeAccent(model));
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/** Default motion accent for a page: the Dark preset accent on a dark background, else the Light one. */
|
|
714
|
+
export function themeAccent(model: DomEl): string {
|
|
715
|
+
return isDarkBackground(attr(model, "background")) ? DEFAULT_DARK_ACCENT : DEFAULT_ACCENT;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// --- SVG injection ---
|
|
719
|
+
|
|
720
|
+
function walk(root: DomEl): DomEl[] {
|
|
721
|
+
const elements: DomEl[] = [root];
|
|
722
|
+
for (const child of elemChildren(root)) elements.push(...walk(child));
|
|
723
|
+
return elements;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function linePath(group: DomEl): DomEl | null {
|
|
727
|
+
return walk(group).find((element) => element.tagName === "path" && attr(element, "fill") === "none") ?? null;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
type Parented = DomEl & { parentNode: Parented | null };
|
|
731
|
+
|
|
732
|
+
/** Mark everything in an edge group except the line path (arrowheads, label) as decoration. */
|
|
733
|
+
function markDecor(group: DomEl, line: DomEl): void {
|
|
734
|
+
let current = line as Parented;
|
|
735
|
+
while (current !== (group as Parented) && current.parentNode) {
|
|
736
|
+
const parent = current.parentNode;
|
|
737
|
+
for (const sibling of elemChildren(parent)) {
|
|
738
|
+
if (sibling !== current) sibling.setAttribute("data-drawme-decor", "1"); // NOSONAR: xmldom XML elements have no browser dataset API.
|
|
739
|
+
}
|
|
740
|
+
current = parent;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function keyTimes(times: number[], total: number): string {
|
|
745
|
+
return times.map((t) => String(Math.min(1, Math.max(0, round(t / total))))).join(";");
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function appendDot(doc: XmlDocument, group: DomEl, path: string, dot: MotionDot, motion: CompiledMotion): void {
|
|
749
|
+
const total = motion.durationMs;
|
|
750
|
+
const { start, duration } = dot;
|
|
751
|
+
const end = start + duration;
|
|
752
|
+
const fade = Math.min(150, duration * 0.15);
|
|
753
|
+
const repeat = motion.loop ? "indefinite" : "1";
|
|
754
|
+
const circle = doc.createElementNS(SVG_NS, "circle");
|
|
755
|
+
circle.setAttribute("r", "5");
|
|
756
|
+
circle.setAttribute("fill", dot.color);
|
|
757
|
+
circle.setAttribute("stroke", "#ffffff");
|
|
758
|
+
circle.setAttribute("stroke-width", "1.5");
|
|
759
|
+
circle.setAttribute("opacity", "0");
|
|
760
|
+
circle.setAttribute("data-drawme-dot", "1"); // NOSONAR: xmldom XML elements have no browser dataset API.
|
|
761
|
+
const travel = doc.createElementNS(SVG_NS, "animateMotion");
|
|
762
|
+
travel.setAttribute("path", path);
|
|
763
|
+
travel.setAttribute("dur", `${total}ms`);
|
|
764
|
+
travel.setAttribute("repeatCount", repeat);
|
|
765
|
+
travel.setAttribute("fill", "freeze");
|
|
766
|
+
travel.setAttribute("calcMode", "linear");
|
|
767
|
+
travel.setAttribute("keyPoints", "0;0;1;1");
|
|
768
|
+
travel.setAttribute("keyTimes", keyTimes([0, start, end, total], total));
|
|
769
|
+
const opacity = doc.createElementNS(SVG_NS, "animate");
|
|
770
|
+
opacity.setAttribute("attributeName", "opacity");
|
|
771
|
+
opacity.setAttribute("dur", `${total}ms`);
|
|
772
|
+
opacity.setAttribute("repeatCount", repeat);
|
|
773
|
+
opacity.setAttribute("fill", "freeze");
|
|
774
|
+
opacity.setAttribute("calcMode", "linear");
|
|
775
|
+
opacity.setAttribute("values", "0;0;1;1;0;0");
|
|
776
|
+
opacity.setAttribute("keyTimes", keyTimes([0, start, start + fade, end - fade, end, total], total));
|
|
777
|
+
circle.appendChild(travel);
|
|
778
|
+
circle.appendChild(opacity);
|
|
779
|
+
(group as unknown as { appendChild(node: unknown): void }).appendChild(circle);
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
function motionSvgGroups(root: DomEl): Map<string, DomEl> {
|
|
783
|
+
const groups = new Map<string, DomEl>();
|
|
784
|
+
for (const element of walk(root)) {
|
|
785
|
+
const id = attr(element, "data-cell-id");
|
|
786
|
+
if (id !== null && !groups.has(id)) groups.set(id, element);
|
|
787
|
+
}
|
|
788
|
+
return groups;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Inject compiled motion into a draw.io SVG string. Throws when a targeted
|
|
793
|
+
* cell or connector line is missing from the SVG, so a static file is never
|
|
794
|
+
* presented as animated.
|
|
795
|
+
*/
|
|
796
|
+
export function injectMotion(svg: string, motion: CompiledMotion, flowEdgeIds: string[] = []): string {
|
|
797
|
+
const doc = new DOMParser().parseFromString(svg, "image/svg+xml");
|
|
798
|
+
const svgRoot = doc.documentElement as unknown as DomEl | null;
|
|
799
|
+
if (svgRoot?.tagName !== "svg") throw new Error("draw.io output is not valid SVG");
|
|
800
|
+
const groups = motionSvgGroups(svgRoot);
|
|
801
|
+
const missing = motion.targetCellIds.filter((id) => !groups.has(id));
|
|
802
|
+
if (missing.length > 0) {
|
|
803
|
+
throw new Error(`SVG is missing animated cell group(s): ${missing.join(", ")}; do not use visible=0 on animated cells`);
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
for (const id of motion.drawInEdgeIds) {
|
|
807
|
+
const group = groups.get(id)!;
|
|
808
|
+
const line = linePath(group);
|
|
809
|
+
if (!line) throw new Error(`connector '${id}' has no line path in the SVG to draw in`);
|
|
810
|
+
line.setAttribute("pathLength", "1");
|
|
811
|
+
line.setAttribute("data-drawme-line", "1"); // NOSONAR: xmldom XML elements have no browser dataset API.
|
|
812
|
+
markDecor(group, line);
|
|
813
|
+
}
|
|
814
|
+
for (const dot of motion.dots) {
|
|
815
|
+
const group = groups.get(dot.cellId)!;
|
|
816
|
+
const line = linePath(group);
|
|
817
|
+
const d = line ? attr(line, "d") : null;
|
|
818
|
+
if (!d) throw new Error(`connector '${dot.cellId}' has no line path in the SVG for a travelling dot`);
|
|
819
|
+
appendDot(doc, group, d, dot, motion);
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
const flowReduced = flowEdgeIds.length > 0
|
|
823
|
+
? `\n@media (prefers-reduced-motion: reduce) {\n${flowEdgeIds
|
|
824
|
+
.map((id) => ` ${groupSelector(id)} * { animation: none !important; }`)
|
|
825
|
+
.join("\n")}\n}`
|
|
826
|
+
: "";
|
|
827
|
+
let defs = walk(svgRoot).find((element) => element.tagName === "defs");
|
|
828
|
+
if (!defs) {
|
|
829
|
+
defs = doc.createElementNS(SVG_NS, "defs") as unknown as DomEl;
|
|
830
|
+
const rootNode = svgRoot as unknown as { firstChild: unknown; insertBefore(node: unknown, before: unknown): void };
|
|
831
|
+
rootNode.insertBefore(defs, rootNode.firstChild);
|
|
832
|
+
}
|
|
833
|
+
const style = doc.createElementNS(SVG_NS, "style");
|
|
834
|
+
style.setAttribute("type", "text/css");
|
|
835
|
+
style.setAttribute("data-drawme-animation", "motion"); // NOSONAR: xmldom XML elements have no browser dataset API.
|
|
836
|
+
style.appendChild(doc.createTextNode(motion.css + flowReduced));
|
|
837
|
+
(defs as unknown as { appendChild(node: unknown): void }).appendChild(style);
|
|
838
|
+
return new XMLSerializer().serializeToString(doc);
|
|
839
|
+
}
|