@senad-d/drawme 0.1.10 → 0.2.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/src/motion.ts CHANGED
@@ -7,8 +7,10 @@
7
7
  * so the motion can be reviewed as static images.
8
8
  */
9
9
  import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
10
- import { type DomEl, attr, childrenByTag, elemChildren, firstByTag } from "./dom";
11
- import { collectCellsWithIds } from "./geometry";
10
+ import { verifyFlowGroups } from "./animation";
11
+ import { type DomEl, attr, childrenByTag, elemChildren, firstByTag, graphModel } from "./dom";
12
+ import { collectCellsWithIds, isVisible, styleNum } from "./geometry";
13
+ import { cssString, walkElements } from "./svg-helpers";
12
14
 
13
15
  /** Attribute on the page root cell (`id="0"`) that stores the motion spec as JSON. */
14
16
  export const MOTION_ATTRIBUTE = "drawmeMotion";
@@ -104,6 +106,8 @@ export interface MotionCell {
104
106
  kind: "vertex" | "edge";
105
107
  style: string;
106
108
  parent: string | null;
109
+ /** Includes authored visibility inherited from non-animatable layers. */
110
+ visible?: boolean;
107
111
  }
108
112
 
109
113
  export interface MotionDot {
@@ -160,6 +164,12 @@ function styleValue(style: string, key: string): string | undefined {
160
164
  return undefined;
161
165
  }
162
166
 
167
+ /** Authored cell opacity before the DrawMe timeline takes control. */
168
+ export function authoredOpacity(style: string | null): number {
169
+ const percent = styleNum(style, "opacity") ?? 100;
170
+ return Number.isFinite(percent) ? Math.min(1, Math.max(0, percent / 100)) : 1;
171
+ }
172
+
163
173
  function transformValue(dx: number, dy: number, scale: number): string {
164
174
  return `translate(${dx}px, ${dy}px) scale(${scale})`;
165
175
  }
@@ -168,18 +178,6 @@ function round(value: number): number {
168
178
  return Math.round(value * 10_000) / 10_000;
169
179
  }
170
180
 
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
181
  function groupSelector(id: string): string {
184
182
  return `g[data-cell-id=${cssString(id)}]`;
185
183
  }
@@ -192,53 +190,81 @@ export function motionCells(model: DomEl): Map<string, MotionCell> {
192
190
  let kind: MotionCell["kind"] | null = null;
193
191
  if (cell.getAttribute("vertex") === "1") kind = "vertex";
194
192
  else if (cell.getAttribute("edge") === "1") kind = "edge";
195
- if (kind) result.set(id, { kind, style: attr(cell, "style") ?? "", parent: attr(cell, "parent") });
193
+ if (kind) result.set(id, {
194
+ kind, style: attr(cell, "style") ?? "", parent: attr(cell, "parent"), visible: isVisible(cell, ids),
195
+ });
196
196
  }
197
197
  return result;
198
198
  }
199
199
 
200
+ type AddMotionError = (render: () => string) => void;
201
+ type MotionFinding = (severity: "errors", render: () => string) => void;
202
+
203
+ function motionFindings(emit?: MotionFinding) {
204
+ const errors: string[] = [];
205
+ let failed = false;
206
+ return {
207
+ errors,
208
+ get failed() { return failed; },
209
+ addError(render: () => string) {
210
+ failed = true;
211
+ if (emit) emit("errors", render);
212
+ else errors.push(render());
213
+ },
214
+ };
215
+ }
216
+
200
217
  /** 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");
218
+ export function parseMotionSpec(
219
+ raw: unknown, errors: string[], overrides?: Pick<MotionSpec, "loop" | "hold">,
220
+ ): MotionSpec | null {
221
+ return parseSpec(raw, (render) => { errors.push(render()); }, overrides);
222
+ }
223
+
224
+ function parseSpec(raw: unknown, addError: AddMotionError, overrides?: Pick<MotionSpec, "loop" | "hold">): MotionSpec | null {
225
+ const original = isObject(raw) && isObject(raw.motion) ? raw.motion : raw;
226
+ if (!isObject(original)) {
227
+ addError(() => "motion spec must be an object with a steps array");
205
228
  return null;
206
229
  }
207
- if (!Array.isArray(value.steps) || value.steps.length === 0) {
208
- errors.push("motion spec must contain a non-empty steps array");
230
+ const rawSteps = original.steps;
231
+ const loop = overrides?.loop === undefined ? original.loop : overrides.loop;
232
+ const rawHold = overrides?.hold === undefined ? original.hold : overrides.hold;
233
+ if (!Array.isArray(rawSteps) || rawSteps.length === 0) {
234
+ addError(() => "motion spec must contain a non-empty steps array");
209
235
  return null;
210
236
  }
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`);
237
+ if (rawSteps.length > MAX_STEPS) addError(() => `motion spec has ${rawSteps.length} steps (maximum ${MAX_STEPS})`);
238
+ if (loop !== undefined && typeof loop !== "boolean") addError(() => "motion loop must be a boolean");
239
+ const hold = rawHold === undefined ? null : finite(rawHold);
240
+ if (rawHold !== undefined && (hold === null || hold < 0 || hold > MAX_DURATION_MS)) {
241
+ addError(() => `motion hold must be between 0 and ${MAX_DURATION_MS} ms`);
216
242
  }
217
243
 
218
244
  const steps: MotionStep[] = [];
219
- value.steps.forEach((raw: unknown, index: number) => {
245
+ rawSteps.forEach((raw: unknown, index: number) => {
220
246
  const n = index + 1;
221
247
  if (!isObject(raw)) {
222
- errors.push(`motion step ${n} must be an object`);
248
+ addError(() => `motion step ${n} must be an object`);
223
249
  return;
224
250
  }
225
251
  const effect = raw.effect;
226
252
  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(", ")})`);
253
+ addError(() => `motion step ${n} has unknown effect '${String(effect)}' (expected ${MOTION_EFFECTS.join(", ")})`);
228
254
  return;
229
255
  }
230
256
  const step: MotionStep = { effect: effect as MotionEffect };
231
- parseStepTiming(raw, step, n, errors);
257
+ parseStepTiming(raw, step, n, addError);
232
258
  if (raw.direction !== undefined) {
233
259
  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(", ")}`);
260
+ addError(() => `motion step ${n} direction must be one of ${SLIDE_DIRECTIONS.join(", ")}`);
235
261
  } else {
236
262
  step.direction = raw.direction as SlideDirection;
237
263
  }
238
264
  }
239
265
  if (raw.color !== undefined) {
240
266
  if (typeof raw.color !== "string" || !COLOR.test(raw.color)) {
241
- errors.push(`motion step ${n} color must be a hex color such as #2563eb`);
267
+ addError(() => `motion step ${n} color must be a hex color such as #2563eb`);
242
268
  } else {
243
269
  step.color = raw.color;
244
270
  }
@@ -246,16 +272,16 @@ export function parseMotionSpec(raw: unknown, errors: string[]): MotionSpec | nu
246
272
  steps.push(step);
247
273
  });
248
274
  return {
249
- ...(value.loop === undefined ? {} : { loop: value.loop === true }),
275
+ ...(loop === undefined ? {} : { loop: loop === true }),
250
276
  ...(hold === null ? {} : { hold }),
251
277
  steps,
252
278
  };
253
279
  }
254
280
 
255
- function parseStepTiming(raw: Record<string, unknown>, step: MotionStep, n: number, errors: string[]): void {
281
+ function parseStepTiming(raw: Record<string, unknown>, step: MotionStep, n: number, addError: AddMotionError): void {
256
282
  if (raw.cells !== undefined) {
257
283
  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`);
284
+ addError(() => `motion step ${n} cells must be an array of cell ids`);
259
285
  } else {
260
286
  step.cells = raw.cells as string[];
261
287
  }
@@ -263,11 +289,11 @@ function parseStepTiming(raw: Record<string, unknown>, step: MotionStep, n: numb
263
289
  for (const key of ["duration", "stagger", "value"] as const) {
264
290
  if (raw[key] === undefined) continue;
265
291
  const number = finite(raw[key]);
266
- if (number === null) errors.push(`motion step ${n} ${key} must be a number`);
292
+ if (number === null) addError(() => `motion step ${n} ${key} must be a number`);
267
293
  else step[key] = number;
268
294
  }
269
295
  if (raw.parallel !== undefined) {
270
- if (typeof raw.parallel !== "boolean") errors.push(`motion step ${n} parallel must be a boolean`);
296
+ if (typeof raw.parallel !== "boolean") addError(() => `motion step ${n} parallel must be a boolean`);
271
297
  else step.parallel = raw.parallel;
272
298
  }
273
299
  }
@@ -338,7 +364,7 @@ interface ResolvedStep {
338
364
  function resolveSteps(
339
365
  spec: MotionSpec,
340
366
  cells: Map<string, MotionCell>,
341
- errors: string[],
367
+ addError: AddMotionError,
342
368
  accent: string,
343
369
  ): ResolvedStep[] {
344
370
  const resolved: ResolvedStep[] = [];
@@ -346,16 +372,16 @@ function resolveSteps(
346
372
  const number = index + 1;
347
373
  const where = `motion step ${number} (${step.effect})`;
348
374
  const duration = step.duration ?? (step.effect === "wait" ? null : DEFAULT_DURATION[step.effect]);
349
- if (duration === null) errors.push(`${where} needs a duration in ms`);
375
+ if (duration === null) addError(() => `${where} needs a duration in ms`);
350
376
  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`);
377
+ addError(() => `${where} duration must be between ${step.effect === "wait" ? 0 : 1} and ${MAX_DURATION_MS} ms`);
352
378
  }
353
379
  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`);
380
+ if (stagger < 0 || stagger > MAX_DURATION_MS) addError(() => `${where} stagger must be between 0 and ${MAX_DURATION_MS} ms`);
381
+ if (step.parallel && index === 0) addError(() => `${where} cannot be parallel: there is no previous step`);
356
382
  const ids = step.cells ?? [];
357
- validateStepOptions(step, ids, where, errors);
358
- validateStepCells(step, ids, cells, where, errors);
383
+ validateStepOptions(step, ids, where, addError);
384
+ validateStepCells(step, ids, cells, where, addError);
359
385
  resolved.push({
360
386
  number,
361
387
  effect: step.effect,
@@ -371,38 +397,39 @@ function resolveSteps(
371
397
  return resolved;
372
398
  }
373
399
 
374
- function validateStepOptions(step: MotionStep, ids: string[], where: string, errors: string[]): void {
400
+ function validateStepOptions(step: MotionStep, ids: string[], where: string, addError: AddMotionError): void {
375
401
  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`);
402
+ addError(() => `${where} value is only valid for dim and must be between 0 and 1`);
377
403
  }
378
- if (step.direction !== undefined && step.effect !== "slideIn") errors.push(`${where} direction is only valid for slideIn`);
404
+ if (step.direction !== undefined && step.effect !== "slideIn") addError(() => `${where} direction is only valid for slideIn`);
379
405
  if (step.color !== undefined && step.effect !== "highlight" && step.effect !== "travel") {
380
- errors.push(`${where} color is only valid for highlight and travel`);
406
+ addError(() => `${where} color is only valid for highlight and travel`);
381
407
  }
382
408
  if (step.effect === "wait") {
383
- if (ids.length > 0) errors.push(`${where} must not list cells`);
409
+ if (ids.length > 0) addError(() => `${where} must not list cells`);
384
410
  } else if (ids.length === 0) {
385
- errors.push(`${where} must list at least one cell id`);
411
+ addError(() => `${where} must list at least one cell id`);
386
412
  }
387
- if (new Set(ids).size !== ids.length) errors.push(`${where} lists a cell more than once`);
413
+ if (new Set(ids).size !== ids.length) addError(() => `${where} lists a cell more than once`);
388
414
  }
389
415
 
390
416
  function validateStepCells(
391
- step: MotionStep, ids: string[], cells: Map<string, MotionCell>, where: string, errors: string[],
417
+ step: MotionStep, ids: string[], cells: Map<string, MotionCell>, where: string, addError: AddMotionError,
392
418
  ): void {
393
419
  for (const id of ids) {
394
420
  const cell = cells.get(id);
395
421
  if (!cell) {
396
- errors.push(`${where} references missing cell '${id}'`);
422
+ addError(() => `${where} references missing cell '${id}'`);
397
423
  continue;
398
424
  }
399
- if (EDGE_ONLY.has(step.effect) && cell.kind !== "edge") errors.push(`${where} needs a connector, but '${id}' is a shape`);
425
+ if (cell.visible === false) addError(() => `${where} targets '${id}', hidden in the authored page; remove visible=0 from the cell or its ancestors`);
426
+ if (EDGE_ONLY.has(step.effect) && cell.kind !== "edge") addError(() => `${where} needs a connector, but '${id}' is a shape`);
400
427
  if (step.effect !== "drawIn" || cell.kind !== "edge") continue;
401
428
  if (styleValue(cell.style, "dashed") === "1") {
402
- errors.push(`${where} cannot draw dashed connector '${id}'; use fadeIn or make it solid`);
429
+ addError(() => `${where} cannot draw dashed connector '${id}'; use fadeIn or make it solid`);
403
430
  }
404
431
  if (styleValue(cell.style, "flowAnimation") === "1") {
405
- errors.push(`${where} cannot draw connector '${id}' because it uses flowAnimation=1; use fadeIn`);
432
+ addError(() => `${where} cannot draw connector '${id}' because it uses flowAnimation=1; use fadeIn`);
406
433
  }
407
434
  }
408
435
  }
@@ -450,120 +477,185 @@ function keyframes(name: string, property: string, track: Track, total: number):
450
477
  return `@keyframes ${name} {\n${lines.join("\n")}\n}`;
451
478
  }
452
479
 
480
+ interface MotionEvent {
481
+ step: ResolvedStep;
482
+ start: number;
483
+ opacity: number;
484
+ }
485
+
486
+ function opacityChange(event: MotionEvent): { to: number; end: number } {
487
+ const { step, start, opacity } = event;
488
+ switch (step.effect) {
489
+ case "drawIn": return { to: 1, end: start };
490
+ case "popIn": return { to: 1, end: start + step.duration * 0.6 };
491
+ case "fadeIn":
492
+ case "slideIn": return { to: 1, end: start + step.duration };
493
+ case "fadeOut": return { to: 0, end: start + step.duration };
494
+ case "dim": return { to: step.value, end: start + step.duration };
495
+ default: return { to: opacity, end: start };
496
+ }
497
+ }
498
+
499
+ function parentVisibility(
500
+ id: string, cells: Map<string, MotionCell>, events: Map<string, MotionEvent>, tracks: Map<string, CellTracks>,
501
+ ): { after: number; until: number; openStart: boolean } {
502
+ let after = -Infinity;
503
+ let until = Infinity;
504
+ let openStart = false;
505
+ const seen = new Set([id]);
506
+ for (let parent = cells.get(id)?.parent; parent && !seen.has(parent); parent = cells.get(parent)?.parent) {
507
+ seen.add(parent);
508
+ const event = events.get(parent);
509
+ const initial = event?.opacity ?? (tracks.get(parent)?.opacity.current as number | undefined)
510
+ ?? authoredOpacity(cells.get(parent)?.style ?? null);
511
+ const change = event && opacityChange(event);
512
+ const final = change?.to ?? initial;
513
+ if (initial === 0 && final === 0) return { after: Infinity, until: -Infinity, openStart: true };
514
+ if (event && change && initial === 0 && event.start >= after) {
515
+ openStart = (event.start === after && openStart) || change.end > event.start;
516
+ after = event.start;
517
+ }
518
+ if (initial > 0 && final === 0 && change) until = Math.min(until, change.end);
519
+ }
520
+ return { after, until, openStart };
521
+ }
522
+
523
+ function batchEvents(batch: ResolvedStep[], time: number, tracks: Map<string, CellTracks>, addError: AddMotionError) {
524
+ const events = new Map<string, MotionEvent>();
525
+ let span = 0;
526
+ for (const step of batch) {
527
+ span = Math.max(span, step.duration + step.stagger * Math.max(0, step.cells.length - 1));
528
+ step.cells.forEach((id, order) => {
529
+ if (events.has(id)) addError(() => `motion step ${step.number} (${step.effect}) targets '${id}' again in the same parallel group`);
530
+ else events.set(id, { step, start: time + step.stagger * order, opacity: tracks.get(id)!.opacity.current as number });
531
+ });
532
+ }
533
+ return { events, span };
534
+ }
535
+
536
+ function visualEvent(id: string, event: MotionEvent, parents: ReturnType<typeof parentVisibility>, addError: AddMotionError): boolean | null {
537
+ const { step, start, opacity } = event;
538
+ const where = () => `motion step ${step.number} (${step.effect})`;
539
+ if (ENTRANCES.has(step.effect) && (step.effect === "fadeIn" ? opacity === 1 : opacity > 0)) {
540
+ addError(() => `${where()} targets '${id}', which is already visible; fade it out first or use highlight`);
541
+ return null;
542
+ }
543
+ const emphasis = step.effect === "highlight" || step.effect === "travel";
544
+ if (emphasis && opacity === 0) {
545
+ addError(() => `${where()} targets '${id}', which is hidden at that point; reveal it first`);
546
+ return null;
547
+ }
548
+ if (emphasis && (start < parents.after || (start === parents.after && parents.openStart) || start >= parents.until)) {
549
+ addError(() => `${where()} targets '${id}', hidden by an ancestor at that point; reveal the container first`);
550
+ return null;
551
+ }
552
+ const change = opacityChange(event);
553
+ const otherTrack = emphasis || step.effect === "popIn" || step.effect === "slideIn" || step.effect === "drawIn";
554
+ const end = otherTrack ? start + step.duration : change.end;
555
+ return (otherTrack || round(opacity) !== round(change.to)) && Math.max(start, parents.after) < Math.min(end, parents.until);
556
+ }
557
+
453
558
  /** Validate a spec against the page and compile it to CSS, SMIL dots, and storyboard frames. */
454
559
  export function compileMotion(
455
560
  spec: MotionSpec,
456
561
  cells: Map<string, MotionCell>,
457
562
  accent: string = DEFAULT_ACCENT,
458
563
  ): MotionAnalysis {
459
- const errors: string[] = [];
460
- const steps = resolveSteps(spec, cells, errors, accent);
461
- if (errors.length > 0) return { spec, compiled: null, errors };
564
+ return compileTimeline(spec, cells, accent, motionFindings());
565
+ }
462
566
 
463
- // A cell whose first effect is an entrance starts hidden; everything else starts visible.
464
- const firstEffect = firstCellEffects(steps);
567
+ function compileTimeline(
568
+ spec: MotionSpec, cells: Map<string, MotionCell>, accent: string, findings: ReturnType<typeof motionFindings>,
569
+ ): MotionAnalysis {
570
+ const { errors, addError } = findings;
571
+ const steps = resolveSteps(spec, cells, addError, accent);
572
+ if (findings.failed) return { spec, compiled: null, errors };
465
573
 
574
+ // A first entrance starts hidden; other effects start from the authored opacity.
466
575
  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);
576
+ for (const [id, firstEffect] of firstCellEffects(steps)) {
577
+ const opacity = ENTRANCES.has(firstEffect) ? 0 : authoredOpacity(cells.get(id)!.style);
578
+ tracks.set(id, { opacity: new Track(opacity) });
579
+ }
476
580
 
477
581
  const dots: MotionDot[] = [];
478
582
  const frames: MotionFrame[] = [];
479
583
  const drawInEdges = new Set<string>();
480
584
  let time = 0;
481
585
  for (const batch of batches(steps)) {
482
- const touched = new Set<string>();
586
+ const { events, span } = batchEvents(batch, time, tracks, addError);
587
+ let visual = false;
588
+ const invalid = new Set<string>();
589
+ // Evaluate the whole batch against its starting state before mutating any track.
590
+ for (const [id, event] of events) {
591
+ const outcome = visualEvent(id, event, parentVisibility(id, cells, events, tracks), addError);
592
+ if (outcome === null) invalid.add(id);
593
+ else if (outcome) visual = true;
594
+ }
483
595
  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;
596
+ for (const [id, { step, start: s }] of events) {
597
+ if (invalid.has(id)) continue;
598
+ const cell = tracks.get(id)!;
599
+ const d = step.duration;
600
+ switch (step.effect) {
601
+ case "fadeIn":
602
+ cell.opacity.tween(s, s + d, cell.opacity.current, 1, EASE.out);
603
+ break;
604
+ case "fadeOut":
605
+ cell.opacity.tween(s, s + d, cell.opacity.current, 0, EASE.in);
606
+ break;
607
+ case "dim":
608
+ cell.opacity.tween(s, s + d, cell.opacity.current, step.value, EASE.inOut);
609
+ break;
610
+ case "popIn":
611
+ cell.transform ??= new Track(IDENTITY);
612
+ cell.opacity.tween(s, s + d * 0.6, 0, 1, EASE.out);
613
+ cell.transform.tween(s, s + d, transformValue(0, 0, 0.6), IDENTITY, EASE.back);
614
+ break;
615
+ case "slideIn": {
616
+ const [dx, dy] = slideOffset(step.direction);
617
+ cell.transform ??= new Track(IDENTITY);
618
+ cell.opacity.tween(s, s + d, 0, 1, EASE.out);
619
+ cell.transform.tween(s, s + d, transformValue(dx, dy, 1), IDENTITY, EASE.out);
620
+ break;
505
621
  }
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":
622
+ case "drawIn":
623
+ cell.line ??= new Track(1);
624
+ cell.decor ??= new Track(0);
625
+ drawInEdges.add(id);
626
+ cell.opacity.jump(s, 1);
627
+ cell.line.tween(s, s + d * 0.8, 1, 0, EASE.inOut);
628
+ cell.decor.tween(s + d * 0.7, s + d, 0, 1, EASE.out);
629
+ break;
630
+ case "highlight": {
631
+ const glow = `drop-shadow(0px 0px 12px ${step.color})`;
632
+ cell.filter ??= new Track(NO_GLOW);
633
+ cell.filter.tween(s, s + d * 0.4, NO_GLOW, glow, EASE.out);
634
+ cell.filter.tween(s + d * 0.4, s + d, glow, NO_GLOW, EASE.inOut);
635
+ if (cells.get(id)!.kind === "vertex") {
517
636
  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;
637
+ cell.transform.tween(s, s + d * 0.4, IDENTITY, transformValue(0, 0, 1.04), EASE.out);
638
+ cell.transform.tween(s + d * 0.4, s + d, transformValue(0, 0, 1.04), IDENTITY, EASE.inOut);
548
639
  }
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;
640
+ accent.set(id, step.color);
641
+ break;
555
642
  }
556
- });
643
+ case "travel":
644
+ dots.push({ cellId: id, start: s, duration: d, color: step.color });
645
+ accent.set(id, step.color);
646
+ break;
647
+ }
557
648
  }
558
649
  time += span;
559
- if (batch.some((step) => step.effect !== "wait")) {
650
+ if (visual) {
560
651
  const opacity = new Map<string, number>();
561
652
  for (const [id, cell] of tracks) opacity.set(id, cell.opacity.current as number);
562
653
  frames.push({ time, label: frameLabel(batch), opacity, accent });
563
654
  }
564
655
  }
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 };
656
+ if (time > MAX_TOTAL_MS) addError(() => `motion sequence lasts ${Math.round(time)} ms (maximum ${MAX_TOTAL_MS} ms)`);
657
+ if (frames.length === 0) addError(() => "motion sequence has no effective visual change");
658
+ if (findings.failed) return { spec, compiled: null, errors };
567
659
 
568
660
  const loop = spec.loop ?? true;
569
661
  const sequenceMs = Math.max(1, time);
@@ -689,25 +781,26 @@ export function selectPage(root: DomEl, pageIndex = 1): { diagram: DomEl; model:
689
781
  const pages = pageList.length > 0 ? pageList : [root];
690
782
  const diagram = pages[pageIndex - 1];
691
783
  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");
784
+ const model = graphModel(diagram);
693
785
  if (!model) throw new Error("compressed or missing page model cannot be animated; save the diagram uncompressed");
694
786
  return { diagram, model, name: attr(diagram, "name") ?? "?" };
695
787
  }
696
788
 
697
- /** Parse and compile the motion stored on a page; null when none is stored. */
698
- export function analyzeStoredMotion(model: DomEl): MotionAnalysis | null {
789
+ /** Parse and compile stored motion. With a sink, emit each error synchronously instead of returning it. */
790
+ export function analyzeStoredMotion(model: DomEl, emit?: MotionFinding): MotionAnalysis | null {
699
791
  const raw = readStoredMotion(model);
700
792
  if (raw === null || raw.trim() === "") return null;
701
- const errors: string[] = [];
793
+ const findings = motionFindings(emit);
702
794
  let parsed: unknown;
703
795
  try {
704
796
  parsed = JSON.parse(raw);
705
797
  } catch (error) {
706
- return { spec: null, compiled: null, errors: [`stored motion contains malformed JSON: ${(error as Error).message}`] };
798
+ findings.addError(() => `stored motion contains malformed JSON: ${(error as Error).message}`);
799
+ return { spec: null, compiled: null, errors: findings.errors };
707
800
  }
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));
801
+ const spec = parseSpec(parsed, findings.addError);
802
+ if (!spec || findings.failed) return { spec, compiled: null, errors: findings.errors };
803
+ return compileTimeline(spec, motionCells(model), themeAccent(model), findings);
711
804
  }
712
805
 
713
806
  /** Default motion accent for a page: the Dark preset accent on a dark background, else the Light one. */
@@ -717,14 +810,8 @@ export function themeAccent(model: DomEl): string {
717
810
 
718
811
  // --- SVG injection ---
719
812
 
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
813
  function linePath(group: DomEl): DomEl | null {
727
- return walk(group).find((element) => element.tagName === "path" && attr(element, "fill") === "none") ?? null;
814
+ return walkElements(group).find((element) => element.tagName === "path" && attr(element, "fill") === "none") ?? null;
728
815
  }
729
816
 
730
817
  type Parented = DomEl & { parentNode: Parented | null };
@@ -781,7 +868,7 @@ function appendDot(doc: XmlDocument, group: DomEl, path: string, dot: MotionDot,
781
868
 
782
869
  function motionSvgGroups(root: DomEl): Map<string, DomEl> {
783
870
  const groups = new Map<string, DomEl>();
784
- for (const element of walk(root)) {
871
+ for (const element of walkElements(root)) {
785
872
  const id = attr(element, "data-cell-id");
786
873
  if (id !== null && !groups.has(id)) groups.set(id, element);
787
874
  }
@@ -789,9 +876,9 @@ function motionSvgGroups(root: DomEl): Map<string, DomEl> {
789
876
  }
790
877
 
791
878
  /**
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.
879
+ * Inject compiled motion into a draw.io SVG string. Throws when targeted
880
+ * cells or connector lines are missing, or the renderer did not preserve
881
+ * a declared connector flow.
795
882
  */
796
883
  export function injectMotion(svg: string, motion: CompiledMotion, flowEdgeIds: string[] = []): string {
797
884
  const doc = new DOMParser().parseFromString(svg, "image/svg+xml");
@@ -802,6 +889,7 @@ export function injectMotion(svg: string, motion: CompiledMotion, flowEdgeIds: s
802
889
  if (missing.length > 0) {
803
890
  throw new Error(`SVG is missing animated cell group(s): ${missing.join(", ")}; do not use visible=0 on animated cells`);
804
891
  }
892
+ verifyFlowGroups(flowEdgeIds, groups);
805
893
 
806
894
  for (const id of motion.drawInEdgeIds) {
807
895
  const group = groups.get(id)!;
@@ -824,7 +912,7 @@ export function injectMotion(svg: string, motion: CompiledMotion, flowEdgeIds: s
824
912
  .map((id) => ` ${groupSelector(id)} * { animation: none !important; }`)
825
913
  .join("\n")}\n}`
826
914
  : "";
827
- let defs = walk(svgRoot).find((element) => element.tagName === "defs");
915
+ let defs = walkElements(svgRoot).find((element) => element.tagName === "defs");
828
916
  if (!defs) {
829
917
  defs = doc.createElementNS(SVG_NS, "defs") as unknown as DomEl;
830
918
  const rootNode = svgRoot as unknown as { firstChild: unknown; insertBefore(node: unknown, before: unknown): void };