@luutuankiet/clipboard2markdown 0.7.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.
package/README.md CHANGED
@@ -79,6 +79,13 @@ Per diagram it writes `<name>.png` (scale 3, lowered until the image has at most
79
79
  c2m excalidraw --png flow.mmd # PNG + link + paste block
80
80
  ```
81
81
 
82
+ **Lint and `--strict`** (every input): the finished scene is checked for a node sticking out of its subgraph frame, overlapping nodes, a literal `<br>` shown as text, unbound or floating arrows, text wider than its box, and text that would print under 8 pt at page width (468 pt, change with `--page-pt`). Findings print as `warning: lint ...` lines. `--strict` turns any error into exit 1 with no PNG and no link; `c2m lint <file>...` (or `c2m excalidraw --lint-only`) only checks. Mermaid input also turns `<br>` into line breaks, redraws `flowchart LR` / `graph LR` as TD (with a warning) and fits subgraph frames around their nodes.
83
+
84
+ ```bash
85
+ c2m lint flow.mmd shot.json # check only; exit 1 on an error
86
+ c2m excalidraw --png --strict flow.mmd # draw only if the lint is clean
87
+ ```
88
+
82
89
  **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
90
 
84
91
  ```bash
package/bin/cli.js CHANGED
@@ -25,6 +25,8 @@ in a few seconds is skipped and its link left as written.
25
25
 
26
26
  c2m excalidraw <file|-> JSON diagram -> excalidraw.com share link and
27
27
  Mermaid preview (see c2m excalidraw --help)
28
+ c2m lint <file>... check diagrams (.mmd, .json, .excalidraw) for layout
29
+ faults; exit 1 on any error (see c2m lint --help)
28
30
  c2m diagrams <command> existing share links <-> Mermaid: expand, strip,
29
31
  show, edit (see c2m diagrams --help)
30
32
 
@@ -149,6 +151,10 @@ if (isEntryPoint()) {
149
151
  const { runExcalidraw } = await import('./excalidraw.js');
150
152
  process.exit(await runExcalidraw(args.slice(1), { stdout: process.stdout, stderr: process.stderr }));
151
153
  }
154
+ if (args[0] === 'lint') {
155
+ const { runExcalidraw } = await import('./excalidraw.js');
156
+ process.exit(await runExcalidraw(['--lint-only', ...args.slice(1)], { stdout: process.stdout, stderr: process.stderr }));
157
+ }
152
158
  if (args[0] === 'diagrams') {
153
159
  const { main } = await import('./diagrams.js');
154
160
  try {
package/bin/excalidraw.js CHANGED
@@ -9,6 +9,7 @@ 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';
12
+ import { lintScene, formatFinding, hasErrors, ALL_CLASSES, PAGE_PT } from '../src/lint.js';
12
13
 
13
14
  export const EXCALIDRAW_HELP = `c2m excalidraw - turn a JSON diagram description into an excalidraw.com share link
14
15
 
@@ -22,6 +23,9 @@ Usage:
22
23
  draw into a working copy's images folder
23
24
  c2m excalidraw <file.mmd> a Mermaid diagram instead (see MERMAID below)
24
25
  c2m excalidraw <shot.json> an annotated screenshot (see DOODLE below)
26
+ c2m excalidraw --strict ... refuse to draw or upload when the lint finds an error
27
+ c2m lint <file>... check only, any input: exit 1 on an error finding
28
+ (same as c2m excalidraw --lint-only <file>...)
25
29
  c2m excalidraw --help show this help
26
30
 
27
31
  OUTPUT (stdout, in this order)
@@ -123,6 +127,25 @@ PREVIEW
123
127
  larger labelled shape -> subgraph. Free text -> "%% note:" line. The preview
124
128
  shows structure only; Mermaid's layout is not your drawing's layout.
125
129
 
130
+ LINT (every input: .mmd, element array, whole scene)
131
+ After the diagram is built, the finished scene is checked. Each finding is a
132
+ line "warning: lint <class> (error|warn): <what, and how to fix it>".
133
+ a a node sticks out of its frame / subgraph, or straddles its edge
134
+ b two nodes overlap (full nesting is fine)
135
+ c a label shows a literal <br> or backslash-n instead of a line break
136
+ d an arrow end is unbound, bound to a missing shape, or far off its outline
137
+ e a label is wider or taller than its shape
138
+ f text prints under 8 pt (warn under 10 pt) once the scene is scaled to the
139
+ page width: 468 pt, or --page-pt <n>
140
+ g (warn) more than 3 filled shapes or 2 fill colours; white, transparent and
141
+ greys are free, frames are skipped. Everything white, colour only the point.
142
+ --strict any error-level finding exits 1, prints the findings to stderr and
143
+ writes no PNG and makes no link. Use it in the loop: fix until clean.
144
+ c2m lint <file>... (or --lint-only) prints one summary line and the findings
145
+ per file, draws and uploads nothing, exits 1 on any error.
146
+ Text widths are estimated (0.6 em per character), so lint can still miss real
147
+ clipping; look at --review for the first diagram of a document.
148
+
126
149
  WARNINGS
127
150
  overlap two shapes partly overlap
128
151
  label does not fit the label's estimated size exceeds its shape minus padding
@@ -167,6 +190,10 @@ PNG (for pasting into a Google Doc): one command, then one write
167
190
 
168
191
  MERMAID (input file ending .mmd or .mermaid)
169
192
  c2m excalidraw --png flow.mmd seq.mmd
193
+ Authoring limits: <br>, <br/> and <br /> in a label become line breaks.
194
+ "flowchart LR" and "graph LR" are redrawn as TD, with a warning: left-to-right
195
+ layouts come out wider than a page and print too small. Subgraph frames are
196
+ fitted tightly around their nodes. Prefer TD chains; run with --strict.
170
197
  Mermaid's own layout, drawn as Excalidraw shapes in the house style's plan
171
198
  pass (white nodes, dark stroke, Excalifont). Flowcharts and sequence
172
199
  diagrams become editable shapes; other types (class, state, gantt ...) come
@@ -238,15 +265,15 @@ function toScene(input) {
238
265
  var built = buildSkeleton(input.elements);
239
266
  if (input.appState) built.scene.appState = input.appState;
240
267
  if (input.files) built.scene.files = input.files;
241
- return built;
268
+ return Object.assign({ fromSkeleton: true }, built);
242
269
  }
243
- return buildSkeleton(input);
270
+ return Object.assign({ fromSkeleton: true }, buildSkeleton(input));
244
271
  }
245
272
 
246
273
  // One input -> { scene, preview, warnings, fence }. A .mmd file is Mermaid; a
247
274
  // JSON object with "image" and "notes" is a doodle; anything else is the
248
275
  // element array or scene described in the help.
249
- async function buildInput(target, io) {
276
+ async function buildInputRaw(target, io) {
250
277
  var text = readInput(target, io.stdin);
251
278
  if (/\.(mmd|mermaid)$/i.test(target)) {
252
279
  var mermaid = await import('../src/mermaid-input.js');
@@ -264,6 +291,20 @@ async function buildInput(target, io) {
264
291
  return Object.assign({ fence: 'mermaid' }, toScene(input));
265
292
  }
266
293
 
294
+ // Lint the finished scene, whatever input it came from. Element arrays and
295
+ // shorthand scenes already get "overlap" and "label does not fit" warnings from
296
+ // the skeleton builder, so those two classes are skipped for them unless the
297
+ // caller wants every finding (--strict, lint-only).
298
+ async function buildInput(target, io, opts) {
299
+ var built = await buildInputRaw(target, io);
300
+ var classes = built.fromSkeleton && !opts.all ? ALL_CLASSES.filter(function (c) { return c !== 'b' && c !== 'e'; }) : ALL_CLASSES;
301
+ var result = lintScene(built.scene, { pagePt: opts.pagePt, classes: classes });
302
+ built.findings = result.findings;
303
+ built.meta = result.meta;
304
+ built.warnings = built.warnings.concat(result.findings.map(formatFinding));
305
+ return built;
306
+ }
307
+
267
308
  function parseJson(text) {
268
309
  try {
269
310
  return JSON.parse(text);
@@ -285,7 +326,7 @@ function looksLikeInput(a) {
285
326
  // Returns the exit code. `io.fetch`, `io.stdin` and `io.env` exist for tests.
286
327
  export async function runExcalidraw(argv, io) {
287
328
  var stdout = io.stdout, stderr = io.stderr;
288
- var noUpload = false;
329
+ var noUpload = false, strict = false, lintOnly = false, pagePt = PAGE_PT;
289
330
  var png = false, pngDir = null, outDir = null, review = false;
290
331
  var targets = [];
291
332
  for (var i = 0; i < argv.length; i++) {
@@ -301,19 +342,29 @@ export async function runExcalidraw(argv, io) {
301
342
  png = true; outDir = argv[++i];
302
343
  } else if (a.startsWith('--out=')) { png = true; outDir = a.slice(6); }
303
344
  else if (a === '--review') review = true;
345
+ else if (a === '--strict') strict = true;
346
+ else if (a === '--lint-only') lintOnly = true;
347
+ else if (a === '--page-pt' || a.startsWith('--page-pt=')) {
348
+ var raw = a === '--page-pt' ? argv[++i] : a.slice(10);
349
+ pagePt = Number(raw);
350
+ if (!(pagePt > 0)) { stderr.write('c2m excalidraw: --page-pt needs a number of points, e.g. 468\n'); return 1; }
351
+ }
304
352
  else if (a.startsWith('--')) { stderr.write('c2m excalidraw: unknown option ' + a + '\n'); return 1; }
305
353
  else targets.push(a);
306
354
  }
307
- if (png ? targets.length < 1 : targets.length !== 1) {
355
+ if (lintOnly ? targets.length < 1 : png ? targets.length < 1 : targets.length !== 1) {
308
356
  stderr.write('c2m excalidraw: expected ' + (png ? 'one or more <file.json>' : 'one <file.json>') +
309
357
  ' or - for stdin. See c2m excalidraw --help.\n');
310
358
  return 1;
311
359
  }
312
360
 
361
+ var lintOpts = { pagePt: pagePt, all: strict || lintOnly };
313
362
  try {
363
+ if (lintOnly) return await runLint(targets, lintOpts, io);
314
364
  if (png && pngDir !== null && outDir !== null) throw new Error('use --png <dir> or --out <dir>, not both');
315
- if (png) return await runPng(targets, { dir: outDir !== null ? outDir : pngDir, folder: outDir !== null, review: review, noUpload: noUpload }, io);
316
- var built = await buildInput(targets[0], io);
365
+ if (png) return await runPng(targets, { dir: outDir !== null ? outDir : pngDir, folder: outDir !== null, review: review, noUpload: noUpload, strict: strict, lint: lintOpts }, io);
366
+ var built = await buildInput(targets[0], io, lintOpts);
367
+ refuseOnErrors([{ name: targets[0], built: built }], strict);
317
368
  var url = noUpload ? null : await upload(built.scene, io.fetch);
318
369
  if (url) stdout.write(url + '\n');
319
370
  stdout.write('```' + built.fence + '\n' + built.preview + '\n```\n');
@@ -325,6 +376,37 @@ export async function runExcalidraw(argv, io) {
325
376
  }
326
377
  }
327
378
 
379
+ // --strict: any error-level finding stops the run before a PNG or a link is
380
+ // made. Every input is reported, not just the first, so one pass shows the
381
+ // whole list.
382
+ function refuseOnErrors(items, strict) {
383
+ if (!strict) return;
384
+ var lines = [];
385
+ items.forEach(function (it) {
386
+ var errs = it.built.findings.filter(function (f) { return f.level === 'error'; });
387
+ if (errs.length) lines.push(it.name + ': ' + errs.length + ' error' + (errs.length === 1 ? '' : 's') + '\n' + errs.map(function (f) { return ' ' + formatFinding(f); }).join('\n'));
388
+ });
389
+ if (lines.length) throw new Error('--strict: lint found errors; nothing was drawn or uploaded\n' + lines.join('\n') + '\nFix the diagram and rerun, or drop --strict to accept the findings as warnings.');
390
+ }
391
+
392
+ // `c2m lint <file>...`: check only. One header line per input, then its
393
+ // findings; exit 1 if any input has an error-level finding.
394
+ async function runLint(targets, lintOpts, io) {
395
+ var failed = false;
396
+ for (var t = 0; t < targets.length; t++) {
397
+ var built = await buildInput(targets[t], io, lintOpts);
398
+ var m = built.meta;
399
+ io.stdout.write(targets[t] + ': ' + m.width + 'x' + m.height + ' px, min text ' + (m.minPt === null ? 'n/a' : m.minPt + ' pt at ' + lintOpts.pagePt + ' pt page width') +
400
+ ', ' + built.findings.length + ' finding' + (built.findings.length === 1 ? '' : 's') + '\n');
401
+ built.warnings.forEach(function (w) {
402
+ if (!/^lint /.test(w)) io.stdout.write(' warning: ' + w + '\n');
403
+ });
404
+ built.findings.forEach(function (f) { io.stdout.write(' ' + formatFinding(f) + '\n'); });
405
+ if (hasErrors(built.findings)) failed = true;
406
+ }
407
+ return failed ? 1 : 0;
408
+ }
409
+
328
410
  async function runPng(targets, opts, io) {
329
411
  var stdout = io.stdout;
330
412
  var names = targets.map(sceneName);
@@ -336,9 +418,10 @@ async function runPng(targets, opts, io) {
336
418
  // last file costs no renders.
337
419
  var items = [];
338
420
  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 });
421
+ var built = await buildInput(targets[t], io, opts.lint);
422
+ items.push({ name: names[t], scene: built.scene, preview: built.preview, warnings: built.warnings, fence: built.fence, built: built });
341
423
  }
424
+ refuseOnErrors(items, opts.strict);
342
425
 
343
426
  var render = await import('../src/excalidraw-png.js');
344
427
  var dir;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luutuankiet/clipboard2markdown",
3
- "version": "0.7.0",
3
+ "version": "0.8.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": {
@@ -80,14 +80,19 @@ function labelOf(raw) {
80
80
  return null;
81
81
  }
82
82
 
83
- // Where the ray from a shape's centre towards `toward` leaves its bounding box.
84
- function edgePoint(el, toward) {
83
+ // Where the ray from a shape's centre towards `toward` leaves the shape's
84
+ // outline: the diamond's slanted sides and the ellipse's curve, not the
85
+ // bounding box around them (a box point floats in empty space at a diamond's
86
+ // corner).
87
+ export function edgePoint(el, toward) {
85
88
  var cx = el.x + el.width / 2, cy = el.y + el.height / 2;
86
89
  var dx = toward[0] - cx, dy = toward[1] - cy;
87
90
  if (!dx && !dy) return [cx, cy];
88
- var sx = dx ? (el.width / 2) / Math.abs(dx) : Infinity;
89
- var sy = dy ? (el.height / 2) / Math.abs(dy) : Infinity;
90
- var s = Math.min(sx, sy);
91
+ var hw = el.width / 2, hh = el.height / 2;
92
+ var s;
93
+ if (el.type === 'diamond') s = 1 / (Math.abs(dx) / hw + Math.abs(dy) / hh);
94
+ else if (el.type === 'ellipse') s = 1 / Math.sqrt((dx / hw) * (dx / hw) + (dy / hh) * (dy / hh));
95
+ else s = Math.min(dx ? hw / Math.abs(dx) : Infinity, dy ? hh / Math.abs(dy) : Infinity);
91
96
  return [cx + dx * s, cy + dy * s];
92
97
  }
93
98
 
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
+ }
@@ -4,6 +4,7 @@
4
4
  // with estimated text sizes standing in for a browser's layout.
5
5
 
6
6
  import { loadExcalidraw } from './excalidraw-png.js';
7
+ import { edgePoint } from './diagrams/skeleton.js';
7
8
 
8
9
  const SHAPES = new Set(['rectangle', 'ellipse', 'diamond']);
9
10
  const INK = '#1e1e1e';
@@ -26,42 +27,138 @@ export function applyHouseStyle(elements) {
26
27
  return elements;
27
28
  }
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
+
29
34
  // 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.
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.
32
38
  export function unwrapLabels(elements) {
33
39
  var byId = {};
34
40
  elements.forEach(function (e) { byId[e.id] = e; });
35
41
  elements.forEach(function (t) {
36
42
  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; }
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; }
42
57
  t.text = t.originalText;
43
58
  t.width = w;
44
- t.height = t.fontSize * t.lineHeight;
59
+ t.height = h;
45
60
  t.x = box.x + (box.width - w) / 2;
46
- t.y = box.y + (box.height - t.height) / 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
+ });
47
128
  });
48
129
  return elements;
49
130
  }
50
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
+
51
146
  // Returns { scene, preview, warnings }, the same shape as buildSkeleton, so
52
147
  // the caller treats a .mmd input like any other. The preview is the source.
53
148
  export async function mermaidToScene(source) {
54
149
  var text = String(source || '').trim();
55
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;
56
154
  var m = await loadExcalidraw();
57
155
  var parsed;
58
156
  try {
59
- parsed = await m.parseMermaidToExcalidraw(text, { themeVariables: { fontSize: '20px' } });
157
+ parsed = await m.parseMermaidToExcalidraw(forParse, { themeVariables: { fontSize: '20px' } });
60
158
  } catch (e) {
61
159
  var msg = e && e.message ? e.message : String(e);
62
160
  throw new Error('Mermaid did not parse: ' + msg.split('\n').slice(0, 4).join(' '));
63
161
  }
64
- var warnings = [];
65
162
  var elements = m.convertToExcalidrawElements(parsed.elements, { regenerateIds: false });
66
163
  // Diagram types the converter has no shapes for (class, state, gantt, pie ...)
67
164
  // come back as one embedded picture of mermaid's own SVG, drawn with our
@@ -70,6 +167,8 @@ export async function mermaidToScene(source) {
70
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');
71
168
  }
72
169
  unwrapLabels(elements);
170
+ fitFrames(elements);
171
+ reanchorArrows(elements);
73
172
  applyHouseStyle(elements);
74
173
  return {
75
174
  scene: { type: 'excalidraw', version: 2, source: 'c2m', elements: elements, appState: { viewBackgroundColor: '#ffffff' }, files: parsed.files || {} },