@grethel-labs/excaliplant 0.1.2 → 0.1.4

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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
 
2
2
  # excaliplant
3
3
 
4
- > PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.  ·  **v0.1.2**  ·  73 tests  ·  MIT
4
+ > PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.  ·  **v0.1.4**  ·  73 tests  ·  MIT
5
5
 
6
6
  `@grethel-labs/excaliplant` takes PlantUML source, runs it through a plugin-based
7
7
  parser, lays it out with [ELK](https://github.com/kieler/elkjs), and
@@ -13,11 +13,11 @@ artefacts.
13
13
  <table>
14
14
  <tr>
15
15
  <td align="center" width="50%">
16
- <a href="docs/ressources/generated/png/modules.png"><img src="docs/ressources/generated/png/modules.png" alt="Module structure" width="380"/></a><br/>
16
+ <a href="docs/ressources/generated/svg/modules.svg"><img src="docs/ressources/generated/svg/modules.svg" alt="Module structure" width="380"/></a><br/>
17
17
  <sub><b>Module structure</b> — rendered by excaliplant itself</sub>
18
18
  </td>
19
19
  <td align="center" width="50%">
20
- <a href="docs/ressources/generated/png/sequence.png"><img src="docs/ressources/generated/png/sequence.png" alt="renderPlantUml flow" width="380"/></a><br/>
20
+ <a href="docs/ressources/generated/svg/sequence.svg"><img src="docs/ressources/generated/svg/sequence.svg" alt="renderPlantUml flow" width="380"/></a><br/>
21
21
  <sub><b>renderPlantUml flow</b> — rendered by excaliplant itself</sub>
22
22
  </td>
23
23
  </tr>
@@ -52,6 +52,21 @@ const excalidraw = await renderPlantUml(plantumlText, { sourceLabel: "demo" });
52
52
 
53
53
  ### Render to SVG / PNG
54
54
 
55
+ The result of `renderPlantUml(...)` is a thenable — you can `await` it
56
+ to get the Excalidraw JSON, or chain `.toSvg()` / `.toPng()` on it to
57
+ get the rasterised diagram in a single line. Both outputs keep the
58
+ hand-drawn Excalidraw look (strokes are produced via `roughjs`, the
59
+ same library Excalidraw uses internally).
60
+
61
+ ```js
62
+ import { renderPlantUml } from "@grethel-labs/excaliplant";
63
+
64
+ const svg = await renderPlantUml(plantumlText).toSvg();
65
+ const png = await renderPlantUml(plantumlText).toPng({ width: 4800 });
66
+ ```
67
+
68
+ The lower-level helpers are still exported if you need them:
69
+
55
70
  ```js
56
71
  import {
57
72
  renderPlantUml,
@@ -96,7 +111,7 @@ JSDoc tags.
96
111
 
97
112
  ### Module structure
98
113
 
99
- ![Module structure](docs/ressources/generated/png/modules.png)
114
+ ![Module structure](docs/ressources/generated/svg/modules.svg)
100
115
 
101
116
  _Sources: [PlantUML](docs/ressources/generated/puml/modules.puml) · [SVG](docs/ressources/generated/svg/modules.svg)_
102
117
 
@@ -107,7 +122,7 @@ each plugin handling one PlantUML construct.
107
122
 
108
123
  ### renderPlantUml flow
109
124
 
110
- ![renderPlantUml flow](docs/ressources/generated/png/sequence.png)
125
+ ![renderPlantUml flow](docs/ressources/generated/svg/sequence.svg)
111
126
 
112
127
  _Sources: [PlantUML](docs/ressources/generated/puml/sequence.puml) · [SVG](docs/ressources/generated/svg/sequence.svg)_
113
128
 
@@ -126,7 +141,7 @@ The call graph for `renderPlantUml(text)` walks three subsystems:
126
141
 
127
142
  ### Parser plugins
128
143
 
129
- ![Parser plugins](docs/ressources/generated/png/plugins.png)
144
+ ![Parser plugins](docs/ressources/generated/svg/plugins.svg)
130
145
 
131
146
  _Sources: [PlantUML](docs/ressources/generated/puml/plugins.puml) · [SVG](docs/ressources/generated/svg/plugins.svg)_
132
147
 
@@ -160,6 +175,10 @@ PlantUML text
160
175
 
161
176
  ```text
162
177
  excaliplant
178
+ ├── assets
179
+ │ └── fonts
180
+ │ ├── Excalifont-Regular.woff2
181
+ │ └── LICENSE.txt
163
182
  ├── docs
164
183
  │ ├── ressources
165
184
  │ ├── scripts
@@ -196,6 +215,7 @@ excaliplant
196
215
  │ │ └── svg.mjs
197
216
  │ └── style
198
217
  │ ├── colors.mjs
218
+ │ ├── font.mjs
199
219
  │ └── text.mjs
200
220
  ├── tests
201
221
  │ ├── edge_cases.test.mjs
@@ -0,0 +1,20 @@
1
+ Excalifont
2
+ ==========
3
+
4
+ The Excalifont woff2 font file in this directory is bundled into
5
+ @grethel-labs/excaliplant so SVG and PNG exports render text in the
6
+ same hand-drawn typeface that Excalidraw uses on screen.
7
+
8
+ Origin: https://github.com/excalidraw/excalidraw (packages/excalidraw/fonts/Excalifont)
9
+ License: SIL Open Font License, Version 1.1 (OFL-1.1)
10
+ https://scripts.sil.org/OFL
11
+
12
+ Copyright (c) 2024 by Excalidraw. All rights reserved.
13
+ Excalifont is a trademark of Excalidraw.
14
+
15
+ Manufacturer/designer:
16
+ - Your Own Font Foundry (Virgil)
17
+ - Ján Filípek / DizajnDesign (Excalifont, modifications)
18
+
19
+ The font is redistributed under the OFL-1.1; see the upstream LICENSE
20
+ for the full text. This bundling is permitted by §2 of the OFL.
package/index.mjs CHANGED
@@ -49,6 +49,9 @@
49
49
  import { parsePlantUml } from "./src/parser/plantuml.mjs";
50
50
  import { layoutDiagram } from "./src/layout/elk_layout.mjs";
51
51
  import { exportDiagram } from "./src/render/excalidraw.mjs";
52
+ import { excalidrawToSvg } from "./src/render/svg.mjs";
53
+ import { excalidrawJsonToCanvasSvg } from "./src/render/canvas_svg.mjs";
54
+ import { svgToPng } from "./src/render/png.mjs";
52
55
 
53
56
  export { parsePlantUml } from "./src/parser/plantuml.mjs";
54
57
  export { layoutDiagram } from "./src/layout/elk_layout.mjs";
@@ -66,31 +69,98 @@ export {
66
69
  SHAPES,
67
70
  } from "./src/model/diagram.mjs";
68
71
 
72
+ /**
73
+ * Chainable result returned by `renderPlantUml` / `renderDiagram`.
74
+ *
75
+ * Awaiting the result yields the Excalidraw JSON document, so existing
76
+ * callers (`const doc = await renderPlantUml(text)`) keep working.
77
+ *
78
+ * On top of that, the result exposes `.toSvg()` and `.toPng()` so a
79
+ * caller can write:
80
+ *
81
+ * ```js
82
+ * const r = renderPlantUml(text);
83
+ * const svg = await r.toSvg();
84
+ * const png = await r.toPng({ width: 4800 });
85
+ * ```
86
+ *
87
+ * Both helpers lazily await the underlying document — so calling
88
+ * `toSvg()` / `toPng()` directly on the unawaited result works too.
89
+ */
90
+ export class RenderResult {
91
+ /** @param {Promise<object>} docPromise */
92
+ constructor(docPromise) {
93
+ this._doc = docPromise;
94
+ }
95
+
96
+ /** Thenable: `await result` yields the Excalidraw JSON document. */
97
+ then(onFulfilled, onRejected) {
98
+ return this._doc.then(onFulfilled, onRejected);
99
+ }
100
+
101
+ /**
102
+ * Letter-boxed sketchy SVG.
103
+ *
104
+ * @param {object} [opts] Forwarded to `excalidrawJsonToCanvasSvg`,
105
+ * plus `{ canvas: false }` to skip the letter-boxing and get the
106
+ * tightly-cropped SVG instead.
107
+ * @returns {Promise<string>}
108
+ */
109
+ async toSvg(opts = {}) {
110
+ const doc = await this._doc;
111
+ if (opts.canvas === false) return excalidrawToSvg(doc, opts);
112
+ return excalidrawJsonToCanvasSvg(doc, opts);
113
+ }
114
+
115
+ /**
116
+ * Sketchy PNG. Renders the SVG (which already carries the
117
+ * Excalidraw-style wobble via roughjs) and rasterises with resvg.
118
+ *
119
+ * @param {object} [opts] Forwarded to `svgToPng` and the SVG step.
120
+ * @returns {Promise<Buffer>}
121
+ */
122
+ async toPng(opts = {}) {
123
+ const svg = await this.toSvg(opts);
124
+ return svgToPng(svg, opts);
125
+ }
126
+ }
127
+
69
128
  /**
70
129
  * Render a PlantUML source string to an Excalidraw JSON document.
71
130
  *
131
+ * The return value is a thenable {@link RenderResult}: `await` it for
132
+ * the Excalidraw JSON, or call `.toSvg()` / `.toPng()` on it to get
133
+ * the rasterised diagram in one chained call.
134
+ *
72
135
  * @param {string} plantuml PlantUML text (see src/parser/plantuml.mjs
73
136
  * for the supported subset).
74
137
  * @param {object} [opts]
75
138
  * @param {string} [opts.sourceLabel] Forwarded to the renderer's
76
139
  * appState.name.
77
- * @returns {Promise<object>} Excalidraw JSON.
140
+ * @returns {RenderResult} Thenable wrapping the Excalidraw
141
+ * JSON document.
78
142
  */
79
- export async function renderPlantUml(plantuml, opts = {}) {
80
- const diagram = parsePlantUml(plantuml);
81
- await layoutDiagram(diagram);
82
- return exportDiagram(diagram, {
83
- sourceLabel: opts.sourceLabel ?? diagram.title ?? "",
84
- });
143
+ export function renderPlantUml(plantuml, opts = {}) {
144
+ return new RenderResult((async () => {
145
+ const diagram = parsePlantUml(plantuml);
146
+ await layoutDiagram(diagram);
147
+ return exportDiagram(diagram, {
148
+ sourceLabel: opts.sourceLabel ?? diagram.title ?? "",
149
+ });
150
+ })());
85
151
  }
86
152
 
87
153
  /**
88
154
  * Render an already-built Diagram model. Useful for callers that want
89
155
  * to bypass the PlantUML parser and feed shapes programmatically.
156
+ *
157
+ * @returns {RenderResult}
90
158
  */
91
- export async function renderDiagram(diagram, opts = {}) {
92
- await layoutDiagram(diagram);
93
- return exportDiagram(diagram, {
94
- sourceLabel: opts.sourceLabel ?? diagram.title ?? "",
95
- });
159
+ export function renderDiagram(diagram, opts = {}) {
160
+ return new RenderResult((async () => {
161
+ await layoutDiagram(diagram);
162
+ return exportDiagram(diagram, {
163
+ sourceLabel: opts.sourceLabel ?? diagram.title ?? "",
164
+ });
165
+ })());
96
166
  }
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@grethel-labs/excaliplant",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
7
7
  "files": [
8
8
  "index.mjs",
9
9
  "src/",
10
+ "assets/fonts/",
10
11
  "README.md",
11
12
  "LICENSE"
12
13
  ],
@@ -45,7 +46,8 @@
45
46
  },
46
47
  "dependencies": {
47
48
  "@resvg/resvg-js": "^2.6.2",
48
- "elkjs": "^0.11.1"
49
+ "elkjs": "^0.11.1",
50
+ "roughjs": "^4.6.6"
49
51
  },
50
52
  "engines": {
51
53
  "node": ">=18"
@@ -6,6 +6,8 @@
6
6
 
7
7
  import { Resvg } from "@resvg/resvg-js";
8
8
 
9
+ import { EXCALIFONT_FONT_PATH } from "../style/font.mjs";
10
+
9
11
  const DEFAULT_PNG_WIDTH = 4800; // 4× the default 1200 SVG canvas.
10
12
 
11
13
  /**
@@ -22,7 +24,15 @@ export function svgToPng(svgText, opts = {}) {
22
24
  const resvg = new Resvg(svgText, {
23
25
  fitTo: { mode: "width", value: width },
24
26
  background: opts.background ?? "#ffffff",
25
- font: { loadSystemFonts: true },
27
+ // resvg ignores @font-face / data-URL fonts in the SVG, so we
28
+ // have to point it at the bundled Excalifont woff2 explicitly —
29
+ // otherwise PNG text would fall back to a system font and lose
30
+ // the Excalidraw-style handwriting.
31
+ font: {
32
+ loadSystemFonts: true,
33
+ fontFiles: [EXCALIFONT_FONT_PATH],
34
+ defaultFontFamily: "Excalifont",
35
+ },
26
36
  });
27
37
  return resvg.render().asPng();
28
38
  }
@@ -1,27 +1,31 @@
1
1
  // Convert an Excalidraw JSON document to a self-contained SVG string.
2
2
  //
3
3
  // The Excalidraw renderer emits a flat list of elements with absolute
4
- // positions; SVG needs the same. We translate the subset we actually
5
- // produce: rectangle, ellipse, line, arrow, text. Roughness is dropped
6
- // (we render geometric primitives — readable in README, no rough-style
7
- // wobble needed).
4
+ // positions; we translate the subset we actually produce: rectangle,
5
+ // ellipse, line, arrow, text. Strokes are routed through `roughjs`
6
+ // (the same library Excalidraw uses internally) so the exported SVG
7
+ // inherits the recognisable hand-drawn wobble — and since the PNG
8
+ // path rasterises this very SVG, the PNG keeps the look too.
8
9
  //
9
- // This exists to give the build pipeline a Node-only path from
10
- // PlantUML → SVG without spinning up a headless browser.
10
+ // The roughjs Generator is dependency-free at runtime: it produces
11
+ // SVG path commands as strings, no DOM required.
11
12
 
12
- const FONT_FAMILY = "Helvetica, Arial, sans-serif";
13
+ import rough from "roughjs";
14
+
15
+ import {
16
+ EXCALIFONT_FONT_FACE,
17
+ EXCALIFONT_FONT_STACK,
18
+ } from "../style/font.mjs";
19
+
20
+ const FONT_FAMILY = EXCALIFONT_FONT_STACK;
21
+ const ROUGHNESS = 1; // Excalidraw's default roughness.
22
+ const BOWING = 1;
23
+ const FILL_WEIGHT = 0; // 0 → roughjs picks a sensible default.
24
+
25
+ const generator = rough.generator();
13
26
 
14
- /**
15
- * @param {object} doc Excalidraw JSON document.
16
- * @param {object} [opts]
17
- * @param {number} [opts.padding=16] Extra margin around content.
18
- * @param {string} [opts.background] Document background colour.
19
- * @returns {string} SVG markup.
20
- */
21
27
  /**
22
28
  * Convert an Excalidraw JSON document to a stand-alone SVG string.
23
- * Used by the build-time documentation pipeline
24
- * ({@link ../../scripts/build-docs.mjs}).
25
29
  *
26
30
  * @param {object} doc The Excalidraw JSON document.
27
31
  * @param {object} [opts]
@@ -40,7 +44,11 @@ export function excalidrawToSvg(doc, opts = {}) {
40
44
 
41
45
  const bg = opts.background ?? doc.appState?.viewBackgroundColor ?? "#ffffff";
42
46
  const out = [];
43
- out.push(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" font-family="${FONT_FAMILY}">`);
47
+ out.push(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" font-family='${FONT_FAMILY}'>`);
48
+ // Inline Excalifont so the SVG carries the same hand-drawn typeface
49
+ // Excalidraw uses on screen, even when GitHub or any other host
50
+ // serves the file as a sandboxed `<img>` (no external font fetches).
51
+ out.push(`<defs><style type="text/css"><![CDATA[${EXCALIFONT_FONT_FACE}]]></style></defs>`);
44
52
  out.push(`<rect width="100%" height="100%" fill="${escapeAttr(bg)}"/>`);
45
53
  out.push(`<g transform="translate(${tx} ${ty})">`);
46
54
  out.push(arrowheadDefs());
@@ -76,39 +84,146 @@ function computeBounds(elements) {
76
84
 
77
85
  function renderOne(el) {
78
86
  switch (el.type) {
79
- case "rectangle": return svgRect(el);
80
- case "ellipse": return svgEllipse(el);
81
- case "line": return svgPolyline(el, false);
82
- case "arrow": return svgPolyline(el, true);
87
+ case "rectangle": return roughRect(el);
88
+ case "ellipse": return roughEllipse(el);
89
+ case "line": return roughPolyline(el, false);
90
+ case "arrow": return roughPolyline(el, true);
83
91
  case "text": return svgText(el);
84
92
  default: return null;
85
93
  }
86
94
  }
87
95
 
88
- function svgRect(el) {
89
- const fill = colorOrNone(el.backgroundColor);
96
+ // ── roughjs helpers ───────────────────────────────────────────────────────
97
+
98
+ // Pull a deterministic seed off each Excalidraw element so re-rendering
99
+ // the same JSON document yields the same wobble. Excalidraw assigns
100
+ // `seed` to every element; if it's missing we fall back to a hash of
101
+ // the element's id so output is still deterministic per-document.
102
+ function seedFor(el) {
103
+ if (typeof el.seed === "number") return el.seed % 2_147_483_647;
104
+ if (el.id) {
105
+ let h = 0;
106
+ for (const c of String(el.id)) h = (h * 31 + c.charCodeAt(0)) | 0;
107
+ return Math.abs(h) % 2_147_483_647;
108
+ }
109
+ return 1;
110
+ }
111
+
112
+ function roughOpts(el) {
113
+ return {
114
+ seed: seedFor(el),
115
+ roughness: ROUGHNESS,
116
+ bowing: BOWING,
117
+ stroke: el.strokeColor || "#000",
118
+ strokeWidth: el.strokeWidth || 1.5,
119
+ fill: undefined,
120
+ fillStyle: "solid",
121
+ fillWeight: FILL_WEIGHT,
122
+ disableMultiStroke: false,
123
+ };
124
+ }
125
+
126
+ function dasharray(el) {
127
+ if (el.strokeStyle === "dashed") return "8 4";
128
+ if (el.strokeStyle === "dotted") return "1.5 6";
129
+ return null;
130
+ }
131
+
132
+ function drawableToSvg(drawable, el) {
133
+ // roughjs returns one or more `OpSet`s. We render path-typed sets
134
+ // as <path> elements. fillSketch/fillPath sets get the fill colour;
135
+ // path sets get the stroke colour.
90
136
  const stroke = el.strokeColor || "#000";
91
- const rx = el.roundness ? 6 : 0;
92
- return `<rect x="${el.x}" y="${el.y}" width="${el.width}" height="${el.height}" rx="${rx}" ry="${rx}" fill="${escapeAttr(fill)}" stroke="${escapeAttr(stroke)}" stroke-width="${el.strokeWidth || 1.5}"/>`;
137
+ const strokeWidth = el.strokeWidth || 1.5;
138
+ const dash = dasharray(el);
139
+ const dashAttr = dash ? ` stroke-dasharray="${dash}"` : "";
140
+
141
+ const out = [];
142
+ for (const set of drawable.sets) {
143
+ const d = generator.opsToPath(set);
144
+ if (!d) continue;
145
+ if (set.type === "fillPath" || set.type === "fillSketch") {
146
+ const fill = el.backgroundColor && el.backgroundColor !== "transparent"
147
+ ? el.backgroundColor : null;
148
+ if (!fill) continue;
149
+ out.push(
150
+ `<path d="${d}" fill="${escapeAttr(fill)}" stroke="none"/>`,
151
+ );
152
+ } else if (set.type === "path") {
153
+ out.push(
154
+ `<path d="${d}" fill="none" stroke="${escapeAttr(stroke)}" `
155
+ + `stroke-width="${strokeWidth}" stroke-linecap="round" `
156
+ + `stroke-linejoin="round"${dashAttr}/>`,
157
+ );
158
+ }
159
+ }
160
+ return out.join("");
161
+ }
162
+
163
+ function roughRect(el) {
164
+ const fill = colorOrNone(el.backgroundColor);
165
+ // Solid fill underneath. roughjs' fill modes look noisy on small
166
+ // shapes, and Excalidraw's own export uses solid fills + sketchy
167
+ // outlines, so we mirror that.
168
+ const fillSvg = fill !== "none"
169
+ ? `<path d="${rectPath(el)}" fill="${escapeAttr(fill)}" stroke="none"/>`
170
+ : "";
171
+ const drawable = generator.rectangle(
172
+ el.x, el.y, el.width, el.height, roughOpts(el),
173
+ );
174
+ return fillSvg + drawableToSvg(drawable, el);
175
+ }
176
+
177
+ function rectPath(el) {
178
+ const r = el.roundness ? Math.min(8, el.width / 4, el.height / 4) : 0;
179
+ if (!r) {
180
+ return `M${el.x},${el.y} h${el.width} v${el.height} h${-el.width} z`;
181
+ }
182
+ const x = el.x, y = el.y, w = el.width, h = el.height;
183
+ return [
184
+ `M${x + r},${y}`,
185
+ `h${w - 2 * r}`,
186
+ `a${r},${r} 0 0 1 ${r},${r}`,
187
+ `v${h - 2 * r}`,
188
+ `a${r},${r} 0 0 1 ${-r},${r}`,
189
+ `h${-(w - 2 * r)}`,
190
+ `a${r},${r} 0 0 1 ${-r},${-r}`,
191
+ `v${-(h - 2 * r)}`,
192
+ `a${r},${r} 0 0 1 ${r},${-r}`,
193
+ "z",
194
+ ].join(" ");
93
195
  }
94
196
 
95
- function svgEllipse(el) {
197
+ function roughEllipse(el) {
96
198
  const cx = el.x + el.width / 2;
97
199
  const cy = el.y + el.height / 2;
98
- const rx = el.width / 2;
99
- const ry = el.height / 2;
100
200
  const fill = colorOrNone(el.backgroundColor);
101
- const stroke = el.strokeColor || "#000";
102
- return `<ellipse cx="${cx}" cy="${cy}" rx="${rx}" ry="${ry}" fill="${escapeAttr(fill)}" stroke="${escapeAttr(stroke)}" stroke-width="${el.strokeWidth || 1.5}"/>`;
201
+ const fillSvg = fill !== "none"
202
+ ? `<ellipse cx="${cx}" cy="${cy}" rx="${el.width / 2}" `
203
+ + `ry="${el.height / 2}" fill="${escapeAttr(fill)}" stroke="none"/>`
204
+ : "";
205
+ const drawable = generator.ellipse(cx, cy, el.width, el.height, roughOpts(el));
206
+ return fillSvg + drawableToSvg(drawable, el);
103
207
  }
104
208
 
105
- function svgPolyline(el, withArrow) {
106
- const pts = (el.points || []).map(([dx, dy]) => `${el.x + dx},${el.y + dy}`).join(" ");
107
- const stroke = el.strokeColor || "#000";
108
- const dash = el.strokeStyle === "dashed" ? `stroke-dasharray="6 4"` : "";
109
- const startMarker = withArrow && el.startArrowhead ? markerForArrowhead(el.startArrowhead, "start") : "";
110
- const endMarker = withArrow && el.endArrowhead ? markerForArrowhead(el.endArrowhead, "end") : "";
111
- return `<polyline points="${pts}" fill="none" stroke="${escapeAttr(stroke)}" stroke-width="${el.strokeWidth || 1.5}" ${dash} ${startMarker} ${endMarker}/>`;
209
+ function roughPolyline(el, withArrow) {
210
+ const pts = (el.points || []).map(([dx, dy]) => [el.x + dx, el.y + dy]);
211
+ if (pts.length < 2) return "";
212
+ const drawable = generator.linearPath(pts, roughOpts(el));
213
+ let body = drawableToSvg(drawable, el);
214
+
215
+ // Arrowheads: keep the same marker-based mechanism, but apply it to
216
+ // a thin invisible <polyline> so the marker ends up at the geometric
217
+ // endpoint (not a wobble-jittered endpoint of the rough path).
218
+ if (withArrow && (el.startArrowhead || el.endArrowhead)) {
219
+ const polyPts = pts.map(([x, y]) => `${x},${y}`).join(" ");
220
+ const startMarker = el.startArrowhead
221
+ ? ` marker-start="url(#m_${el.startArrowhead}_start)"` : "";
222
+ const endMarker = el.endArrowhead
223
+ ? ` marker-end="url(#m_${el.endArrowhead}_end)"` : "";
224
+ body += `<polyline points="${polyPts}" fill="none" stroke="${escapeAttr(el.strokeColor || "#000")}" stroke-width="0" stroke-opacity="0"${startMarker}${endMarker}/>`;
225
+ }
226
+ return body;
112
227
  }
113
228
 
114
229
  function svgText(el) {
@@ -118,26 +233,19 @@ function svgText(el) {
118
233
  const lines = String(el.text ?? "").split("\n");
119
234
  const align = el.textAlign || "left";
120
235
  const anchor = align === "center" ? "middle" : align === "right" ? "end" : "start";
121
- // Excalidraw text x is the box's left edge; baseline depends on align.
122
236
  let xRef = el.x;
123
237
  if (align === "center") xRef = el.x + (el.width || 0) / 2;
124
238
  else if (align === "right") xRef = el.x + (el.width || 0);
125
- const yTop = el.y + fs; // first baseline
239
+ const yTop = el.y + fs;
126
240
  const tspans = lines.map((l, i) =>
127
241
  `<tspan x="${xRef}" dy="${i === 0 ? 0 : lineHeight}">${escapeText(l)}</tspan>`,
128
242
  ).join("");
129
243
  return `<text x="${xRef}" y="${yTop}" fill="${escapeAttr(fill)}" font-size="${fs}" text-anchor="${anchor}">${tspans}</text>`;
130
244
  }
131
245
 
132
- // Arrowhead helpers --------------------------------------------------------
133
-
134
- function markerForArrowhead(kind, end) {
135
- const id = `m_${kind}_${end}`;
136
- return `marker-${end}="url(#${id})"`;
137
- }
246
+ // ── arrowheads ────────────────────────────────────────────────────────────
138
247
 
139
248
  function arrowheadDefs() {
140
- // Inline definitions so each generated SVG is self-contained.
141
249
  return `<defs>
142
250
  <marker id="m_arrow_end" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path d="M0,0 L10,5 L0,10 z" fill="#000"/></marker>
143
251
  <marker id="m_arrow_start" viewBox="0 0 10 10" refX="1" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#000"/></marker>
@@ -152,7 +260,7 @@ function arrowheadDefs() {
152
260
  </defs>`;
153
261
  }
154
262
 
155
- // Misc helpers -------------------------------------------------------------
263
+ // ── misc ──────────────────────────────────────────────────────────────────
156
264
 
157
265
  function colorOrNone(c) {
158
266
  if (!c || c === "transparent") return "none";
@@ -0,0 +1,39 @@
1
+ // Inline Excalifont so exported SVGs and PNGs render text in the same
2
+ // hand-drawn typeface that Excalidraw uses on screen.
3
+ //
4
+ // Excalidraw ships Excalifont as a multi-subset family. We bundle the
5
+ // Latin subset (U+20-7E plus common punctuation) — that's all our
6
+ // labels need, and keeps the inline data URL small (~33 KB base64).
7
+ //
8
+ // At import time we read the woff2 once and cache:
9
+ // - `EXCALIFONT_WOFF2` the raw bytes (resvg-js consumes these)
10
+ // - `EXCALIFONT_DATA_URL` base64 data URL for inlining in SVG
11
+ // - `EXCALIFONT_FONT_FACE` a `@font-face` rule string ready to
12
+ // drop inside an SVG `<style>` element
13
+ // - `EXCALIFONT_FAMILY` the family name ("Excalifont")
14
+ //
15
+ // The font is OFL-licensed; the upstream copy lives at
16
+ // excalidraw/excalidraw on GitHub. The OFL notice is preserved in the
17
+ // repo's NOTICE/LICENSE-fonts file alongside the binary.
18
+
19
+ import { readFileSync } from "node:fs";
20
+ import { fileURLToPath } from "node:url";
21
+ import path from "node:path";
22
+
23
+ const here = path.dirname(fileURLToPath(import.meta.url));
24
+ const FONT_PATH = path.resolve(here, "..", "..", "assets", "fonts", "Excalifont-Regular.woff2");
25
+
26
+ export const EXCALIFONT_FAMILY = "Excalifont";
27
+ export const EXCALIFONT_FONT_PATH = FONT_PATH;
28
+ export const EXCALIFONT_WOFF2 = readFileSync(FONT_PATH);
29
+ export const EXCALIFONT_DATA_URL =
30
+ `data:font/woff2;base64,${EXCALIFONT_WOFF2.toString("base64")}`;
31
+
32
+ // `@font-face` rule for embedding inside an SVG `<style>` block. The
33
+ // fallback chain after Excalifont keeps text legible if a renderer
34
+ // strips `<style>` (some sanitizers do).
35
+ export const EXCALIFONT_FONT_FACE =
36
+ `@font-face{font-family:"${EXCALIFONT_FAMILY}";src:url(${EXCALIFONT_DATA_URL}) format("woff2");font-display:swap;}`;
37
+
38
+ export const EXCALIFONT_FONT_STACK =
39
+ `"${EXCALIFONT_FAMILY}", "Segoe Print", "Comic Sans MS", "Apple Chancery", cursive`;