@senad-d/drawme 0.1.11 → 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/CHANGELOG.md +10 -1
- package/README.md +47 -46
- package/SECURITY.md +1 -1
- package/assets/references/diagram-types.md +3 -3
- package/assets/references/mermaid-authoring.md +10 -9
- package/assets/references/troubleshooting.md +5 -27
- package/assets/references/xml-authoring.md +5 -3
- package/docs/reference.md +75 -73
- package/docs/visual-review-implementation-tasks.md +4 -2
- package/example/README.md +9 -9
- package/example/drawme-architecture.drawio +5 -5
- package/example/drawme-how-it-works.drawio +7 -7
- package/example/drawme-installation-guide.drawio +6 -6
- package/package.json +5 -3
- package/src/animate.ts +124 -88
- package/src/animation.ts +105 -109
- package/src/diagram-files.ts +159 -0
- package/src/dom.ts +5 -0
- package/src/drawio.ts +324 -566
- package/src/editable-import.ts +228 -0
- package/src/explain.ts +81 -88
- package/src/export-plan.ts +175 -0
- package/src/fitcanvas.ts +29 -25
- package/src/geometry.ts +68 -29
- package/src/index.ts +201 -142
- package/src/motion.ts +251 -163
- package/src/png.ts +233 -34
- package/src/renderer.ts +361 -0
- package/src/shapesearch.ts +33 -32
- package/src/storyboard.ts +41 -26
- package/src/svg-helpers.ts +129 -0
- package/src/svgexport.ts +6 -9
- package/src/validate.ts +686 -292
- package/src/workflow.ts +41 -30
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { mkdtemp, open, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { basename, dirname, extname, join } from "node:path";
|
|
5
|
+
import { DOMParser, XMLSerializer, onWarningStopParsing, type Document, type Element } from "@xmldom/xmldom";
|
|
6
|
+
import { DEFAULT_XML_BYTES, DiagramLimitError, readDiagramXml, sessionPath, siblingPath, withDiagramFiles } from "./diagram-files";
|
|
7
|
+
import { attr, childrenByTag, firstByTag, graphModel, type DomEl } from "./dom";
|
|
8
|
+
import { collectCellsWithIds, pyFloat } from "./geometry";
|
|
9
|
+
import { FEATURE_MIN, invokeRenderer, rendererUnavailable, resolveBinary } from "./renderer";
|
|
10
|
+
|
|
11
|
+
export interface MermaidOptions {
|
|
12
|
+
/** Path to a `.mmd` file. */
|
|
13
|
+
input?: string;
|
|
14
|
+
/** Inline Mermaid text (written to a temp `.mmd`). Provide exactly one source. */
|
|
15
|
+
mermaid?: string;
|
|
16
|
+
output?: string;
|
|
17
|
+
binary?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface MermaidResult {
|
|
21
|
+
output: string;
|
|
22
|
+
binary: string;
|
|
23
|
+
version?: string;
|
|
24
|
+
command: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** ELK layout presets the CLI accepts. Any other value can hang headless runs. */
|
|
28
|
+
export const LAYOUT_PRESETS = ["verticalFlow", "horizontalFlow", "verticalTree", "horizontalTree", "radialTree", "organic"] as const;
|
|
29
|
+
export type LayoutPreset = (typeof LAYOUT_PRESETS)[number];
|
|
30
|
+
|
|
31
|
+
export interface LayoutOptions {
|
|
32
|
+
input: string;
|
|
33
|
+
preset: LayoutPreset;
|
|
34
|
+
/** Defaults to a sibling `<name>.layout.drawio`. */
|
|
35
|
+
output?: string;
|
|
36
|
+
binary?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface LayoutResult extends MermaidResult {
|
|
40
|
+
preset: LayoutPreset;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function mermaidArgs(mmdPath: string, output: string): string[] {
|
|
44
|
+
return ["-x", "-f", "xml", "-o", output, mmdPath];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function layoutArgs(input: string, preset: LayoutPreset, output: string): string[] {
|
|
48
|
+
return ["-x", "-f", "xml", "--layout", preset, "-o", output, input];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function requireFeature(feature: "supportsMermaid" | "supportsLayout", label: string, override?: string) {
|
|
52
|
+
const info = await resolveBinary(override);
|
|
53
|
+
if (!info.available || !info.binary) throw new Error(rendererUnavailable(info));
|
|
54
|
+
if (!info[feature]) {
|
|
55
|
+
throw new Error(`${label} needs draw.io v${FEATURE_MIN}+, but ${info.version ?? "an unknown version"} is installed. Upgrade draw.io Desktop.`);
|
|
56
|
+
}
|
|
57
|
+
return { binary: info.binary, version: info.version };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function defaultOutput(input: string, suffix: string): string {
|
|
61
|
+
return siblingPath(input, `${basename(input, extname(input))}${suffix}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function withStaging<T>(action: (dir: string) => Promise<T>): Promise<T> {
|
|
65
|
+
const dir = await mkdtemp(join(await realpath(tmpdir()), "drawme-import-"));
|
|
66
|
+
try {
|
|
67
|
+
return await action(dir);
|
|
68
|
+
} finally {
|
|
69
|
+
await rm(dir, { recursive: true, force: true });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function readEditableXml(path: string, label: string, missing: string): Promise<Document> {
|
|
74
|
+
const xml = await readDiagramXml(path).catch((error: NodeJS.ErrnoException) => {
|
|
75
|
+
if (error.code === "ENOENT") throw new Error(missing);
|
|
76
|
+
throw error;
|
|
77
|
+
});
|
|
78
|
+
try {
|
|
79
|
+
return new DOMParser({ onError: onWarningStopParsing }).parseFromString(xml, "text/xml");
|
|
80
|
+
} catch {
|
|
81
|
+
// Do not surface raw XML snippets from the parser, including renderer output.
|
|
82
|
+
throw new Error(`${label} is not valid XML`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
type XmlElement = Element & DomEl;
|
|
87
|
+
|
|
88
|
+
function pages(doc: Document): DomEl[] {
|
|
89
|
+
const root = doc.documentElement as XmlElement | null;
|
|
90
|
+
if (root?.tagName === "mxfile") return childrenByTag(root, "diagram");
|
|
91
|
+
return root?.tagName === "mxGraphModel" || root?.tagName === "diagram" ? [root] : [];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function editableModel(page: DomEl | undefined, label: string): XmlElement {
|
|
95
|
+
const model = page && graphModel(page);
|
|
96
|
+
if (!model) {
|
|
97
|
+
throw new Error(`${label} has no uncompressed <mxGraphModel>; save the selected page uncompressed in draw.io`);
|
|
98
|
+
}
|
|
99
|
+
return model as XmlElement;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function graphCells(model: DomEl, label: string) {
|
|
103
|
+
const root = firstByTag(model, "root");
|
|
104
|
+
if (!root) throw new Error(`${label} has no graph <root>`);
|
|
105
|
+
const { cells, ids } = collectCellsWithIds(root);
|
|
106
|
+
if (ids.has("") || cells.length !== ids.size) throw new Error(`${label} has missing or duplicate cell IDs`);
|
|
107
|
+
return ids;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function checkedGeometry(cell: DomEl, label: string): XmlElement | undefined {
|
|
111
|
+
const geometries = childrenByTag(cell, "mxGeometry");
|
|
112
|
+
const geometry = geometries[0];
|
|
113
|
+
if (!geometry) return undefined;
|
|
114
|
+
const parts = [geometry, ...childrenByTag(geometry, "mxPoint"), ...childrenByTag(geometry, "mxRectangle")];
|
|
115
|
+
for (const array of childrenByTag(geometry, "Array")) parts.push(...childrenByTag(array, "mxPoint"));
|
|
116
|
+
const invalid = parts.some((part) => ["x", "y", "width", "height"].some((name) => {
|
|
117
|
+
const value = attr(part, name);
|
|
118
|
+
return value !== null && !Number.isFinite(pyFloat(value));
|
|
119
|
+
}));
|
|
120
|
+
if (geometries.length !== 1 || invalid) throw new Error(`${label} has invalid geometry`);
|
|
121
|
+
return geometry as XmlElement;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function installEditableXml(output: string, doc: Document): Promise<void> {
|
|
125
|
+
const xml = new XMLSerializer().serializeToString(doc);
|
|
126
|
+
const bytes = Buffer.byteLength(xml);
|
|
127
|
+
if (bytes > DEFAULT_XML_BYTES) throw new DiagramLimitError(DEFAULT_XML_BYTES);
|
|
128
|
+
// Don't truncate before checking the descriptor. Writing in place keeps existing
|
|
129
|
+
// hard links (including aliases reserved by other diagram mutators) intact.
|
|
130
|
+
const file = await open(output, constants.O_WRONLY | constants.O_CREAT | (constants.O_NONBLOCK ?? 0));
|
|
131
|
+
try {
|
|
132
|
+
if (!(await file.stat()).isFile()) throw new Error(`output is not a regular file: ${output}`);
|
|
133
|
+
await file.writeFile(xml, "utf8");
|
|
134
|
+
await file.truncate(bytes);
|
|
135
|
+
} finally {
|
|
136
|
+
await file.close();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function mermaidFileOperand(input: string): Promise<string> {
|
|
141
|
+
const file = await stat(input).catch((error: NodeJS.ErrnoException) => {
|
|
142
|
+
if (error.code === "ENOENT") throw new Error(`input file not found: ${input}`);
|
|
143
|
+
throw error;
|
|
144
|
+
});
|
|
145
|
+
if (!file.isFile()) throw new Error(`input is not a regular file: ${input}`);
|
|
146
|
+
// Let the OS resolve directory symlink/.. components, but preserve the .mmd
|
|
147
|
+
// basename (draw.io uses the filename extension, including on symlinks).
|
|
148
|
+
return join(await realpath(dirname(input)), basename(input));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Convert Mermaid to a finite, editable diagram. Mermaid already supplies placement. */
|
|
152
|
+
export async function convertMermaid(opts: MermaidOptions): Promise<MermaidResult> {
|
|
153
|
+
const input = opts.input?.trim() ? opts.input : undefined;
|
|
154
|
+
const mermaid = opts.mermaid?.trim() ? opts.mermaid : undefined;
|
|
155
|
+
if ((input === undefined) === (mermaid === undefined)) {
|
|
156
|
+
throw new Error("provide exactly one: either `input` (a .mmd file path) or `mermaid` (inline Mermaid text)");
|
|
157
|
+
}
|
|
158
|
+
const cwd = process.cwd();
|
|
159
|
+
const output = opts.output ?? (input ? defaultOutput(input, ".drawio") : join(cwd, "diagram.drawio"));
|
|
160
|
+
const destination = sessionPath(cwd, output);
|
|
161
|
+
const source = input === undefined ? undefined : sessionPath(cwd, input);
|
|
162
|
+
return withDiagramFiles(source ? [source, destination] : [destination], undefined, async () => {
|
|
163
|
+
const info = await requireFeature("supportsMermaid", "Mermaid conversion", opts.binary);
|
|
164
|
+
return withStaging(async (dir) => {
|
|
165
|
+
const mmd = source ? await mermaidFileOperand(source) : join(dir, "diagram.mmd");
|
|
166
|
+
if (mermaid !== undefined) await writeFile(mmd, mermaid, "utf8");
|
|
167
|
+
const staged = join(dir, "converted.drawio");
|
|
168
|
+
const command = await invokeRenderer(info.binary, mermaidArgs(mmd, staged));
|
|
169
|
+
const label = "Mermaid conversion output";
|
|
170
|
+
const doc = await readEditableXml(staged, label, "Mermaid conversion produced no output");
|
|
171
|
+
const convertedPages = pages(doc);
|
|
172
|
+
if (!convertedPages.length) throw new Error(`${label} has no diagram pages`);
|
|
173
|
+
for (const page of convertedPages) {
|
|
174
|
+
const model = editableModel(page, label);
|
|
175
|
+
for (const cell of graphCells(model, label).values()) checkedGeometry(cell, label);
|
|
176
|
+
model.setAttribute("page", "1");
|
|
177
|
+
}
|
|
178
|
+
await installEditableXml(destination, doc);
|
|
179
|
+
return { output, ...info, command };
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Lay out only the first graph, retaining the original document outside of cell geometry. */
|
|
185
|
+
export async function applyLayout(opts: LayoutOptions): Promise<LayoutResult> {
|
|
186
|
+
const { input, preset } = opts;
|
|
187
|
+
if (!LAYOUT_PRESETS.includes(preset)) {
|
|
188
|
+
throw new Error(`unknown layout preset '${preset}'. Allowed: ${LAYOUT_PRESETS.join(", ")}`);
|
|
189
|
+
}
|
|
190
|
+
const cwd = process.cwd();
|
|
191
|
+
const source = sessionPath(cwd, input);
|
|
192
|
+
const output = opts.output ?? defaultOutput(input, ".layout.drawio");
|
|
193
|
+
const destination = sessionPath(cwd, output);
|
|
194
|
+
return withDiagramFiles([source, destination], undefined, async () => {
|
|
195
|
+
const doc = await readEditableXml(source, "layout input", `input file not found: ${input}`);
|
|
196
|
+
const original = editableModel(pages(doc)[0], "layout input");
|
|
197
|
+
const originalCells = graphCells(original, "layout input");
|
|
198
|
+
const info = await requireFeature("supportsLayout", "The --layout pass", opts.binary);
|
|
199
|
+
return withStaging(async (dir) => {
|
|
200
|
+
const snapshot = join(dir, "selected.drawio");
|
|
201
|
+
const staged = join(dir, "laid-out.drawio");
|
|
202
|
+
await writeFile(snapshot, new XMLSerializer().serializeToString(original), "utf8");
|
|
203
|
+
const command = await invokeRenderer(info.binary, layoutArgs(snapshot, preset, staged));
|
|
204
|
+
const label = "layout output";
|
|
205
|
+
const result = await readEditableXml(staged, label, "layout produced no output");
|
|
206
|
+
const updates = graphCells(editableModel(pages(result)[0], label), label);
|
|
207
|
+
if (updates.size !== originalCells.size) throw new Error(`${label} does not match the selected graph`);
|
|
208
|
+
for (const [id, cell] of originalCells) {
|
|
209
|
+
const update = updates.get(id);
|
|
210
|
+
// Placement is relative to the parent, and waypoints are for these exact terminals.
|
|
211
|
+
if (!update || ["parent", "source", "target"].some((name) => (attr(cell, name) ?? "") !== (attr(update, name) ?? ""))) {
|
|
212
|
+
throw new Error(`${label} does not match the selected graph`);
|
|
213
|
+
}
|
|
214
|
+
const oldGeometry = firstByTag(cell, "mxGeometry") as XmlElement | null;
|
|
215
|
+
const geometry = checkedGeometry(update, label);
|
|
216
|
+
if (oldGeometry && !geometry) throw new Error(`${label} is missing cell geometry`);
|
|
217
|
+
if (geometry) {
|
|
218
|
+
const node = cell as XmlElement;
|
|
219
|
+
const placed = doc.importNode(geometry, true);
|
|
220
|
+
if (oldGeometry) node.replaceChild(placed, oldGeometry);
|
|
221
|
+
else node.appendChild(placed);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
await installEditableXml(destination, doc);
|
|
225
|
+
return { output, preset, ...info, command };
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
}
|
package/src/explain.ts
CHANGED
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
* them (edge labels become the relation verb), and a per-page breakdown for
|
|
5
5
|
* multi-page files. Handy for a README/PR summary or a text-only read-back.
|
|
6
6
|
*/
|
|
7
|
-
import { readFile } from "node:fs/promises";
|
|
8
7
|
import { basename } from "node:path";
|
|
9
8
|
import { DOMParser } from "@xmldom/xmldom";
|
|
10
|
-
import {
|
|
9
|
+
import { readDiagramXml } from "./diagram-files";
|
|
10
|
+
import { type DomEl, attr, childrenByTag, firstByTag, graphModel } from "./dom";
|
|
11
|
+
import { collectCells, isEdgeLabel } from "./geometry";
|
|
11
12
|
|
|
12
13
|
// style fragment -> human noun. First match wins; order matters (specific first).
|
|
13
14
|
const SHAPE_TYPES: [string, string][] = [
|
|
@@ -26,17 +27,16 @@ const SHAPE_TYPES: [string, string][] = [
|
|
|
26
27
|
["shape=hexagon", "queue"],
|
|
27
28
|
];
|
|
28
29
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
.
|
|
36
|
-
|
|
37
|
-
.
|
|
38
|
-
|
|
39
|
-
.replaceAll("&", "&");
|
|
30
|
+
const NAMED_ENTITIES: Record<string, string> = { quot: '"', apos: "'", lt: "<", gt: ">", nbsp: " ", amp: "&" };
|
|
31
|
+
|
|
32
|
+
/** Decode the HTML entities draw.io may leave in a doubly-encoded label, once. */
|
|
33
|
+
function decodeEntities(text: string): string {
|
|
34
|
+
return text.replace(/&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|(quot|apos|lt|gt|nbsp|amp));/g, (reference, decimal, hex, name) => {
|
|
35
|
+
if (name) return NAMED_ENTITIES[name];
|
|
36
|
+
const code = hex ? Number.parseInt(hex, 16) : Number(decimal);
|
|
37
|
+
if (code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)) return reference;
|
|
38
|
+
return String.fromCodePoint(code);
|
|
39
|
+
});
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
/** Strip tag-shaped spans in linear time while preserving unmatched delimiters. */
|
|
@@ -46,10 +46,11 @@ function stripTags(text: string): string {
|
|
|
46
46
|
let tagStart = -1;
|
|
47
47
|
|
|
48
48
|
for (let i = 0; i < text.length; i += 1) {
|
|
49
|
-
if (text[i] === "<"
|
|
49
|
+
if (text[i] === "<") {
|
|
50
50
|
tagStart = i;
|
|
51
51
|
} else if (text[i] === ">" && tagStart !== -1) {
|
|
52
|
-
|
|
52
|
+
// Do not mistake angle-bracketed URLs or comparisons for HTML tags.
|
|
53
|
+
if (/^<(?:\/?[a-z][a-z0-9-]*(?:\s[^<>]*)?\/?|!--[^<>]*--)>$/i.test(text.slice(tagStart, i + 1))) {
|
|
53
54
|
parts.push(text.slice(copiedThrough, tagStart));
|
|
54
55
|
copiedThrough = i + 1;
|
|
55
56
|
}
|
|
@@ -68,6 +69,16 @@ function clean(text: string | null): string {
|
|
|
68
69
|
return decodeEntities(stripTags(withLineBreaks)).replace(/\s+/g, " ").trim();
|
|
69
70
|
}
|
|
70
71
|
|
|
72
|
+
/** One line of literal Markdown text, including in GFM autolink and list contexts. */
|
|
73
|
+
function literal(text: string): string {
|
|
74
|
+
// ASCII punctuation is backslash-escapable; the empty pair <> is already inert.
|
|
75
|
+
return text.replace(/\s+/g, " ").trim().replace(/<>|[!-/:-@[-`{-~]/g, (part) => part === "<>" ? part : `\\${part}`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function displayName(label: string, id: string | null): string {
|
|
79
|
+
return label ? literal(label) : `(unlabeled ${literal(id ?? "null")})`;
|
|
80
|
+
}
|
|
81
|
+
|
|
71
82
|
function shapeOf(style: string): string | null {
|
|
72
83
|
for (const [frag, noun] of SHAPE_TYPES) if ((style || "").includes(frag)) return noun;
|
|
73
84
|
return null;
|
|
@@ -79,51 +90,35 @@ interface Entry {
|
|
|
79
90
|
label: string;
|
|
80
91
|
}
|
|
81
92
|
|
|
82
|
-
/** Entries for a page, unwrapping UserObject/object wrappers; null for a compressed/empty page. */
|
|
83
|
-
function cellsOf(page: DomEl): Entry[] | null {
|
|
84
|
-
const model = firstByTag(page, "mxGraphModel");
|
|
85
|
-
const root = model ? firstByTag(model, "root") : null;
|
|
86
|
-
if (!root) return null;
|
|
87
|
-
const out: Entry[] = [];
|
|
88
|
-
for (const child of elemChildren(root)) {
|
|
89
|
-
if (child.tagName === "mxCell") {
|
|
90
|
-
out.push({ cell: child, id: attr(child, "id"), label: clean(attr(child, "value")) });
|
|
91
|
-
} else if (child.tagName === "UserObject" || child.tagName === "object") {
|
|
92
|
-
const inner = firstByTag(child, "mxCell");
|
|
93
|
-
if (inner) {
|
|
94
|
-
inner.setAttribute("id", attr(child, "id") ?? "");
|
|
95
|
-
out.push({ cell: inner, id: attr(child, "id"), label: clean(attr(child, "label") ?? attr(child, "value")) });
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
return out;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
93
|
interface PageIndex {
|
|
103
|
-
/** cell id -> cleaned label */
|
|
104
|
-
|
|
105
|
-
/**
|
|
106
|
-
|
|
94
|
+
/** cell id -> cleaned label, including empty labels */
|
|
95
|
+
labels: Map<string, string>;
|
|
96
|
+
/** parent edge id -> separate label texts in file order */
|
|
97
|
+
edgeLabels: Map<string, string[]>;
|
|
107
98
|
/** ids of vertices that are a parent of some other cell */
|
|
108
99
|
containers: Set<string>;
|
|
109
100
|
}
|
|
110
101
|
|
|
111
|
-
/** Index a page's cells: labels, styles, and which vertices act as containers. */
|
|
112
102
|
function indexPage(cells: Entry[]): PageIndex {
|
|
113
|
-
const
|
|
114
|
-
const
|
|
103
|
+
const labels = new Map<string, string>();
|
|
104
|
+
const edgeLabels = new Map<string, string[]>();
|
|
115
105
|
const parents = new Set<string>();
|
|
116
|
-
for (const
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
106
|
+
for (const { id, cell, label } of cells) {
|
|
107
|
+
if (id !== null) labels.set(id, label);
|
|
108
|
+
const parent = attr(cell, "parent");
|
|
109
|
+
if (!parent) continue;
|
|
110
|
+
parents.add(parent);
|
|
111
|
+
if (label && cell.getAttribute("vertex") === "1" && isEdgeLabel(cell)) {
|
|
112
|
+
const siblings = edgeLabels.get(parent);
|
|
113
|
+
if (siblings) siblings.push(label);
|
|
114
|
+
else edgeLabels.set(parent, [label]);
|
|
115
|
+
}
|
|
121
116
|
}
|
|
122
117
|
const containers = new Set<string>();
|
|
123
118
|
for (const e of cells) {
|
|
124
119
|
if (e.cell.getAttribute("vertex") === "1" && e.id !== null && parents.has(e.id)) containers.add(e.id);
|
|
125
120
|
}
|
|
126
|
-
return {
|
|
121
|
+
return { labels, edgeLabels, containers };
|
|
127
122
|
}
|
|
128
123
|
|
|
129
124
|
/** Leaf vertices: real nodes (not containers, not edge labels). */
|
|
@@ -132,64 +127,62 @@ function leafEntries(cells: Entry[], idx: PageIndex): Entry[] {
|
|
|
132
127
|
(e) =>
|
|
133
128
|
e.cell.getAttribute("vertex") === "1" &&
|
|
134
129
|
(e.id === null || !idx.containers.has(e.id)) &&
|
|
135
|
-
!(
|
|
130
|
+
!isEdgeLabel(e.cell),
|
|
136
131
|
);
|
|
137
132
|
}
|
|
138
133
|
|
|
139
134
|
/** Group leaves by their container's label (else "Ungrouped"), keeping first-seen order. */
|
|
140
|
-
function
|
|
135
|
+
function renderComponents(leaves: Entry[], idx: PageIndex): string[] {
|
|
141
136
|
const groups = new Map<string, string[]>();
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
const
|
|
145
|
-
const
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const typ = shapeOf(idx.style.get(e.id) ?? "");
|
|
152
|
-
const name = idx.label.get(e.id) || `(unlabeled ${e.id})`;
|
|
153
|
-
groups.get(gname)!.push(name + (typ ? ` _${typ}_` : ""));
|
|
137
|
+
for (const { cell, id, label } of leaves) {
|
|
138
|
+
const parent = attr(cell, "parent");
|
|
139
|
+
const named = parent !== null && idx.containers.has(parent) ? idx.labels.get(parent) : undefined;
|
|
140
|
+
const group = named || "Ungrouped";
|
|
141
|
+
const typ = shapeOf(attr(cell, "style") ?? "");
|
|
142
|
+
const item = displayName(label, id) + (typ ? ` _${typ}_` : "");
|
|
143
|
+
const items = groups.get(group);
|
|
144
|
+
if (items) items.push(item);
|
|
145
|
+
else groups.set(group, [item]);
|
|
154
146
|
}
|
|
155
|
-
return { groups, order };
|
|
156
|
-
}
|
|
157
147
|
|
|
158
|
-
function renderComponents(leaves: Entry[], groups: Map<string, string[]>, order: string[]): string[] {
|
|
159
148
|
const lines: string[] = [`### Components (${leaves.length})`, ""];
|
|
160
|
-
const
|
|
161
|
-
for (const
|
|
162
|
-
if (
|
|
163
|
-
|
|
164
|
-
} else {
|
|
165
|
-
lines.push(`- **${gname}**`);
|
|
166
|
-
for (const item of groups.get(gname)!) lines.push(` - ${item}`);
|
|
167
|
-
}
|
|
149
|
+
const flat = groups.size === 1 && groups.has("Ungrouped");
|
|
150
|
+
for (const [group, items] of groups) {
|
|
151
|
+
if (!flat) lines.push(`- **${literal(group)}**`);
|
|
152
|
+
for (const item of items) lines.push(`${flat ? "" : " "}- ${item}`);
|
|
168
153
|
}
|
|
169
|
-
lines
|
|
170
|
-
return lines;
|
|
154
|
+
return [...lines, ""];
|
|
171
155
|
}
|
|
172
156
|
|
|
173
157
|
function renderRelations(cells: Entry[], idx: PageIndex): string[] {
|
|
174
158
|
const rels: string[] = [];
|
|
175
159
|
for (const e of cells) {
|
|
176
160
|
if (e.cell.getAttribute("edge") !== "1") continue;
|
|
177
|
-
const
|
|
178
|
-
const
|
|
179
|
-
if (!
|
|
180
|
-
const
|
|
181
|
-
|
|
161
|
+
const source = attr(e.cell, "source");
|
|
162
|
+
const target = attr(e.cell, "target");
|
|
163
|
+
if (!source || !target) continue;
|
|
164
|
+
const sourceLabel = idx.labels.get(source);
|
|
165
|
+
const targetLabel = idx.labels.get(target);
|
|
166
|
+
if (sourceLabel === undefined || targetLabel === undefined) continue; // dangling endpoint
|
|
167
|
+
const children = e.id === null ? [] : idx.edgeLabels.get(e.id) ?? [];
|
|
168
|
+
const verb = [e.label, ...children].filter(Boolean).map(literal).join("; ");
|
|
169
|
+
const from = displayName(sourceLabel, source);
|
|
170
|
+
const to = displayName(targetLabel, target);
|
|
171
|
+
rels.push(verb ? `- ${from} —${verb}→ ${to}` : `- ${from} → ${to}`);
|
|
182
172
|
}
|
|
183
173
|
return [`### Relations (${rels.length})`, "", ...(rels.length ? rels : ["_(none)_"]), ""];
|
|
184
174
|
}
|
|
185
175
|
|
|
186
176
|
function describePage(page: DomEl): string[] {
|
|
187
|
-
const
|
|
188
|
-
if (
|
|
177
|
+
const model = graphModel(page);
|
|
178
|
+
if (!model) return ["_(compressed page — cannot describe)_"];
|
|
179
|
+
const cells = collectCells(firstByTag(model, "root")).map((cell) => ({
|
|
180
|
+
cell,
|
|
181
|
+
id: attr(cell, "id") || null,
|
|
182
|
+
label: clean(attr(cell, "value")),
|
|
183
|
+
}));
|
|
189
184
|
const idx = indexPage(cells);
|
|
190
|
-
|
|
191
|
-
const { groups, order } = groupLeaves(leaves, idx);
|
|
192
|
-
return [...renderComponents(leaves, groups, order), ...renderRelations(cells, idx)];
|
|
185
|
+
return [...renderComponents(leafEntries(cells, idx), idx), ...renderRelations(cells, idx)];
|
|
193
186
|
}
|
|
194
187
|
|
|
195
188
|
/** Describe a `.drawio` XML string as Markdown. */
|
|
@@ -200,10 +193,10 @@ export function explainXml(xml: string, title = "diagram"): string {
|
|
|
200
193
|
const pageList = childrenByTag(rootEl, "diagram");
|
|
201
194
|
const pages = pageList.length ? pageList : [rootEl];
|
|
202
195
|
|
|
203
|
-
const lines: string[] = [`# ${title}`, ""];
|
|
196
|
+
const lines: string[] = [`# ${literal(title)}`, ""];
|
|
204
197
|
pages.forEach((page, i) => {
|
|
205
198
|
if (pages.length > 1) {
|
|
206
|
-
const name = attr(page, "name");
|
|
199
|
+
const name = literal(attr(page, "name") ?? "");
|
|
207
200
|
lines.push(name ? `## Page ${i + 1}: ${name}` : `## Page ${i + 1}`, "");
|
|
208
201
|
}
|
|
209
202
|
lines.push(...describePage(page));
|
|
@@ -213,7 +206,7 @@ export function explainXml(xml: string, title = "diagram"): string {
|
|
|
213
206
|
|
|
214
207
|
/** Read a `.drawio` file and describe it as Markdown. */
|
|
215
208
|
export async function explainFile(path: string): Promise<string> {
|
|
216
|
-
const xml = await
|
|
209
|
+
const xml = await readDiagramXml(path);
|
|
217
210
|
const title = basename(path).replace(/\.[^.]*$/, "");
|
|
218
211
|
return explainXml(xml, title);
|
|
219
212
|
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { platform } from "node:os";
|
|
2
|
+
import { basename, extname } from "node:path";
|
|
3
|
+
import { siblingPath } from "./diagram-files";
|
|
4
|
+
import { DEFAULT_FIT_MARGIN } from "./fitcanvas";
|
|
5
|
+
import { assertRendererUser } from "./renderer";
|
|
6
|
+
|
|
7
|
+
export type ExportFormat = "png" | "svg" | "pdf" | "jpg";
|
|
8
|
+
export type ExportMode = "preview" | "final";
|
|
9
|
+
|
|
10
|
+
export interface ExportOptions {
|
|
11
|
+
input: string;
|
|
12
|
+
format?: ExportFormat;
|
|
13
|
+
mode?: ExportMode;
|
|
14
|
+
output?: string;
|
|
15
|
+
scale?: number;
|
|
16
|
+
width?: number;
|
|
17
|
+
height?: number;
|
|
18
|
+
transparent?: boolean;
|
|
19
|
+
border?: number;
|
|
20
|
+
pageIndex?: number;
|
|
21
|
+
embed?: boolean;
|
|
22
|
+
/** Require and verify animation in a final SVG, compiling portable page sequences when present. */
|
|
23
|
+
animated?: boolean;
|
|
24
|
+
binary?: string;
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ExportPlan {
|
|
29
|
+
format: ExportFormat;
|
|
30
|
+
mode: ExportMode;
|
|
31
|
+
embed: boolean;
|
|
32
|
+
animated: boolean;
|
|
33
|
+
output: string;
|
|
34
|
+
/** Export flags ending with `-o <output>`. The input path is appended after these. */
|
|
35
|
+
args: string[];
|
|
36
|
+
input: string;
|
|
37
|
+
/** Flags that must go AFTER the input path on Linux (draw.io argument-parsing quirk). */
|
|
38
|
+
linuxExtra: string[];
|
|
39
|
+
/** SVG only: outer margin DrawMe adds after export (draw.io's own SVG border is uneven). */
|
|
40
|
+
svgMargin: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const MAX_FINAL_RASTER_PIXELS = 6_000_000;
|
|
44
|
+
export const MAX_REVIEW_SIDE = 2_000;
|
|
45
|
+
|
|
46
|
+
/** Derive a sibling without normalizing symlink/.. in its parent path. */
|
|
47
|
+
export function deriveOutput(input: string, format: ExportFormat, embed: boolean, mode: ExportMode = "final"): string {
|
|
48
|
+
const name = basename(input);
|
|
49
|
+
const ext = extname(name);
|
|
50
|
+
const stem = ext ? name.slice(0, -ext.length) : name;
|
|
51
|
+
const suffix = mode === "preview" ? `preview.${format}` : format === "png" && embed ? "drawio.png" : format;
|
|
52
|
+
return siblingPath(input, `${stem}.${suffix}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function requirePositiveInteger(name: string, value: number | undefined): void {
|
|
56
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value <= 0)) {
|
|
57
|
+
throw new Error(`${name} must be a positive integer`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isPositiveFinite(value: number | undefined): value is number {
|
|
62
|
+
return value !== undefined && Number.isFinite(value) && value > 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The requested scale, lowered so the bordered raster stays within MAX_FINAL_RASTER_PIXELS. */
|
|
66
|
+
export function cappedScale(scale: number, margin: number, contentWidth?: number, contentHeight?: number): number {
|
|
67
|
+
if (!isPositiveFinite(contentWidth) || !isPositiveFinite(contentHeight)) return scale;
|
|
68
|
+
const max = Math.sqrt(MAX_FINAL_RASTER_PIXELS) / Math.sqrt(contentWidth + 2 * margin) / Math.sqrt(contentHeight + 2 * margin);
|
|
69
|
+
if (scale <= max) return scale;
|
|
70
|
+
// Leave rounding room at ordinary scales, without rounding very small scales to zero.
|
|
71
|
+
return Math.floor(max * 100) / 100 || max;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
type Sizing = { flag: "--width" | "--height" | "-s"; value: number; border: number };
|
|
75
|
+
|
|
76
|
+
/** Find the largest fitting request on one axis. The other axis is only an estimate. */
|
|
77
|
+
function boundedSide(request: number, border: number, sideLimit: number, ratio?: number): number {
|
|
78
|
+
const padding = 2 * border;
|
|
79
|
+
const hi = Math.min(request, sideLimit);
|
|
80
|
+
const lo = Math.floor(padding) + 1;
|
|
81
|
+
if (hi < lo) throw new Error("raster size is too small for the border; reduce border or change the requested size");
|
|
82
|
+
// With unmeasurable bounds a single axis does not guarantee the actual area.
|
|
83
|
+
if (ratio === undefined) return hi;
|
|
84
|
+
|
|
85
|
+
const fits = (side: number) => {
|
|
86
|
+
// draw.io fits the content to the given axis, adds padding, then resizes the
|
|
87
|
+
// bordered image to enforce the final dimension. Reserve room for rounding on the other axis.
|
|
88
|
+
const estimated = Math.ceil(side * ((side * ratio + padding) / (side + padding))) + 2;
|
|
89
|
+
const other = ratio <= 1 ? Math.min(side, estimated) : estimated;
|
|
90
|
+
return other <= sideLimit && side * other <= MAX_FINAL_RASTER_PIXELS;
|
|
91
|
+
};
|
|
92
|
+
let low = lo;
|
|
93
|
+
let high = hi;
|
|
94
|
+
while (low <= high) {
|
|
95
|
+
const side = Math.floor((low + high) / 2);
|
|
96
|
+
if (fits(side)) low = side + 1;
|
|
97
|
+
else high = side - 1;
|
|
98
|
+
}
|
|
99
|
+
if (high < lo) throw new Error("raster aspect and border cannot fit the pixel budget; use a smaller border or split the diagram");
|
|
100
|
+
return high;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function rasterSize(opts: ExportOptions, mode: ExportMode, margin: number, width?: number, height?: number): Sizing {
|
|
104
|
+
const explicit = opts.width ?? opts.height;
|
|
105
|
+
const byHeight = explicit !== undefined ? opts.width === undefined : isPositiveFinite(height) && (!isPositiveFinite(width) || height > width);
|
|
106
|
+
const primary = byHeight ? height : width;
|
|
107
|
+
const secondary = byHeight ? width : height;
|
|
108
|
+
const ratio = isPositiveFinite(primary) && isPositiveFinite(secondary) ? secondary / primary : undefined;
|
|
109
|
+
const sideLimit = mode === "preview" ? MAX_REVIEW_SIDE : MAX_FINAL_RASTER_PIXELS;
|
|
110
|
+
const flag = byHeight ? "--height" : "--width";
|
|
111
|
+
if (explicit !== undefined || mode === "preview") {
|
|
112
|
+
return { flag, value: boundedSide(explicit ?? MAX_REVIEW_SIDE, margin, sideLimit, ratio), border: margin };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const scale = cappedScale(opts.scale ?? 2, margin, width, height);
|
|
116
|
+
if (!isPositiveFinite(primary)) return { flag: "-s", value: scale, border: margin };
|
|
117
|
+
// With an explicit axis the border is in output pixels, on all sides. Size
|
|
118
|
+
// the diagram and border together so scale applies evenly to both.
|
|
119
|
+
const border = Math.floor(margin * scale);
|
|
120
|
+
const side = Math.max(1, Math.round(primary * scale)) + 2 * border;
|
|
121
|
+
return { flag, value: boundedSide(side, border, sideLimit, ratio), border };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Build export arguments without touching either the input or destination. */
|
|
125
|
+
export function planExport(
|
|
126
|
+
opts: ExportOptions,
|
|
127
|
+
plat: string = platform(),
|
|
128
|
+
isRoot = false,
|
|
129
|
+
contentWidth?: number,
|
|
130
|
+
contentHeight?: number,
|
|
131
|
+
): ExportPlan {
|
|
132
|
+
const animated = opts.animated ?? false;
|
|
133
|
+
const format = opts.format ?? (animated ? "svg" : "png");
|
|
134
|
+
const mode = opts.mode ?? "final";
|
|
135
|
+
if (animated && format !== "svg") throw new Error("animated export requires format='svg'");
|
|
136
|
+
if (animated && mode !== "final") throw new Error("animated export requires mode='final'; use a PNG preview for review");
|
|
137
|
+
if (format === "jpg" && opts.embed === true) throw new Error("JPEG (JPG) cannot embed an editable diagram");
|
|
138
|
+
const embed = mode === "final" && (opts.embed ?? format !== "jpg");
|
|
139
|
+
const output = opts.output ?? deriveOutput(opts.input, format, embed, mode);
|
|
140
|
+
const ext = extname(output).toLowerCase();
|
|
141
|
+
if (opts.output !== undefined && ext && ext !== `.${format}` && !(format === "jpg" && ext === ".jpeg")) {
|
|
142
|
+
throw new Error(`output suffix ${ext} does not match export format ${format}`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
requirePositiveInteger("pageIndex", opts.pageIndex);
|
|
146
|
+
requirePositiveInteger("width", opts.width);
|
|
147
|
+
requirePositiveInteger("height", opts.height);
|
|
148
|
+
if (opts.scale !== undefined && !isPositiveFinite(opts.scale)) throw new Error("scale must be finite and positive");
|
|
149
|
+
const margin = opts.border ?? DEFAULT_FIT_MARGIN;
|
|
150
|
+
if (!Number.isFinite(margin) || margin < 0) throw new Error("border must be finite and nonnegative");
|
|
151
|
+
assertRendererUser(plat, isRoot);
|
|
152
|
+
|
|
153
|
+
const args: string[] = ["-x", "-f", format];
|
|
154
|
+
if (embed) args.push("-e");
|
|
155
|
+
let border = margin;
|
|
156
|
+
if (format === "png" || format === "jpg") {
|
|
157
|
+
const size = rasterSize(opts, mode, margin, contentWidth, contentHeight);
|
|
158
|
+
args.push(size.flag, String(size.value));
|
|
159
|
+
border = size.border;
|
|
160
|
+
} else if (format === "svg") {
|
|
161
|
+
if (opts.width !== undefined) args.push("--width", String(opts.width));
|
|
162
|
+
else if (opts.height !== undefined) args.push("--height", String(opts.height));
|
|
163
|
+
border = 0;
|
|
164
|
+
}
|
|
165
|
+
// PDF retains authored print-page sizing; width/height would switch to a content crop.
|
|
166
|
+
args.push("-b", String(border));
|
|
167
|
+
if (opts.transparent && format === "png") args.push("-t");
|
|
168
|
+
if (opts.pageIndex !== undefined) args.push("--page-index", String(opts.pageIndex));
|
|
169
|
+
args.push("-o", output);
|
|
170
|
+
return {
|
|
171
|
+
format, mode, embed, animated, output, args, input: opts.input,
|
|
172
|
+
linuxExtra: plat === "linux" ? ["--disable-gpu"] : [],
|
|
173
|
+
svgMargin: format === "svg" ? margin : 0,
|
|
174
|
+
};
|
|
175
|
+
}
|