@senad-d/drawme 0.1.8 → 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.
@@ -0,0 +1,637 @@
1
+ /**
2
+ * Animation analysis and standalone SVG enhancement. draw.io natively emits
3
+ * persistent connector-flow CSS; DrawMe adds a portable opacity timeline for
4
+ * page-level sequences and verifies that the requested motion survived export.
5
+ */
6
+ import { readFile, writeFile } from "node:fs/promises";
7
+ import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
8
+ import { type DomEl, attr, childrenByTag, elemChildren, firstByTag } from "./dom";
9
+ import { collectCells } from "./geometry";
10
+
11
+ const PORTABLE_ACTIONS = new Set(["opacity", "show", "hide", "toggle", "fadeIn", "fadeOut", "fadeTo"]);
12
+ const DRAWIO_ONLY_ACTIONS = new Set([
13
+ "wipeIn",
14
+ "wipeOut",
15
+ "popIn",
16
+ "popOut",
17
+ "style",
18
+ "toggleStyle",
19
+ "highlight",
20
+ "flow",
21
+ "select",
22
+ "scroll",
23
+ "viewbox",
24
+ "open",
25
+ "tags",
26
+ ]);
27
+ const FLOW_DIRECTIONS = new Set(["normal", "reverse", "alternate", "alternate-reverse"]);
28
+ const FLOW_TIMINGS = new Set(["linear", "ease", "ease-in", "ease-out", "ease-in-out"]);
29
+ const SVG_NS = "http://www.w3.org/2000/svg";
30
+ const DEFAULT_FADE_DURATION_MS = 1000;
31
+ const INSTANT_EPSILON_MS = 0.01;
32
+
33
+ type JsonObject = Record<string, unknown>;
34
+
35
+ export interface NativeAnimationSequence {
36
+ enabled: boolean;
37
+ loop: boolean;
38
+ steps: JsonObject[];
39
+ }
40
+
41
+ export interface PageAnimationAnalysis {
42
+ pageName: string;
43
+ flowEdgeIds: string[];
44
+ sequence: NativeAnimationSequence | null;
45
+ cells: Map<string, DomEl>;
46
+ animatableCellIds: string[];
47
+ errors: string[];
48
+ warnings: string[];
49
+ observations: string[];
50
+ }
51
+
52
+ export interface AnimatedSvgSummary {
53
+ page: string;
54
+ connectorFlows: number;
55
+ sequenceSteps: number;
56
+ sequenceDurationMs: number;
57
+ sequenceCompiled: boolean;
58
+ verified: boolean;
59
+ }
60
+
61
+ interface OpacityPoint {
62
+ time: number;
63
+ value: number;
64
+ }
65
+
66
+ interface CompiledTimeline {
67
+ css: string;
68
+ durationMs: number;
69
+ animatedCellIds: string[];
70
+ }
71
+
72
+ function isObject(value: unknown): value is JsonObject {
73
+ return typeof value === "object" && value !== null && !Array.isArray(value);
74
+ }
75
+
76
+ function styleMap(style: string | null): Map<string, string> {
77
+ const values = new Map<string, string>();
78
+ for (const item of (style ?? "").split(";")) {
79
+ const separator = item.indexOf("=");
80
+ if (separator > 0) values.set(item.slice(0, separator), item.slice(separator + 1));
81
+ }
82
+ return values;
83
+ }
84
+
85
+ function finiteNumber(value: unknown): number | null {
86
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
87
+ }
88
+
89
+ /** Quote an arbitrary draw.io cell id as a CSS attribute-selector string. */
90
+ function cssString(value: string): string {
91
+ let escaped = '"';
92
+ for (const char of value) {
93
+ const code = char.codePointAt(0)!;
94
+ if (char === '"' || char === "\\") escaped += `\\${char}`;
95
+ else if (code <= 0x1f || code === 0x7f) escaped += `\\${code.toString(16)} `;
96
+ else escaped += char;
97
+ }
98
+ return `${escaped}"`;
99
+ }
100
+
101
+ function pageModel(diagram: DomEl): DomEl | null {
102
+ return firstByTag(diagram, "mxGraphModel");
103
+ }
104
+
105
+ function animationAttribute(model: DomEl): string | null {
106
+ const root = firstByTag(model, "root");
107
+ if (!root) return null;
108
+ for (const child of elemChildren(root)) {
109
+ if (attr(child, "id") !== "0") continue;
110
+ const direct = attr(child, "animation");
111
+ if (direct !== null) return direct;
112
+ const inner = firstByTag(child, "mxCell");
113
+ const nested = inner ? attr(inner, "animation") : null;
114
+ if (nested !== null) return nested;
115
+ }
116
+ return null;
117
+ }
118
+
119
+ function parseSequence(raw: string | null, errors: string[], warnings: string[]): NativeAnimationSequence | null {
120
+ if (raw === null || raw.trim() === "") return null;
121
+ if (!raw.trimStart().startsWith("{")) {
122
+ warnings.push("legacy text page animations cannot be compiled to standalone animated SVG; save the animation as JSON");
123
+ return null;
124
+ }
125
+
126
+ let parsed: unknown;
127
+ try {
128
+ parsed = JSON.parse(raw);
129
+ } catch (error) {
130
+ errors.push(`page animation contains malformed JSON: ${(error as Error).message}`);
131
+ return null;
132
+ }
133
+
134
+ if (!isObject(parsed)) {
135
+ errors.push("page animation JSON must be an object");
136
+ return null;
137
+ }
138
+ const value = isObject(parsed.animation) ? parsed.animation : parsed;
139
+ if (!Array.isArray(value.steps)) {
140
+ errors.push("page animation JSON must contain a steps array");
141
+ return null;
142
+ }
143
+ if (value.enabled !== undefined && typeof value.enabled !== "boolean") {
144
+ errors.push("page animation enabled must be a boolean");
145
+ }
146
+ if (value.loop !== undefined && typeof value.loop !== "boolean") {
147
+ errors.push("page animation loop must be a boolean");
148
+ }
149
+
150
+ const steps = parseSequenceSteps(value.steps, errors);
151
+ return {
152
+ enabled: value.enabled === undefined ? true : value.enabled === true,
153
+ loop: value.loop === undefined ? true : value.loop === true,
154
+ steps,
155
+ };
156
+ }
157
+
158
+ function parseSequenceSteps(raw: unknown[], errors: string[]): JsonObject[] {
159
+ const steps: JsonObject[] = [];
160
+ raw.forEach((step, index) => {
161
+ if (!isObject(step)) errors.push(`page animation step ${index + 1} must be an object`);
162
+ else steps.push(step);
163
+ });
164
+ return steps;
165
+ }
166
+
167
+ function collectCellData(cells: DomEl[]): { byId: Map<string, DomEl>; animatable: string[] } {
168
+ const byId = new Map<string, DomEl>();
169
+ const animatable: string[] = [];
170
+ for (const cell of cells) {
171
+ const id = attr(cell, "id");
172
+ if (id === null) continue;
173
+ byId.set(id, cell);
174
+ if (cell.getAttribute("vertex") === "1" || cell.getAttribute("edge") === "1") animatable.push(id);
175
+ }
176
+ return { byId, animatable };
177
+ }
178
+
179
+ function validateFlowAnimations(cells: DomEl[], errors: string[], flowEdgeIds: string[]): void {
180
+ for (const cell of cells) {
181
+ const style = styleMap(attr(cell, "style"));
182
+ const flow = style.get("flowAnimation");
183
+ const id = attr(cell, "id") ?? "?";
184
+ if (flow !== undefined && flow !== "0" && flow !== "1") {
185
+ errors.push(`cell '${id}' has invalid flowAnimation '${flow}' (expected 0 or 1)`);
186
+ continue;
187
+ }
188
+ if (flow !== "1") continue;
189
+ if (cell.getAttribute("edge") !== "1") {
190
+ errors.push(`cell '${id}' uses flowAnimation=1 but is not an edge`);
191
+ continue;
192
+ }
193
+ flowEdgeIds.push(id);
194
+
195
+ validateFlowStyle(style, id, errors);
196
+ }
197
+ }
198
+
199
+ function validateFlowStyle(style: Map<string, string>, id: string, errors: string[]): void {
200
+ const duration = style.get("flowAnimationDuration");
201
+ if (duration !== undefined && (Number(duration) <= 0 || !Number.isFinite(Number(duration)))) {
202
+ errors.push(`edge '${id}' has invalid flowAnimationDuration '${duration}' (expected a positive millisecond value)`);
203
+ }
204
+ const direction = style.get("flowAnimationDirection");
205
+ if (direction !== undefined && !FLOW_DIRECTIONS.has(direction)) {
206
+ errors.push(`edge '${id}' has invalid flowAnimationDirection '${direction}'`);
207
+ }
208
+ const timing = style.get("flowAnimationTimingFunction");
209
+ if (timing !== undefined && !FLOW_TIMINGS.has(timing)) {
210
+ errors.push(`edge '${id}' has invalid flowAnimationTimingFunction '${timing}'`);
211
+ }
212
+ }
213
+
214
+ function selectorIds(
215
+ params: JsonObject,
216
+ stepNumber: number,
217
+ action: string,
218
+ cells: Map<string, DomEl>,
219
+ animatable: string[],
220
+ errors: string[],
221
+ warnings: string[],
222
+ ): string[] {
223
+ if (params.layers !== undefined || params.tags !== undefined) {
224
+ warnings.push(
225
+ `page animation step ${stepNumber} action '${action}' uses layer/tag selectors, which standalone animated SVG does not support`,
226
+ );
227
+ }
228
+ if (!Array.isArray(params.cells)) {
229
+ errors.push(`page animation step ${stepNumber} action '${action}' must provide a cells array`);
230
+ return [];
231
+ }
232
+
233
+ const requested = new Set<string>();
234
+ const animatableIds = new Set(animatable);
235
+ for (const cellId of params.cells) {
236
+ if (typeof cellId !== "string") {
237
+ errors.push(`page animation step ${stepNumber} action '${action}' has a non-string cell id`);
238
+ continue;
239
+ }
240
+ if (cellId === "*") {
241
+ for (const id of animatable) requested.add(id);
242
+ } else if (!cells.has(cellId)) {
243
+ errors.push(`page animation step ${stepNumber} action '${action}' references missing cell '${cellId}'`);
244
+ } else if (!animatableIds.has(cellId)) {
245
+ errors.push(`page animation step ${stepNumber} action '${action}' references non-animatable cell '${cellId}'`);
246
+ } else {
247
+ requested.add(cellId);
248
+ }
249
+ }
250
+
251
+ excludeSelectorIds(params.excludeCells, requested, stepNumber, action, errors);
252
+ return [...requested];
253
+ }
254
+
255
+ function excludeSelectorIds(raw: unknown, requested: Set<string>, stepNumber: number, action: string, errors: string[]): void {
256
+ if (raw === undefined) return;
257
+ if (!Array.isArray(raw) || raw.some((id) => typeof id !== "string")) {
258
+ errors.push(`page animation step ${stepNumber} action '${action}' has an invalid excludeCells array`);
259
+ return;
260
+ }
261
+ for (const id of raw as string[]) {
262
+ if (id === "*") requested.clear();
263
+ else requested.delete(id);
264
+ }
265
+ }
266
+
267
+ function validateActionParameters(action: string, params: JsonObject, stepNumber: number, errors: string[]): void {
268
+ if (action === "opacity" || action === "fadeTo") {
269
+ const value = finiteNumber(params.value);
270
+ if (value === null || value < 0 || value > 1) {
271
+ errors.push(`page animation step ${stepNumber} action '${action}' needs value between 0 and 1`);
272
+ }
273
+ }
274
+ if (action.startsWith("fade") && params.delay !== undefined) {
275
+ const delay = finiteNumber(params.delay);
276
+ if (delay === null || delay < 0) {
277
+ errors.push(`page animation step ${stepNumber} action '${action}' has an invalid delay`);
278
+ }
279
+ }
280
+ }
281
+
282
+ function validateSequence(
283
+ sequence: NativeAnimationSequence,
284
+ cells: Map<string, DomEl>,
285
+ animatable: string[],
286
+ errors: string[],
287
+ warnings: string[],
288
+ ): void {
289
+ if (sequence.enabled && sequence.steps.length === 0) errors.push("enabled page animation must contain at least one step");
290
+ let hasPortableVisualAction = false;
291
+ for (let index = 0; index < sequence.steps.length; index++) {
292
+ const step = sequence.steps[index];
293
+ const stepNumber = index + 1;
294
+ if (step.immediate !== undefined && typeof step.immediate !== "boolean") {
295
+ errors.push(`page animation step ${stepNumber} immediate must be a boolean`);
296
+ }
297
+
298
+ const actions = Object.keys(step).filter((key) => key !== "immediate");
299
+ if (actions.length === 0) errors.push(`page animation step ${stepNumber} has no action`);
300
+ for (const action of actions) {
301
+ const portable = validateSequenceAction(action, step[action], stepNumber, cells, animatable, errors, warnings);
302
+ hasPortableVisualAction ||= portable;
303
+ }
304
+ }
305
+ if (sequence.enabled && sequence.steps.length > 0 && !hasPortableVisualAction) {
306
+ errors.push("enabled page animation must contain at least one portable visual action");
307
+ }
308
+ }
309
+
310
+ function validateSequenceAction(
311
+ action: string, raw: unknown, stepNumber: number, cells: Map<string, DomEl>,
312
+ animatable: string[], errors: string[], warnings: string[],
313
+ ): boolean {
314
+ if (action === "wait") {
315
+ const delay = finiteNumber(raw);
316
+ if (delay === null || delay < 0) errors.push(`page animation step ${stepNumber} wait must be a non-negative number`);
317
+ return false;
318
+ }
319
+ if (DRAWIO_ONLY_ACTIONS.has(action) || !PORTABLE_ACTIONS.has(action)) {
320
+ warnings.push(`page animation step ${stepNumber} action '${action}' is not supported in standalone animated SVG`);
321
+ return false;
322
+ }
323
+ if (!isObject(raw)) {
324
+ errors.push(`page animation step ${stepNumber} action '${action}' must be an object`);
325
+ return true;
326
+ }
327
+ selectorIds(raw, stepNumber, action, cells, animatable, errors, warnings);
328
+ validateActionParameters(action, raw, stepNumber, errors);
329
+ return true;
330
+ }
331
+
332
+ export function analyzeAnimationPage(diagram: DomEl): PageAnimationAnalysis {
333
+ const pageName = attr(diagram, "name") ?? "?";
334
+ const errors: string[] = [];
335
+ const warnings: string[] = [];
336
+ const observations: string[] = [];
337
+ const model = pageModel(diagram);
338
+ if (!model) {
339
+ errors.push("compressed or missing page model cannot be inspected for animation");
340
+ return {
341
+ pageName,
342
+ flowEdgeIds: [],
343
+ sequence: null,
344
+ cells: new Map(),
345
+ animatableCellIds: [],
346
+ errors,
347
+ warnings,
348
+ observations,
349
+ };
350
+ }
351
+
352
+ const cells = collectCells(firstByTag(model, "root"));
353
+ const { byId, animatable } = collectCellData(cells);
354
+ const flowEdgeIds: string[] = [];
355
+ validateFlowAnimations(cells, errors, flowEdgeIds);
356
+ const sequence = parseSequence(animationAttribute(model), errors, warnings);
357
+ if (sequence) validateSequence(sequence, byId, animatable, errors, warnings);
358
+
359
+ if (flowEdgeIds.length > 0) {
360
+ const connectorIds = flowEdgeIds.map((id) => "'" + id + "'").join(", ");
361
+ observations.push(
362
+ `${flowEdgeIds.length} connector(s) use persistent flow animation; SVG preserves it, static formats do not: ${connectorIds}`,
363
+ );
364
+ }
365
+ if (sequence) {
366
+ observations.push(
367
+ sequence.enabled
368
+ ? `page animation contains ${sequence.steps.length} step(s); standalone animated SVG supports visibility, opacity, fade, and wait actions`
369
+ : `page animation contains ${sequence.steps.length} step(s) but autoplay is disabled`,
370
+ );
371
+ }
372
+
373
+ return {
374
+ pageName,
375
+ flowEdgeIds,
376
+ sequence,
377
+ cells: byId,
378
+ animatableCellIds: animatable,
379
+ errors,
380
+ warnings,
381
+ observations,
382
+ };
383
+ }
384
+
385
+ export function analyzeDrawioAnimation(xml: string, pageIndex = 1): PageAnimationAnalysis {
386
+ if (!Number.isInteger(pageIndex) || pageIndex < 1) throw new Error("pageIndex must be a positive 1-based integer");
387
+ const doc = new DOMParser().parseFromString(xml, "text/xml");
388
+ const root = doc.documentElement as unknown as DomEl | null;
389
+ if (!root) throw new Error("no root element (malformed XML)");
390
+ const pageList = childrenByTag(root, "diagram");
391
+ const pages = pageList.length > 0 ? pageList : [root];
392
+ const page = pages[pageIndex - 1];
393
+ if (!page) throw new Error(`pageIndex ${pageIndex} is out of range (diagram has ${pages.length} page(s))`);
394
+ return analyzeAnimationPage(page);
395
+ }
396
+
397
+ function actionDuration(action: string, value: unknown): number {
398
+ if (action === "wait") return finiteNumber(value) ?? 0;
399
+ if (!action.startsWith("fade") || !isObject(value)) return 0;
400
+ return finiteNumber(value.delay) ?? DEFAULT_FADE_DURATION_MS;
401
+ }
402
+
403
+ function baseOpacity(cell: DomEl): number {
404
+ const raw = styleMap(attr(cell, "style")).get("opacity");
405
+ const opacity = raw === undefined ? 1 : Number(raw) / 100;
406
+ return Number.isFinite(opacity) ? Math.min(1, Math.max(0, opacity)) : 1;
407
+ }
408
+
409
+ function putPoint(points: OpacityPoint[], time: number, value: number): void {
410
+ const existing = points.find((point) => Math.abs(point.time - time) < 1e-9);
411
+ if (existing) existing.value = value;
412
+ else points.push({ time, value });
413
+ }
414
+
415
+ function putInstant(points: OpacityPoint[], time: number, before: number, after: number): void {
416
+ if (time > 0) putPoint(points, Math.max(0, time - INSTANT_EPSILON_MS), before);
417
+ putPoint(points, time, after);
418
+ }
419
+
420
+ function selectedIds(params: JsonObject, analysis: PageAnimationAnalysis): string[] {
421
+ const include = new Set<string>();
422
+ for (const value of params.cells as string[]) {
423
+ if (value === "*") for (const id of analysis.animatableCellIds) include.add(id);
424
+ else include.add(value);
425
+ }
426
+ for (const value of (params.excludeCells as string[] | undefined) ?? []) {
427
+ if (value === "*") include.clear();
428
+ else include.delete(value);
429
+ }
430
+ return [...include];
431
+ }
432
+
433
+ function compileOpacityTimeline(analysis: PageAnimationAnalysis): CompiledTimeline | null {
434
+ const sequence = analysis.sequence;
435
+ if (!sequence?.enabled || sequence.steps.length === 0) return null;
436
+
437
+ const states = new Map<string, number>();
438
+ const tracks = new Map<string, OpacityPoint[]>();
439
+ for (const id of analysis.animatableCellIds) {
440
+ const value = baseOpacity(analysis.cells.get(id)!);
441
+ states.set(id, value);
442
+ tracks.set(id, [{ time: 0, value }]);
443
+ }
444
+
445
+ let time = 0;
446
+ for (let index = 0; index < sequence.steps.length; ) {
447
+ const batch: JsonObject[] = [sequence.steps[index++]];
448
+ while (index < sequence.steps.length && sequence.steps[index].immediate === true) batch.push(sequence.steps[index++]);
449
+
450
+ time += compileOpacityBatch(batch, analysis, states, tracks, time);
451
+ }
452
+
453
+ const durationMs = Math.max(1, time);
454
+ const animated = [...tracks.entries()].filter(([, points]) => {
455
+ const values = new Set(points.map((point) => point.value));
456
+ return values.size > 1;
457
+ });
458
+ if (animated.length === 0) throw new Error("page animation has no visible opacity change to compile");
459
+
460
+ const reducedMotionRules: string[] = [];
461
+ const rules: string[] = [];
462
+ for (let index = 0; index < animated.length; index++) {
463
+ const [id, points] = animated[index];
464
+ putPoint(points, durationMs, states.get(id) ?? 1);
465
+ points.sort((a, b) => a.time - b.time);
466
+ const name = `drawme-opacity-${index + 1}`;
467
+ const selector = `g[data-cell-id=${cssString(id)}]`;
468
+ reducedMotionRules.push(
469
+ ` ${selector} { animation: none !important; opacity: ${baseOpacity(analysis.cells.get(id)!)} !important; }`,
470
+ );
471
+ const keyframes = points
472
+ .map((point) => ` ${((point.time / durationMs) * 100).toFixed(9)}% { opacity: ${point.value}; }`)
473
+ .join("\n");
474
+ rules.push(
475
+ `@keyframes ${name} {\n${keyframes}\n}`,
476
+ `${selector} { animation: ${name} ${durationMs}ms ease-in-out 0ms ${sequence.loop ? "infinite" : "1"} normal forwards; }`,
477
+ );
478
+ }
479
+ rules.push(
480
+ `@media (prefers-reduced-motion: reduce) {\n${reducedMotionRules.join("\n")}\n g[data-cell-id] * { animation: none !important; }\n}`,
481
+ );
482
+ return { css: rules.join("\n"), durationMs, animatedCellIds: animated.map(([id]) => id) };
483
+ }
484
+
485
+ function opacityEndpoints(action: string, params: JsonObject, current: number): [number, number] {
486
+ switch (action) {
487
+ case "opacity":
488
+ case "fadeTo": return [current, params.value as number];
489
+ case "show": return [current, 1];
490
+ case "hide": return [current, 0];
491
+ case "toggle": return [current, current > 0 ? 0 : 1];
492
+ case "fadeIn": return [0, 1];
493
+ case "fadeOut": return [1, 0];
494
+ default: return [current, current];
495
+ }
496
+ }
497
+
498
+ function compileOpacityAction(
499
+ action: string, params: JsonObject, id: string, states: Map<string, number>,
500
+ tracks: Map<string, OpacityPoint[]>, time: number,
501
+ ): number {
502
+ const current = states.get(id) ?? 1;
503
+ const points = tracks.get(id)!;
504
+ const [from, target] = opacityEndpoints(action, params, current);
505
+ const duration = actionDuration(action, params);
506
+ if (duration > 0) {
507
+ if (Math.abs(current - from) > 1e-9) putInstant(points, time, current, from);
508
+ else putPoint(points, time, from);
509
+ putPoint(points, time + duration, target);
510
+ } else {
511
+ putInstant(points, time, current, target);
512
+ }
513
+ return target;
514
+ }
515
+
516
+ function compileOpacityBatch(
517
+ batch: JsonObject[], analysis: PageAnimationAnalysis, states: Map<string, number>,
518
+ tracks: Map<string, OpacityPoint[]>, time: number,
519
+ ): number {
520
+ let duration = 0;
521
+ const touched = new Set<string>();
522
+ const updates = new Map<string, number>();
523
+ for (const [action, raw] of batch.flatMap((step) => Object.entries(step))) {
524
+ if (action === "immediate") continue;
525
+ duration = Math.max(duration, actionDuration(action, raw));
526
+ if (action === "wait") continue;
527
+ const params = raw as JsonObject;
528
+ for (const id of selectedIds(params, analysis)) {
529
+ if (touched.has(id)) {
530
+ throw new Error(`parallel animation actions target cell '${id}' more than once in the same batch`);
531
+ }
532
+ touched.add(id);
533
+ updates.set(id, compileOpacityAction(action, params, id, states, tracks, time));
534
+ }
535
+ }
536
+ for (const [id, value] of updates) states.set(id, value);
537
+ return duration;
538
+ }
539
+
540
+ function walkElements(root: DomEl): DomEl[] {
541
+ const elements: DomEl[] = [root];
542
+ for (const child of elemChildren(root)) elements.push(...walkElements(child));
543
+ return elements;
544
+ }
545
+
546
+ function hasAnimatedPath(root: DomEl): boolean {
547
+ return walkElements(root).some((element) => {
548
+ if (element.tagName !== "path") return false;
549
+ const style = attr(element, "style") ?? "";
550
+ return /(?:^|;)\s*animation\s*:/.test(style);
551
+ });
552
+ }
553
+
554
+ function verifyFlowGroups(ids: string[], groups: Map<string, DomEl>): void {
555
+ const missing = ids.filter((id) => !groups.has(id));
556
+ if (missing.length > 0) {
557
+ throw new Error(`SVG is missing animated connector group(s): ${missing.join(", ")}`);
558
+ }
559
+ const staticGroups = ids.filter((id) => !hasAnimatedPath(groups.get(id)!));
560
+ if (staticGroups.length > 0) {
561
+ throw new Error(`draw.io did not preserve flow animation for connector(s): ${staticGroups.join(", ")}`);
562
+ }
563
+ }
564
+
565
+ function verifyTimelineGroups(timeline: CompiledTimeline | null, groups: Map<string, DomEl>): void {
566
+ if (!timeline) return;
567
+ const missing = timeline.animatedCellIds.filter((id) => !groups.has(id));
568
+ if (missing.length > 0) {
569
+ throw new Error(
570
+ `SVG is missing page-animation cell group(s): ${missing.join(", ")}; do not use visible=0 for cells revealed by an animation`,
571
+ );
572
+ }
573
+ }
574
+
575
+ export async function enhanceAnimatedSvg(
576
+ input: string,
577
+ output: string,
578
+ pageIndex = 1,
579
+ ): Promise<AnimatedSvgSummary> {
580
+ const source = await readFile(input, "utf8");
581
+ const analysis = analyzeDrawioAnimation(source, pageIndex);
582
+ const blockers = [
583
+ ...analysis.errors,
584
+ ...(analysis.sequence?.enabled === false ? [] : analysis.warnings),
585
+ ];
586
+ if (blockers.length > 0) throw new Error(blockers.join("; "));
587
+ const activeSequence = analysis.sequence?.enabled === true && analysis.sequence.steps.length > 0;
588
+ if (analysis.flowEdgeIds.length === 0 && !activeSequence) {
589
+ throw new Error("the selected page has no enabled page sequence or connector with flowAnimation=1");
590
+ }
591
+
592
+ const svg = await readFile(output, "utf8");
593
+ const doc = new DOMParser().parseFromString(svg, "image/svg+xml");
594
+ const svgRoot = doc.documentElement as unknown as DomEl | null;
595
+ if (svgRoot?.tagName !== "svg") throw new Error("draw.io output is not valid SVG");
596
+
597
+ const groupElements = new Map(
598
+ walkElements(svgRoot)
599
+ .map((element) => [attr(element, "data-cell-id"), element] as const)
600
+ .filter((entry): entry is readonly [string, DomEl] => entry[0] !== null),
601
+ );
602
+ verifyFlowGroups(analysis.flowEdgeIds, groupElements);
603
+
604
+ const timeline = compileOpacityTimeline(analysis);
605
+ verifyTimelineGroups(timeline, groupElements);
606
+
607
+ const flowReducedMotion = analysis.flowEdgeIds.length > 0
608
+ ? `@media (prefers-reduced-motion: reduce) {\n${analysis.flowEdgeIds
609
+ .map((id) => ` g[data-cell-id=${cssString(id)}] * { animation: none !important; }`)
610
+ .join("\n")}\n}`
611
+ : "";
612
+ const injectedCss = [timeline?.css, flowReducedMotion].filter(Boolean).join("\n");
613
+ if (injectedCss) {
614
+ const documentNode = doc;
615
+ let defs = walkElements(svgRoot).find((element) => element.tagName === "defs");
616
+ if (!defs) {
617
+ defs = documentNode.createElementNS(SVG_NS, "defs") as unknown as DomEl;
618
+ const rootNode = svgRoot as unknown as { firstChild: unknown; insertBefore(node: unknown, before: unknown): void };
619
+ rootNode.insertBefore(defs, rootNode.firstChild);
620
+ }
621
+ const style = documentNode.createElementNS(SVG_NS, "style");
622
+ style.setAttribute("type", "text/css");
623
+ style.setAttribute("data-drawme-animation", timeline ? "opacity-timeline" : "reduced-motion"); // NOSONAR: xmldom XML elements have no browser dataset API.
624
+ style.appendChild(documentNode.createTextNode(injectedCss));
625
+ (defs as unknown as { appendChild(node: unknown): void }).appendChild(style);
626
+ await writeFile(output, new XMLSerializer().serializeToString(doc), "utf8");
627
+ }
628
+
629
+ return {
630
+ page: analysis.pageName,
631
+ connectorFlows: analysis.flowEdgeIds.length,
632
+ sequenceSteps: activeSequence ? analysis.sequence!.steps.length : 0,
633
+ sequenceDurationMs: timeline?.durationMs ?? 0,
634
+ sequenceCompiled: timeline !== null,
635
+ verified: analysis.flowEdgeIds.length > 0 || timeline !== null,
636
+ };
637
+ }