@senad-d/drawme 0.1.6 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/drawio.ts CHANGED
@@ -6,10 +6,16 @@
6
6
  */
7
7
  import { execFile } 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. */
@@ -122,25 +133,35 @@ export function deriveOutput(input: string, format: ExportFormat, embed: boolean
122
133
  * Export planning rules:
123
134
  * - preview → never `-e`, width-capped at 2000px (Claude vision rejects >2576px)
124
135
  * - final → `-e` for png/svg/pdf (jpg can't embed), raster scale 2
136
+ * - animated → final SVG only; defaults the format to SVG and verifies motion after export
125
137
  * - `--width` and `-s` are never combined; an explicit width/height wins
126
138
  * - `-t` (transparent) is PNG-only; `--page-index` is 1-based
139
+ * - the outer margin defaults to the canvas-fit margin in diagram units. draw.io
140
+ * applies `-b` unevenly with `-s` (left/top get border × scale) and with SVG
141
+ * (the canvas grows by 3 × border), so a scaled raster is sized with `--width`
142
+ * from `contentWidth`, and SVG is exported borderless and padded afterwards.
127
143
  */
128
- export function planExport(opts: ExportOptions, plat: string = platform(), isRoot = false): ExportPlan {
129
- const format = opts.format ?? "png";
144
+ export function planExport(
145
+ opts: ExportOptions,
146
+ plat: string = platform(),
147
+ isRoot = false,
148
+ contentWidth?: number,
149
+ ): ExportPlan {
150
+ const animated = opts.animated ?? false;
151
+ const format = opts.format ?? (animated ? "svg" : "png");
130
152
  const mode = opts.mode ?? "final";
153
+ if (animated && format !== "svg") throw new Error("animated export requires format='svg'");
154
+ if (animated && mode !== "final") throw new Error("animated export requires mode='final'; use a PNG preview for review");
131
155
  const embed = opts.embed ?? (mode === "final" && format !== "jpg");
132
156
  const output = opts.output ?? deriveOutput(opts.input, format, embed);
133
157
  const raster = format === "png" || format === "jpg";
134
158
 
159
+ const margin = opts.border ?? DEFAULT_FIT_MARGIN;
135
160
  const args: string[] = ["-x", "-f", format];
136
161
  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));
162
+ const border = planExportSize(opts, mode, raster, contentWidth, margin, args);
163
+ // draw.io crops exports to the content, so the border is the image's only outer margin.
164
+ args.push("-b", String(format === "svg" ? 0 : border));
144
165
  if (opts.transparent && format === "png") args.push("-t");
145
166
  if (opts.pageIndex != null) args.push("--page-index", String(opts.pageIndex));
146
167
  args.push("-o", output);
@@ -151,7 +172,29 @@ export function planExport(opts: ExportOptions, plat: string = platform(), isRoo
151
172
  linuxExtra.push("--disable-gpu");
152
173
  if (isRoot) linuxExtra.push("--no-sandbox");
153
174
  }
154
- return { format, mode, embed, output, args, input: opts.input, linuxExtra };
175
+ return { format, mode, embed, animated, output, args, input: opts.input, linuxExtra, svgMargin: format === "svg" ? margin : 0 };
176
+ }
177
+
178
+ function planExportSize(
179
+ opts: ExportOptions, mode: ExportMode, raster: boolean, contentWidth: number | undefined,
180
+ margin: number, args: string[],
181
+ ): number {
182
+ if (opts.width != null) args.push("--width", String(opts.width));
183
+ else if (opts.height != null) args.push("--height", String(opts.height));
184
+ else if (raster) {
185
+ if (mode === "preview") args.push("--width", "2000");
186
+ else {
187
+ const scale = opts.scale ?? 2;
188
+ if (contentWidth !== undefined && contentWidth > 0 && scale !== 1) {
189
+ // With --width the border is in output pixels and applied evenly.
190
+ const border = Math.round(margin * scale);
191
+ args.push("--width", String(Math.round(contentWidth * scale + 2 * border)));
192
+ return border;
193
+ }
194
+ args.push("-s", String(scale));
195
+ }
196
+ }
197
+ return margin;
155
198
  }
156
199
 
157
200
  export interface ExportResult {
@@ -159,6 +202,9 @@ export interface ExportResult {
159
202
  format: ExportFormat;
160
203
  mode: ExportMode;
161
204
  embed: boolean;
205
+ /** True only when animated SVG export was explicitly requested and verified. */
206
+ animated: boolean;
207
+ animation?: AnimatedSvgSummary;
162
208
  binary: string;
163
209
  version?: string;
164
210
  /** True if the truncated `-e` PNG IEND chunk was repaired after export. */
@@ -209,17 +255,12 @@ async function replaceTrackedPreview(input: string, latestOutput: string): Promi
209
255
  const removed: string[] = [];
210
256
  const warnings: string[] = [];
211
257
 
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
- }
258
+ const cleanup = await deletePreviewFiles(previous, latestPath);
259
+ for (const result of cleanup) {
260
+ if (result.warning !== undefined) {
261
+ retained.set(result.path, result.displayPath);
262
+ warnings.push(result.warning);
263
+ } else if (result.existed) removed.push(result.displayPath);
223
264
  }
224
265
 
225
266
  previewOutputs.set(key, retained);
@@ -237,23 +278,41 @@ async function removeTrackedPreviews(input: string, finalOutput: string): Promis
237
278
  const warnings: string[] = [];
238
279
  const retry = new Map<string, string>();
239
280
 
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
- }
281
+ const cleanup = await deletePreviewFiles(previews, finalPath);
282
+ for (const result of cleanup) {
283
+ if (result.warning !== undefined) {
284
+ retry.set(result.path, result.displayPath);
285
+ warnings.push(result.warning);
286
+ } else if (result.existed) removed.push(result.displayPath);
251
287
  }
252
288
 
253
289
  if (retry.size > 0) previewOutputs.set(key, retry);
254
290
  return { removed, warnings, replaced: false };
255
291
  }
256
292
 
293
+ interface PreviewDeletion {
294
+ path: string;
295
+ displayPath: string;
296
+ existed: boolean;
297
+ warning?: string;
298
+ }
299
+
300
+ /** Independent file deletions run concurrently; receipts retain insertion order. */
301
+ async function deletePreviewFiles(previews: Map<string, string>, protectedPath: string): Promise<PreviewDeletion[]> {
302
+ return Promise.all(
303
+ [...previews].filter(([path]) => path !== protectedPath).map(async ([path, displayPath]) => {
304
+ const existed = existsSync(path);
305
+ try {
306
+ await rm(path, { force: true });
307
+ return { path, displayPath, existed };
308
+ } catch (error) {
309
+ const message = error instanceof Error ? error.message : String(error);
310
+ return { path, displayPath, existed, warning: `${displayPath}: ${message}` };
311
+ }
312
+ }),
313
+ );
314
+ }
315
+
257
316
  async function withSourceExportQueue<T>(input: string, action: () => Promise<T>): Promise<T> {
258
317
  const key = sourceKey(input);
259
318
  const previous = exportQueues.get(key) ?? Promise.resolve();
@@ -273,6 +332,23 @@ async function withSourceExportQueue<T>(input: string, action: () => Promise<T>)
273
332
  }
274
333
  }
275
334
 
335
+ /** Width of the visible content of a page in diagram units, or undefined when it cannot be measured. */
336
+ export async function pageContentWidth(input: string, pageIndex: number): Promise<number | undefined> {
337
+ try {
338
+ const root = new DOMParser().parseFromString(await readFile(input, "utf8"), "text/xml").documentElement as unknown as DomEl | null;
339
+ if (!root) return undefined;
340
+ const pages = childrenByTag(root, "diagram");
341
+ const page = pages.length > 0 ? pages[pageIndex - 1] : root;
342
+ const model = page && (page.tagName === "mxGraphModel" ? page : firstByTag(page, "mxGraphModel"));
343
+ if (!model) return undefined;
344
+ const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
345
+ const bounds = contentBounds(cells, ids);
346
+ return bounds ? bounds.maxX - bounds.minX : undefined;
347
+ } catch {
348
+ return undefined;
349
+ }
350
+ }
351
+
276
352
  function isRootUser(): boolean {
277
353
  const getuid = (process as NodeJS.Process & { getuid?: () => number }).getuid;
278
354
  return typeof getuid === "function" && getuid() === 0;
@@ -312,7 +388,7 @@ async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
312
388
  );
313
389
  }
314
390
 
315
- const plan = planExport(opts, platform(), isRootUser());
391
+ const plan = planExport(opts, platform(), isRootUser(), await pageContentWidth(opts.input, opts.pageIndex ?? 1));
316
392
  const fullArgs = [...plan.args, plan.input, ...plan.linuxExtra];
317
393
 
318
394
  let command: string;
@@ -327,6 +403,24 @@ async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
327
403
  }
328
404
 
329
405
  const repaired = plan.embed && plan.format === "png" ? await repairPng(plan.output) : false;
406
+ // Every SVG gets an even outer margin and shows its authored colors, matching PNG/PDF output in any viewer.
407
+ if (plan.format === "svg") {
408
+ try {
409
+ await finishSvgFile(plan.output, plan.svgMargin);
410
+ } catch (error) {
411
+ await rm(plan.output, { force: true });
412
+ throw new Error(`SVG post-processing failed: ${(error as Error).message}`, { cause: error });
413
+ }
414
+ }
415
+ let animation: AnimatedSvgSummary | undefined;
416
+ if (plan.animated) {
417
+ try {
418
+ animation = await enhanceAnimatedSvg(plan.input, plan.output, opts.pageIndex ?? 1);
419
+ } catch (error) {
420
+ await rm(plan.output, { force: true });
421
+ throw new Error(`animated SVG verification failed: ${(error as Error).message}`, { cause: error });
422
+ }
423
+ }
330
424
  const cleanup =
331
425
  plan.mode === "preview"
332
426
  ? await replaceTrackedPreview(plan.input, plan.output)
@@ -336,6 +430,8 @@ async function exportDiagramQueued(opts: ExportOptions): Promise<ExportResult> {
336
430
  format: plan.format,
337
431
  mode: plan.mode,
338
432
  embed: plan.embed,
433
+ animated: plan.animated,
434
+ animation,
339
435
  binary: info.binary,
340
436
  version: info.version,
341
437
  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/geometry.ts CHANGED
@@ -72,12 +72,10 @@ export function styleNum(style: string | null, key: string): number | undefined
72
72
  return undefined;
73
73
  }
74
74
 
75
- /** Absolute (x, y, w, h) of a non-relative vertex, summing parent-container offsets. */
76
- export function absRect(cell: DomEl, byId: ById): Rect | null {
77
- const r = rect(cell);
78
- if (r === null || hasInvalidNumber(r)) return null;
79
- let [x, y] = r;
80
- const [, , w, h] = r;
75
+ /** Accumulated origin of a cell's ancestor containers — the offset from parent-relative to absolute coordinates. */
76
+ export function parentOrigin(cell: DomEl, byId: ById): Point {
77
+ let dx = 0;
78
+ let dy = 0;
81
79
  let parent = attr(cell, "parent");
82
80
  const seen = new Set<string>();
83
81
  while (parent && byId.has(parent) && !seen.has(parent)) {
@@ -86,13 +84,21 @@ export function absRect(cell: DomEl, byId: ById): Rect | null {
86
84
  if (p.getAttribute("vertex") === "1" && !geometryIsRelative(p)) {
87
85
  const pr = rect(p);
88
86
  if (pr && !hasInvalidNumber(pr)) {
89
- x += pr[0];
90
- y += pr[1];
87
+ dx += pr[0];
88
+ dy += pr[1];
91
89
  }
92
90
  }
93
91
  parent = attr(p, "parent");
94
92
  }
95
- return [x, y, w, h];
93
+ return [dx, dy];
94
+ }
95
+
96
+ /** Absolute (x, y, w, h) of a non-relative vertex, summing parent-container offsets. */
97
+ export function absRect(cell: DomEl, byId: ById): Rect | null {
98
+ const r = rect(cell);
99
+ if (r === null || hasInvalidNumber(r)) return null;
100
+ const [ox, oy] = parentOrigin(cell, byId);
101
+ return [r[0] + ox, r[1] + oy, r[2], r[3]];
96
102
  }
97
103
 
98
104
  /** Absolute point where `edge` meets its source/target vertex (honours exit/entry). */
@@ -122,17 +128,19 @@ export function edgeWaypoints(edge: DomEl): Point[] {
122
128
  return points;
123
129
  }
124
130
 
125
- /** Absolute polyline for a waypointed edge, or null when auto-routed / unresolved. */
131
+ /** Absolute polyline for a waypointed edge, or null when auto-routed / unresolved. Waypoints are stored relative to the edge's parent. */
126
132
  export function edgeRoute(edge: DomEl, byId: ById): Point[] | null {
127
133
  const waypoints = edgeWaypoints(edge);
128
134
  if (waypoints.length === 0) return null;
129
135
  const source = endpoint(edge, "source", byId);
130
136
  const target = endpoint(edge, "target", byId);
131
137
  if (source === null || target === null) return null;
132
- return [source, ...waypoints, target];
138
+ const [ox, oy] = parentOrigin(edge, byId);
139
+ return [source, ...waypoints.map(([x, y]): Point => [x + ox, y + oy]), target];
133
140
  }
134
141
 
135
- export function routeMidpoint(points: Point[]): Point {
142
+ /** Point at `fraction` (0..1) of the route's arc length. */
143
+ export function routePointAt(points: Point[], fraction: number): Point {
136
144
  const lengths: number[] = [];
137
145
  let total = 0;
138
146
  for (let i = 0; i < points.length - 1; i++) {
@@ -140,7 +148,7 @@ export function routeMidpoint(points: Point[]): Point {
140
148
  lengths.push(length);
141
149
  total += length;
142
150
  }
143
- let remaining = total / 2;
151
+ let remaining = total * fraction;
144
152
  for (let i = 0; i < lengths.length; i++) {
145
153
  if (remaining <= lengths[i]) {
146
154
  const fraction = lengths[i] === 0 ? 0 : remaining / lengths[i];
@@ -154,6 +162,10 @@ export function routeMidpoint(points: Point[]): Point {
154
162
  return points.at(-1) ?? [0, 0];
155
163
  }
156
164
 
165
+ export function routeMidpoint(points: Point[]): Point {
166
+ return routePointAt(points, 0.5);
167
+ }
168
+
157
169
  /** Conservative box for a separately sized label on an explicitly routed edge. */
158
170
  export function explicitEdgeLabelRect(cell: DomEl, byId: ById): Rect | null {
159
171
  if (!isEdgeLabel(cell)) return null;
@@ -253,7 +265,11 @@ export function contentBounds(cells: DomEl[], ids: ById): ContentBounds | null {
253
265
  if (!isVisible(cell, ids)) continue;
254
266
  const box = contentRect(cell, ids);
255
267
  if (box && !hasInvalidNumber(box)) bounds = addRectToBounds(bounds, box);
256
- for (const point of contentWaypoints(cell)) bounds = addPointToBounds(bounds, point);
268
+ const waypoints = contentWaypoints(cell);
269
+ if (waypoints.length > 0) {
270
+ const [ox, oy] = parentOrigin(cell, ids);
271
+ for (const [x, y] of waypoints) bounds = addPointToBounds(bounds, [x + ox, y + oy]);
272
+ }
257
273
  }
258
274
  return bounds;
259
275
  }
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, and explicit routes through shapes or across edges. 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) {
@@ -158,7 +251,7 @@ export default function drawme(pi: ExtensionAPI): void {
158
251
  ...(r.warnings.length > 0 ? r.warnings.map((warning) => `- ${warning}`) : ["- none"]),
159
252
  `Informational observations (${r.observations.length}):`,
160
253
  ...(r.observations.length > 0 ? r.observations.map((observation) => `- ${observation}`) : ["- none"]),
161
- `Readability score: ${r.score.total} (route-through=${r.score.through}, crossings=${r.score.crossings}, overlaps=${r.score.overlaps}; lower is better for variants of this graph)`,
254
+ `Readability score: ${r.score.total} (route-through=${r.score.through}, crossings=${r.score.crossings}, overlaps=${r.score.overlaps}, anchors=${r.score.anchors}; lower is better for variants of this graph)`,
162
255
  `${r.errors.length} error(s), ${r.warnings.length} unresolved warning(s)`,
163
256
  ];
164
257
  return textResult(lines.join("\n"), r);
@@ -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
  }