@luutuankiet/clipboard2markdown 0.6.0 → 0.8.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.
@@ -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
package/src/lint.js ADDED
@@ -0,0 +1,239 @@
1
+ // Scene-level lint for `c2m excalidraw`: checks a finished Excalidraw scene,
2
+ // whatever input it came from (Mermaid, JSON elements, a whole scene), for the
3
+ // faults that make a diagram wrong in a document. Pure, deterministic, no
4
+ // network. Each finding is { cls, level, message }; `error` findings are what
5
+ // `--strict` refuses to render.
6
+ //
7
+ // a child sticks out of its frame / subgraph, or a node straddles a frame
8
+ // b node boxes overlap (partial overlap; full nesting is fine)
9
+ // c a text label holds a literal <br> or backslash-n
10
+ // d an arrow end is unbound, bound to a missing element, or far from its shape
11
+ // e label text is wider (or taller) than the box that holds it
12
+ // f font size, once the whole scene is scaled to page width, is too small
13
+ // g colour budget (warn): more than 3 filled shapes or 2 fill colours
14
+
15
+ const SHAPES = new Set(['rectangle', 'diamond', 'ellipse']);
16
+ const DRAWN = new Set(['rectangle', 'diamond', 'ellipse', 'text', 'arrow', 'line']);
17
+ const CHAR_W = 0.6; // keep equal to CHAR_W in mermaid-input.js
18
+ const PAD = 10; // padding inside a container
19
+ const TOL = 1; // px slack for "inside"
20
+ const ARROW_FAR = 20; // px: a bound end farther than this from its shape is wrong
21
+ const NEAR = 12; // px: an unbound end this close to a shape only touches
22
+ const MIN_AREA = 4; // px^2 overlap below which a touch is ignored
23
+ export const PAGE_PT = 468;
24
+ export const ALL_CLASSES = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
25
+
26
+ function bbox(e) { return [e.x, e.y, e.x + e.width, e.y + e.height]; }
27
+
28
+ function poly(e) {
29
+ var b = bbox(e), cx = (b[0] + b[2]) / 2, cy = (b[1] + b[3]) / 2;
30
+ if (e.type === 'diamond') return [[cx, b[1]], [b[2], cy], [cx, b[3]], [b[0], cy]];
31
+ if (e.type === 'ellipse') {
32
+ var rx = (b[2] - b[0]) / 2, ry = (b[3] - b[1]) / 2, pts = [];
33
+ for (var a = 0; a < 16; a++) pts.push([cx + rx * Math.cos(a * Math.PI / 8), cy + ry * Math.sin(a * Math.PI / 8)]);
34
+ return pts;
35
+ }
36
+ return [[b[0], b[1]], [b[2], b[1]], [b[2], b[3]], [b[0], b[3]]];
37
+ }
38
+
39
+ // Separating-axis test on convex polygons; touching is not overlap.
40
+ function satOverlap(p, q) {
41
+ var sets = [p, q];
42
+ for (var s = 0; s < 2; s++) {
43
+ var P = sets[s];
44
+ for (var i = 0; i < P.length; i++) {
45
+ var A = P[i], B = P[(i + 1) % P.length];
46
+ var nx = A[1] - B[1], ny = B[0] - A[0];
47
+ var pa = p.map(function (v) { return nx * v[0] + ny * v[1]; });
48
+ var qa = q.map(function (v) { return nx * v[0] + ny * v[1]; });
49
+ if (Math.max.apply(null, pa) <= Math.min.apply(null, qa) + 1e-6 || Math.max.apply(null, qa) <= Math.min.apply(null, pa) + 1e-6) return false;
50
+ }
51
+ }
52
+ return true;
53
+ }
54
+
55
+ function interArea(a, b) {
56
+ var w = Math.min(a[2], b[2]) - Math.max(a[0], b[0]);
57
+ var h = Math.min(a[3], b[3]) - Math.max(a[1], b[1]);
58
+ return Math.max(0, w) * Math.max(0, h);
59
+ }
60
+
61
+ function contains(a, b, tol) {
62
+ tol = tol === undefined ? TOL : tol;
63
+ return a[0] - tol <= b[0] && a[1] - tol <= b[1] && a[2] + tol >= b[2] && a[3] + tol >= b[3];
64
+ }
65
+
66
+ function segDist(px, py, ax, ay, bx, by) {
67
+ var dx = bx - ax, dy = by - ay;
68
+ var t = dx === 0 && dy === 0 ? 0 : Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)));
69
+ return Math.hypot(px - (ax + t * dx), py - (ay + t * dy));
70
+ }
71
+
72
+ function distToShape(pt, e) {
73
+ var p = poly(e), best = Infinity;
74
+ for (var i = 0; i < p.length; i++) {
75
+ var a = p[i], b = p[(i + 1) % p.length];
76
+ best = Math.min(best, segDist(pt[0], pt[1], a[0], a[1], b[0], b[1]));
77
+ }
78
+ return best;
79
+ }
80
+
81
+ // `scene` is a scene object ({elements}) or a bare element array.
82
+ // opts: { pagePt: 468, classes: ['a'..'f'] }. Returns { findings, meta }.
83
+ export function lintScene(scene, opts) {
84
+ opts = opts || {};
85
+ var pagePt = opts.pagePt || PAGE_PT;
86
+ var want = new Set(opts.classes || ALL_CLASSES);
87
+ var els = (Array.isArray(scene) ? scene : (scene && scene.elements) || []).filter(function (e) { return e && !e.isDeleted; });
88
+ var findings = [];
89
+ function add(cls, level, message) { if (want.has(cls)) findings.push({ cls: cls, level: level, message: message }); }
90
+
91
+ var byId = {};
92
+ els.forEach(function (e) { if (!(e.id in byId)) byId[e.id] = e; });
93
+ var shapes = els.filter(function (e) { return SHAPES.has(e.type); });
94
+ var texts = els.filter(function (e) { return e.type === 'text'; });
95
+ var labelOf = {};
96
+ texts.forEach(function (t) { if (t.containerId) labelOf[t.containerId] = t; });
97
+
98
+ function name(e) {
99
+ var t = labelOf[e.id];
100
+ var txt = t ? t.text : e.type === 'text' ? e.text : '';
101
+ return '"' + (String(txt || '').replace(/\n/g, ' ').slice(0, 28) || e.id) + '"';
102
+ }
103
+
104
+ // Frames: shapes named by a "subgraph_group_<id>" group id (Mermaid
105
+ // subgraphs), or any shape that fully contains a smaller one.
106
+ var frames = new Map();
107
+ shapes.forEach(function (e) {
108
+ var gid = 'subgraph_group_' + e.id;
109
+ if (els.some(function (m) { return (m.groupIds || []).indexOf(gid) >= 0; })) frames.set(e.id, gid);
110
+ });
111
+ shapes.forEach(function (e) {
112
+ if (frames.has(e.id)) return;
113
+ var eb = bbox(e);
114
+ if (shapes.some(function (o) { return o !== e && contains(eb, bbox(o)) && o.width * o.height < e.width * e.height; })) frames.set(e.id, null);
115
+ });
116
+
117
+ // a: children outside their frame
118
+ var stuck = new Set();
119
+ frames.forEach(function (gid, fid) {
120
+ var fr = byId[fid], fb = bbox(fr);
121
+ shapes.forEach(function (m) {
122
+ if (m === fr) return;
123
+ var member = (gid && (m.groupIds || []).indexOf(gid) >= 0) || contains(fb, bbox(m));
124
+ if (!member) return;
125
+ var mb = bbox(m);
126
+ if (contains(fb, mb)) return;
127
+ var over = Math.max(fb[0] - mb[0], fb[1] - mb[1], mb[2] - fb[2], mb[3] - fb[3]);
128
+ add('a', 'error', name(m) + ' sticks out of frame ' + name(fr) + ' by ' + Math.round(over) + ' px; widen the frame or move the node in');
129
+ stuck.add(m.id + '|' + fr.id);
130
+ });
131
+ });
132
+
133
+ // a / b: partial overlaps
134
+ for (var i = 0; i < shapes.length; i++) {
135
+ for (var j = i + 1; j < shapes.length; j++) {
136
+ var A = shapes[i], B = shapes[j], ba = bbox(A), bb = bbox(B);
137
+ if (interArea(ba, bb) < MIN_AREA || contains(ba, bb) || contains(bb, ba)) continue;
138
+ if (!satOverlap(poly(A), poly(B))) continue;
139
+ var area = Math.round(interArea(ba, bb));
140
+ var fa = frames.has(A.id), fb2 = frames.has(B.id);
141
+ if (fa && fb2) add('b', 'error', 'frames ' + name(A) + ' and ' + name(B) + ' overlap (~' + area + ' px^2); move them apart');
142
+ else if (fa || fb2) {
143
+ var fr = fa ? A : B, nd = fa ? B : A;
144
+ if (stuck.has(nd.id + '|' + fr.id)) continue; // already reported as sticking out
145
+ add('a', 'error', 'node ' + name(nd) + ' straddles frame ' + name(fr) + ' (~' + area + ' px^2); move it fully in or out');
146
+ } else add('b', 'error', 'nodes ' + name(A) + ' and ' + name(B) + ' overlap (~' + area + ' px^2); move them apart');
147
+ }
148
+ }
149
+
150
+ // c: literal line-break text
151
+ texts.forEach(function (t) {
152
+ var hit = ['text', 'originalText'].some(function (k) {
153
+ var v = t[k] || '';
154
+ return /<br\s*\/?>/i.test(v) || v.indexOf('\\n') >= 0;
155
+ });
156
+ if (hit) add('c', 'error', 'text ' + String(t.id).slice(0, 10) + ' shows a literal line-break (' + JSON.stringify(String(t.text || '').slice(0, 40)) + '); use a real newline');
157
+ });
158
+
159
+ // d: arrows
160
+ els.forEach(function (a) {
161
+ if (a.type !== 'arrow') return;
162
+ var pts = a.points && a.points.length ? a.points : [[0, 0], [a.width || 0, a.height || 0]];
163
+ var ends = { start: [a.x + pts[0][0], a.y + pts[0][1]], end: [a.x + pts[pts.length - 1][0], a.y + pts[pts.length - 1][1]] };
164
+ ['start', 'end'].forEach(function (which) {
165
+ var pt = ends[which], b = a[which + 'Binding'], id = String(a.id).slice(0, 14);
166
+ if (b) {
167
+ var tgt = byId[b.elementId];
168
+ if (!tgt) add('d', 'error', 'arrow ' + id + ' ' + which + ' is bound to a missing element');
169
+ else if (SHAPES.has(tgt.type)) {
170
+ var d = distToShape(pt, tgt);
171
+ if (d > ARROW_FAR) add('d', 'error', 'arrow ' + id + ' ' + which + ' lands ' + Math.round(d) + ' px from ' + name(tgt) + '; it floats off the outline');
172
+ }
173
+ } else {
174
+ var best = null, bd = Infinity;
175
+ shapes.forEach(function (s) { var dd = distToShape(pt, s); if (dd < bd) { bd = dd; best = s; } });
176
+ if (bd > NEAR) add('d', 'error', 'arrow ' + id + ' ' + which + ' is unbound and ends in empty space' + (best ? ' (' + Math.round(bd) + ' px from the nearest shape)' : ''));
177
+ else add('d', 'warn', 'arrow ' + id + ' ' + which + ' is unbound (touches ' + name(best) + '); bind it so it follows the shape');
178
+ }
179
+ });
180
+ });
181
+
182
+ // e: text wider than its box
183
+ texts.forEach(function (t) {
184
+ var c = byId[t.containerId];
185
+ if (!c || !SHAPES.has(c.type)) return;
186
+ var fs = t.fontSize || 20;
187
+ var lines = String(t.text || '').split('\n');
188
+ var w = Math.max.apply(null, lines.map(function (l) { return l.length; })) * CHAR_W * fs;
189
+ var h = lines.length * 1.25 * fs;
190
+ var k = c.type === 'ellipse' ? Math.SQRT2 : c.type === 'diamond' ? 2 : 1;
191
+ var aw = c.width / k - 2 * PAD, ah = c.height / k - 2 * PAD;
192
+ var use = t.width ? Math.max(w, t.width) : w;
193
+ if (use > aw + 1 || h > ah + 1) {
194
+ add('e', 'error', 'label ' + JSON.stringify(String(t.text || '').slice(0, 28)) + ' needs about ' + Math.round(use) + 'x' + Math.round(h) +
195
+ ' but the ' + c.type + ' has room for ' + Math.round(aw) + 'x' + Math.round(ah) + '; enlarge the shape');
196
+ }
197
+ });
198
+
199
+ // f: font size at page width
200
+ var boxes = els.filter(function (e) { return DRAWN.has(e.type); }).map(bbox);
201
+ var sw = 0, sh = 0, minPt = null;
202
+ if (boxes.length) {
203
+ sw = Math.max.apply(null, boxes.map(function (b) { return b[2]; })) - Math.min.apply(null, boxes.map(function (b) { return b[0]; }));
204
+ sh = Math.max.apply(null, boxes.map(function (b) { return b[3]; })) - Math.min.apply(null, boxes.map(function (b) { return b[1]; }));
205
+ var scale = sw ? pagePt / sw : 1;
206
+ if (texts.length) {
207
+ var fs0 = Math.min.apply(null, texts.map(function (t) { return t.fontSize || 20; }));
208
+ minPt = fs0 * scale;
209
+ if (minPt < 8) add('f', 'error', 'scene is ' + Math.round(sw) + ' px wide; at ' + pagePt + ' pt page width its ' + fs0 + ' px text prints at ' + minPt.toFixed(1) + ' pt (minimum 8); make the diagram narrower');
210
+ else if (minPt < 10) add('f', 'warn', 'text prints at ' + minPt.toFixed(1) + ' pt at page width (scene ' + Math.round(sw) + ' px wide)');
211
+ }
212
+ }
213
+
214
+ // g: colour budget. White, transparent and greys (RGB channels within 16 of
215
+ // each other) are neutral; frames and subgraph containers are skipped.
216
+ function neutral(c) {
217
+ c = String(c || 'transparent').toLowerCase();
218
+ if (c === 'transparent' || c === 'white' || c === '#fff' || c === '#ffffff') return true;
219
+ var m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(c);
220
+ if (!m) return false;
221
+ var ch = [1, 2, 3].map(function (i) { return parseInt(m[i], 16); });
222
+ return Math.max.apply(null, ch) - Math.min.apply(null, ch) < 16;
223
+ }
224
+ var filled = shapes.filter(function (e) { return !neutral(e.backgroundColor) && !frames.has(e.id); });
225
+ var hues = new Set(filled.map(function (e) { return String(e.backgroundColor).toLowerCase(); }));
226
+ if (filled.length > 3 || hues.size > 2) {
227
+ add('g', 'warn', filled.length + ' filled shapes in ' + hues.size + ' colours; keep everything white and colour only the 1 to 3 that carry the point');
228
+ }
229
+ return { findings: findings, meta: { width: Math.round(sw), height: Math.round(sh), minPt: minPt === null ? null : Math.round(minPt * 10) / 10, frames: frames.size, shapes: shapes.length } };
230
+ }
231
+
232
+ // One output line per finding, as printed by `c2m excalidraw` and `c2m lint`.
233
+ export function formatFinding(f) {
234
+ return 'lint ' + f.cls + ' (' + f.level + '): ' + f.message;
235
+ }
236
+
237
+ export function hasErrors(findings) {
238
+ return findings.some(function (f) { return f.level === 'error'; });
239
+ }
@@ -0,0 +1,178 @@
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
+ import { edgePoint } from './diagrams/skeleton.js';
8
+
9
+ const SHAPES = new Set(['rectangle', 'ellipse', 'diamond']);
10
+ const INK = '#1e1e1e';
11
+
12
+ // The house style's plan pass: every node white with a dark stroke, dark text
13
+ // and arrows. Mermaid's own fills (grey actors, yellow notes, lilac subgraphs)
14
+ // would otherwise read as emphasis. Lifelines and other plain lines keep their
15
+ // light grey so they stay in the background. Dashes are kept: they carry
16
+ // meaning (replies, notes, dotted links).
17
+ export function applyHouseStyle(elements) {
18
+ elements.forEach(function (el) {
19
+ if (SHAPES.has(el.type)) {
20
+ el.backgroundColor = '#ffffff';
21
+ el.fillStyle = 'solid';
22
+ el.strokeColor = INK;
23
+ } else if (el.type === 'text' || el.type === 'arrow') {
24
+ el.strokeColor = INK;
25
+ }
26
+ });
27
+ return elements;
28
+ }
29
+
30
+ // Glyph width as a share of the font size, shared with the scene lint so the
31
+ // boxes drawn here are never flagged there.
32
+ export const CHAR_W = 0.6;
33
+
34
+ // A label Excalidraw wrapped mid-word because its shape came out narrow
35
+ // (short labels in diamonds: "OK?" -> "OK / ?") goes back on one line, and a
36
+ // label with deliberate line breaks (from <br>) gets its shape checked too.
37
+ // The shape grows around its centre to fit the text.
38
+ export function unwrapLabels(elements) {
39
+ var byId = {};
40
+ elements.forEach(function (e) { byId[e.id] = e; });
41
+ elements.forEach(function (t) {
42
+ var box = t.type === 'text' && t.containerId && byId[t.containerId];
43
+ if (!box || !t.originalText) return;
44
+ var multi = /\n/.test(t.originalText);
45
+ if (t.text === t.originalText && !multi) return;
46
+ var lines = t.originalText.split('\n');
47
+ var longest = lines.reduce(function (m, l) { return Math.max(m, l.length); }, 0);
48
+ var w = longest * t.fontSize * CHAR_W;
49
+ var h = lines.length * t.fontSize * t.lineHeight;
50
+ var k = box.type === 'diamond' ? 2 : box.type === 'ellipse' ? 1.42 : 1;
51
+ var pad = box.type === 'diamond' ? 40 : box.type === 'ellipse' ? 30 : 40;
52
+ var needW = k * w + pad;
53
+ var needH = k * h + (box.type === 'rectangle' ? 20 : pad);
54
+ if (box.width < needW) { box.x -= (needW - box.width) / 2; box.width = needW; }
55
+ if (box.height < needH) { box.y -= (needH - box.height) / 2; box.height = needH; }
56
+ if (box.type === 'diamond' && box.height < box.width / 2) { box.y -= (box.width / 2 - box.height) / 2; box.height = box.width / 2; }
57
+ t.text = t.originalText;
58
+ t.width = w;
59
+ t.height = h;
60
+ t.x = box.x + (box.width - w) / 2;
61
+ t.y = box.y + (box.height - h) / 2;
62
+ });
63
+ return elements;
64
+ }
65
+
66
+ // Mermaid's subgraph frames are sized before the labels are measured, so a
67
+ // frame can come out narrower than the node inside it. Each frame (a shape
68
+ // named by a "subgraph_group_<id>" group id) grows to hold its member shapes
69
+ // with a margin and a title strip, and its title is re-centred. Frames are
70
+ // processed smallest first so a nested frame is already settled when its
71
+ // parent is measured. Sibling frames pushed into one another are left for the
72
+ // lint to report; this pass does not move nodes.
73
+ export function fitFrames(elements) {
74
+ var PAD = 20, TITLE = 36;
75
+ var frames = elements.filter(function (e) {
76
+ var gid = 'subgraph_group_' + e.id;
77
+ return SHAPES.has(e.type) && elements.some(function (m) { return (m.groupIds || []).indexOf(gid) >= 0; });
78
+ }).sort(function (a, b) { return a.width * a.height - b.width * b.height; });
79
+ frames.forEach(function (fr) {
80
+ var gid = 'subgraph_group_' + fr.id;
81
+ var members = elements.filter(function (m) { return m !== fr && SHAPES.has(m.type) && (m.groupIds || []).indexOf(gid) >= 0; });
82
+ if (!members.length) return;
83
+ var x0 = Math.min.apply(null, members.map(function (m) { return m.x; })) - PAD;
84
+ var y0 = Math.min.apply(null, members.map(function (m) { return m.y; })) - TITLE;
85
+ var x1 = Math.max.apply(null, members.map(function (m) { return m.x + m.width; })) + PAD;
86
+ var y1 = Math.max.apply(null, members.map(function (m) { return m.y + m.height; })) + PAD;
87
+ // Tight fit: mermaid also leaves frames far taller than their contents.
88
+ var nx0 = x0, ny0 = y0, nx1 = x1, ny1 = y1;
89
+ if (nx0 === fr.x && ny0 === fr.y && nx1 === fr.x + fr.width && ny1 === fr.y + fr.height) return;
90
+ var oldTop = fr.y;
91
+ fr.x = nx0; fr.y = ny0; fr.width = nx1 - nx0; fr.height = ny1 - ny0;
92
+ // The title: a text in the group that is not inside a node, near the frame's old top edge.
93
+ elements.forEach(function (t) {
94
+ if (t.type !== 'text' || (t.containerId && t.containerId !== fr.id) || (t.groupIds || []).indexOf(gid) < 0) return;
95
+ if (Math.abs(t.y - oldTop) > TITLE) return;
96
+ t.x = fr.x + (fr.width - t.width) / 2;
97
+ t.y = fr.y + 6;
98
+ });
99
+ });
100
+ return elements;
101
+ }
102
+
103
+ // Growing a node (unwrapLabels) leaves the arrows that were bound to it
104
+ // ending short of or inside the new outline. Each bound end that is no longer
105
+ // on the outline is moved to where the line towards the arrow's next point
106
+ // meets it; the arrow's other points keep their places.
107
+ export function reanchorArrows(elements) {
108
+ var byId = {};
109
+ elements.forEach(function (e) { byId[e.id] = e; });
110
+ elements.forEach(function (a) {
111
+ if (a.type !== 'arrow' || !a.points || a.points.length < 2) return;
112
+ ['start', 'end'].forEach(function (which) {
113
+ var b = a[which + 'Binding'], shape = b && byId[b.elementId];
114
+ if (!shape || !SHAPES.has(shape.type)) return;
115
+ var abs = a.points.map(function (p) { return [a.x + p[0], a.y + p[1]]; });
116
+ var i = which === 'start' ? 0 : abs.length - 1;
117
+ var next = abs[which === 'start' ? 1 : abs.length - 2];
118
+ var cx = shape.x + shape.width / 2, cy = shape.y + shape.height / 2;
119
+ var onOutline = edgePoint(shape, [cx + (abs[i][0] - cx) * 1e3, cy + (abs[i][1] - cy) * 1e3]);
120
+ if (Math.hypot(onOutline[0] - abs[i][0], onOutline[1] - abs[i][1]) <= 6) return;
121
+ abs[i] = edgePoint(shape, next);
122
+ a.x = abs[0][0]; a.y = abs[0][1];
123
+ a.points = abs.map(function (p) { return [p[0] - abs[0][0], p[1] - abs[0][1]]; });
124
+ var xs = a.points.map(function (p) { return p[0]; }), ys = a.points.map(function (p) { return p[1]; });
125
+ a.width = Math.max.apply(null, xs) - Math.min.apply(null, xs);
126
+ a.height = Math.max.apply(null, ys) - Math.min.apply(null, ys);
127
+ });
128
+ });
129
+ return elements;
130
+ }
131
+
132
+ // Source-level fixes before Mermaid sees the text. <br> in a label is a line
133
+ // break to Mermaid but would be drawn as the literal characters, so it becomes
134
+ // a real newline. A left-to-right flowchart is laid out far wider than a page,
135
+ // so it is redrawn top-down.
136
+ export function prepareMermaid(text) {
137
+ var warnings = [];
138
+ var out = text.replace(/<br\s*\/?>/gi, '\n');
139
+ out = out.replace(/^(\s*(?:flowchart|graph)\s+)(LR|RL)\b/im, function (m, head, dir) {
140
+ warnings.push('rewrote "' + head.trim() + ' ' + dir + '" to TD: left-to-right layouts come out wider than a page and print too small');
141
+ return head + 'TD';
142
+ });
143
+ return { text: out, warnings: warnings };
144
+ }
145
+
146
+ // Returns { scene, preview, warnings }, the same shape as buildSkeleton, so
147
+ // the caller treats a .mmd input like any other. The preview is the source.
148
+ export async function mermaidToScene(source) {
149
+ var text = String(source || '').trim();
150
+ if (!text) throw new Error('the Mermaid file is empty');
151
+ var prepared = prepareMermaid(text);
152
+ var warnings = prepared.warnings;
153
+ var forParse = prepared.text;
154
+ var m = await loadExcalidraw();
155
+ var parsed;
156
+ try {
157
+ parsed = await m.parseMermaidToExcalidraw(forParse, { themeVariables: { fontSize: '20px' } });
158
+ } catch (e) {
159
+ var msg = e && e.message ? e.message : String(e);
160
+ throw new Error('Mermaid did not parse: ' + msg.split('\n').slice(0, 4).join(' '));
161
+ }
162
+ var elements = m.convertToExcalidrawElements(parsed.elements, { regenerateIds: false });
163
+ // Diagram types the converter has no shapes for (class, state, gantt, pie ...)
164
+ // come back as one embedded picture of mermaid's own SVG, drawn with our
165
+ // estimated text sizes.
166
+ if (elements.some(function (e) { return e.type === 'image'; })) {
167
+ 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');
168
+ }
169
+ unwrapLabels(elements);
170
+ fitFrames(elements);
171
+ reanchorArrows(elements);
172
+ applyHouseStyle(elements);
173
+ return {
174
+ scene: { type: 'excalidraw', version: 2, source: 'c2m', elements: elements, appState: { viewBackgroundColor: '#ffffff' }, files: parsed.files || {} },
175
+ preview: text,
176
+ warnings: warnings,
177
+ };
178
+ }