Public: anyone can read this; the crew can change it.

A Mermaid, draw.io or Excalidraw file opens as a picture, with its source one tap away #13041

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/13028-a-mermaid-draw-io-or-excalidraw-file-ope → main 5 commits fork

  • Merged. mason/13028-a-mermaid-draw-io-or-excalidraw-file-ope was merged into main as 6b4b128.

Review

Sign in to review this change.
10 files changed +457 −0
docs/design/areas/render.md +4
@@ -75,3 +75,7 @@ A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the exis
7575 ## SQL schema (*.sql)
7676
7777 `src/web/render/sql.ts` draws, per statement, either an `h3` with the table name and one existing `.table` (`data-dense`) of its columns, or a one-row `.table` with the statement's first line. `.sql-view` is only a hook on the wrapper and has no rule. How it works: `docs/features/file-sql.md`.
78
79 ## Diagrams (.drawio, .excalidraw, .mmd)
80
81 `src/web/render/diagram.ts` draws a draw.io or Excalidraw file as one inline SVG in `.diagram-view` (same rules as `.dxf-view`: `currentColor`, no accent), inside `.diagram-scroll`, a frame that never lets the SVG exceed it (no fixed width, so no rule fixes a width over 390 px). A Mermaid file shows its diagram type and its source in a native `<details>` (`.diagram-source`, its summary a 44px tap target), folded, whose `pre` scrolls sideways inside its own box.
docs/features/README.md +1
@@ -224,6 +224,7 @@ Read with the guide page [Your apps](../guide-your-apps.md).
224224
225225 - [An .obj or .ply file opens in the 3D viewer](mesh-files.md)
226226 - [A .dxf file as a picture](file-dxf.md)
227 - [Mermaid, draw.io and Excalidraw files](file-diagrams.md)
227228 - [A .psd file: facts, preview and layers](psd.md)
228229 - [A .har file as a request waterfall](file-har.md)
229230 - [A .sarif file opens as its findings](file-sarif.md)
docs/features/file-diagrams.md added +22
@@ -0,0 +1,22 @@
1 # Mermaid, draw.io and Excalidraw files as pictures
2
3 - `.drawio` and `.excalidraw` open as one inline SVG drawn on the server:
4 rectangles, ellipses, diamonds, text and arrows at their own coordinates.
5 - `.mmd` and `.mermaid` cannot be drawn without Mermaid, which the forge does
6 not ship: the page names the diagram type the first line gives and folds the
7 source below it.
8 - A compressed draw.io page, malformed input, a file over 1 MB, or a Mermaid
9 file with no diagram type shows the source view with the reason.
10 - Text is escaped; no script runs on the origin; no dependency.
11 - `src/web/render/diagram.ts` draws; `kinds.ts` maps the extensions.
12
13 ## What is not drawn
14
15 - Colours, fills, strokes and fonts: shapes are outlines in the page's text colour.
16 - Nesting and grouping: a draw.io child is placed at its own coordinates, not
17 offset by its parent container or group.
18 - Compressed draw.io pages (the default "compressed XML" export): the page says so and
19 shows the source; export uncompressed to see the drawing.
20 - Past 5,000 elements or coordinates beyond 1,000,000, the file shows as source.
21
22 A wide drawing scales down to the frame, as the other picture views do.
src/web/render/diagram.ts added +265
@@ -0,0 +1,265 @@
1 /**
2 * Diagram files opened as drawings, with no library and no script.
3 *
4 * `.drawio` (mxGraph XML) and `.excalidraw` (JSON) are drawn on the server as
5 * one inline SVG: rectangles, ellipses, diamonds, text and arrows, at their
6 * own coordinates, fitted by the viewBox. `.mmd`/`.mermaid` cannot be drawn
7 * without Mermaid itself, so the page shows the diagram type the first line
8 * names and the source in a folded block. A compressed draw.io page, a file
9 * past the cap, or anything malformed falls back to the source view, with the
10 * reason; never an error. Every number is finite and clamped, every string
11 * escaped.
12 */
13
14 import { html, raw } from "../html.ts";
15 import type { Rendered, RenderInput } from "./renderers.ts";
16 import { RENDER_CAP } from "./kinds.ts";
17 import { fileSize } from "../ui.ts";
18
19 /** Elements drawn in all; the rest are counted out. */
20 export const ELEMENT_CAP = 5_000;
21 /** Coordinates beyond this magnitude are treated as corrupt. */
22 const LIMIT = 1e6;
23 const PAD = 12;
24 const FONT = 14;
25
26 export type Item =
27 | { readonly t: "box"; readonly shape: "rect" | "ellipse" | "diamond"; readonly x: number; readonly y: number; readonly w: number; readonly h: number }
28 | { readonly t: "line"; readonly pts: readonly (readonly [number, number])[]; readonly arrow: boolean }
29 | { readonly t: "text"; readonly x: number; readonly y: number; readonly lines: readonly string[]; readonly size: number; readonly anchor: "start" | "middle" };
30
31 const num = (v: unknown): number | undefined => {
32 const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
33 return typeof n === "number" && Number.isFinite(n) && Math.abs(n) <= LIMIT ? n : undefined;
34 };
35
36 const ENTITIES: Record<string, string> = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'", nbsp: " " };
37 const decode = (s: string): string =>
38 s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e: string) => {
39 if (e[0] === "#") {
40 const code = e[1]!.toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
41 return code > 0 && code < 0x110000 ? String.fromCodePoint(code) : "";
42 }
43 return ENTITIES[e.toLowerCase()] ?? m;
44 });
45
46 /** A draw.io label is HTML in an attribute: break tags become newlines, the rest is dropped. */
47 const labelText = (value: string): string[] =>
48 decode(decode(value).replace(/<br\s*\/?>|<\/(div|p)>/gi, "\n").replace(/<[^>]*>/g, ""))
49 .split("\n")
50 .map((l) => l.trim())
51 .filter((l) => l !== "")
52 .slice(0, 50)
53 .map((l) => l.slice(0, 200));
54
55 const attrs = (tag: string): Map<string, string> => {
56 const out = new Map<string, string>();
57 for (const m of tag.matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) out.set(m[1]!, m[2] ?? m[3] ?? "");
58 return out;
59 }
60
61 /** Parse draw.io XML. Pure. An error string when it cannot be drawn. */
62 export function parseDrawio(text: string): Item[] | { error: string } {
63 if (!/<mxGraphModel\b/.test(text)) {
64 return { error: /<diagram\b/.test(text) ? "its page is compressed" : "it is not a draw.io file" };
65 }
66 const items: Item[] = [];
67 const boxes = new Map<string, { x: number; y: number; w: number; h: number }>();
68 const edges: { source?: string | undefined; target?: string | undefined; label: string[]; pts: [number, number][] }[] = [];
69 const chunks = text.split(/<mxCell\b/).slice(1);
70 if (chunks.length > ELEMENT_CAP * 2) return { error: "it has too many elements" };
71 for (const chunk of chunks) {
72 const open = chunk.indexOf(">");
73 if (open < 0) continue;
74 const a = attrs(chunk.slice(0, open));
75 const label = labelText(a.get("value") ?? "");
76 const style = a.get("style") ?? "";
77 const geo = /<mxGeometry\b([^>]*)/.exec(chunk);
78 const g = geo ? attrs(geo[1]!) : new Map<string, string>();
79 if (a.get("vertex") === "1") {
80 const x = num(g.get("x") ?? "0"), y = num(g.get("y") ?? "0"), w = num(g.get("width")), h = num(g.get("height"));
81 if (x === undefined || y === undefined || w === undefined || h === undefined || w < 0 || h < 0) continue;
82 if (items.length >= ELEMENT_CAP) break;
83 const id = a.get("id");
84 if (id !== undefined) boxes.set(id, { x, y, w, h });
85 const plain = /(^|;)(text|group)(;|$)/.test(style);
86 if (!plain) {
87 const shape = /(^|;)ellipse(;|$)/.test(style) ? "ellipse" : /(^|;)rhombus(;|$)/.test(style) ? "diamond" : "rect";
88 items.push({ t: "box", shape, x, y, w, h });
89 }
90 if (label.length > 0) items.push({ t: "text", x: x + w / 2, y: y + h / 2, lines: label, size: FONT, anchor: "middle" });
91 } else if (a.get("edge") === "1") {
92 const pts: [number, number][] = [];
93 for (const p of chunk.matchAll(/<mxPoint\b([^>]*)/g)) {
94 const pa = attrs(p[1]!);
95 if (pa.get("as") !== undefined) continue;
96 const px = num(pa.get("x")), py = num(pa.get("y"));
97 if (px !== undefined && py !== undefined) pts.push([px, py]);
98 }
99 edges.push({ source: a.get("source"), target: a.get("target"), label, pts });
100 }
101 }
102 const centre = (id: string | undefined): [number, number] | undefined => {
103 const b = id === undefined ? undefined : boxes.get(id);
104 return b === undefined ? undefined : [b.x + b.w / 2, b.y + b.h / 2];
105 };
106 for (const e of edges.slice(0, ELEMENT_CAP)) {
107 const from = centre(e.source), to = centre(e.target);
108 const line = [...(from ? [from] : []), ...e.pts, ...(to ? [to] : [])];
109 if (line.length < 2) continue;
110 items.push({ t: "line", pts: line, arrow: true });
111 if (e.label.length > 0) {
112 const mid = line[Math.floor(line.length / 2)]!;
113 items.push({ t: "text", x: mid[0], y: mid[1], lines: e.label, size: FONT, anchor: "middle" });
114 }
115 }
116 if (items.length === 0) return { error: "it has nothing to draw" };
117 return items;
118 }
119
120 /** Parse Excalidraw JSON. Pure. An error string when it cannot be drawn. */
121 export function parseExcalidraw(text: string): Item[] | { error: string } {
122 let doc: unknown;
123 try {
124 doc = JSON.parse(text);
125 } catch {
126 return { error: "it is not valid JSON" };
127 }
128 const elements = (doc as { elements?: unknown } | null)?.elements;
129 if (!Array.isArray(elements)) return { error: "it has no elements" };
130 const items: Item[] = [];
131 for (const el of elements) {
132 if (items.length >= ELEMENT_CAP) break;
133 if (typeof el !== "object" || el === null) continue;
134 const e = el as Record<string, unknown>;
135 if (e.isDeleted === true) continue;
136 const x = num(e.x), y = num(e.y);
137 if (x === undefined || y === undefined) continue;
138 const type = e.type;
139 if (type === "rectangle" || type === "ellipse" || type === "diamond") {
140 const w = num(e.width), h = num(e.height);
141 if (w === undefined || h === undefined) continue;
142 items.push({ t: "box", shape: type === "rectangle" ? "rect" : type, x: Math.min(x, x + w), y: Math.min(y, y + h), w: Math.abs(w), h: Math.abs(h) });
143 } else if (type === "text" && typeof e.text === "string") {
144 const lines = e.text.split("\n").slice(0, 50).map((l) => l.slice(0, 200));
145 const size = num(e.fontSize) ?? 20;
146 const center = e.textAlign === "center";
147 const w = num(e.width) ?? 0;
148 items.push({ t: "text", x: center ? x + w / 2 : x, y: y + size, lines, size: Math.min(Math.max(size, 6), 200), anchor: center ? "middle" : "start" });
149 } else if ((type === "arrow" || type === "line") && Array.isArray(e.points)) {
150 const pts: [number, number][] = [];
151 for (const p of e.points.slice(0, 1000)) {
152 const px = Array.isArray(p) ? num(p[0]) : undefined, py = Array.isArray(p) ? num(p[1]) : undefined;
153 if (px !== undefined && py !== undefined) pts.push([x + px, y + py]);
154 }
155 if (pts.length >= 2) items.push({ t: "line", pts, arrow: type === "arrow" && e.endArrowhead !== null });
156 }
157 }
158 if (items.length === 0) return { error: "it has nothing to draw" };
159 return items;
160 }
161
162 const f = (n: number): string => (Number.isFinite(n) ? n : 0).toFixed(1);
163
164 /** One SVG body and its extent, from the items. Pure. */
165 export function draw(items: readonly Item[]): { width: number; height: number; body: string } {
166 let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
167 const see = (x: number, y: number): void => {
168 minX = Math.min(minX, x); maxX = Math.max(maxX, x);
169 minY = Math.min(minY, y); maxY = Math.max(maxY, y);
170 };
171 let body = "";
172 for (const it of items) {
173 if (it.t === "box") {
174 see(it.x, it.y); see(it.x + it.w, it.y + it.h);
175 const cx = it.x + it.w / 2, cy = it.y + it.h / 2;
176 body +=
177 it.shape === "rect"
178 ? `<rect x="${f(it.x)}" y="${f(it.y)}" width="${f(it.w)}" height="${f(it.h)}"/>`
179 : it.shape === "ellipse"
180 ? `<ellipse cx="${f(cx)}" cy="${f(cy)}" rx="${f(it.w / 2)}" ry="${f(it.h / 2)}"/>`
181 : `<polygon points="${f(cx)},${f(it.y)} ${f(it.x + it.w)},${f(cy)} ${f(cx)},${f(it.y + it.h)} ${f(it.x)},${f(cy)}"/>`;
182 } else if (it.t === "line") {
183 for (const p of it.pts) see(p[0], p[1]);
184 body += `<polyline points="${it.pts.map((p) => `${f(p[0])},${f(p[1])}`).join(" ")}"${it.arrow ? ' marker-end="url(#arrow)"' : ""}/>`;
185 } else {
186 const widest = Math.max(...it.lines.map((l) => l.length)) * it.size * 0.6;
187 const left = it.anchor === "middle" ? it.x - widest / 2 : it.x;
188 const top = it.anchor === "middle" ? it.y - (it.lines.length * it.size * 1.2) / 2 : it.y - it.size;
189 see(left, top); see(left + widest, top + it.lines.length * it.size * 1.2);
190 const first = it.anchor === "middle" ? top + it.size : it.y;
191 body += `<text x="${f(it.x)}" y="${f(first)}" font-size="${f(it.size)}" text-anchor="${it.anchor}">${it.lines
192 .map((l, i) => `<tspan x="${f(it.x)}" dy="${i === 0 ? 0 : f(it.size * 1.2)}">${String(html`${l}`)}</tspan>`)
193 .join("")}</text>`;
194 }
195 }
196 if (!Number.isFinite(minX)) { minX = minY = 0; maxX = maxY = 1; }
197 return { width: Math.ceil(maxX - minX + 2 * PAD), height: Math.ceil(maxY - minY + 2 * PAD), body: `<g transform="translate(${f(PAD - minX)} ${f(PAD - minY)})">${body}</g>` };
198 }
199
200 const MERMAID_TYPES = [
201 "flowchart", "graph", "sequenceDiagram", "classDiagram", "stateDiagram-v2", "stateDiagram", "erDiagram", "journey",
202 "gantt", "pie", "quadrantChart", "requirementDiagram", "gitGraph", "mindmap", "timeline", "sankey-beta", "xychart-beta",
203 "block-beta", "packet-beta", "architecture-beta", "kanban", "C4Context", "C4Container", "C4Component", "C4Dynamic", "C4Deployment",
204 ];
205
206 /**
207 * The diagram type a Mermaid source opens with, past frontmatter, directives and comments;
208 * undefined when none.
209 */
210 export function mermaidType(text: string): string | undefined {
211 const lines = text.replace(/^/, "").split(/\r\n|\n|\r/);
212 let i = 0;
213 if (lines[0]?.trim() === "---") {
214 i = lines.findIndex((l, n) => n > 0 && l.trim() === "---") + 1;
215 if (i === 0) return undefined;
216 }
217 for (; i < lines.length; i++) {
218 const line = lines[i]!.trim();
219 if (line === "" || line.startsWith("%%")) continue;
220 const word = /^[A-Za-z0-9-]+/.exec(line)?.[0];
221 return word !== undefined && MERMAID_TYPES.includes(word) ? word : undefined;
222 }
223 return undefined;
224 }
225
226 const fall = (why: string): Rendered => ({ content: html``, lines: 0, fallback: `This file is shown as text because ${why}.` });
227 const gate = (input: RenderInput, cap: number): Rendered | undefined =>
228 input.size > cap || input.body.length > cap ? fall("it is too large to draw") : undefined;
229
230 const figure = (items: Item[], label: string, size: number): Rendered => {
231 const d = draw(items);
232 const content = html`<figure class="diagram-view">
233 <div class="diagram-scroll" tabindex="0" role="group" aria-label="${label}, scrolls sideways"><svg viewBox="0 0 ${d.width} ${d.height}" role="img" aria-label="${label}" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" fill="none"><defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="currentColor" stroke="none"/></marker></defs>${raw(d.body)}</svg></div>
234 </figure>`;
235 return { content, lines: 0, summary: `${items.length.toLocaleString("en")} elements · ${fileSize(size)}` };
236 };
237
238 export function drawio(input: RenderInput): Rendered {
239 const big = gate(input, RENDER_CAP.drawio);
240 if (big) return big;
241 const items = parseDrawio(new TextDecoder().decode(input.body));
242 if ("error" in items) return fall(items.error);
243 return figure(items, "draw.io diagram", input.size);
244 }
245
246 export function excalidraw(input: RenderInput): Rendered {
247 const big = gate(input, RENDER_CAP.excalidraw);
248 if (big) return big;
249 const items = parseExcalidraw(new TextDecoder().decode(input.body));
250 if ("error" in items) return fall(items.error);
251 return figure(items, "Excalidraw diagram", input.size);
252 }
253
254 export function mermaid(input: RenderInput): Rendered {
255 const big = gate(input, RENDER_CAP.mermaid);
256 if (big) return big;
257 const text = new TextDecoder().decode(input.body);
258 const type = mermaidType(text);
259 if (type === undefined) return fall("it does not open with a Mermaid diagram type");
260 const content = html`<div class="diagram-view">
261 <p><strong>Mermaid ${type}</strong></p>
262 <details class="diagram-source"><summary>Source</summary><pre><code>${text}</code></pre></details>
263 </div>`;
264 return { content, lines: 0, summary: `Mermaid ${type} · ${fileSize(input.size)}` };
265 }
src/web/render/kinds.ts +10
@@ -46,6 +46,9 @@ export type FileKind =
4646 | "mail"
4747 | "gcode"
4848 | "dxf"
49 | "mermaid"
50 | "drawio"
51 | "excalidraw"
4952 | "step"
5053 | "sarif"
5154 | "lcov"
@@ -106,6 +109,9 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
106109 mail: 5 * MB,
107110 gcode: 50 * MB,
108111 dxf: 5 * MB,
112 mermaid: 1 * MB,
113 drawio: 1 * MB,
114 excalidraw: 1 * MB,
109115 step: 5 * MB,
110116 sarif: 5 * MB,
111117 lcov: 5 * MB,
@@ -246,6 +252,10 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = {
246252 gcode: "gcode",
247253 gco: "gcode",
248254 dxf: "dxf",
255 mmd: "mermaid",
256 mermaid: "mermaid",
257 drawio: "drawio",
258 excalidraw: "excalidraw",
249259 step: "step",
250260 stp: "step",
251261 sarif: "sarif",
src/web/render/renderers.ts +4
@@ -17,6 +17,7 @@ import { eml } from "./eml.ts";
1717 import { csv } from "./csv.ts";
1818 import { geojson } from "./geojson.ts";
1919 import { dxf } from "./dxf.ts";
20 import { drawio, excalidraw, mermaid } from "./diagram.ts";
2021 import { step } from "./step.ts";
2122 import { gcode } from "./gcode.ts";
2223 import { gpx } from "./gpx.ts";
@@ -114,6 +115,9 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
114115 har,
115116 gcode,
116117 dxf,
118 mermaid,
119 drawio,
120 excalidraw,
117121 step,
118122 geojson,
119123 calendar: ics,
src/web/style/content.ts +6
@@ -557,6 +557,12 @@ form.inline { display: inline; margin-left: auto; }
557557 .dxf-view { margin: 0; }
558558 .dxf-view svg { display: block; max-width: 100%; height: auto; margin: 0 auto; color: var(--fg); }
559559 .dxf-view .status-rows { margin-top: 12px; }
560 .diagram-view { margin: 0; }
561 .diagram-scroll { overflow-x: auto; max-width: 100%; }
562 .diagram-scroll:focus-visible { outline: 1px solid var(--fg); outline-offset: 2px; }
563 .diagram-view svg { display: block; max-width: 100%; width: 100%; height: auto; margin: 0 auto; color: var(--fg); }
564 .diagram-source pre { overflow-x: auto; }
565 .diagram-source summary { cursor: pointer; min-height: 44px; display: flex; align-items: center; }
560566 .gj-view { margin: 0; }
561567 .gj-view svg { display: block; max-width: 100%; height: auto; margin: 0 auto; color: var(--fg); }
562568 .gj-table { overflow-x: auto; max-width: 100%; }
test/fuzz-renderers.test.ts +18
@@ -16,6 +16,7 @@ import { eml } from "../src/web/render/eml.ts";
1616 import { vcf } from "../src/web/render/vcf.ts";
1717 import { gpx } from "../src/web/render/gpx.ts";
1818 import { dxf } from "../src/web/render/dxf.ts";
19 import { drawio, excalidraw, mermaid } from "../src/web/render/diagram.ts";
1920 import { geojson } from "../src/web/render/geojson.ts";
2021 import { subtitles } from "../src/web/render/subtitles.ts";
2122 import { patch } from "../src/web/render/patch.ts";
@@ -111,6 +112,23 @@ const SAMPLES: Record<string, { path: string; render: Renderer; files: readonly
111112 render: dxf,
112113 files: ["0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n<script>alert(1)</script>\n10\n0\n20\n0\n11\n5\n21\n5\n0\nCIRCLE\n10\n1\n20\n1\n40\n2\n0\nENDSEC\n0\nEOF\n"],
113114 },
115 drawio: {
116 path: "a.drawio",
117 render: drawio,
118 files: [
119 `<mxfile><diagram><mxGraphModel><root><mxCell id="2" value="<script>alert(1)</script>" style="ellipse;" vertex="1"><mxGeometry x="1" y="2" width="30" height="40"/></mxCell><mxCell id='3' value="b" vertex="1"><mxGeometry x="90" y="9" width="30" height="40"/></mxCell><mxCell id="4" edge="1" source="2" target="3"><mxGeometry><mxPoint x="5" y="5"/></mxGeometry></mxCell></root></mxGraphModel></diagram></mxfile>`,
120 ],
121 },
122 excalidraw: {
123 path: "a.excalidraw",
124 render: excalidraw,
125 files: ['{"elements":[{"type":"rectangle","x":0,"y":0,"width":9,"height":9},{"type":"text","x":1,"y":1,"text":"<script>a</script>\\nb","fontSize":20},{"type":"arrow","x":0,"y":0,"points":[[0,0],[5,5]]}]}'],
126 },
127 mermaid: {
128 path: "a.mmd",
129 render: mermaid,
130 files: ["---\ntitle: <b>x</b>\n---\nflowchart TD\n A[<script>alert(1)</script>] --> B\n"],
131 },
114132 geojson: {
115133 path: "map.geojson",
116134 render: geojson,
test/render-diagram.test.ts added +123
@@ -0,0 +1,123 @@
1 /** Mermaid, draw.io and Excalidraw files on the blob page. */
2 import { describe, expect, test } from "bun:test";
3 import { drawio, ELEMENT_CAP, excalidraw, mermaid, mermaidType } from "../src/web/render/diagram.ts";
4 import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts";
5 import { RENDERERS } from "../src/web/render/renderers.ts";
6
7 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
8 const run = (r: typeof drawio, path: string, text: string, size = text.length) =>
9 r({ path, size, body: enc(text), media: "/m", download: "/d" });
10
11 const DRAWIO = `<mxfile><diagram id="a"><mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/>
12 <mxCell id="2" value="Start &lt;script&gt;alert(1)&lt;/script&gt;" style="rounded=1;" vertex="1" parent="1"><mxGeometry x="10" y="10" width="100" height="40" as="geometry"/></mxCell>
13 <mxCell id="3" value="End" style="ellipse;" vertex="1" parent="1"><mxGeometry x="10" y="200" width="100" height="40" as="geometry"/></mxCell>
14 <mxCell id="4" value="go" edge="1" source="2" target="3" parent="1"><mxGeometry relative="1" as="geometry"/></mxCell>
15 </root></mxGraphModel></diagram></mxfile>`;
16
17 const EXCALI = JSON.stringify({
18 elements: [
19 { type: "rectangle", x: 0, y: 0, width: 100, height: 50 },
20 { type: "diamond", x: 200, y: 0, width: 60, height: 60 },
21 { type: "text", x: 10, y: 10, text: "<img src=x onerror=alert(1)>", fontSize: 20 },
22 { type: "arrow", x: 100, y: 25, points: [[0, 0], [100, 0]] },
23 { type: "rectangle", x: 0, y: 0, width: 5, height: 5, isDeleted: true },
24 ],
25 });
26
27 describe("diagram kinds", () => {
28 test("registered by extension, with a renderer", () => {
29 expect(fileKind("a.mmd", enc("flowchart TD\n"))).toBe("mermaid");
30 expect(fileKind("a.mermaid", enc("flowchart TD\n"))).toBe("mermaid");
31 expect(fileKind("a.drawio", enc(DRAWIO))).toBe("drawio");
32 expect(fileKind("a.excalidraw", enc(EXCALI))).toBe("excalidraw");
33 expect(RENDERERS.mermaid).toBe(mermaid);
34 expect(RENDERERS.drawio).toBe(drawio);
35 expect(RENDERERS.excalidraw).toBe(excalidraw);
36 expect(RENDER_CAP.drawio).toBeGreaterThan(0);
37 });
38 });
39
40 describe("drawio", () => {
41 test("draws boxes, an ellipse, an arrow and escaped text", () => {
42 const out = String(run(drawio, "a.drawio", DRAWIO).content);
43 expect(out).toContain("<svg");
44 expect(out).toContain("<rect");
45 expect(out).toContain("<ellipse");
46 expect(out).toContain("<polyline");
47 expect(out).toContain("marker-end");
48 expect(out).toContain("go");
49 expect(out).not.toContain("<script");
50 });
51 test("compressed, malformed or oversized falls back", () => {
52 expect(run(drawio, "a.drawio", "<mxfile><diagram>eJzLSM3JyQcABiwCFQ==</diagram></mxfile>").fallback).toContain("compressed");
53 expect(run(drawio, "a.drawio", "nonsense").fallback).toBeDefined();
54 expect(run(drawio, "a.drawio", "<mxGraphModel><root/></mxGraphModel>").fallback).toBeDefined();
55 expect(run(drawio, "a.drawio", DRAWIO, RENDER_CAP.drawio + 1).fallback).toContain("too large");
56 });
57 });
58
59 describe("excalidraw", () => {
60 test("draws shapes, arrow and text, skipping deleted, escaping text", () => {
61 const out = String(run(excalidraw, "a.excalidraw", EXCALI).content);
62 expect(out.match(/<rect/g)?.length).toBe(1);
63 expect(out).toContain("<polygon");
64 expect(out).toContain("<polyline");
65 expect(out).toContain("&lt;img");
66 expect(out).not.toContain("<img");
67 });
68 test("malformed or oversized falls back", () => {
69 expect(run(excalidraw, "a.excalidraw", "{").fallback).toBeDefined();
70 expect(run(excalidraw, "a.excalidraw", '{"elements":[]}').fallback).toBeDefined();
71 expect(run(excalidraw, "a.excalidraw", '{"elements":[{"type":"rectangle","x":1e99,"y":0,"width":1,"height":1}]}').fallback).toBeDefined();
72 expect(run(excalidraw, "a.excalidraw", EXCALI, RENDER_CAP.excalidraw + 1).fallback).toContain("too large");
73 });
74 });
75
76 describe("mermaid", () => {
77 test("names the type past frontmatter and comments, and folds an escaped source", () => {
78 const src = "---\ntitle: x\n---\n%% note\nsequenceDiagram\n A->>B: <b>hi</b>\n";
79 expect(mermaidType(src)).toBe("sequenceDiagram");
80 const out = String(run(mermaid, "a.mmd", src).content);
81 expect(out).toContain("Mermaid sequenceDiagram");
82 expect(out).toContain("<details");
83 expect(out).not.toContain("<details open");
84 expect(out).toContain("&lt;b&gt;hi");
85 });
86 test("no type or too large falls back", () => {
87 expect(run(mermaid, "a.mmd", "hello world\n").fallback).toBeDefined();
88 expect(run(mermaid, "a.mmd", "").fallback).toBeDefined();
89 expect(run(mermaid, "a.mmd", "graph TD\n", RENDER_CAP.mermaid + 1).fallback).toContain("too large");
90 });
91 });
92
93 describe("diagram edge cases", () => {
94 test("a draw.io edge with waypoints is one polyline through them, and a multi-line Excalidraw text is one tspan a line", () => {
95 const xml = `<mxGraphModel><root>
96 <mxCell id="2" value="A" vertex="1"><mxGeometry x="0" y="0" width="10" height="10"/></mxCell>
97 <mxCell id="3" value="B" vertex="1"><mxGeometry x="100" y="100" width="10" height="10"/></mxCell>
98 <mxCell id="4" edge="1" source="2" target="3"><mxGeometry relative="1"><Array as="points"><mxPoint x="100" y="5"/><mxPoint x="100" y="50"/></Array></mxGeometry></mxCell>
99 </root></mxGraphModel>`;
100 const out = String(run(drawio, "a.drawio", xml).content);
101 expect(out).toContain('points="5.0,5.0 100.0,5.0 100.0,50.0 105.0,105.0"');
102 const ex = JSON.stringify({ elements: [{ type: "text", x: 0, y: 0, text: "one\ntwo\nthree", fontSize: 20 }] });
103 expect(String(run(excalidraw, "a.excalidraw", ex).content).match(/<tspan/g)?.length).toBe(3);
104 });
105 test("draw.io past the caps or the coordinate limit falls back", () => {
106 const cell = (i: number) => `<mxCell id="v${i}" vertex="1"><mxGeometry x="${i}" y="0" width="1" height="1"/></mxCell>`;
107 const many = `<mxGraphModel><root>${Array.from({ length: ELEMENT_CAP * 2 + 1 }, (_, i) => cell(i)).join("")}</root></mxGraphModel>`;
108 expect(run(drawio, "a.drawio", many).fallback).toContain("too many");
109 const far = '<mxGraphModel><root><mxCell id="a" vertex="1"><mxGeometry x="1e99" y="0" width="1" height="1"/></mxCell></root></mxGraphModel>';
110 expect(run(drawio, "a.drawio", far).fallback).toBeDefined();
111 });
112 test("single-quoted attributes are read, not a crash", () => {
113 const xml = "<mxGraphModel><root><mxCell id='2' value='Q' vertex='1'><mxGeometry x='0' y='0' width='10' height='10'/></mxCell></root></mxGraphModel>";
114 const out = run(drawio, "a.drawio", xml);
115 expect(out.fallback).toBeUndefined();
116 expect(String(out.content)).toContain("<rect");
117 });
118 test("the mermaid page names the type once, with no explanation", () => {
119 const out = String(run(mermaid, "a.mmd", "graph TD\n A-->B\n").content);
120 expect(out.match(/Mermaid graph/g)?.length).toBe(1);
121 expect(out).not.toContain("does not run");
122 });
123 });
test/render-kinds.test.ts +4
@@ -90,6 +90,10 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
9090 gcode: [enc("G28\nG1 X1 E1\n"), "gcode", "application/octet-stream"],
9191 gco: [enc("G28\n"), "gcode", "application/octet-stream"],
9292 dxf: [enc("0\nSECTION\n2\nENTITIES\n0\nENDSEC\n0\nEOF\n"), "dxf", "application/octet-stream"],
93 mmd: [enc("flowchart TD\n"), "mermaid", "application/octet-stream"],
94 mermaid: [enc("flowchart TD\n"), "mermaid", "application/octet-stream"],
95 drawio: [enc("<mxfile/>"), "drawio", "application/octet-stream"],
96 excalidraw: [enc("{}"), "excalidraw", "application/octet-stream"],
9397 step: [enc("ISO-10303-21;\nHEADER;\n"), "step", "application/octet-stream"],
9498 stp: [enc("ISO-10303-21;\nHEADER;\n"), "step", "application/octet-stream"],
9599 har: [enc(`{"log":{"entries":[]}}`), "har", "application/octet-stream"],

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs