@senad-d/drawme 0.1.8 → 0.1.10

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/drawio.ts CHANGED
@@ -4,12 +4,18 @@
4
4
  * `-e` PNG IEND repair, page indexing, and headless-Linux handling so callers never
5
5
  * hand-build a draw.io command line.
6
6
  */
7
- import { execFile } from "node:child_process";
7
+ import { spawn } from "node:child_process";
8
8
  import { existsSync, realpathSync } from "node:fs";
9
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
9
+ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
10
10
  import { basename, dirname, extname, join, resolve } from "node:path";
11
11
  import { platform, tmpdir } from "node:os";
12
12
  import { repairPng } from "./png";
13
+ import { enhanceAnimatedSvg, type AnimatedSvgSummary } from "./animation";
14
+ import { DEFAULT_FIT_MARGIN } from "./fitcanvas";
15
+ import { DOMParser } from "@xmldom/xmldom";
16
+ import { type DomEl, childrenByTag, firstByTag } from "./dom";
17
+ import { collectCellsWithIds, contentBounds } from "./geometry";
18
+ import { finishSvgFile } from "./svgexport";
13
19
 
14
20
  export type ExportFormat = "png" | "svg" | "pdf" | "jpg";
15
21
  export type ExportMode = "preview" | "final";
@@ -36,6 +42,8 @@ export interface ExportOptions {
36
42
  border?: number;
37
43
  pageIndex?: number;
38
44
  embed?: boolean;
45
+ /** Require and verify animation in a final SVG, compiling portable page sequences when present. */
46
+ animated?: boolean;
39
47
  binary?: string;
40
48
  }
41
49
 
@@ -43,12 +51,15 @@ export interface ExportPlan {
43
51
  format: ExportFormat;
44
52
  mode: ExportMode;
45
53
  embed: boolean;
54
+ animated: boolean;
46
55
  output: string;
47
56
  /** Export flags ending with `-o <output>`. The input path is appended after these. */
48
57
  args: string[];
49
58
  input: string;
50
59
  /** Flags that must go AFTER the input path on Linux (draw.io argument-parsing quirk). */
51
60
  linuxExtra: string[];
61
+ /** SVG only: outer margin DrawMe adds after export (draw.io's own SVG border is uneven). */
62
+ svgMargin: number;
52
63
  }
53
64
 
54
65
  /** Candidate binary names and paths in resolution order. */
@@ -61,20 +72,57 @@ const CANDIDATES = [
61
72
  "/mnt/c/Program Files/draw.io/draw.io.exe", // WSL2
62
73
  ];
63
74
 
64
- function run(bin: string, args: string[], timeout = 120_000): Promise<{ stdout: string; stderr: string }> {
75
+ /**
76
+ * Run a command and collect its output. Off Windows the child leads its own process
77
+ * group, so a timeout ends the whole tree (xvfb-run, Xvfb, Electron), not only the
78
+ * direct child: SIGTERM first so xvfb-run can clean up, SIGKILL after a grace period.
79
+ */
80
+ export function run(bin: string, args: string[], timeout = 120_000): Promise<{ stdout: string; stderr: string }> {
65
81
  return new Promise((resolve, reject) => {
66
- execFile(bin, args, { timeout, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {
67
- if (err) {
68
- (err as NodeJS.ErrnoException & { stderr?: string }).stderr = stderr?.toString();
69
- const reason = err instanceof Error ? err : new Error("draw.io process failed with an unknown error");
70
- reject(reason);
71
- } else {
72
- resolve({ stdout: stdout.toString(), stderr: stderr?.toString() ?? "" });
82
+ const group = platform() !== "win32";
83
+ const child = spawn(bin, args, { detached: group, stdio: ["ignore", "pipe", "pipe"] });
84
+ let stdout = "";
85
+ let stderr = "";
86
+ let timedOut = false;
87
+ let killTimer: NodeJS.Timeout | undefined;
88
+ child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString()));
89
+ child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString()));
90
+ const timer = setTimeout(() => {
91
+ timedOut = true;
92
+ killTree(child.pid, group, "SIGTERM");
93
+ killTimer = setTimeout(() => killTree(child.pid, group, "SIGKILL"), 5_000);
94
+ }, timeout);
95
+ child.on("error", (err) => {
96
+ clearTimeout(timer);
97
+ reject(Object.assign(err, { stderr }));
98
+ });
99
+ child.on("close", (code, signal) => {
100
+ clearTimeout(timer);
101
+ if (timedOut) {
102
+ // Reap anything in the group that ignored SIGTERM.
103
+ clearTimeout(killTimer);
104
+ killTree(child.pid, group, "SIGKILL");
105
+ }
106
+ if (code === 0 && !timedOut) {
107
+ resolve({ stdout, stderr });
108
+ return;
73
109
  }
110
+ const exitReason = signal ?? `code ${code}`;
111
+ const why = timedOut ? `timed out after ${timeout / 1000}s` : `exited with ${exitReason}`;
112
+ reject(Object.assign(new Error(`${bin} ${why}`), { code, signal, stderr }));
74
113
  });
75
114
  });
76
115
  }
77
116
 
117
+ function killTree(pid: number | undefined, group: boolean, signal: NodeJS.Signals): void {
118
+ if (pid === undefined) return;
119
+ try {
120
+ process.kill(group ? -pid : pid, signal);
121
+ } catch {
122
+ // already gone
123
+ }
124
+ }
125
+
78
126
  function parseMajor(version: string): number {
79
127
  const m = /(\d+)/.exec(version);
80
128
  return m ? Number.parseInt(m[1], 10) : 0;
@@ -122,25 +170,35 @@ export function deriveOutput(input: string, format: ExportFormat, embed: boolean
122
170
  * Export planning rules:
123
171
  * - preview → never `-e`, width-capped at 2000px (Claude vision rejects >2576px)
124
172
  * - final → `-e` for png/svg/pdf (jpg can't embed), raster scale 2
173
+ * - animated → final SVG only; defaults the format to SVG and verifies motion after export
125
174
  * - `--width` and `-s` are never combined; an explicit width/height wins
126
175
  * - `-t` (transparent) is PNG-only; `--page-index` is 1-based
176
+ * - the outer margin defaults to the canvas-fit margin in diagram units. draw.io
177
+ * applies `-b` unevenly with `-s` (left/top get border × scale) and with SVG
178
+ * (the canvas grows by 3 × border), so a scaled raster is sized with `--width`
179
+ * from `contentWidth`, and SVG is exported borderless and padded afterwards.
127
180
  */
128
- export function planExport(opts: ExportOptions, plat: string = platform(), isRoot = false): ExportPlan {
129
- const format = opts.format ?? "png";
181
+ export function planExport(
182
+ opts: ExportOptions,
183
+ plat: string = platform(),
184
+ isRoot = false,
185
+ contentWidth?: number,
186
+ ): ExportPlan {
187
+ const animated = opts.animated ?? false;
188
+ const format = opts.format ?? (animated ? "svg" : "png");
130
189
  const mode = opts.mode ?? "final";
190
+ if (animated && format !== "svg") throw new Error("animated export requires format='svg'");
191
+ if (animated && mode !== "final") throw new Error("animated export requires mode='final'; use a PNG preview for review");
131
192
  const embed = opts.embed ?? (mode === "final" && format !== "jpg");
132
193
  const output = opts.output ?? deriveOutput(opts.input, format, embed);
133
194
  const raster = format === "png" || format === "jpg";
134
195
 
196
+ const margin = opts.border ?? DEFAULT_FIT_MARGIN;
135
197
  const args: string[] = ["-x", "-f", format];
136
198
  if (embed) args.push("-e");
137
- if (opts.width != null) args.push("--width", String(opts.width));
138
- else if (opts.height != null) args.push("--height", String(opts.height));
139
- else if (raster) {
140
- if (mode === "preview") args.push("--width", "2000");
141
- else args.push("-s", String(opts.scale ?? 2));
142
- }
143
- args.push("-b", String(opts.border ?? 10));
199
+ const border = planExportSize(opts, mode, raster, contentWidth, margin, args);
200
+ // draw.io crops exports to the content, so the border is the image's only outer margin.
201
+ args.push("-b", String(format === "svg" ? 0 : border));
144
202
  if (opts.transparent && format === "png") args.push("-t");
145
203
  if (opts.pageIndex != null) args.push("--page-index", String(opts.pageIndex));
146
204
  args.push("-o", output);
@@ -151,7 +209,29 @@ export function planExport(opts: ExportOptions, plat: string = platform(), isRoo
151
209
  linuxExtra.push("--disable-gpu");
152
210
  if (isRoot) linuxExtra.push("--no-sandbox");
153
211
  }
154
- return { format, mode, embed, output, args, input: opts.input, linuxExtra };
212
+ return { format, mode, embed, animated, output, args, input: opts.input, linuxExtra, svgMargin: format === "svg" ? margin : 0 };
213
+ }
214
+
215
+ function planExportSize(
216
+ opts: ExportOptions, mode: ExportMode, raster: boolean, contentWidth: number | undefined,
217
+ margin: number, args: string[],
218
+ ): number {
219
+ if (opts.width != null) args.push("--width", String(opts.width));
220
+ else if (opts.height != null) args.push("--height", String(opts.height));
221
+ else if (raster) {
222
+ if (mode === "preview") args.push("--width", "2000");
223
+ else {
224
+ const scale = opts.scale ?? 2;
225
+ if (contentWidth !== undefined && contentWidth > 0 && scale !== 1) {
226
+ // With --width the border is in output pixels and applied evenly.
227
+ const border = Math.round(margin * scale);
228
+ args.push("--width", String(Math.round(contentWidth * scale + 2 * border)));
229
+ return border;
230
+ }
231
+ args.push("-s", String(scale));
232
+ }
233
+ }
234
+ return margin;
155
235
  }
156
236
 
157
237
  export interface ExportResult {
@@ -159,6 +239,9 @@ export interface ExportResult {
159
239
  format: ExportFormat;
160
240
  mode: ExportMode;
161
241
  embed: boolean;
242
+ /** True only when animated SVG export was explicitly requested and verified. */
243
+ animated: boolean;
244
+ animation?: AnimatedSvgSummary;
162
245
  binary: string;
163
246
  version?: string;
164
247
  /** True if the truncated `-e` PNG IEND chunk was repaired after export. */
@@ -209,17 +292,12 @@ async function replaceTrackedPreview(input: string, latestOutput: string): Promi
209
292
  const removed: string[] = [];
210
293
  const warnings: string[] = [];
211
294
 
212
- for (const [path, displayPath] of previous) {
213
- if (path === latestPath) continue;
214
- const existed = existsSync(path);
215
- try {
216
- await rm(path, { force: true });
217
- if (existed) removed.push(displayPath);
218
- } catch (error) {
219
- retained.set(path, displayPath);
220
- const message = error instanceof Error ? error.message : String(error);
221
- warnings.push(`${displayPath}: ${message}`);
222
- }
295
+ const cleanup = await deletePreviewFiles(previous, latestPath);
296
+ for (const result of cleanup) {
297
+ if (result.warning !== undefined) {
298
+ retained.set(result.path, result.displayPath);
299
+ warnings.push(result.warning);
300
+ } else if (result.existed) removed.push(result.displayPath);
223
301
  }
224
302
 
225
303
  previewOutputs.set(key, retained);
@@ -237,23 +315,41 @@ async function removeTrackedPreviews(input: string, finalOutput: string): Promis
237
315
  const warnings: string[] = [];
238
316
  const retry = new Map<string, string>();
239
317
 
240
- for (const [path, displayPath] of previews) {
241
- if (path === finalPath) continue;
242
- const existed = existsSync(path);
243
- try {
244
- await rm(path, { force: true });
245
- if (existed) removed.push(displayPath);
246
- } catch (error) {
247
- retry.set(path, displayPath);
248
- const message = error instanceof Error ? error.message : String(error);
249
- warnings.push(`${displayPath}: ${message}`);
250
- }
318
+ const cleanup = await deletePreviewFiles(previews, finalPath);
319
+ for (const result of cleanup) {
320
+ if (result.warning !== undefined) {
321
+ retry.set(result.path, result.displayPath);
322
+ warnings.push(result.warning);
323
+ } else if (result.existed) removed.push(result.displayPath);
251
324
  }
252
325
 
253
326
  if (retry.size > 0) previewOutputs.set(key, retry);
254
327
  return { removed, warnings, replaced: false };
255
328
  }
256
329
 
330
+ interface PreviewDeletion {
331
+ path: string;
332
+ displayPath: string;
333
+ existed: boolean;
334
+ warning?: string;
335
+ }
336
+
337
+ /** Independent file deletions run concurrently; receipts retain insertion order. */
338
+ async function deletePreviewFiles(previews: Map<string, string>, protectedPath: string): Promise<PreviewDeletion[]> {
339
+ return Promise.all(
340
+ [...previews].filter(([path]) => path !== protectedPath).map(async ([path, displayPath]) => {
341
+ const existed = existsSync(path);
342
+ try {
343
+ await rm(path, { force: true });
344
+ return { path, displayPath, existed };
345
+ } catch (error) {
346
+ const message = error instanceof Error ? error.message : String(error);
347
+ return { path, displayPath, existed, warning: `${displayPath}: ${message}` };
348
+ }
349
+ }),
350
+ );
351
+ }
352
+
257
353
  async function withSourceExportQueue<T>(input: string, action: () => Promise<T>): Promise<T> {
258
354
  const key = sourceKey(input);
259
355
  const previous = exportQueues.get(key) ?? Promise.resolve();
@@ -273,17 +369,52 @@ async function withSourceExportQueue<T>(input: string, action: () => Promise<T>)
273
369
  }
274
370
  }
275
371
 
372
+ /** Width of the visible content of a page in diagram units, or undefined when it cannot be measured. */
373
+ export async function pageContentWidth(input: string, pageIndex: number): Promise<number | undefined> {
374
+ try {
375
+ const root = new DOMParser().parseFromString(await readFile(input, "utf8"), "text/xml").documentElement as unknown as DomEl | null;
376
+ if (!root) return undefined;
377
+ const pages = childrenByTag(root, "diagram");
378
+ const page = pages.length > 0 ? pages[pageIndex - 1] : root;
379
+ const model = page && (page.tagName === "mxGraphModel" ? page : firstByTag(page, "mxGraphModel"));
380
+ if (!model) return undefined;
381
+ const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
382
+ const bounds = contentBounds(cells, ids);
383
+ return bounds ? bounds.maxX - bounds.minX : undefined;
384
+ } catch {
385
+ return undefined;
386
+ }
387
+ }
388
+
276
389
  function isRootUser(): boolean {
277
390
  const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
278
391
  return typeof getuid === "function" && getuid() === 0;
279
392
  }
280
393
 
394
+ /**
395
+ * Xvfb screen for an export: draw.io fails (UnknownVizError, then hangs) when the
396
+ * requested raster is wider than the virtual screen. The height is unknown when only
397
+ * a width is requested, so the larger requested side sizes both, plus a margin,
398
+ * floored at 1280x1024 and capped at 8192.
399
+ */
400
+ export function xvfbScreen(args: string[]): string {
401
+ const want = Math.max(flagNumber(args, "--width"), flagNumber(args, "--height"));
402
+ const side = want > 0 ? Math.min(8192, want + 256) : 0;
403
+ return `${Math.max(1280, side)}x${Math.max(1024, side)}x24`;
404
+ }
405
+
406
+ function flagNumber(args: string[], flag: string): number {
407
+ const i = args.indexOf(flag);
408
+ return i >= 0 ? Number(args[i + 1]) || 0 : 0;
409
+ }
410
+
281
411
  /** Run the export, wrapping in `xvfb-run` on headless Linux and falling back to a direct call if it's absent. */
282
412
  async function invoke(binary: string, fullArgs: string[]): Promise<string> {
283
413
  if (platform() === "linux" && !process.env.DISPLAY) {
414
+ const screen = `-screen 0 ${xvfbScreen(fullArgs)}`;
284
415
  try {
285
- await run("xvfb-run", ["-a", "--server-args=-screen 0 1280x1024x24", binary, ...fullArgs]);
286
- return `xvfb-run -a --server-args="-screen 0 1280x1024x24" ${binary} ${fullArgs.join(" ")}`;
416
+ await run("xvfb-run", ["-a", `--server-args=${screen}`, binary, ...fullArgs]);
417
+ return `xvfb-run -a --server-args="${screen}" ${binary} ${fullArgs.join(" ")}`;
287
418
  } catch (e) {
288
419
  if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
289
420
  // xvfb-run not installed — fall through to a direct call
@@ -303,6 +434,17 @@ export async function exportDiagram(opts: ExportOptions): Promise<ExportResult>
303
434
  return withSourceExportQueue(opts.input, () => exportDiagramQueued(opts));
304
435
  }
305
436
 
437
+ async function invokeExport(binary: string, args: string[]): Promise<string> {
438
+ try {
439
+ return await invoke(binary, args);
440
+ } catch (e) {
441
+ const message = e instanceof Error ? e.message : String(e);
442
+ const stderr = (e as { stderr?: string }).stderr?.trim();
443
+ const detail = stderr ? `${message}\n${stderr}` : message;
444
+ throw new Error(`draw.io export failed: ${detail}`, { cause: e });
445
+ }
446
+ }
447
+
306
448
  async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
307
449
  const info = await resolveBinary(opts.binary);
308
450
  if (!info.available || !info.binary) {
@@ -312,21 +454,33 @@ async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
312
454
  );
313
455
  }
314
456
 
315
- const plan = planExport(opts, platform(), isRootUser());
457
+ const plan = planExport(opts, platform(), isRootUser(), await pageContentWidth(opts.input, opts.pageIndex ?? 1));
316
458
  const fullArgs = [...plan.args, plan.input, ...plan.linuxExtra];
317
459
 
318
- let command: string;
319
- try {
320
- command = await invoke(info.binary, fullArgs);
321
- } catch (e) {
322
- const detail = ((e as { stderr?: string }).stderr || (e as Error).message || String(e)).trim();
323
- throw new Error(`draw.io export failed: ${detail}`, { cause: e });
324
- }
460
+ const command = await invokeExport(info.binary, fullArgs);
325
461
  if (!existsSync(plan.output)) {
326
462
  throw new Error(`draw.io reported no error but the output was not created: ${plan.output}`);
327
463
  }
328
464
 
329
465
  const repaired = plan.embed && plan.format === "png" ? await repairPng(plan.output) : false;
466
+ // Every SVG gets an even outer margin and shows its authored colors, matching PNG/PDF output in any viewer.
467
+ if (plan.format === "svg") {
468
+ try {
469
+ await finishSvgFile(plan.output, plan.svgMargin);
470
+ } catch (error) {
471
+ await rm(plan.output, { force: true });
472
+ throw new Error(`SVG post-processing failed: ${(error as Error).message}`, { cause: error });
473
+ }
474
+ }
475
+ let animation: AnimatedSvgSummary | undefined;
476
+ if (plan.animated) {
477
+ try {
478
+ animation = await enhanceAnimatedSvg(plan.input, plan.output, opts.pageIndex ?? 1);
479
+ } catch (error) {
480
+ await rm(plan.output, { force: true });
481
+ throw new Error(`animated SVG verification failed: ${(error as Error).message}`, { cause: error });
482
+ }
483
+ }
330
484
  const cleanup =
331
485
  plan.mode === "preview"
332
486
  ? await replaceTrackedPreview(plan.input, plan.output)
@@ -336,6 +490,8 @@ async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
336
490
  format: plan.format,
337
491
  mode: plan.mode,
338
492
  embed: plan.embed,
493
+ animated: plan.animated,
494
+ animation,
339
495
  binary: info.binary,
340
496
  version: info.version,
341
497
  repaired,
package/src/fitcanvas.ts CHANGED
@@ -50,7 +50,7 @@ function shiftAttr(el: DomEl, name: "x" | "y", delta: number): void {
50
50
  }
51
51
 
52
52
  /** Shift one top-level cell: absolute vertex origin, or edge points/waypoints. */
53
- function shiftCell(cell: DomEl, dx: number, dy: number): void {
53
+ export function shiftCell(cell: DomEl, dx: number, dy: number): void {
54
54
  const geometry = firstByTag(cell, "mxGeometry");
55
55
  if (!geometry) return;
56
56
  if (cell.getAttribute("vertex") === "1" && !geometryIsRelative(cell)) {
package/src/index.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * DrawMe — a native Pi extension that turns natural-language descriptions into
3
3
  * `.drawio` diagrams and exports them to PNG/SVG/PDF/JPG via the draw.io desktop
4
- * CLI. It exposes the authoring workflow as plain commands and model-callable
4
+ * CLI, including verified animated SVGs. It exposes the authoring workflow as plain commands and model-callable
5
5
  * tools.
6
6
  *
7
- * Tools: drawio_check · drawio_export · drawio_validate · drawio_fit_canvas
8
- * drawio_from_mermaid · drawio_layout · drawio_shapesearch
7
+ * Tools: drawio_check · drawio_export · drawio_animate · drawio_validate
8
+ * drawio_fit_canvas · drawio_from_mermaid · drawio_layout · drawio_shapesearch
9
9
  * drawio_explain · drawio_open
10
10
  * Commands: /drawme · /drawme-check · /drawme-export
11
11
  */
@@ -29,6 +29,8 @@ import { fitCanvasFile } from "./fitcanvas";
29
29
  import { searchShapes } from "./shapesearch";
30
30
  import { explainFile } from "./explain";
31
31
  import { drawmeWorkflow } from "./workflow";
32
+ import { animateDiagram } from "./animate";
33
+ import { MOTION_EFFECTS, SLIDE_DIRECTIONS } from "./motion";
32
34
 
33
35
  const HERE = dirname(fileURLToPath(import.meta.url));
34
36
  const REF_DIR = resolve(HERE, "..", "assets", "references");
@@ -44,15 +46,52 @@ const exportParams = Type.Object({
44
46
  scale: Type.Optional(Type.Number({ description: "Raster scale for a final PNG/JPG (default 2)" })),
45
47
  width: Type.Optional(Type.Number({ description: "Target width in px; overrides scale. Preview uses 2000" })),
46
48
  transparent: Type.Optional(Type.Boolean({ description: "Transparent background (PNG only)" })),
47
- border: Type.Optional(Type.Number({ description: "Border in px (default 10)" })),
49
+ border: Type.Optional(Type.Number({ description: "Outer margin in px around the content (default 40, matching drawio_fit_canvas)" })),
48
50
  pageIndex: Type.Optional(Type.Number({ description: "1-based page to export from a multi-page file" })),
49
51
  embed: Type.Optional(
50
52
  Type.Boolean({ description: "Embed diagram XML for an editable output. Default: on for final PNG/SVG/PDF, off for preview" }),
51
53
  ),
54
+ animated: Type.Optional(
55
+ Type.Boolean({
56
+ description:
57
+ "Require a verified final animated SVG. Defaults format to SVG; preserves connector flow and compiles portable page fade/visibility/wait sequences.",
58
+ }),
59
+ ),
52
60
  binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
53
61
  });
54
62
  export type DrawioExportInput = Static<typeof exportParams>;
55
63
 
64
+ const motionStep = Type.Object({
65
+ effect: Type.Union(MOTION_EFFECTS.map((effect) => Type.Literal(effect)), {
66
+ description:
67
+ "fadeIn/fadeOut/dim change opacity; popIn and slideIn reveal hidden shapes; drawIn draws a hidden solid connector from source to target; highlight glows a visible cell briefly; travel sends a dot along a visible connector; wait pauses",
68
+ }),
69
+ cells: Type.Optional(Type.Array(Type.String(), { description: "Cell ids the effect targets (not used by wait)" })),
70
+ duration: Type.Optional(Type.Number({ description: "Effect length in ms; required for wait. Defaults: 500–1400 by effect" })),
71
+ stagger: Type.Optional(Type.Number({ description: "Start offset in ms between consecutive cells of this step, for a cascade" })),
72
+ parallel: Type.Optional(Type.Boolean({ description: "Start together with the previous step instead of after it" })),
73
+ direction: Type.Optional(
74
+ Type.Union(SLIDE_DIRECTIONS.map((direction) => Type.Literal(direction)), { description: "slideIn movement direction (default up)" }),
75
+ ),
76
+ color: Type.Optional(Type.String({ description: "Hex accent for highlight and travel (default #2563eb)" })),
77
+ value: Type.Optional(Type.Number({ description: "Target opacity 0–1 for dim (default 0.25)" })),
78
+ });
79
+
80
+ const animateParams = Type.Object({
81
+ input: Type.String({ description: "Path to the .drawio source file" }),
82
+ steps: Type.Optional(
83
+ Type.Array(motionStep, { description: "Motion steps in order. Omit to re-export the motion already stored on the page" }),
84
+ ),
85
+ loop: Type.Optional(Type.Boolean({ description: "Repeat the sequence (default true)" })),
86
+ hold: Type.Optional(Type.Number({ description: "Pause in ms on the final state before a loop restarts (default 1600)" })),
87
+ pageIndex: Type.Optional(Type.Number({ description: "1-based page to animate (default 1)" })),
88
+ output: Type.Optional(Type.String({ description: "Animated SVG path (default <name>.animated.svg next to the input)" })),
89
+ storyboard: Type.Optional(
90
+ Type.Boolean({ description: "Render <name>.storyboard.png with one frame per step for review (default true)" }),
91
+ ),
92
+ binary: Type.Optional(Type.String({ description: "Explicit path to the draw.io binary" })),
93
+ });
94
+
56
95
  const textResult = (text: string, details: unknown = {}) => ({ content: [{ type: "text" as const, text }], details });
57
96
 
58
97
  /**
@@ -106,15 +145,21 @@ export default function drawme(pi: ExtensionAPI): void {
106
145
  name: "drawio_export",
107
146
  label: "draw.io: export",
108
147
  description:
109
- "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. A successful mode:'preview' PNG is clean, width-capped, and never embedded; when the current model can view images it is attached to the tool result for visual review, and the result text always states whether it was attached. Each successful preview removes the prior preview artifact for the same source, leaving only the latest file; a replacement preview asks for a fixed/not-fixed/regressed verdict against the prior image. mode:'final' creates the deliverable (embedded editable output; truncated PNG IEND is repaired) and removes the remaining preview.",
148
+ "Export a .drawio file to PNG/SVG/PDF/JPG via the draw.io CLI. Set animated:true for a verified final SVG: persistent flowAnimation connectors are preserved and portable page visibility/opacity/fade/wait sequences are compiled into standalone SVG CSS with a reduced-motion fallback. Animated export rejects static output and unsupported sequence effects. A successful mode:'preview' PNG is clean, width-capped, and never embedded; when the current model can view images it is attached to the tool result for visual review, and the result text always states whether it was attached. Each successful preview removes the prior preview artifact for the same source, leaving only the latest file; a replacement preview asks for a fixed/not-fixed/regressed verdict against the prior image. mode:'final' creates the deliverable (embedded editable output; truncated PNG IEND is repaired) and removes the remaining preview. SVG output is pinned to the authored colors so it matches PNG/PDF in every viewer, including dark-mode ones.",
110
149
  promptSnippet:
111
- "Export a .drawio to PNG/SVG/PDF/JPG (mode:'preview' attaches the review image when the current model can view images — the result text says so — and removes the previous preview file; mode:'final' creates the deliverable and cleans the remaining preview).",
150
+ "Export a .drawio to PNG/SVG/PDF/JPG; set animated:true for a verified final animated SVG. Preview mode attaches a PNG for visual review when supported.",
112
151
  parameters: exportParams,
113
152
  async execute(_id, params, _signal, _onUpdate, ctx) {
114
153
  try {
115
154
  const r = await exportDiagram(params as ExportOptions);
116
155
  const canView = modelSupportsImages(ctx);
117
- const lines = [`Exported ${r.output}`, `format=${r.format} mode=${r.mode} embed=${r.embed}`];
156
+ const lines = [`Exported ${r.output}`, `format=${r.format} mode=${r.mode} embed=${r.embed} animated=${r.animated}`];
157
+ if (r.animation) {
158
+ lines.push(
159
+ `Animation verified: ${r.animation.connectorFlows} connector flow(s), ${r.animation.sequenceSteps} page step(s)` +
160
+ (r.animation.sequenceCompiled ? ` (${r.animation.sequenceDurationMs}ms sequence compiled)` : ""),
161
+ );
162
+ }
118
163
  if (r.repaired) lines.push("(repaired truncated -e PNG IEND chunk)");
119
164
  if (r.removedPreviews.length > 0) lines.push(`Removed preview artifact(s): ${r.removedPreviews.join(", ")}`);
120
165
  if (r.previewCleanupWarnings.length > 0) {
@@ -142,11 +187,59 @@ export default function drawme(pi: ExtensionAPI): void {
142
187
  },
143
188
  });
144
189
 
190
+ pi.registerTool({
191
+ name: "drawio_animate",
192
+ label: "draw.io: animate",
193
+ description:
194
+ "Animate an existing .drawio page and export a verified standalone animated SVG. Pass ordered motion steps (fadeIn, fadeOut, dim, popIn, slideIn, drawIn, highlight, travel, wait) with cell ids, optional duration, stagger, parallel, direction, and color. Cells whose first effect is an entrance start hidden. The steps are validated against the page, stored on the page root cell (a source edit), compiled to CSS keyframes and SMIL connector dots with a reduced-motion fallback, and injected into a draw.io SVG export. Omit steps to re-export the stored motion after layout edits. By default a storyboard PNG shows the end state of each step as a captioned frame grid; when the current model can view images it is attached. The storyboard is static: it proves order and visibility, not easing. Effects play in browsers and SVG image embeds; draw.io itself does not play them. Persistent flowAnimation connectors are kept. highlight and travel default to the page theme's accent, and the SVG keeps the authored theme colors in every viewer.",
195
+ promptSnippet:
196
+ "Add motion to a .drawio page (draw-in connectors, pop/slide entrances, highlights, travelling dots, cascades) and export a verified animated SVG with a storyboard.",
197
+ parameters: animateParams,
198
+ async execute(_id, params, _signal, _onUpdate, ctx) {
199
+ try {
200
+ const r = await animateDiagram(params);
201
+ const playback = r.loop ? `loop every ${r.durationMs}ms` : "plays once";
202
+ const lines = [
203
+ `Animated ${r.output} (page '${r.page}')`,
204
+ `Animation verified: ${r.steps} step(s), ${r.animatedCells} animated cell(s), ${r.drawnConnectors} drawn connector(s), ${r.travellingDots} travelling dot(s), ${r.connectorFlows} connector flow(s); sequence ${r.sequenceMs}ms, ${playback}`,
205
+ r.saved
206
+ ? `Stored the motion on the page root cell of ${r.source}. This is a source edit: run drawio_validate.`
207
+ : `Re-used the motion stored in ${r.source}.`,
208
+ ];
209
+ const content: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: "image/png" })[] = [];
210
+ let imageAttached = false;
211
+ if (r.storyboard) {
212
+ const sampled =
213
+ r.storyboardFramesTotal !== r.storyboardFrames ? ` (sampled from ${r.storyboardFramesTotal} steps)` : "";
214
+ lines.push(`Storyboard: ${r.storyboard}, ${r.storyboardFrames} frame(s)${sampled}`);
215
+ if (modelSupportsImages(ctx)) {
216
+ imageAttached = true;
217
+ lines.push(
218
+ "Storyboard attached below. Check each frame's caption against the intended order: the right cells visible, hidden, dimmed, or accented at each step, and nothing appearing before what it depends on.",
219
+ );
220
+ } else {
221
+ lines.push("Storyboard NOT attached: the current model cannot view images. Check the step order structurally instead.");
222
+ }
223
+ }
224
+ const versionLabel = r.version ? ` (${r.version})` : "";
225
+ lines.push(`binary=${r.binary}${versionLabel}`);
226
+ content.push({ type: "text", text: lines.join("\n") });
227
+ if (imageAttached && r.storyboard) {
228
+ const png = await readFile(r.storyboard);
229
+ content.push({ type: "image", data: png.toString("base64"), mimeType: "image/png" });
230
+ }
231
+ return { content, details: { ...r, imageAttached } };
232
+ } catch (e) {
233
+ return textResult(`Animate failed: ${(e as Error).message}`, { error: (e as Error).message });
234
+ }
235
+ },
236
+ });
237
+
145
238
  pi.registerTool({
146
239
  name: "drawio_validate",
147
240
  label: "draw.io: validate",
148
241
  description:
149
- "Structurally lint a .drawio file: errors for dangling endpoints, duplicate/reserved ids, broken parents, and missing/malformed vertex or edge geometry; actionable warnings for overlap, page/containment bounds, conservative readability defects, explicit routes through shapes or across edges, pinned anchors facing away from the next route direction, edge labels likely overlapping shapes, labels sitting on their own line, and auto-routed edges (no waypoints) whose routing cannot be checked. Auto-routed edges whose direct path pierces a shape are called out as preview-review observations. Give every edge facing-side anchors and explicit waypoints so deterministic route checks engage. Reports observations and a readability score. Deterministic and does not launch draw.io. Compressed pages cannot be linted and are reported as skipped. Fix boundary/margin/empty-space warnings (and make room for overlapping elements) by spreading elements and running drawio_fit_canvas — never by shrinking content. Run after every source edit and before exporting.",
242
+ "Structurally lint a .drawio file: errors for dangling endpoints, duplicate/reserved ids, broken parents, and missing/malformed vertex or edge geometry; actionable warnings for overlap, page/containment bounds, conservative readability defects, explicit routes through shapes or across edges, pinned anchors facing away from the next route direction, edge labels likely overlapping shapes, labels sitting on their own line, labels landing on a bend of their own connector or on another routed connector, and auto-routed edges (no waypoints) whose routing cannot be checked. Auto-routed edges whose direct path pierces a shape are called out as preview-review observations. Give every edge facing-side anchors and explicit waypoints so deterministic route checks engage. Reports observations and a readability score. Deterministic and does not launch draw.io. Compressed pages cannot be linted and are reported as skipped. Fix boundary/margin/empty-space warnings (and make room for overlapping elements) by spreading elements and running drawio_fit_canvas — never by shrinking content. Run after every source edit and before exporting.",
150
243
  promptSnippet: "Lint a .drawio after every source edit and before exporting.",
151
244
  parameters: Type.Object({ input: Type.String({ description: "Path to the .drawio file" }) }),
152
245
  async execute(_id, params) {
@@ -273,11 +366,11 @@ export default function drawme(pi: ExtensionAPI): void {
273
366
  query: Type.String({ description: "Keywords, e.g. 'aws lambda' or 'uml actor'" }),
274
367
  limit: Type.Optional(Type.Number({ description: "Max results (default 10)" })),
275
368
  }),
276
- async execute(_id, params) {
369
+ execute(_id, params) {
277
370
  const matches = searchShapes(params.query, params.limit ?? 10);
278
- if (matches.length === 0) return textResult(`No shapes matched "${params.query}".`, { matches });
371
+ if (matches.length === 0) return Promise.resolve(textResult(`No shapes matched "${params.query}".`, { matches }));
279
372
  const lines = matches.map((m) => `${m.title} (${m.w}x${m.h})\n ${m.style}`);
280
- return textResult(lines.join("\n"), { matches });
373
+ return Promise.resolve(textResult(lines.join("\n"), { matches }));
281
374
  },
282
375
  });
283
376
 
@@ -335,6 +428,7 @@ export default function drawme(pi: ExtensionAPI): void {
335
428
  drawmeWorkflow(desc, REF_DIR, cli, {
336
429
  diagramTypes: await readReference("diagram-types.md"),
337
430
  xmlAuthoring: await readReference("xml-authoring.md"),
431
+ stylePresets: await readReference("style-presets.md"),
338
432
  mermaidAuthoring: cli.supportsMermaid ? await readReference("mermaid-authoring.md") : null,
339
433
  }),
340
434
  );
@@ -353,17 +447,26 @@ export default function drawme(pi: ExtensionAPI): void {
353
447
  });
354
448
 
355
449
  pi.registerCommand("drawme-export", {
356
- description: "Export a .drawio file: /drawme-export <file> [png|svg|pdf|jpg]",
450
+ description: "Export a .drawio file: /drawme-export <file> [png|svg|animated-svg|pdf|jpg]",
357
451
  handler: async (args, ctx) => {
358
452
  const parts = args.trim().split(/\s+/).filter(Boolean);
359
453
  if (parts.length === 0) {
360
- ctx.ui.notify("Usage: /drawme-export <file> [png|svg|pdf|jpg]", "info");
454
+ ctx.ui.notify("Usage: /drawme-export <file> [png|svg|animated-svg|pdf|jpg]", "info");
455
+ return;
456
+ }
457
+ const [input, requestedFormat = "png"] = parts;
458
+ const animated = requestedFormat === "animated-svg";
459
+ const format = animated ? "svg" : requestedFormat;
460
+ if (!["png", "svg", "pdf", "jpg"].includes(format)) {
461
+ ctx.ui.notify("Usage: /drawme-export <file> [png|svg|animated-svg|pdf|jpg]", "info");
361
462
  return;
362
463
  }
363
- const [input, format = "png"] = parts;
364
464
  try {
365
- const r = await exportDiagram({ input, format: format as ExportFormat, mode: "final" });
366
- ctx.ui.notify(`Exported ${r.output}${r.repaired ? " (repaired PNG)" : ""}`, "info");
465
+ const r = await exportDiagram({ input, format: format as ExportFormat, mode: "final", animated });
466
+ let status = "";
467
+ if (r.animation) status = " (animation verified)";
468
+ else if (r.repaired) status = " (repaired PNG)";
469
+ ctx.ui.notify(`Exported ${r.output}${status}`, "info");
367
470
  } catch (e) {
368
471
  ctx.ui.notify(`Export failed: ${(e as Error).message}`, "error");
369
472
  }