@senad-d/drawme 0.1.10 → 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.
@@ -4,8 +4,8 @@
4
4
  * see the notice beside it). Resolves a keyword query such as "aws lambda" or
5
5
  * "uml actor" to the real palette style instead of a guess.
6
6
  *
7
- * Uses a tag map with exact + Soundex matching, strict AND first, a scored OR
8
- * fallback, and a verbatim-title tiebreaker.
7
+ * Gives exact alphanumeric titles priority, then uses a tag map with exact +
8
+ * Soundex matching, strict AND first, a scored OR fallback, and title tiebreakers.
9
9
  */
10
10
  import { readFileSync } from "node:fs";
11
11
  import { gunzipSync } from "node:zlib";
@@ -85,16 +85,15 @@ function buildTagMap(shapes: Shape[]): Map<string, Set<number>> {
85
85
  return tagMap;
86
86
  }
87
87
 
88
- function splitCompound(token: string): string[] {
89
- const spaced = token
90
- .replace(/([a-z])([A-Z])/g, "$1 $2")
91
- .replace(/([a-zA-Z])(\d)/g, "$1 $2")
92
- .replace(/(\d)([a-zA-Z])/g, "$1 $2");
93
- return spaced
94
- .trim()
88
+ function splitCompound(token: string, tagMap: Map<string, Set<number>>): string[] {
89
+ const whole = token.toLowerCase();
90
+ // Known identifiers such as 1Click and 10GbE are single searchable tags.
91
+ if (/\d/.test(whole) && tagMap.has(whole)) return [whole];
92
+ return token
93
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
94
+ .replace(/([A-Z])([A-Z][a-z])/g, "$1 $2")
95
95
  .toLowerCase()
96
- .split(/\s+/)
97
- .filter((p) => p.length >= 2);
96
+ .split(" ");
98
97
  }
99
98
 
100
99
  interface TermMatch {
@@ -118,19 +117,11 @@ function pickTerms(subs: string[], raw: string): string[] {
118
117
  return raw.length >= 2 ? [raw] : [];
119
118
  }
120
119
 
121
- /** Tokenize the query into unique search terms (compound-split, deduped, order-preserving). */
122
- function parseTerms(query: string): string[] {
123
- const terms: string[] = [];
124
- const seen = new Set<string>();
125
- for (const raw of query.toLowerCase().split(/\s+/).filter(Boolean)) {
126
- for (const t of pickTerms(splitCompound(raw), raw)) {
127
- if (!seen.has(t)) {
128
- seen.add(t);
129
- terms.push(t);
130
- }
131
- }
132
- }
133
- return terms;
120
+ /** Keep the full compound-split phrase as well as the distinct search terms. */
121
+ function parseTerms(words: string[], tagMap: Map<string, Set<number>>): { terms: string[]; phrase: string } {
122
+ const parts = words.map((word) => splitCompound(word, tagMap));
123
+ const terms = parts.flatMap((subTerms, i) => pickTerms(subTerms.filter((t) => t.length >= 2), words[i].toLowerCase()));
124
+ return { terms: [...new Set(terms)], phrase: parts.flat().join(" ") };
134
125
  }
135
126
 
136
127
  /** Strict AND across all terms (exact ∪ phonetic per term). Null when there are no terms. */
@@ -160,8 +151,8 @@ function scoreMatches(termMatches: TermMatch[], pool: Set<number> | null): Map<n
160
151
  return scores;
161
152
  }
162
153
 
163
- /** Rank scored shapes: by score, then verbatim-title hits, then title, then index. */
164
- function rankMatches(scores: Map<number, number>, shapes: Shape[], terms: string[], limit: number): ShapeMatch[] {
154
+ /** Rank exact alphanumeric titles first, then use the existing tag-score ordering. */
155
+ function rankMatches(scores: Map<number, number>, shapes: Shape[], terms: string[], exactTitles: Set<number>, limit: number): ShapeMatch[] {
165
156
  const termSet = new Set(terms);
166
157
  const titleHits = (idx: number): number => {
167
158
  const toks = new Set(shapes[idx].title.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean));
@@ -170,7 +161,8 @@ function rankMatches(scores: Map<number, number>, shapes: Shape[], terms: string
170
161
  return n;
171
162
  };
172
163
 
173
- const ranked = [...scores.keys()].sort((a, b) => {
164
+ const ranked = [...new Set([...scores.keys(), ...exactTitles])].sort((a, b) => {
165
+ if (exactTitles.has(a) !== exactTitles.has(b)) return exactTitles.has(a) ? -1 : 1;
174
166
  const ds = (scores.get(b) ?? 0) - (scores.get(a) ?? 0);
175
167
  if (ds !== 0) return ds;
176
168
  const dh = titleHits(b) - titleHits(a);
@@ -185,15 +177,22 @@ function rankMatches(scores: Map<number, number>, shapes: Shape[], terms: string
185
177
  }
186
178
 
187
179
  function search(shapes: Shape[], tagMap: Map<string, Set<number>>, query: string, limit: number): ShapeMatch[] {
188
- if (!query) return [];
189
- const terms = parseTerms(query);
190
- if (!terms.length) return [];
180
+ const words = query.trim().split(/\s+/);
181
+ const { terms, phrase } = parseTerms(words, tagMap);
182
+ const verbatim = words.join(" ").toLowerCase();
183
+ const exactTitles = new Set<number>();
184
+ if (/[a-z]/.test(verbatim) && /\d/.test(verbatim)) {
185
+ shapes.forEach(({ title }, i) => {
186
+ const normalized = title.trim().toLowerCase().replace(/\s+/g, " ");
187
+ if (normalized === verbatim || normalized === phrase) exactTitles.add(i);
188
+ });
189
+ }
191
190
 
192
191
  const termMatches = terms.map((t) => matchTerm(tagMap, t));
193
192
  const andSet = intersectAll(termMatches);
194
193
  const pool = andSet?.size ? andSet : null; // AND results if any, else OR across all terms
195
194
  const scores = scoreMatches(termMatches, pool);
196
- return rankMatches(scores, shapes, terms, limit);
195
+ return rankMatches(scores, shapes, terms, exactTitles, limit);
197
196
  }
198
197
 
199
198
  const INDEX_PATH = resolve(dirname(fileURLToPath(import.meta.url)), "..", "assets", "data", "shape-index.json.gz");
@@ -208,8 +207,10 @@ function load(): { shapes: Shape[]; tagMap: Map<string, Set<number>> } {
208
207
  return { shapes: cachedShapes, tagMap: cachedTagMap };
209
208
  }
210
209
 
211
- /** Search the bundled shape index; returns up to `limit` matches ranked by relevance. */
210
+ /** Search the bundled shape index; `limit` must be a nonnegative integer. */
212
211
  export function searchShapes(query: string, limit = 10): ShapeMatch[] {
212
+ if (!Number.isInteger(limit) || limit < 0) throw new RangeError("Shape search limit must be a nonnegative integer.");
213
+ if (limit === 0) return [];
213
214
  const { shapes, tagMap } = load();
214
215
  return search(shapes, tagMap, query, limit);
215
216
  }
package/src/storyboard.ts CHANGED
@@ -1,15 +1,15 @@
1
1
  /**
2
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
3
+ * draw.io page, one tile per sampled visual batch, so motion order and visibility
4
4
  * can be reviewed in a single PNG. Each tile is a copy of the page with cell
5
5
  * opacity set to its state after that step; highlight and travel steps show
6
6
  * their accent color on the stroke.
7
7
  */
8
- import { XMLSerializer } from "@xmldom/xmldom";
8
+ import { type Element, XMLSerializer } from "@xmldom/xmldom";
9
9
  import { type DomEl, attr, elemChildren, firstByTag } from "./dom";
10
- import { contentBounds, collectCellsWithIds, pyFloat } from "./geometry";
10
+ import { contentBounds, collectCellsWithIds, isVisible, pyFloat } from "./geometry";
11
11
  import { shiftCell } from "./fitcanvas";
12
- import { type MotionFrame, isDarkBackground } from "./motion";
12
+ import { type MotionFrame, authoredOpacity, isDarkBackground } from "./motion";
13
13
 
14
14
  export const MAX_STORYBOARD_FRAMES = 12;
15
15
  const GAP = 80;
@@ -71,44 +71,57 @@ function pageEntries(model: DomEl): PageEntry[] {
71
71
  }
72
72
 
73
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 {
74
+ function effectiveOpacity(id: string, frame: MotionFrame, byId: Map<string, DomEl>): number {
75
75
  let opacity = 1;
76
76
  let current: string | null | undefined = id;
77
77
  const seen = new Set<string>();
78
78
  while (current && !seen.has(current)) {
79
79
  seen.add(current);
80
- opacity *= frame.opacity.get(current) ?? 1;
81
- current = parents.get(current);
80
+ const cell = byId.get(current);
81
+ if (!cell) break;
82
+ opacity *= frame.opacity.get(current) ?? authoredOpacity(attr(cell, "style"));
83
+ current = attr(cell, "parent");
82
84
  }
83
85
  return opacity;
84
86
  }
85
87
 
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
+ function storyboardCell(entry: PageEntry, clones: Map<string, string>, ox: number, oy: number): DomEl {
89
+ const element = (entry.element as unknown as Element).cloneNode(true) as unknown as DomEl;
88
90
  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}`);
91
+ element.setAttribute("id", clones.get(entry.id)!);
92
+ if (cell !== element) (cell as unknown as Element).removeAttribute("id");
93
+ const parent = clones.get(attr(cell, "parent") ?? "");
94
+ cell.setAttribute("parent", parent ?? "1");
93
95
  for (const end of ["source", "target"]) {
94
96
  const ref = attr(cell, end);
95
- if (ref !== null) cell.setAttribute(end, `${prefix}${ref}`);
97
+ if (ref === null) continue;
98
+ const clone = clones.get(ref);
99
+ if (clone === undefined) (cell as unknown as Element).removeAttribute(end);
100
+ else cell.setAttribute(end, clone);
96
101
  }
102
+ const topLevel = parent === undefined;
97
103
  if (topLevel) shiftCell(cell, ox, oy);
98
104
  return element;
99
105
  }
100
106
 
101
- function applyFrameStyle(element: DomEl, id: string, frame: MotionFrame, parents: Map<string, string | null>): void {
107
+ function applyFrameStyle(element: DomEl, id: string, frame: MotionFrame, byId: Map<string, DomEl>): void {
102
108
  const cell = element.tagName === "mxCell" ? element : firstByTag(element, "mxCell")!;
103
109
  const updates: Record<string, string> = {};
104
- const opacity = effectiveOpacity(id, frame, parents);
105
- if (opacity < 1) {
110
+ const style = attr(cell, "style");
111
+ const opacity = effectiveOpacity(id, frame, byId);
112
+ if (opacity !== authoredOpacity(style)) {
106
113
  const percent = String(Math.round(opacity * 100));
107
114
  Object.assign(updates, { opacity: percent, textOpacity: percent });
108
115
  }
109
116
  const accent = frame.accent.get(id);
110
117
  if (accent) Object.assign(updates, { strokeColor: accent, strokeWidth: "3" });
111
- if (Object.keys(updates).length > 0) cell.setAttribute("style", setStyle(attr(cell, "style") ?? "", updates));
118
+ if (Object.keys(updates).length > 0) cell.setAttribute("style", setStyle(style ?? "", updates));
119
+ }
120
+
121
+ function decorationName(base: string, sourceIds: Map<string, DomEl>): string {
122
+ let name = base;
123
+ for (let suffix = 1; sourceIds.has(name); suffix++) name = `${base}-${suffix}`;
124
+ return name;
112
125
  }
113
126
 
114
127
  /** Build a one-page `.drawio` document that lays out the frames as a captioned grid. */
@@ -116,8 +129,10 @@ export function buildStoryboard(model: DomEl, frames: MotionFrame[]): string {
116
129
  if (frames.length === 0) throw new Error("motion has no visual steps to storyboard");
117
130
  const { width, height } = pageSize(model);
118
131
  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));
132
+ const byId = new Map(entries.map((entry) => [entry.id, entry.cell]));
133
+ const visible = entries.filter(({ id, cell }) => id !== "0" && attr(cell, "parent") !== "0" && isVisible(cell, byId));
134
+ const frameName = decorationName("frame", byId);
135
+ const captionName = decorationName("caption", byId);
121
136
  const columns = Math.min(frames.length, width >= height ? 2 : 3);
122
137
  const rows = Math.ceil(frames.length / columns);
123
138
  const tileHeight = CAPTION_HEIGHT + height;
@@ -129,18 +144,18 @@ export function buildStoryboard(model: DomEl, frames: MotionFrame[]): string {
129
144
 
130
145
  frames.forEach((frame, index) => {
131
146
  const prefix = `f${index + 1}-`;
147
+ const clones = new Map(visible.map(({ id }) => [id, `${prefix}${id}`]));
132
148
  const ox = GAP + (index % columns) * (width + GAP);
133
149
  const oy = GAP + Math.floor(index / columns) * (tileHeight + GAP);
134
150
  const seconds = (frame.time / 1000).toFixed(1);
135
151
  const caption = `${index + 1} · ${seconds}s · ${frame.label}`;
136
152
  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>`,
153
+ `<mxCell id="${prefix}${frameName}" 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>`,
154
+ `<mxCell id="${prefix}${captionName}" 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
155
  );
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);
156
+ for (const entry of visible) {
157
+ const element = storyboardCell(entry, clones, ox, oy + CAPTION_HEIGHT);
158
+ applyFrameStyle(element, entry.id, frame, byId);
144
159
  parts.push(serializer.serializeToString(element as never));
145
160
  }
146
161
  });
@@ -0,0 +1,129 @@
1
+ import { DOMParser, NAMESPACE, type Element } from "@xmldom/xmldom";
2
+ import { type DomEl, elemChildren } from "./dom";
3
+
4
+ const XLINK_NS = "http://www.w3.org/1999/xlink";
5
+ const SVG_IMAGE_ELEMENTS = new Set(["image", "feImage", "use"]);
6
+ const SVG_URL_PROPERTIES = new Set([
7
+ "clip-path", "cursor", "fill", "filter", "marker", "marker-end", "marker-mid", "marker-start", "mask", "mask-image", "stroke",
8
+ ]);
9
+
10
+ /** Quote an arbitrary draw.io cell ID as a CSS attribute-selector string. */
11
+ export function cssString(value: string): string {
12
+ let escaped = '"';
13
+ for (const char of value) {
14
+ const code = char.codePointAt(0)!;
15
+ if (char === '"' || char === "\\") escaped += `\\${char}`;
16
+ else if (code <= 0x1f || code === 0x7f) escaped += `\\${code.toString(16)} `;
17
+ else escaped += char;
18
+ }
19
+ return `${escaped}"`;
20
+ }
21
+
22
+ /** Visit elements in document order, including the root and skipping text/comments. */
23
+ export function walkElements(root: DomEl): DomEl[] {
24
+ const elements: DomEl[] = [];
25
+ const pending = [root];
26
+ while (pending.length > 0) {
27
+ const element = pending.pop()!;
28
+ elements.push(element);
29
+ const children = elemChildren(element);
30
+ for (let index = children.length - 1; index >= 0; index--) pending.push(children[index]);
31
+ }
32
+ return elements;
33
+ }
34
+
35
+ function assertEmbedded(reference: string | null, location: string): void {
36
+ const url = reference?.trim();
37
+ if (!url || url.startsWith("#") || /^data:/i.test(url)) return;
38
+ throw new Error(`standalone animated SVG has an unresolved image dependency (${location}); re-embed the image in draw.io and export again`);
39
+ }
40
+
41
+ function checkSrcset(value: string, location: string): void {
42
+ // The URL token ends at whitespace, not a comma (data URLs contain commas).
43
+ // A trailing comma, or a comma after the descriptors, starts the next candidate.
44
+ const candidate = /[, \t\r\n\f]*([^, \t\r\n\f][^ \t\r\n\f]*)/y;
45
+ const descriptors = /(?:\([^)]*(?:\)|$)|[^,(])*,?/y;
46
+ for (let match = candidate.exec(value); match; match = candidate.exec(value)) {
47
+ const url = match[1];
48
+ let end = url.length;
49
+ while (url[end - 1] === ",") end--;
50
+ assertEmbedded(url.slice(0, end), location);
51
+ if (end === url.length) {
52
+ descriptors.lastIndex = candidate.lastIndex;
53
+ descriptors.exec(value);
54
+ candidate.lastIndex = descriptors.lastIndex;
55
+ }
56
+ }
57
+ }
58
+
59
+ const CSS_ESCAPE_BODY = String.raw`(?:[a-f0-9]{1,6}(?:\r\n|[ \t\r\n\f])?|\r\n|[\s\S])`;
60
+ const CSS_ESCAPE = new RegExp(String.raw`\\(${CSS_ESCAPE_BODY})`, "gi");
61
+ const CSS_STRING = String.raw`"(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*'`;
62
+
63
+ function unescapeCss(value: string): string {
64
+ return value.replace(CSS_ESCAPE, (_whole, escaped: string) => {
65
+ const hex = /^[a-f0-9]{1,6}/i.exec(escaped);
66
+ if (!hex) return /^[\r\n\f]/.test(escaped) ? "" : escaped;
67
+ const code = Number.parseInt(hex[0], 16);
68
+ return code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff) ? "\ufffd" : String.fromCodePoint(code);
69
+ });
70
+ }
71
+
72
+ function unquoteCss(value: string): string {
73
+ return unescapeCss(value[0] === '"' || value[0] === "'" ? value.slice(1, -1) : value);
74
+ }
75
+
76
+ function checkCssImages(css: string | null): void {
77
+ if (!css || !/url|image-set|\\/i.test(css)) return;
78
+ // Skip comments and ordinary strings; only URL functions and image-set's
79
+ // string candidates load images. CSS escapes can occur in either name or URL.
80
+ const tokens = new RegExp(String.raw`/\*[\s\S]*?(?:\*/|$)|(${CSS_STRING})|((?:[\w\u0080-\uFFFF-]|\\${CSS_ESCAPE_BODY})+)(\()?|[()]`, "gi");
81
+ const urlArgument = new RegExp(String.raw`[ \t\r\n\f]*(${CSS_STRING}|(?:[^"'()\\]|\\[\s\S])+)?`, "y");
82
+ const functions: string[] = [];
83
+ for (let token = tokens.exec(css); token; token = tokens.exec(css)) {
84
+ const [text, quoted, identifier, open] = token;
85
+ if (text === ")") functions.pop();
86
+ else if (text === "(") functions.push("");
87
+ else if (open) {
88
+ const name = unescapeCss(identifier).toLowerCase();
89
+ functions.push(name);
90
+ if (name === "url") {
91
+ urlArgument.lastIndex = tokens.lastIndex;
92
+ const url = urlArgument.exec(css)?.[1];
93
+ if (url) assertEmbedded(unquoteCss(url), "CSS url()");
94
+ tokens.lastIndex = urlArgument.lastIndex;
95
+ }
96
+ } else if (quoted && /^(?:-webkit-)?image-set$/.test(functions.at(-1) ?? "")) {
97
+ assertEmbedded(unquoteCss(quoted), "CSS image-set()");
98
+ }
99
+ }
100
+ }
101
+
102
+ function checkElementImages(element: Element): void {
103
+ const { localName, namespaceURI } = element;
104
+ if (namespaceURI === NAMESPACE.SVG && localName !== null && SVG_IMAGE_ELEMENTS.has(localName)) {
105
+ // SVG 2 href wins over the legacy XLink attribute when both are present.
106
+ assertEmbedded(element.getAttribute("href") ?? element.getAttributeNS(XLINK_NS, "href"), `<${localName}> href`);
107
+ }
108
+ if (namespaceURI === NAMESPACE.HTML && (localName === "img" || localName === "source")) {
109
+ assertEmbedded(element.getAttribute("src"), `<${localName}> src`);
110
+ checkSrcset(element.getAttribute("srcset") ?? "", `<${localName}> srcset`);
111
+ }
112
+ if (namespaceURI !== NAMESPACE.SVG && namespaceURI !== NAMESPACE.HTML) return;
113
+ checkCssImages(element.getAttribute("style"));
114
+ if (localName === "style") checkCssImages(element.textContent);
115
+ if (namespaceURI === NAMESPACE.SVG) {
116
+ for (const attribute of Array.from(element.attributes)) {
117
+ if (attribute.namespaceURI === null && SVG_URL_PROPERTIES.has(attribute.name)) checkCssImages(attribute.value);
118
+ }
119
+ }
120
+ }
121
+
122
+ /** Check final animated SVG image references without reading files or fetching URLs. */
123
+ export function assertStandaloneImages(svg: string): void {
124
+ const root = new DOMParser({ onError(level) {
125
+ if (level !== "warning") throw new Error("draw.io output is not valid SVG");
126
+ } }).parseFromString(svg, "image/svg+xml").documentElement;
127
+ if (root?.localName !== "svg" || root.namespaceURI !== NAMESPACE.SVG) throw new Error("draw.io output is not valid SVG");
128
+ for (const element of walkElements(root as unknown as DomEl)) checkElementImages(element as unknown as Element);
129
+ }
package/src/svgexport.ts CHANGED
@@ -11,6 +11,7 @@
11
11
  import { readFile, writeFile } from "node:fs/promises";
12
12
  import { DOMParser, XMLSerializer } from "@xmldom/xmldom";
13
13
  import { type DomEl, TEXT_NODE, attr, elemChildren } from "./dom";
14
+ import { walkElements } from "./svg-helpers";
14
15
 
15
16
  const FUNCTION = "light-dark(";
16
17
  const CDATA_NODE = 4;
@@ -48,19 +49,13 @@ function pinColorScheme(style: string): string {
48
49
  return style.replace(/color-scheme\s*:\s*[^;]*/g, "color-scheme: light");
49
50
  }
50
51
 
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
52
  /** Return the SVG with all adaptive colors resolved to the authored ones. */
58
53
  export function pinAuthoredColors(svg: string): string {
59
54
  if (!svg.includes(FUNCTION) && !/color-scheme\s*:\s*light\s+dark/.test(svg)) return svg;
60
55
  const doc = new DOMParser().parseFromString(svg, "image/svg+xml");
61
56
  const root = doc.documentElement as unknown as DomEl | null;
62
57
  if (root?.tagName !== "svg") throw new Error("draw.io output is not valid SVG");
63
- for (const element of walk(root)) {
58
+ for (const element of walkElements(root)) {
64
59
  const style = attr(element, "style");
65
60
  if (style !== null) element.setAttribute("style", pinColorScheme(resolveLightDark(style)));
66
61
  if (element.tagName === "style") pinStyleText(element);
@@ -88,10 +83,12 @@ function dimension(value: string | null): number | undefined {
88
83
  * full-size background rect) into the middle.
89
84
  */
90
85
  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");
86
+ const doc = new DOMParser({ onError: (level, message) => {
87
+ if (level !== "warning") throw new Error(message);
88
+ } }).parseFromString(svg, "image/svg+xml");
93
89
  const root = doc.documentElement as unknown as DomEl | null;
94
90
  if (root?.tagName !== "svg") throw new Error("draw.io output is not valid SVG");
91
+ if (margin <= 0 || Number.isNaN(margin)) return svg;
95
92
  const box = (attr(root, "viewBox") ?? "").trim().split(/[\s,]+/).map(Number);
96
93
  const width = box.length === 4 && box.every(Number.isFinite) ? box[2] : dimension(attr(root, "width"));
97
94
  const height = box.length === 4 && box.every(Number.isFinite) ? box[3] : dimension(attr(root, "height"));