@luutuankiet/clipboard2markdown 0.6.0 → 0.7.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.
package/README.md CHANGED
@@ -73,6 +73,18 @@ c2m excalidraw --out work/images/ a.json # into a working copy: ![a](./images
73
73
 
74
74
  Per diagram it writes `<name>.png` (scale 3, lowered until the image has at most 25,000,000 pixels, Google Docs' limit), then prints the Mermaid preview, any warnings, an image line `![<name>](attach:<name>)`, an `Edit: <share link>` line (the link as plain text under the image, so it shows in the doc) and the images map entry `"<name>": "@file64:/abs/path/<name>.png"`. With `--out <folder>/images/` instead of `--png`, the PNG goes into that folder and the image line reads `![<name>](./images/<name>.png)`, ready for a working copy. No review PNG is written unless you pass `--review`; the preview and warnings are the check. Each run first deletes PNGs older than 24 hours in the default cache folder; a folder you name is never cleaned. CJK text is not drawn, because the 13 MB CJK font is left out of the package; such diagrams get a warning.
75
75
 
76
+ **Mermaid in, Excalidraw out** (`c2m excalidraw <file>.mmd`): a Mermaid file goes through the same command and gives the same outputs (link, PNG, paste block), drawn by Mermaid's layout as Excalidraw shapes in the house style. Flowcharts and sequence diagrams become editable boxes and arrows; other diagram types come out as one picture, with a warning.
77
+
78
+ ```bash
79
+ c2m excalidraw --png flow.mmd # PNG + link + paste block
80
+ ```
81
+
82
+ **Annotated screenshots** (doodles): a JSON object naming a PNG or JPEG and a list of notes, each with a `target` point `[x, y]` or box `[x, y, w, h]` in the image's pixels and an optional `side`. Notes go in the margins in Excalidraw's hand font, never on the picture or on each other, with a curved arrow to each target. The share link opens without the picture (excalidraw.com stores pictures apart from the link); the PNG is complete. Full spec in `c2m excalidraw --help`, section DOODLE.
83
+
84
+ ```bash
85
+ c2m excalidraw --png shot.doodle.json # {"image": "shot.png", "notes": [{"text": "...", "target": [10, 20, 300, 40]}]}
86
+ ```
87
+
76
88
  ## Demo
77
89
 
78
90
  **Live:** https://luutuankiet.github.io/clipboard2markdown/
package/bin/excalidraw.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // step with src/diagrams/skeleton.js.
6
6
 
7
7
  import { mkdirSync, readFileSync, writeFileSync } from 'fs';
8
- import { basename, resolve } from 'path';
8
+ import { basename, dirname, resolve } from 'path';
9
9
  import { buildSkeleton } from '../src/diagrams/skeleton.js';
10
10
  import { saveScene } from '../src/diagrams/share-link.js';
11
11
  import { sceneToMermaid } from '../src/diagrams/scene-to-mermaid.js';
@@ -20,6 +20,8 @@ Usage:
20
20
  also draw each diagram as PNG (see PNG below)
21
21
  c2m excalidraw --out <folder>/images/ <file.json>...
22
22
  draw into a working copy's images folder
23
+ c2m excalidraw <file.mmd> a Mermaid diagram instead (see MERMAID below)
24
+ c2m excalidraw <shot.json> an annotated screenshot (see DOODLE below)
23
25
  c2m excalidraw --help show this help
24
26
 
25
27
  OUTPUT (stdout, in this order)
@@ -163,9 +165,36 @@ PNG (for pasting into a Google Doc): one command, then one write
163
165
  Text uses Excalidraw's fonts; CJK text is not drawn (the CJK font is not
164
166
  shipped) and gets a warning.
165
167
 
168
+ MERMAID (input file ending .mmd or .mermaid)
169
+ c2m excalidraw --png flow.mmd seq.mmd
170
+ Mermaid's own layout, drawn as Excalidraw shapes in the house style's plan
171
+ pass (white nodes, dark stroke, Excalifont). Flowcharts and sequence
172
+ diagrams become editable shapes; other types (class, state, gantt ...) come
173
+ out as one picture and get a warning. The preview is your Mermaid source.
174
+ Colour a node afterwards with c2m diagrams edit (style op).
175
+
176
+ DOODLE (annotated screenshot: a JSON object with "image" and "notes")
177
+ {"image": "shot.png", PNG or JPEG, relative to this JSON file
178
+ "width": 1100, optional: drawn width in px (default the
179
+ image's own, at most 1400); targets stay
180
+ in the image's own pixels
181
+ "color": "#1971c2", optional: pen colour for notes and arrows
182
+ "notes": [
183
+ {"text": "honest about gaps", "target": [100, 150, 370, 45]},
184
+ {"text": "green = in the warehouse", "target": [1662, 341], "side": "right"}]}
185
+ target [x, y] a point, or [x, y, width, height] a box (gets an outline),
186
+ in the image's pixels, measured from its top-left corner
187
+ side left, right, top or bottom; default: the image edge nearest the
188
+ target. Notes stack in the margin on that side, never on the
189
+ image or on each other, wrapped at ~28 characters ("\n" breaks).
190
+ Each note gets a curved arrow from its edge to the target, in Excalidraw's
191
+ hand font. The preview lists the notes. The share link opens WITHOUT the
192
+ picture (excalidraw.com stores pictures apart from the link), so every
193
+ doodle warns; the PNG is the deliverable.
194
+
166
195
  NOT SUPPORTED
167
- images, frames, freedraw, Mermaid as input, editing an existing link (use
168
- c2m diagrams edit for that), writing .excalidraw files.
196
+ frames, freedraw, editing an existing link (use c2m diagrams edit for that),
197
+ writing .excalidraw files, pictures in share links.
169
198
  `;
170
199
 
171
200
  function readInput(target, stdin) {
@@ -214,6 +243,27 @@ function toScene(input) {
214
243
  return buildSkeleton(input);
215
244
  }
216
245
 
246
+ // One input -> { scene, preview, warnings, fence }. A .mmd file is Mermaid; a
247
+ // JSON object with "image" and "notes" is a doodle; anything else is the
248
+ // element array or scene described in the help.
249
+ async function buildInput(target, io) {
250
+ var text = readInput(target, io.stdin);
251
+ if (/\.(mmd|mermaid)$/i.test(target)) {
252
+ var mermaid = await import('../src/mermaid-input.js');
253
+ return Object.assign({ fence: 'mermaid' }, await mermaid.mermaidToScene(text));
254
+ }
255
+ var input = parseJson(text);
256
+ var doodle = await import('../src/doodle.js');
257
+ if (doodle.isDoodleSpec(input)) {
258
+ var base = target === '-' ? process.cwd() : dirname(resolve(target));
259
+ var bytes;
260
+ try { bytes = readFileSync(resolve(base, input.image)); } catch (e) { throw new Error('cannot read image ' + input.image + ': ' + e.message); }
261
+ var render = await import('../src/excalidraw-png.js');
262
+ return Object.assign({ fence: 'text' }, await doodle.doodleToScene(input, bytes, render.loadExcalidraw));
263
+ }
264
+ return Object.assign({ fence: 'mermaid' }, toScene(input));
265
+ }
266
+
217
267
  function parseJson(text) {
218
268
  try {
219
269
  return JSON.parse(text);
@@ -223,13 +273,13 @@ function parseJson(text) {
223
273
  }
224
274
 
225
275
  function sceneName(target) {
226
- return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw)$/i, '');
276
+ return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw|mmd|mermaid)$/i, '');
227
277
  }
228
278
 
229
279
  // `--png` takes an optional folder: the next argument is the folder unless it
230
280
  // looks like an input (-, *.json, *.excalidraw) or an option.
231
281
  function looksLikeInput(a) {
232
- return a === '-' || a.startsWith('--') || /\.(json|excalidraw)$/i.test(a);
282
+ return a === '-' || a.startsWith('--') || /\.(json|excalidraw|mmd|mermaid)$/i.test(a);
233
283
  }
234
284
 
235
285
  // Returns the exit code. `io.fetch`, `io.stdin` and `io.env` exist for tests.
@@ -263,10 +313,10 @@ export async function runExcalidraw(argv, io) {
263
313
  try {
264
314
  if (png && pngDir !== null && outDir !== null) throw new Error('use --png <dir> or --out <dir>, not both');
265
315
  if (png) return await runPng(targets, { dir: outDir !== null ? outDir : pngDir, folder: outDir !== null, review: review, noUpload: noUpload }, io);
266
- var built = buildSkeleton(parseJson(readInput(targets[0], io.stdin)));
316
+ var built = await buildInput(targets[0], io);
267
317
  var url = noUpload ? null : await upload(built.scene, io.fetch);
268
318
  if (url) stdout.write(url + '\n');
269
- stdout.write('```mermaid\n' + built.preview + '\n```\n');
319
+ stdout.write('```' + built.fence + '\n' + built.preview + '\n```\n');
270
320
  built.warnings.forEach(function (w) { stdout.write('warning: ' + w + '\n'); });
271
321
  return 0;
272
322
  } catch (e) {
@@ -284,10 +334,11 @@ async function runPng(targets, opts, io) {
284
334
 
285
335
  // Read and build every input before drawing anything, so a typo in the
286
336
  // last file costs no renders.
287
- var items = targets.map(function (t, k) {
288
- var built = toScene(parseJson(readInput(t, io.stdin)));
289
- return { name: names[k], scene: built.scene, preview: built.preview, warnings: built.warnings };
290
- });
337
+ var items = [];
338
+ for (var t = 0; t < targets.length; t++) {
339
+ var built = await buildInput(targets[t], io);
340
+ items.push({ name: names[t], scene: built.scene, preview: built.preview, warnings: built.warnings, fence: built.fence });
341
+ }
291
342
 
292
343
  var render = await import('../src/excalidraw-png.js');
293
344
  var dir;
@@ -320,7 +371,7 @@ async function runPng(targets, opts, io) {
320
371
  // which is how a working copy's push finds a new image.
321
372
  var target = opts.folder ? './' + basename(dir) + '/' + it.name + '.png' : 'attach:' + it.name;
322
373
  var lines = [];
323
- if (it.preview) lines.push('```mermaid\n' + it.preview + '\n```');
374
+ if (it.preview) lines.push('```' + it.fence + '\n' + it.preview + '\n```');
324
375
  lines.push('![' + it.name + '](' + target + ')');
325
376
  // The share link sits as a plain text line under the image, so it shows in
326
377
  // the doc: no API request sets an image's alt text, and a link hidden
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luutuankiet/clipboard2markdown",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Convert rich clipboard HTML from Jira, Confluence, Slack and Google apps into clean Markdown, and back.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/doodle.js ADDED
@@ -0,0 +1,225 @@
1
+ // Annotated screenshot ("doodle") spec -> Excalidraw scene for `c2m excalidraw`.
2
+ // The picture sits in the middle, handwritten notes in the margins around it,
3
+ // and a curved arrow runs from each note to the spot it explains. Notes never
4
+ // sit on the picture or on each other: each side is a column (left, right) or
5
+ // a row (top, bottom) stacked outward from the target, then a final pass
6
+ // pushes apart anything that still touches.
7
+ //
8
+ // Pure layout: the caller hands in the image bytes, so tests need no files.
9
+
10
+ export const DOODLE_DEFAULTS = { fontSize: 20, color: '#1971c2', maxWidth: 1400, wrap: 28 };
11
+ const GAP = 90; // picture edge -> note
12
+ const STACK = 24; // note -> note
13
+ const PAD = 8; // note edge -> arrow start
14
+ const SIDES = ['left', 'right', 'top', 'bottom'];
15
+
16
+ export function isDoodleSpec(input) {
17
+ return !!input && !Array.isArray(input) && typeof input === 'object' &&
18
+ typeof input.image === 'string' && Array.isArray(input.notes);
19
+ }
20
+
21
+ // PNG width and height from the IHDR chunk; JPEG from its first SOFn marker.
22
+ export function imageInfo(buf) {
23
+ if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) {
24
+ return { mimeType: 'image/png', width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
25
+ }
26
+ if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {
27
+ for (var i = 2; i + 9 < buf.length;) {
28
+ if (buf[i] !== 0xff) { i++; continue; }
29
+ var marker = buf[i + 1], len = buf.readUInt16BE(i + 2);
30
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
31
+ return { mimeType: 'image/jpeg', width: buf.readUInt16BE(i + 7), height: buf.readUInt16BE(i + 5) };
32
+ }
33
+ i += 2 + len;
34
+ }
35
+ }
36
+ throw new Error('the image is not a PNG or JPEG');
37
+ }
38
+
39
+ // Greedy word wrap; the writer's own "\n" always breaks.
40
+ export function wrapText(text, width) {
41
+ return String(text).split('\n').map(function (para) {
42
+ var out = [], line = '';
43
+ para.split(/\s+/).filter(Boolean).forEach(function (w) {
44
+ if (line && (line + ' ' + w).length > width) { out.push(line); line = w; } else line = line ? line + ' ' + w : w;
45
+ });
46
+ out.push(line);
47
+ return out.join('\n');
48
+ }).join('\n');
49
+ }
50
+
51
+ // 0.55 em per character, the width Excalidraw's own text measure gives here
52
+ // (see the canvas stand-in in src/excalidraw-png.js); 1.25 em per line.
53
+ function textSize(text, fontSize) {
54
+ var lines = text.split('\n');
55
+ var longest = lines.reduce(function (m, l) { return Math.max(m, l.length); }, 0);
56
+ return { w: Math.ceil(longest * fontSize * 0.55), h: Math.ceil(lines.length * fontSize * 1.25) };
57
+ }
58
+
59
+ function parseTarget(t, k, info) {
60
+ if (!Array.isArray(t) || (t.length !== 2 && t.length !== 4) || t.some(function (v) { return typeof v !== 'number' || !isFinite(v); })) {
61
+ throw new Error('note ' + (k + 1) + ': "target" must be [x, y] (a point) or [x, y, width, height] (a box), in image pixels');
62
+ }
63
+ var box = { x: t[0], y: t[1], w: t[2] || 0, h: t[3] || 0, isBox: t.length === 4 };
64
+ if (box.x < 0 || box.y < 0 || box.x + box.w > info.width || box.y + box.h > info.height) {
65
+ throw new Error('note ' + (k + 1) + ': target ' + JSON.stringify(t) + ' lies outside the ' + info.width + 'x' + info.height + ' image');
66
+ }
67
+ return box;
68
+ }
69
+
70
+ // The side whose image edge is nearest the target's centre.
71
+ function nearestSide(c, W, H) {
72
+ var d = { left: c.x, right: W - c.x, top: c.y, bottom: H - c.y };
73
+ return SIDES.reduce(function (best, s) { return d[s] < d[best] ? s : best; }, 'left');
74
+ }
75
+
76
+ function overlaps(a, b, pad) {
77
+ return a.x < b.x + b.w + pad && b.x < a.x + a.w + pad && a.y < b.y + b.h + pad && b.y < a.y + a.h + pad;
78
+ }
79
+
80
+ // Stack one side's notes along its axis, each as close to its target as the
81
+ // notes before it allow.
82
+ function stack(notes, axis) {
83
+ var pos = axis === 'y' ? 'y' : 'x', size = axis === 'y' ? 'h' : 'w';
84
+ notes.sort(function (a, b) { return a[pos] - b[pos]; });
85
+ for (var i = 1; i < notes.length; i++) {
86
+ var min = notes[i - 1][pos] + notes[i - 1][size] + STACK;
87
+ if (notes[i][pos] < min) notes[i][pos] = min;
88
+ }
89
+ }
90
+
91
+ // Returns { notes: [{text, x, y, w, h, side, target, start, end}], W, H }:
92
+ // the layout in scene pixels with the picture at (0, 0) to (W, H).
93
+ export function layoutDoodle(spec, info) {
94
+ var opt = Object.assign({}, DOODLE_DEFAULTS, spec);
95
+ var natural = info.width;
96
+ var W = spec.width ? Number(spec.width) : Math.min(natural, opt.maxWidth);
97
+ if (!(W > 0)) throw new Error('"width" must be a positive number of pixels');
98
+ var s = W / natural, H = Math.round(info.height * s);
99
+ if (!spec.notes.length) throw new Error('"notes" is empty: give at least one {"text", "target"}');
100
+
101
+ var notes = spec.notes.map(function (n, k) {
102
+ if (!n || typeof n.text !== 'string' || !n.text.trim()) throw new Error('note ' + (k + 1) + ': needs "text"');
103
+ var t = parseTarget(n.target, k, info);
104
+ var target = { x: t.x * s, y: t.y * s, w: t.w * s, h: t.h * s, isBox: t.isBox };
105
+ var c = { x: target.x + target.w / 2, y: target.y + target.h / 2 };
106
+ var side = n.side || nearestSide(c, W, H);
107
+ if (SIDES.indexOf(side) < 0) throw new Error('note ' + (k + 1) + ': "side" must be one of ' + SIDES.join(', '));
108
+ var fontSize = n.fontSize || opt.fontSize;
109
+ var text = wrapText(n.text.trim(), opt.wrap);
110
+ var sz = textSize(text, fontSize);
111
+ var note = { k: k, text: text, textAlign: side === 'left' ? 'right' : side === 'right' ? 'left' : 'center', fontSize: fontSize, color: n.color || opt.color, side: side, target: target, c: c, w: sz.w, h: sz.h };
112
+ if (side === 'left') { note.x = -GAP - sz.w; note.y = c.y - sz.h / 2; }
113
+ if (side === 'right') { note.x = W + GAP; note.y = c.y - sz.h / 2; }
114
+ if (side === 'top') { note.y = -GAP - sz.h; note.x = Math.max(0, Math.min(W - sz.w, c.x - sz.w / 2)); }
115
+ if (side === 'bottom') { note.y = H + GAP; note.x = Math.max(0, Math.min(W - sz.w, c.x - sz.w / 2)); }
116
+ return note;
117
+ });
118
+
119
+ stack(notes.filter(function (n) { return n.side === 'left'; }), 'y');
120
+ stack(notes.filter(function (n) { return n.side === 'right'; }), 'y');
121
+ stack(notes.filter(function (n) { return n.side === 'top'; }), 'x');
122
+ stack(notes.filter(function (n) { return n.side === 'bottom'; }), 'x');
123
+
124
+ // Corners: a long column can reach a row's notes. Push the later note
125
+ // outward (columns away from the picture sideways, rows up or down) until
126
+ // nothing touches; outward moves never bring a note onto the picture.
127
+ for (var pass = 0; pass < 50; pass++) {
128
+ var moved = false;
129
+ for (var i = 0; i < notes.length; i++) {
130
+ for (var j = i + 1; j < notes.length; j++) {
131
+ var a = notes[i], b = notes[j];
132
+ if (!overlaps(a, b, STACK / 2)) continue;
133
+ if (b.side === 'left') b.x = a.x - STACK - b.w;
134
+ else if (b.side === 'right') b.x = a.x + a.w + STACK;
135
+ else if (b.side === 'top') b.y = a.y - STACK - b.h;
136
+ else b.y = a.y + a.h + STACK;
137
+ moved = true;
138
+ }
139
+ }
140
+ if (!moved) break;
141
+ }
142
+
143
+ notes.forEach(function (n) {
144
+ var mid = { x: n.x + n.w / 2, y: n.y + n.h / 2 };
145
+ if (n.side === 'left') n.start = { x: n.x + n.w + PAD, y: mid.y };
146
+ if (n.side === 'right') n.start = { x: n.x - PAD, y: mid.y };
147
+ if (n.side === 'top') n.start = { x: mid.x, y: n.y + n.h + PAD };
148
+ if (n.side === 'bottom') n.start = { x: mid.x, y: n.y - PAD };
149
+ n.end = arrowEnd(n.target, n.start);
150
+ });
151
+ notes.sort(function (a, b) { return a.k - b.k; });
152
+ return { notes: notes, W: W, H: H, scale: s };
153
+ }
154
+
155
+ // A point target: the point. A box: the point on its outline nearest the
156
+ // note, pulled 4 px off the line so the arrowhead does not hide the box.
157
+ function arrowEnd(t, from) {
158
+ if (!t.isBox) return { x: t.x, y: t.y };
159
+ var x = Math.max(t.x, Math.min(t.x + t.w, from.x));
160
+ var y = Math.max(t.y, Math.min(t.y + t.h, from.y));
161
+ if (x > t.x && x < t.x + t.w && y > t.y && y < t.y + t.h) return { x: x, y: y };
162
+ var dx = from.x - x, dy = from.y - y, len = Math.hypot(dx, dy) || 1;
163
+ return { x: x + dx / len * 4, y: y + dy / len * 4 };
164
+ }
165
+
166
+ // Excalidraw element skeletons (for convertToExcalidrawElements) plus files.
167
+ export function doodleSkeleton(spec, bytes, now) {
168
+ var info = imageInfo(bytes);
169
+ var lay = layoutDoodle(spec, info);
170
+ var fileId = 'doodle-image';
171
+ var els = [
172
+ { type: 'image', id: 'image', fileId: fileId, x: 0, y: 0, width: lay.W, height: lay.H, status: 'saved' },
173
+ { type: 'rectangle', id: 'image-frame', x: 0, y: 0, width: lay.W, height: lay.H, strokeColor: '#868e96', strokeWidth: 1, roughness: 0, backgroundColor: 'transparent' },
174
+ ];
175
+ lay.notes.forEach(function (n, k) {
176
+ var id = 'note-' + (k + 1);
177
+ if (n.target.isBox) {
178
+ els.push({ type: 'rectangle', id: id + '-box', x: n.target.x - 4, y: n.target.y - 4, width: n.target.w + 8, height: n.target.h + 8,
179
+ strokeColor: n.color, strokeWidth: 2, backgroundColor: 'transparent', roundness: { type: 3 } });
180
+ }
181
+ els.push({ type: 'text', id: id, x: n.x, y: n.y, text: n.text, fontSize: n.fontSize, fontFamily: 5, strokeColor: n.color,
182
+ textAlign: n.textAlign });
183
+ // Curve: one bend point off the straight line, alternating sides so
184
+ // neighbouring arrows do not mirror each other.
185
+ var dx = n.end.x - n.start.x, dy = n.end.y - n.start.y, len = Math.hypot(dx, dy) || 1;
186
+ var bend = Math.min(40, len * 0.18) * (k % 2 ? -1 : 1);
187
+ var mid = [dx / 2 - dy / len * bend, dy / 2 + dx / len * bend];
188
+ els.push({ type: 'arrow', id: id + '-arrow', x: n.start.x, y: n.start.y, points: [[0, 0], mid, [dx, dy]],
189
+ strokeColor: n.color, strokeWidth: 2, roundness: { type: 2 }, endArrowhead: 'arrow' });
190
+ });
191
+ var b64 = Buffer.from(bytes).toString('base64');
192
+ var files = {};
193
+ files[fileId] = { id: fileId, mimeType: info.mimeType, dataURL: 'data:' + info.mimeType + ';base64,' + b64, created: now || 0 };
194
+ return { elements: els, files: files, layout: lay };
195
+ }
196
+
197
+ // The preview for a doodle: one line per note, so an agent can check which
198
+ // note points where without opening the picture.
199
+ export function doodlePreview(spec, lay) {
200
+ return ['%% doodle: ' + spec.image + ' (' + Math.round(lay.W) + 'x' + Math.round(lay.H) + ' px)'].concat(lay.notes.map(function (n, k) {
201
+ var t = n.target;
202
+ return '%% note ' + (k + 1) + ' (' + n.side + ') -> ' + (t.isBox ? 'box' : 'point') + ': ' + n.text.replace(/\n/g, ' ');
203
+ })).join('\n');
204
+ }
205
+
206
+ export async function doodleToScene(spec, bytes, loadExcalidraw) {
207
+ var built = doodleSkeleton(spec, bytes, Date.now());
208
+ var m = await loadExcalidraw();
209
+ var elements = m.convertToExcalidrawElements(built.elements, { regenerateIds: false });
210
+ // The converter shifts a right- or centre-aligned text left by its width,
211
+ // as if x were its anchor. Put each note back on the box the layout chose.
212
+ var placed = {};
213
+ built.layout.notes.forEach(function (n, k) { placed['note-' + (k + 1)] = n; });
214
+ elements.forEach(function (e) {
215
+ var n = e.type === 'text' && placed[e.id];
216
+ if (!n) return;
217
+ e.x = n.textAlign === 'right' ? n.x + n.w - e.width : n.textAlign === 'center' ? n.x + (n.w - e.width) / 2 : n.x;
218
+ e.y = n.y;
219
+ });
220
+ return {
221
+ scene: { type: 'excalidraw', version: 2, source: 'c2m', elements: elements, appState: { viewBackgroundColor: '#ffffff' }, files: built.files },
222
+ preview: doodlePreview(spec, built.layout),
223
+ warnings: ['the share link opens without the picture: excalidraw.com stores images apart from the link (see c2m excalidraw --help, DOODLE); the PNG is complete'],
224
+ };
225
+ }
@@ -52,7 +52,7 @@ export function pickScale(width, height) {
52
52
 
53
53
  // ------------------------------------------------------------ excalidraw ---
54
54
 
55
- var exportToSvgPromise;
55
+ var bundlePromise;
56
56
 
57
57
  function installDom() {
58
58
  var bundle = join(VENDOR, 'excalidraw.bundle.mjs');
@@ -87,6 +87,12 @@ function installDom() {
87
87
  });
88
88
  };
89
89
 
90
+ // jsdom has no layout either. Mermaid (used by the Mermaid input) sizes
91
+ // every label with getBBox / getBoundingClientRect before dagre lays the
92
+ // graph out; estimate from the text at Excalidraw's average glyph width,
93
+ // which is what the resulting labels are measured with anyway.
94
+ installLayoutEstimates(win);
95
+
90
96
  // No CSS Font Loading API in jsdom either.
91
97
  function FontFace(family, source, desc) { Object.assign(this, { family: family, source: source, status: 'loaded' }, desc); }
92
98
  FontFace.prototype.load = function () { return Promise.resolve(this); };
@@ -121,12 +127,18 @@ function installDom() {
121
127
  };
122
128
  win.EXCALIDRAW_ASSET_PATH = ASSET_ORIGIN;
123
129
  return import(pathToFileURL(bundle).href);
124
- }).then(function (m) { return m.exportToSvg; });
130
+ });
131
+ }
132
+
133
+ // The vendored bundle: exportToSvg, convertToExcalidrawElements and
134
+ // parseMermaidToExcalidraw, loaded once under the jsdom globals above.
135
+ export function loadExcalidraw() {
136
+ if (!bundlePromise) bundlePromise = installDom();
137
+ return bundlePromise;
125
138
  }
126
139
 
127
140
  export async function sceneToSvg(scene) {
128
- if (!exportToSvgPromise) exportToSvgPromise = installDom();
129
- var exportToSvg = await exportToSvgPromise;
141
+ var exportToSvg = (await loadExcalidraw()).exportToSvg;
130
142
  var elements = (scene.elements || []).filter(function (e) { return !e.isDeleted; });
131
143
  if (!elements.length) throw new Error('the scene has no elements to draw');
132
144
  // Excalidraw reports the missing CJK font on console.error; the caller gets
@@ -142,12 +154,22 @@ export async function sceneToSvg(scene) {
142
154
  appState: Object.assign({}, scene.appState, { exportBackground: true, viewBackgroundColor: '#ffffff' }),
143
155
  files: scene.files || {},
144
156
  });
145
- return svg.outerHTML;
157
+ return fixImageSymbols(svg.outerHTML);
146
158
  } finally {
147
159
  console.error = consoleError;
148
160
  }
149
161
  }
150
162
 
163
+ // Excalidraw draws each picture as <symbol><image width="100%" height="100%">
164
+ // placed by <use width height>. resvg sizes that 100% against the whole
165
+ // drawing instead of the <use>, so the picture comes out at its own pixel
166
+ // size, cropped. A viewBox on the symbol makes it scale to the <use> box.
167
+ export function fixImageSymbols(svg) {
168
+ return svg.replace(/<symbol id="(image-[^"]*)">(\s*<image\b[^>]*?)width="100%" height="100%"/g, function (_, id, img) {
169
+ return '<symbol id="' + id + '" viewBox="0 0 100 100" preserveAspectRatio="none">' + img + 'width="100" height="100"';
170
+ });
171
+ }
172
+
151
173
  // CJK text needs Xiaolai, which the package leaves out (13 MB); it renders blank.
152
174
  export function hasCjkText(scene) {
153
175
  return (scene.elements || []).some(function (e) {
@@ -155,6 +177,71 @@ export function hasCjkText(scene) {
155
177
  });
156
178
  }
157
179
 
180
+ // Text box estimate shared by the getBBox stand-in: 0.7 em per character,
181
+ // 1.25 em per line. Generous on purpose: Excalifont is wide, and a shape sized
182
+ // too tight makes Excalidraw wrap its label mid-word ("Retr / y").
183
+ export function estimateTextBox(text, fontSize) {
184
+ var lines = String(text || '').split(/\n|<br\s*\/?>/i);
185
+ var longest = lines.reduce(function (m, l) { return Math.max(m, l.length); }, 0);
186
+ return { width: longest * fontSize * 0.7, height: lines.length * fontSize * 1.25 };
187
+ }
188
+
189
+ function fontSizeOf(win, el) {
190
+ for (var e = el; e && e.getAttribute; e = e.parentNode) {
191
+ var fs = e.style && e.style.fontSize ? e.style.fontSize : e.getAttribute('font-size');
192
+ if (fs) return parseFloat(fs) || 16;
193
+ }
194
+ return 16;
195
+ }
196
+
197
+ function installLayoutEstimates(win) {
198
+ var num = function (el, k) { return parseFloat(el.getAttribute(k)) || 0; };
199
+ function box(el) {
200
+ var tag = (el.tagName || '').toLowerCase().replace(/^svg:/, '');
201
+ if (tag === 'rect' || tag === 'foreignobject' || tag === 'image') {
202
+ return { x: num(el, 'x'), y: num(el, 'y'), width: num(el, 'width'), height: num(el, 'height') };
203
+ }
204
+ if (tag === 'circle') { var r = num(el, 'r'); return { x: num(el, 'cx') - r, y: num(el, 'cy') - r, width: 2 * r, height: 2 * r }; }
205
+ if (tag === 'polygon' || tag === 'polyline' || tag === 'path' || tag === 'line') {
206
+ // Bounding box of the listed coordinates: exact for polygons and for
207
+ // the absolute paths mermaid draws, close enough for the rest.
208
+ var src = tag === 'path' ? el.getAttribute('d') : tag === 'line'
209
+ ? [num(el, 'x1'), num(el, 'y1'), num(el, 'x2'), num(el, 'y2')].join(' ') : el.getAttribute('points');
210
+ var n = String(src || '').match(/-?\d*\.?\d+(?:e-?\d+)?/gi) || [];
211
+ var xs = [], ys = [];
212
+ for (var i = 0; i + 1 < n.length; i += 2) { xs.push(+n[i]); ys.push(+n[i + 1]); }
213
+ if (!xs.length) return { x: 0, y: 0, width: 0, height: 0 };
214
+ var px = Math.min.apply(null, xs), py = Math.min.apply(null, ys);
215
+ return { x: px, y: py, width: Math.max.apply(null, xs) - px, height: Math.max.apply(null, ys) - py };
216
+ }
217
+ if (tag === 'text' || tag === 'tspan') {
218
+ var lines = el.querySelectorAll('tspan.row, tspan[dy]');
219
+ var text = lines.length > 1 ? Array.from(lines).map(function (t) { return t.textContent; }).join('\n') : el.textContent;
220
+ var t = estimateTextBox(text, fontSizeOf(win, el));
221
+ return { x: 0, y: -t.height / 2, width: t.width, height: t.height };
222
+ }
223
+ var kids = Array.from(el.children || []).map(box).filter(function (b) { return b.width || b.height; });
224
+ if (!kids.length) {
225
+ if (el.textContent && el.textContent.trim()) { var tb = estimateTextBox(el.textContent.trim(), fontSizeOf(win, el)); return { x: 0, y: 0, width: tb.width, height: tb.height }; }
226
+ return { x: 0, y: 0, width: 0, height: 0 };
227
+ }
228
+ var x0 = Math.min.apply(null, kids.map(function (b) { return b.x; }));
229
+ var y0 = Math.min.apply(null, kids.map(function (b) { return b.y; }));
230
+ var x1 = Math.max.apply(null, kids.map(function (b) { return b.x + b.width; }));
231
+ var y1 = Math.max.apply(null, kids.map(function (b) { return b.y + b.height; }));
232
+ return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };
233
+ }
234
+ var rect = function (b) { return Object.assign({ top: b.y, left: b.x, right: b.x + b.width, bottom: b.y + b.height }, b); };
235
+ win.SVGElement.prototype.getBBox = function () { return box(this); };
236
+ win.SVGElement.prototype.getComputedTextLength = function () { return box(this).width; };
237
+ win.Element.prototype.getBoundingClientRect = function () {
238
+ var text = (this.textContent || '').trim();
239
+ if (!text) return rect({ x: 0, y: 0, width: 0, height: 0 });
240
+ var t = estimateTextBox(text, fontSizeOf(win, this));
241
+ return rect({ x: 0, y: 0, width: t.width, height: t.height });
242
+ };
243
+ }
244
+
158
245
  // ------------------------------------------------------------------ resvg ---
159
246
 
160
247
  // resvg ignores @font-face, and resvg-js 2.6.2 silently ignores fontBuffers, so
@@ -0,0 +1,79 @@
1
+ // Mermaid source (.mmd) -> Excalidraw scene for `c2m excalidraw`.
2
+ // @excalidraw/mermaid-to-excalidraw needs a DOM to run mermaid's layout, so it
3
+ // runs inside the same jsdom the PNG renderer uses (src/excalidraw-png.js),
4
+ // with estimated text sizes standing in for a browser's layout.
5
+
6
+ import { loadExcalidraw } from './excalidraw-png.js';
7
+
8
+ const SHAPES = new Set(['rectangle', 'ellipse', 'diamond']);
9
+ const INK = '#1e1e1e';
10
+
11
+ // The house style's plan pass: every node white with a dark stroke, dark text
12
+ // and arrows. Mermaid's own fills (grey actors, yellow notes, lilac subgraphs)
13
+ // would otherwise read as emphasis. Lifelines and other plain lines keep their
14
+ // light grey so they stay in the background. Dashes are kept: they carry
15
+ // meaning (replies, notes, dotted links).
16
+ export function applyHouseStyle(elements) {
17
+ elements.forEach(function (el) {
18
+ if (SHAPES.has(el.type)) {
19
+ el.backgroundColor = '#ffffff';
20
+ el.fillStyle = 'solid';
21
+ el.strokeColor = INK;
22
+ } else if (el.type === 'text' || el.type === 'arrow') {
23
+ el.strokeColor = INK;
24
+ }
25
+ });
26
+ return elements;
27
+ }
28
+
29
+ // A label Excalidraw wrapped mid-word because its shape came out narrow
30
+ // (short labels in diamonds: "OK?" -> "OK / ?") goes back on one line, and
31
+ // the shape grows around its centre to fit it.
32
+ export function unwrapLabels(elements) {
33
+ var byId = {};
34
+ elements.forEach(function (e) { byId[e.id] = e; });
35
+ elements.forEach(function (t) {
36
+ var box = t.type === 'text' && t.containerId && byId[t.containerId];
37
+ if (!box || !t.originalText || t.text === t.originalText || /\n/.test(t.originalText)) return;
38
+ var w = t.originalText.length * t.fontSize * 0.55;
39
+ var need = box.type === 'diamond' ? 2 * w + 40 : box.type === 'ellipse' ? 1.42 * w + 30 : w + 40;
40
+ if (box.width < need) { box.x -= (need - box.width) / 2; box.width = need; }
41
+ if (box.type === 'diamond' && box.height < need / 2) { box.y -= (need / 2 - box.height) / 2; box.height = need / 2; }
42
+ t.text = t.originalText;
43
+ t.width = w;
44
+ t.height = t.fontSize * t.lineHeight;
45
+ t.x = box.x + (box.width - w) / 2;
46
+ t.y = box.y + (box.height - t.height) / 2;
47
+ });
48
+ return elements;
49
+ }
50
+
51
+ // Returns { scene, preview, warnings }, the same shape as buildSkeleton, so
52
+ // the caller treats a .mmd input like any other. The preview is the source.
53
+ export async function mermaidToScene(source) {
54
+ var text = String(source || '').trim();
55
+ if (!text) throw new Error('the Mermaid file is empty');
56
+ var m = await loadExcalidraw();
57
+ var parsed;
58
+ try {
59
+ parsed = await m.parseMermaidToExcalidraw(text, { themeVariables: { fontSize: '20px' } });
60
+ } catch (e) {
61
+ var msg = e && e.message ? e.message : String(e);
62
+ throw new Error('Mermaid did not parse: ' + msg.split('\n').slice(0, 4).join(' '));
63
+ }
64
+ var warnings = [];
65
+ var elements = m.convertToExcalidrawElements(parsed.elements, { regenerateIds: false });
66
+ // Diagram types the converter has no shapes for (class, state, gantt, pie ...)
67
+ // come back as one embedded picture of mermaid's own SVG, drawn with our
68
+ // estimated text sizes.
69
+ if (elements.some(function (e) { return e.type === 'image'; })) {
70
+ warnings.push('this Mermaid diagram type has no Excalidraw shapes; it is drawn as one picture, not editable boxes. Flowchart and sequence diagrams convert to shapes');
71
+ }
72
+ unwrapLabels(elements);
73
+ applyHouseStyle(elements);
74
+ return {
75
+ scene: { type: 'excalidraw', version: 2, source: 'c2m', elements: elements, appState: { viewBackgroundColor: '#ffffff' }, files: parsed.files || {} },
76
+ preview: text,
77
+ warnings: warnings,
78
+ };
79
+ }