@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.
package/src/animate.ts ADDED
@@ -0,0 +1,177 @@
1
+ /**
2
+ * `drawio_animate` orchestration: validate a typed motion spec against a page,
3
+ * store it on the page root cell, export the page to SVG with the draw.io CLI,
4
+ * inject the compiled motion, and render a storyboard PNG for review.
5
+ */
6
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
7
+ import { existsSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { basename, dirname, extname, join } from "node:path";
10
+ import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
11
+ import type { DomEl } from "./dom";
12
+ import { analyzeDrawioAnimation } from "./animation";
13
+ import { exportDiagram } from "./drawio";
14
+ import {
15
+ type MotionSpec,
16
+ compileMotion,
17
+ injectMotion,
18
+ motionCells,
19
+ parseMotionSpec,
20
+ readStoredMotion,
21
+ selectPage,
22
+ storeMotion,
23
+ themeAccent,
24
+ } from "./motion";
25
+ import { buildStoryboard, sampleFrames } from "./storyboard";
26
+
27
+ export interface AnimateOptions {
28
+ input: string;
29
+ /** New motion steps. Omit to re-export the motion already stored on the page. */
30
+ steps?: unknown[];
31
+ loop?: boolean;
32
+ hold?: number;
33
+ pageIndex?: number;
34
+ output?: string;
35
+ /** Render a storyboard PNG of the step end states (default true). */
36
+ storyboard?: boolean;
37
+ binary?: string;
38
+ }
39
+
40
+ export interface AnimateResult {
41
+ source: string;
42
+ /** True when the motion spec was written into the source file. */
43
+ saved: boolean;
44
+ page: string;
45
+ output: string;
46
+ steps: number;
47
+ loop: boolean;
48
+ sequenceMs: number;
49
+ durationMs: number;
50
+ animatedCells: number;
51
+ drawnConnectors: number;
52
+ travellingDots: number;
53
+ connectorFlows: number;
54
+ storyboard?: string;
55
+ storyboardFrames?: number;
56
+ storyboardFramesTotal?: number;
57
+ binary: string;
58
+ version?: string;
59
+ }
60
+
61
+ function stem(path: string): string {
62
+ const ext = extname(path);
63
+ return join(dirname(path), ext ? basename(path).slice(0, -ext.length) : basename(path));
64
+ }
65
+
66
+ function serialize(original: string, doc: unknown): string {
67
+ let serialized = new XMLSerializer().serializeToString(doc as never);
68
+ const declaration = /^<\?xml[^>]*\?>/.exec(original)?.[0];
69
+ if (declaration && !serialized.startsWith("<?xml")) serialized = `${declaration}\n${serialized}`;
70
+ if (original.endsWith("\n") && !serialized.endsWith("\n")) serialized += "\n";
71
+ return serialized;
72
+ }
73
+
74
+ function resolveSpec(opts: AnimateOptions, model: DomEl): { spec: MotionSpec; changed: boolean } {
75
+ const errors: string[] = [];
76
+ let spec: MotionSpec | null;
77
+ const stored = readStoredMotion(model);
78
+ if (opts.steps !== undefined) {
79
+ spec = parseMotionSpec({ loop: opts.loop, hold: opts.hold, steps: opts.steps }, errors);
80
+ } else {
81
+ if (stored === null || stored.trim() === "") {
82
+ throw new Error("the page has no stored motion; pass steps to define one");
83
+ }
84
+ let parsed: unknown;
85
+ try {
86
+ parsed = JSON.parse(stored);
87
+ } catch (error) {
88
+ throw new Error(`stored motion contains malformed JSON: ${(error as Error).message}`, { cause: error });
89
+ }
90
+ spec = parseMotionSpec(parsed, errors);
91
+ if (spec && opts.loop !== undefined) spec.loop = opts.loop;
92
+ if (spec && opts.hold !== undefined) spec.hold = opts.hold;
93
+ }
94
+ if (!spec || errors.length > 0) throw new Error(errors.join("; ") || "motion specification is invalid");
95
+ return { spec, changed: JSON.stringify(spec) !== stored };
96
+ }
97
+
98
+ /** Validate, store, export, and verify motion for one page. Throws on any failure. */
99
+ export async function animateDiagram(opts: AnimateOptions): Promise<AnimateResult> {
100
+ if (!existsSync(opts.input)) throw new Error(`input file not found: ${opts.input}`);
101
+ const pageIndex = opts.pageIndex ?? 1;
102
+ const xml = await readFile(opts.input, "utf8");
103
+ const doc = new DOMParser().parseFromString(xml, "text/xml");
104
+ const root = doc.documentElement as unknown as DomEl | null;
105
+ if (!root) throw new Error("no root element (malformed XML)");
106
+ const { model, name } = selectPage(root, pageIndex);
107
+
108
+ // Analyze native animation on its own parse: cell collection rewrites wrapper ids in the DOM it reads.
109
+ const native = analyzeDrawioAnimation(xml, pageIndex);
110
+ if (native.errors.length > 0) throw new Error(native.errors.join("; "));
111
+ if (native.sequence?.enabled) {
112
+ throw new Error(
113
+ "the page already has a native draw.io page animation; remove its animation attribute (or set enabled:false) so the motion steps are the only timeline",
114
+ );
115
+ }
116
+
117
+ const { spec, changed } = resolveSpec(opts, model);
118
+ const analysis = compileMotion(spec, motionCells(model), themeAccent(model));
119
+ if (!analysis.compiled) throw new Error(analysis.errors.join("; "));
120
+ const motion = analysis.compiled;
121
+
122
+ if (changed) {
123
+ storeMotion(model, JSON.stringify(spec));
124
+ await writeFile(opts.input, serialize(xml, doc), "utf8");
125
+ }
126
+
127
+ const output = opts.output ?? `${stem(opts.input)}.animated.svg`;
128
+ const exported = await exportDiagram({ input: opts.input, format: "svg", mode: "final", output, pageIndex, binary: opts.binary });
129
+ try {
130
+ const svg = await readFile(output, "utf8");
131
+ await writeFile(output, injectMotion(svg, motion, native.flowEdgeIds), "utf8");
132
+ } catch (error) {
133
+ await rm(output, { force: true });
134
+ throw new Error(`animated SVG verification failed: ${(error as Error).message}`, { cause: error });
135
+ }
136
+
137
+ const result: AnimateResult = {
138
+ source: opts.input,
139
+ saved: changed,
140
+ page: name,
141
+ output,
142
+ steps: spec.steps.length,
143
+ loop: motion.loop,
144
+ sequenceMs: Math.round(motion.sequenceMs),
145
+ durationMs: Math.round(motion.durationMs),
146
+ animatedCells: motion.targetCellIds.length,
147
+ drawnConnectors: motion.drawInEdgeIds.length,
148
+ travellingDots: motion.dots.length,
149
+ connectorFlows: native.flowEdgeIds.length,
150
+ binary: exported.binary,
151
+ version: exported.version,
152
+ };
153
+
154
+ if (opts.storyboard ?? true) {
155
+ const frames = sampleFrames(motion.frames);
156
+ const tempDir = await mkdtemp(join(tmpdir(), "drawme-storyboard-"));
157
+ try {
158
+ const boardSource = join(tempDir, "storyboard.drawio");
159
+ await writeFile(boardSource, buildStoryboard(model, frames), "utf8");
160
+ const board = await exportDiagram({
161
+ input: boardSource,
162
+ format: "png",
163
+ mode: "final",
164
+ embed: false,
165
+ width: 2000,
166
+ output: `${stem(opts.input)}.storyboard.png`,
167
+ binary: opts.binary,
168
+ });
169
+ result.storyboard = board.output;
170
+ result.storyboardFrames = frames.length;
171
+ result.storyboardFramesTotal = motion.frames.length;
172
+ } finally {
173
+ await rm(tempDir, { recursive: true, force: true });
174
+ }
175
+ }
176
+ return result;
177
+ }