@grethel-labs/excaliplant 0.1.2 → 0.1.3

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.3**  ·  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
@@ -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,
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@grethel-labs/excaliplant",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "PlantUML → ELK layout → Excalidraw renderer with a plugin-based parser.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
@@ -45,7 +45,8 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@resvg/resvg-js": "^2.6.2",
48
- "elkjs": "^0.11.1"
48
+ "elkjs": "^0.11.1",
49
+ "roughjs": "^4.6.6"
49
50
  },
50
51
  "engines": {
51
52
  "node": ">=18"
@@ -1,27 +1,26 @@
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.
12
+
13
+ import rough from "roughjs";
11
14
 
12
15
  const FONT_FAMILY = "Helvetica, Arial, sans-serif";
16
+ const ROUGHNESS = 1; // Excalidraw's default roughness.
17
+ const BOWING = 1;
18
+ const FILL_WEIGHT = 0; // 0 → roughjs picks a sensible default.
19
+
20
+ const generator = rough.generator();
13
21
 
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
22
  /**
22
23
  * 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
24
  *
26
25
  * @param {object} doc The Excalidraw JSON document.
27
26
  * @param {object} [opts]
@@ -76,39 +75,146 @@ function computeBounds(elements) {
76
75
 
77
76
  function renderOne(el) {
78
77
  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);
78
+ case "rectangle": return roughRect(el);
79
+ case "ellipse": return roughEllipse(el);
80
+ case "line": return roughPolyline(el, false);
81
+ case "arrow": return roughPolyline(el, true);
83
82
  case "text": return svgText(el);
84
83
  default: return null;
85
84
  }
86
85
  }
87
86
 
88
- function svgRect(el) {
89
- const fill = colorOrNone(el.backgroundColor);
87
+ // ── roughjs helpers ───────────────────────────────────────────────────────
88
+
89
+ // Pull a deterministic seed off each Excalidraw element so re-rendering
90
+ // the same JSON document yields the same wobble. Excalidraw assigns
91
+ // `seed` to every element; if it's missing we fall back to a hash of
92
+ // the element's id so output is still deterministic per-document.
93
+ function seedFor(el) {
94
+ if (typeof el.seed === "number") return el.seed % 2_147_483_647;
95
+ if (el.id) {
96
+ let h = 0;
97
+ for (const c of String(el.id)) h = (h * 31 + c.charCodeAt(0)) | 0;
98
+ return Math.abs(h) % 2_147_483_647;
99
+ }
100
+ return 1;
101
+ }
102
+
103
+ function roughOpts(el) {
104
+ return {
105
+ seed: seedFor(el),
106
+ roughness: ROUGHNESS,
107
+ bowing: BOWING,
108
+ stroke: el.strokeColor || "#000",
109
+ strokeWidth: el.strokeWidth || 1.5,
110
+ fill: undefined,
111
+ fillStyle: "solid",
112
+ fillWeight: FILL_WEIGHT,
113
+ disableMultiStroke: false,
114
+ };
115
+ }
116
+
117
+ function dasharray(el) {
118
+ if (el.strokeStyle === "dashed") return "8 4";
119
+ if (el.strokeStyle === "dotted") return "1.5 6";
120
+ return null;
121
+ }
122
+
123
+ function drawableToSvg(drawable, el) {
124
+ // roughjs returns one or more `OpSet`s. We render path-typed sets
125
+ // as <path> elements. fillSketch/fillPath sets get the fill colour;
126
+ // path sets get the stroke colour.
90
127
  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}"/>`;
128
+ const strokeWidth = el.strokeWidth || 1.5;
129
+ const dash = dasharray(el);
130
+ const dashAttr = dash ? ` stroke-dasharray="${dash}"` : "";
131
+
132
+ const out = [];
133
+ for (const set of drawable.sets) {
134
+ const d = generator.opsToPath(set);
135
+ if (!d) continue;
136
+ if (set.type === "fillPath" || set.type === "fillSketch") {
137
+ const fill = el.backgroundColor && el.backgroundColor !== "transparent"
138
+ ? el.backgroundColor : null;
139
+ if (!fill) continue;
140
+ out.push(
141
+ `<path d="${d}" fill="${escapeAttr(fill)}" stroke="none"/>`,
142
+ );
143
+ } else if (set.type === "path") {
144
+ out.push(
145
+ `<path d="${d}" fill="none" stroke="${escapeAttr(stroke)}" `
146
+ + `stroke-width="${strokeWidth}" stroke-linecap="round" `
147
+ + `stroke-linejoin="round"${dashAttr}/>`,
148
+ );
149
+ }
150
+ }
151
+ return out.join("");
152
+ }
153
+
154
+ function roughRect(el) {
155
+ const fill = colorOrNone(el.backgroundColor);
156
+ // Solid fill underneath. roughjs' fill modes look noisy on small
157
+ // shapes, and Excalidraw's own export uses solid fills + sketchy
158
+ // outlines, so we mirror that.
159
+ const fillSvg = fill !== "none"
160
+ ? `<path d="${rectPath(el)}" fill="${escapeAttr(fill)}" stroke="none"/>`
161
+ : "";
162
+ const drawable = generator.rectangle(
163
+ el.x, el.y, el.width, el.height, roughOpts(el),
164
+ );
165
+ return fillSvg + drawableToSvg(drawable, el);
93
166
  }
94
167
 
95
- function svgEllipse(el) {
168
+ function rectPath(el) {
169
+ const r = el.roundness ? Math.min(8, el.width / 4, el.height / 4) : 0;
170
+ if (!r) {
171
+ return `M${el.x},${el.y} h${el.width} v${el.height} h${-el.width} z`;
172
+ }
173
+ const x = el.x, y = el.y, w = el.width, h = el.height;
174
+ return [
175
+ `M${x + r},${y}`,
176
+ `h${w - 2 * r}`,
177
+ `a${r},${r} 0 0 1 ${r},${r}`,
178
+ `v${h - 2 * r}`,
179
+ `a${r},${r} 0 0 1 ${-r},${r}`,
180
+ `h${-(w - 2 * r)}`,
181
+ `a${r},${r} 0 0 1 ${-r},${-r}`,
182
+ `v${-(h - 2 * r)}`,
183
+ `a${r},${r} 0 0 1 ${r},${-r}`,
184
+ "z",
185
+ ].join(" ");
186
+ }
187
+
188
+ function roughEllipse(el) {
96
189
  const cx = el.x + el.width / 2;
97
190
  const cy = el.y + el.height / 2;
98
- const rx = el.width / 2;
99
- const ry = el.height / 2;
100
191
  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}"/>`;
192
+ const fillSvg = fill !== "none"
193
+ ? `<ellipse cx="${cx}" cy="${cy}" rx="${el.width / 2}" `
194
+ + `ry="${el.height / 2}" fill="${escapeAttr(fill)}" stroke="none"/>`
195
+ : "";
196
+ const drawable = generator.ellipse(cx, cy, el.width, el.height, roughOpts(el));
197
+ return fillSvg + drawableToSvg(drawable, el);
103
198
  }
104
199
 
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}/>`;
200
+ function roughPolyline(el, withArrow) {
201
+ const pts = (el.points || []).map(([dx, dy]) => [el.x + dx, el.y + dy]);
202
+ if (pts.length < 2) return "";
203
+ const drawable = generator.linearPath(pts, roughOpts(el));
204
+ let body = drawableToSvg(drawable, el);
205
+
206
+ // Arrowheads: keep the same marker-based mechanism, but apply it to
207
+ // a thin invisible <polyline> so the marker ends up at the geometric
208
+ // endpoint (not a wobble-jittered endpoint of the rough path).
209
+ if (withArrow && (el.startArrowhead || el.endArrowhead)) {
210
+ const polyPts = pts.map(([x, y]) => `${x},${y}`).join(" ");
211
+ const startMarker = el.startArrowhead
212
+ ? ` marker-start="url(#m_${el.startArrowhead}_start)"` : "";
213
+ const endMarker = el.endArrowhead
214
+ ? ` marker-end="url(#m_${el.endArrowhead}_end)"` : "";
215
+ body += `<polyline points="${polyPts}" fill="none" stroke="${escapeAttr(el.strokeColor || "#000")}" stroke-width="0" stroke-opacity="0"${startMarker}${endMarker}/>`;
216
+ }
217
+ return body;
112
218
  }
113
219
 
114
220
  function svgText(el) {
@@ -118,26 +224,19 @@ function svgText(el) {
118
224
  const lines = String(el.text ?? "").split("\n");
119
225
  const align = el.textAlign || "left";
120
226
  const anchor = align === "center" ? "middle" : align === "right" ? "end" : "start";
121
- // Excalidraw text x is the box's left edge; baseline depends on align.
122
227
  let xRef = el.x;
123
228
  if (align === "center") xRef = el.x + (el.width || 0) / 2;
124
229
  else if (align === "right") xRef = el.x + (el.width || 0);
125
- const yTop = el.y + fs; // first baseline
230
+ const yTop = el.y + fs;
126
231
  const tspans = lines.map((l, i) =>
127
232
  `<tspan x="${xRef}" dy="${i === 0 ? 0 : lineHeight}">${escapeText(l)}</tspan>`,
128
233
  ).join("");
129
234
  return `<text x="${xRef}" y="${yTop}" fill="${escapeAttr(fill)}" font-size="${fs}" text-anchor="${anchor}">${tspans}</text>`;
130
235
  }
131
236
 
132
- // Arrowhead helpers --------------------------------------------------------
133
-
134
- function markerForArrowhead(kind, end) {
135
- const id = `m_${kind}_${end}`;
136
- return `marker-${end}="url(#${id})"`;
137
- }
237
+ // ── arrowheads ────────────────────────────────────────────────────────────
138
238
 
139
239
  function arrowheadDefs() {
140
- // Inline definitions so each generated SVG is self-contained.
141
240
  return `<defs>
142
241
  <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
242
  <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 +251,7 @@ function arrowheadDefs() {
152
251
  </defs>`;
153
252
  }
154
253
 
155
- // Misc helpers -------------------------------------------------------------
254
+ // ── misc ──────────────────────────────────────────────────────────────────
156
255
 
157
256
  function colorOrNone(c) {
158
257
  if (!c || c === "transparent") return "none";