@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/CHANGELOG.md +45 -1
- package/README.md +34 -18
- package/assets/references/diagram-types.md +1 -1
- package/assets/references/style-presets.md +94 -0
- package/assets/references/xml-authoring.md +101 -8
- package/docs/reference.md +96 -12
- package/example/README.md +37 -0
- package/example/drawme-architecture.drawio +62 -0
- package/example/drawme-how-it-works.drawio +79 -122
- package/example/drawme-installation-guide.drawio +63 -97
- package/example/drawme-validation-decision-tree.drawio +79 -73
- package/example/event-driven-orders.drawio +119 -0
- package/example/git-graph-example.drawio +77 -69
- package/package.json +7 -7
- package/src/animate.ts +177 -0
- package/src/animation.ts +637 -0
- package/src/drawio.ts +130 -34
- package/src/fitcanvas.ts +1 -1
- package/src/geometry.ts +30 -14
- package/src/index.ts +120 -17
- package/src/motion.ts +839 -0
- package/src/storyboard.ts +161 -0
- package/src/svgexport.ts +124 -0
- package/src/validate.ts +448 -6
- package/src/workflow.ts +8 -5
- package/example/drawme-extension-waterfall-overview.drawio +0 -72
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Storyboard: renders a motion timeline as a grid of static frames on one
|
|
3
|
+
* draw.io page, one tile per sequential step, so motion order and visibility
|
|
4
|
+
* can be reviewed in a single PNG. Each tile is a copy of the page with cell
|
|
5
|
+
* opacity set to its state after that step; highlight and travel steps show
|
|
6
|
+
* their accent color on the stroke.
|
|
7
|
+
*/
|
|
8
|
+
import { XMLSerializer } from "@xmldom/xmldom";
|
|
9
|
+
import { type DomEl, attr, elemChildren, firstByTag } from "./dom";
|
|
10
|
+
import { contentBounds, collectCellsWithIds, pyFloat } from "./geometry";
|
|
11
|
+
import { shiftCell } from "./fitcanvas";
|
|
12
|
+
import { type MotionFrame, isDarkBackground } from "./motion";
|
|
13
|
+
|
|
14
|
+
export const MAX_STORYBOARD_FRAMES = 12;
|
|
15
|
+
const GAP = 80;
|
|
16
|
+
const CAPTION_HEIGHT = 56;
|
|
17
|
+
|
|
18
|
+
interface PageEntry {
|
|
19
|
+
id: string;
|
|
20
|
+
element: DomEl;
|
|
21
|
+
cell: DomEl;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function escapeXml(value: string): string {
|
|
25
|
+
return value
|
|
26
|
+
.replaceAll("&", "&")
|
|
27
|
+
.replaceAll("<", "<")
|
|
28
|
+
.replaceAll(">", ">")
|
|
29
|
+
.replaceAll('"', """);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function setStyle(style: string, values: Record<string, string>): string {
|
|
33
|
+
const items = style.split(";").filter((item) => item.trim() !== "");
|
|
34
|
+
for (const [key, value] of Object.entries(values)) {
|
|
35
|
+
const index = items.findIndex((item) => item.split("=")[0].trim() === key);
|
|
36
|
+
if (index >= 0) items[index] = `${key}=${value}`;
|
|
37
|
+
else items.push(`${key}=${value}`);
|
|
38
|
+
}
|
|
39
|
+
return `${items.join(";")};`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Evenly sample at most MAX_STORYBOARD_FRAMES frames, always keeping the first and last. */
|
|
43
|
+
export function sampleFrames(frames: MotionFrame[]): MotionFrame[] {
|
|
44
|
+
if (frames.length <= MAX_STORYBOARD_FRAMES) return frames;
|
|
45
|
+
const last = frames.length - 1;
|
|
46
|
+
const picks = new Set<number>();
|
|
47
|
+
for (let i = 0; i < MAX_STORYBOARD_FRAMES; i++) picks.add(Math.round((i * last) / (MAX_STORYBOARD_FRAMES - 1)));
|
|
48
|
+
return [...picks].map((index) => frames[index]);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function pageSize(model: DomEl): { width: number; height: number } {
|
|
52
|
+
const width = pyFloat(attr(model, "pageWidth") ?? "");
|
|
53
|
+
const height = pyFloat(attr(model, "pageHeight") ?? "");
|
|
54
|
+
if (width !== undefined && height !== undefined && width > 0 && height > 0 && Number.isFinite(width + height)) {
|
|
55
|
+
return { width, height };
|
|
56
|
+
}
|
|
57
|
+
const { cells, ids } = collectCellsWithIds(firstByTag(model, "root"));
|
|
58
|
+
const bounds = contentBounds(cells, ids);
|
|
59
|
+
return { width: Math.ceil((bounds?.maxX ?? 800) + 40), height: Math.ceil((bounds?.maxY ?? 600) + 40) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function pageEntries(model: DomEl): PageEntry[] {
|
|
63
|
+
const root = firstByTag(model, "root");
|
|
64
|
+
const entries: PageEntry[] = [];
|
|
65
|
+
for (const element of root ? elemChildren(root) : []) {
|
|
66
|
+
const cell = element.tagName === "mxCell" ? element : firstByTag(element, "mxCell");
|
|
67
|
+
const id = attr(element, "id");
|
|
68
|
+
if (cell && id !== null) entries.push({ id, element, cell });
|
|
69
|
+
}
|
|
70
|
+
return entries;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Opacity a cell shows in a frame: its own value times every container ancestor's (SVG groups nest). */
|
|
74
|
+
function effectiveOpacity(id: string, frame: MotionFrame, parents: Map<string, string | null>): number {
|
|
75
|
+
let opacity = 1;
|
|
76
|
+
let current: string | null | undefined = id;
|
|
77
|
+
const seen = new Set<string>();
|
|
78
|
+
while (current && !seen.has(current)) {
|
|
79
|
+
seen.add(current);
|
|
80
|
+
opacity *= frame.opacity.get(current) ?? 1;
|
|
81
|
+
current = parents.get(current);
|
|
82
|
+
}
|
|
83
|
+
return opacity;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function storyboardCell(entry: PageEntry, prefix: string, layers: Set<string>, ox: number, oy: number): DomEl {
|
|
87
|
+
const element = (entry.element as unknown as { cloneNode(deep: boolean): DomEl }).cloneNode(true);
|
|
88
|
+
const cell = element.tagName === "mxCell" ? element : firstByTag(element, "mxCell")!;
|
|
89
|
+
element.setAttribute("id", `${prefix}${entry.id}`);
|
|
90
|
+
const parent = attr(cell, "parent");
|
|
91
|
+
const topLevel = parent === null || layers.has(parent);
|
|
92
|
+
cell.setAttribute("parent", topLevel ? "1" : `${prefix}${parent}`);
|
|
93
|
+
for (const end of ["source", "target"]) {
|
|
94
|
+
const ref = attr(cell, end);
|
|
95
|
+
if (ref !== null) cell.setAttribute(end, `${prefix}${ref}`);
|
|
96
|
+
}
|
|
97
|
+
if (topLevel) shiftCell(cell, ox, oy);
|
|
98
|
+
return element;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function applyFrameStyle(element: DomEl, id: string, frame: MotionFrame, parents: Map<string, string | null>): void {
|
|
102
|
+
const cell = element.tagName === "mxCell" ? element : firstByTag(element, "mxCell")!;
|
|
103
|
+
const updates: Record<string, string> = {};
|
|
104
|
+
const opacity = effectiveOpacity(id, frame, parents);
|
|
105
|
+
if (opacity < 1) {
|
|
106
|
+
const percent = String(Math.round(opacity * 100));
|
|
107
|
+
Object.assign(updates, { opacity: percent, textOpacity: percent });
|
|
108
|
+
}
|
|
109
|
+
const accent = frame.accent.get(id);
|
|
110
|
+
if (accent) Object.assign(updates, { strokeColor: accent, strokeWidth: "3" });
|
|
111
|
+
if (Object.keys(updates).length > 0) cell.setAttribute("style", setStyle(attr(cell, "style") ?? "", updates));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Build a one-page `.drawio` document that lays out the frames as a captioned grid. */
|
|
115
|
+
export function buildStoryboard(model: DomEl, frames: MotionFrame[]): string {
|
|
116
|
+
if (frames.length === 0) throw new Error("motion has no visual steps to storyboard");
|
|
117
|
+
const { width, height } = pageSize(model);
|
|
118
|
+
const entries = pageEntries(model);
|
|
119
|
+
const parents = new Map(entries.map((entry) => [entry.id, attr(entry.cell, "parent")]));
|
|
120
|
+
const layers = new Set(entries.filter((entry) => attr(entry.cell, "parent") === "0").map((entry) => entry.id));
|
|
121
|
+
const columns = Math.min(frames.length, width >= height ? 2 : 3);
|
|
122
|
+
const rows = Math.ceil(frames.length / columns);
|
|
123
|
+
const tileHeight = CAPTION_HEIGHT + height;
|
|
124
|
+
const serializer = new XMLSerializer();
|
|
125
|
+
const parts: string[] = [];
|
|
126
|
+
const dark = isDarkBackground(attr(model, "background"));
|
|
127
|
+
const captionColor = dark ? "#CBD5E1" : "#334155";
|
|
128
|
+
const frameColor = dark ? "#334155" : "#CBD5E1";
|
|
129
|
+
|
|
130
|
+
frames.forEach((frame, index) => {
|
|
131
|
+
const prefix = `f${index + 1}-`;
|
|
132
|
+
const ox = GAP + (index % columns) * (width + GAP);
|
|
133
|
+
const oy = GAP + Math.floor(index / columns) * (tileHeight + GAP);
|
|
134
|
+
const seconds = (frame.time / 1000).toFixed(1);
|
|
135
|
+
const caption = `${index + 1} · ${seconds}s · ${frame.label}`;
|
|
136
|
+
parts.push(
|
|
137
|
+
`<mxCell id="${prefix}frame" value="" style="rounded=1;absoluteArcSize=1;arcSize=16;fillColor=none;strokeColor=${frameColor};dashed=1;" vertex="1" parent="1"><mxGeometry x="${ox}" y="${oy + CAPTION_HEIGHT}" width="${width}" height="${height}" as="geometry"/></mxCell>`,
|
|
138
|
+
`<mxCell id="${prefix}caption" value="${escapeXml(caption)}" style="text;html=1;align=left;verticalAlign=middle;whiteSpace=wrap;fontSize=22;fontStyle=1;fontColor=${captionColor};" vertex="1" parent="1"><mxGeometry x="${ox}" y="${oy}" width="${width}" height="${CAPTION_HEIGHT - 8}" as="geometry"/></mxCell>`,
|
|
139
|
+
);
|
|
140
|
+
for (const entry of entries) {
|
|
141
|
+
if (entry.id === "0" || layers.has(entry.id)) continue;
|
|
142
|
+
const element = storyboardCell(entry, prefix, layers, ox, oy + CAPTION_HEIGHT);
|
|
143
|
+
applyFrameStyle(element, entry.id, frame, parents);
|
|
144
|
+
parts.push(serializer.serializeToString(element as never));
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
const pageWidth = GAP + columns * (width + GAP);
|
|
149
|
+
const pageHeight = GAP + rows * (tileHeight + GAP);
|
|
150
|
+
const background = attr(model, "background");
|
|
151
|
+
const backgroundAttr = background ? ` background="${escapeXml(background)}"` : "";
|
|
152
|
+
return [
|
|
153
|
+
'<mxfile host="drawme">',
|
|
154
|
+
'<diagram name="Storyboard">',
|
|
155
|
+
`<mxGraphModel grid="0" page="1" pageScale="1" pageWidth="${pageWidth}" pageHeight="${pageHeight}"${backgroundAttr}>`,
|
|
156
|
+
'<root><mxCell id="0"/><mxCell id="1" parent="0"/>',
|
|
157
|
+
...parts,
|
|
158
|
+
"</root></mxGraphModel></diagram></mxfile>",
|
|
159
|
+
"",
|
|
160
|
+
].join("\n");
|
|
161
|
+
}
|
package/src/svgexport.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* draw.io SVG post-processing: an even outer margin, and authored colors.
|
|
3
|
+
*
|
|
4
|
+
* Pin draw.io SVG exports to their authored colors. draw.io wraps every color
|
|
5
|
+
* in CSS `light-dark(authored, generated-dark)` and declares
|
|
6
|
+
* `color-scheme: light dark`, so a viewer in dark mode sees an automatically
|
|
7
|
+
* inverted diagram that no longer matches the PNG/PDF output or the chosen
|
|
8
|
+
* theme. Resolving each `light-dark()` to its first argument makes every
|
|
9
|
+
* export show the same colors in every viewer.
|
|
10
|
+
*/
|
|
11
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
12
|
+
import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
|
|
13
|
+
import { type DomEl, TEXT_NODE, attr, elemChildren } from "./dom";
|
|
14
|
+
|
|
15
|
+
const FUNCTION = "light-dark(";
|
|
16
|
+
const CDATA_NODE = 4;
|
|
17
|
+
|
|
18
|
+
/** Replace every `light-dark(a, b)` in a CSS string with `a`, honoring nested parentheses. */
|
|
19
|
+
export function resolveLightDark(css: string): string {
|
|
20
|
+
let result = "";
|
|
21
|
+
let index = 0;
|
|
22
|
+
for (;;) {
|
|
23
|
+
const start = css.indexOf(FUNCTION, index);
|
|
24
|
+
if (start < 0) return result + css.slice(index);
|
|
25
|
+
const { depth, comma, cursor } = findFunctionEnd(css, start + FUNCTION.length);
|
|
26
|
+
if (depth !== 0) return result + css.slice(index);
|
|
27
|
+
const end = cursor - 1;
|
|
28
|
+
const first = css.slice(start + FUNCTION.length, comma < 0 ? end : comma).trim();
|
|
29
|
+
result += css.slice(index, start) + resolveLightDark(first);
|
|
30
|
+
index = cursor;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function findFunctionEnd(css: string, start: number): { depth: number; comma: number; cursor: number } {
|
|
35
|
+
let depth = 1;
|
|
36
|
+
let comma = -1;
|
|
37
|
+
let cursor = start;
|
|
38
|
+
for (; cursor < css.length && depth > 0; cursor++) {
|
|
39
|
+
const char = css[cursor];
|
|
40
|
+
if (char === "(") depth++;
|
|
41
|
+
else if (char === ")") depth--;
|
|
42
|
+
else if (char === "," && depth === 1 && comma < 0) comma = cursor;
|
|
43
|
+
}
|
|
44
|
+
return { depth, comma, cursor };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function pinColorScheme(style: string): string {
|
|
48
|
+
return style.replace(/color-scheme\s*:\s*[^;]*/g, "color-scheme: light");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function walk(root: DomEl): DomEl[] {
|
|
52
|
+
const elements: DomEl[] = [root];
|
|
53
|
+
for (const child of elemChildren(root)) elements.push(...walk(child));
|
|
54
|
+
return elements;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Return the SVG with all adaptive colors resolved to the authored ones. */
|
|
58
|
+
export function pinAuthoredColors(svg: string): string {
|
|
59
|
+
if (!svg.includes(FUNCTION) && !/color-scheme\s*:\s*light\s+dark/.test(svg)) return svg;
|
|
60
|
+
const doc = new DOMParser().parseFromString(svg, "image/svg+xml");
|
|
61
|
+
const root = doc.documentElement as unknown as DomEl | null;
|
|
62
|
+
if (root?.tagName !== "svg") throw new Error("draw.io output is not valid SVG");
|
|
63
|
+
for (const element of walk(root)) {
|
|
64
|
+
const style = attr(element, "style");
|
|
65
|
+
if (style !== null) element.setAttribute("style", pinColorScheme(resolveLightDark(style)));
|
|
66
|
+
if (element.tagName === "style") pinStyleText(element);
|
|
67
|
+
}
|
|
68
|
+
return new XMLSerializer().serializeToString(doc);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function pinStyleText(element: DomEl): void {
|
|
72
|
+
for (const node of Array.from(element.childNodes) as (DomEl & { data?: string })[]) {
|
|
73
|
+
if ((node.nodeType === TEXT_NODE || node.nodeType === CDATA_NODE) && node.data) {
|
|
74
|
+
node.data = resolveLightDark(node.data);
|
|
75
|
+
node.nodeValue = node.data;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function dimension(value: string | null): number | undefined {
|
|
81
|
+
const parsed = Number.parseFloat(value ?? "");
|
|
82
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Add an even outer margin to a borderless draw.io SVG: grow the canvas by
|
|
87
|
+
* `margin` on every side and shift the drawing (everything except `defs` and the
|
|
88
|
+
* full-size background rect) into the middle.
|
|
89
|
+
*/
|
|
90
|
+
export function padSvg(svg: string, margin: number): string {
|
|
91
|
+
if (margin <= 0 || Number.isNaN(margin)) return svg;
|
|
92
|
+
const doc = new DOMParser().parseFromString(svg, "image/svg+xml");
|
|
93
|
+
const root = doc.documentElement as unknown as DomEl | null;
|
|
94
|
+
if (root?.tagName !== "svg") throw new Error("draw.io output is not valid SVG");
|
|
95
|
+
const box = (attr(root, "viewBox") ?? "").trim().split(/[\s,]+/).map(Number);
|
|
96
|
+
const width = box.length === 4 && box.every(Number.isFinite) ? box[2] : dimension(attr(root, "width"));
|
|
97
|
+
const height = box.length === 4 && box.every(Number.isFinite) ? box[3] : dimension(attr(root, "height"));
|
|
98
|
+
if (width === undefined || height === undefined) throw new Error("SVG has no measurable size to pad");
|
|
99
|
+
const [minX, minY] = box.length === 4 && box.every(Number.isFinite) ? box : [0, 0];
|
|
100
|
+
|
|
101
|
+
const node = root as unknown as { appendChild(child: unknown): void };
|
|
102
|
+
const group = doc.createElementNS("http://www.w3.org/2000/svg", "g");
|
|
103
|
+
group.setAttribute("transform", `translate(${margin - minX},${margin - minY})`);
|
|
104
|
+
group.setAttribute("data-drawme-margin", String(margin)); // NOSONAR: xmldom XML elements have no browser dataset API.
|
|
105
|
+
for (const child of elemChildren(root)) {
|
|
106
|
+
const background = child.tagName === "rect" && attr(child, "width") === "100%" && attr(child, "height") === "100%";
|
|
107
|
+
if (child.tagName === "defs" || child.tagName === "style" || background) continue;
|
|
108
|
+
group.appendChild(child as never);
|
|
109
|
+
}
|
|
110
|
+
node.appendChild(group);
|
|
111
|
+
const newWidth = Math.round((width + 2 * margin) * 100) / 100;
|
|
112
|
+
const newHeight = Math.round((height + 2 * margin) * 100) / 100;
|
|
113
|
+
root.setAttribute("viewBox", `0 0 ${newWidth} ${newHeight}`);
|
|
114
|
+
root.setAttribute("width", `${newWidth}px`);
|
|
115
|
+
root.setAttribute("height", `${newHeight}px`);
|
|
116
|
+
return new XMLSerializer().serializeToString(doc);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Finish an exported SVG file in place: even margin, then authored colors. */
|
|
120
|
+
export async function finishSvgFile(path: string, margin: number): Promise<void> {
|
|
121
|
+
const svg = await readFile(path, "utf8");
|
|
122
|
+
const finished = pinAuthoredColors(padSvg(svg, margin));
|
|
123
|
+
if (finished !== svg) await writeFile(path, finished, "utf8");
|
|
124
|
+
}
|