@luutuankiet/clipboard2markdown 0.7.0 → 0.9.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 +13 -0
- package/bin/cli.js +6 -0
- package/bin/excalidraw.js +117 -11
- package/package.json +1 -1
- package/src/diagrams/skeleton.js +10 -5
- package/src/lint.js +239 -0
- package/src/mermaid-input.js +110 -11
- package/src/sketch.js +388 -0
package/README.md
CHANGED
|
@@ -79,6 +79,19 @@ 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
|
+
**Comics and doodles in a compact text format** (`c2m excalidraw <file>.c2m`, also `.sketch`): an agent writes about 20 lines (panels, stick figures, speech bubbles, boxes, arrows, a callout) and gets a laid-out comic in the house style, with no coordinates. The same link, PNG and paste block come out, and the lint runs on the result. A 3-panel strip is under 1,000 characters instead of roughly 7,600 characters of element JSON. Errors name the file, the line and a fix. Full grammar in `c2m excalidraw --help`, section SKETCH.
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
c2m excalidraw --strict --png comic.c2m # panel "Title" / me: figure @left / me says "Hi" / a -> b "label"
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
**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.
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
c2m lint flow.mmd shot.json # check only; exit 1 on an error
|
|
92
|
+
c2m excalidraw --png --strict flow.mmd # draw only if the lint is clean
|
|
93
|
+
```
|
|
94
|
+
|
|
82
95
|
**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
96
|
|
|
84
97
|
```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
|
@@ -7,8 +7,10 @@
|
|
|
7
7
|
import { mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
8
8
|
import { basename, dirname, resolve } from 'path';
|
|
9
9
|
import { buildSkeleton } from '../src/diagrams/skeleton.js';
|
|
10
|
+
import { sketchToSkeleton, SKETCH_EXT } from '../src/sketch.js';
|
|
10
11
|
import { saveScene } from '../src/diagrams/share-link.js';
|
|
11
12
|
import { sceneToMermaid } from '../src/diagrams/scene-to-mermaid.js';
|
|
13
|
+
import { lintScene, formatFinding, hasErrors, ALL_CLASSES, PAGE_PT } from '../src/lint.js';
|
|
12
14
|
|
|
13
15
|
export const EXCALIDRAW_HELP = `c2m excalidraw - turn a JSON diagram description into an excalidraw.com share link
|
|
14
16
|
|
|
@@ -22,6 +24,10 @@ Usage:
|
|
|
22
24
|
draw into a working copy's images folder
|
|
23
25
|
c2m excalidraw <file.mmd> a Mermaid diagram instead (see MERMAID below)
|
|
24
26
|
c2m excalidraw <shot.json> an annotated screenshot (see DOODLE below)
|
|
27
|
+
c2m excalidraw <file.c2m> a comic or doodle in the compact text format (see SKETCH below)
|
|
28
|
+
c2m excalidraw --strict ... refuse to draw or upload when the lint finds an error
|
|
29
|
+
c2m lint <file>... check only, any input: exit 1 on an error finding
|
|
30
|
+
(same as c2m excalidraw --lint-only <file>...)
|
|
25
31
|
c2m excalidraw --help show this help
|
|
26
32
|
|
|
27
33
|
OUTPUT (stdout, in this order)
|
|
@@ -123,6 +129,25 @@ PREVIEW
|
|
|
123
129
|
larger labelled shape -> subgraph. Free text -> "%% note:" line. The preview
|
|
124
130
|
shows structure only; Mermaid's layout is not your drawing's layout.
|
|
125
131
|
|
|
132
|
+
LINT (every input: .mmd, element array, whole scene)
|
|
133
|
+
After the diagram is built, the finished scene is checked. Each finding is a
|
|
134
|
+
line "warning: lint <class> (error|warn): <what, and how to fix it>".
|
|
135
|
+
a a node sticks out of its frame / subgraph, or straddles its edge
|
|
136
|
+
b two nodes overlap (full nesting is fine)
|
|
137
|
+
c a label shows a literal <br> or backslash-n instead of a line break
|
|
138
|
+
d an arrow end is unbound, bound to a missing shape, or far off its outline
|
|
139
|
+
e a label is wider or taller than its shape
|
|
140
|
+
f text prints under 8 pt (warn under 10 pt) once the scene is scaled to the
|
|
141
|
+
page width: 468 pt, or --page-pt <n>
|
|
142
|
+
g (warn) more than 3 filled shapes or 2 fill colours; white, transparent and
|
|
143
|
+
greys are free, frames are skipped. Everything white, colour only the point.
|
|
144
|
+
--strict any error-level finding exits 1, prints the findings to stderr and
|
|
145
|
+
writes no PNG and makes no link. Use it in the loop: fix until clean.
|
|
146
|
+
c2m lint <file>... (or --lint-only) prints one summary line and the findings
|
|
147
|
+
per file, draws and uploads nothing, exits 1 on any error.
|
|
148
|
+
Text widths are estimated (0.6 em per character), so lint can still miss real
|
|
149
|
+
clipping; look at --review for the first diagram of a document.
|
|
150
|
+
|
|
126
151
|
WARNINGS
|
|
127
152
|
overlap two shapes partly overlap
|
|
128
153
|
label does not fit the label's estimated size exceeds its shape minus padding
|
|
@@ -167,6 +192,10 @@ PNG (for pasting into a Google Doc): one command, then one write
|
|
|
167
192
|
|
|
168
193
|
MERMAID (input file ending .mmd or .mermaid)
|
|
169
194
|
c2m excalidraw --png flow.mmd seq.mmd
|
|
195
|
+
Authoring limits: <br>, <br/> and <br /> in a label become line breaks.
|
|
196
|
+
"flowchart LR" and "graph LR" are redrawn as TD, with a warning: left-to-right
|
|
197
|
+
layouts come out wider than a page and print too small. Subgraph frames are
|
|
198
|
+
fitted tightly around their nodes. Prefer TD chains; run with --strict.
|
|
170
199
|
Mermaid's own layout, drawn as Excalidraw shapes in the house style's plan
|
|
171
200
|
pass (white nodes, dark stroke, Excalifont). Flowcharts and sequence
|
|
172
201
|
diagrams become editable shapes; other types (class, state, gantt ...) come
|
|
@@ -192,6 +221,26 @@ DOODLE (annotated screenshot: a JSON object with "image" and "notes")
|
|
|
192
221
|
picture (excalidraw.com stores pictures apart from the link), so every
|
|
193
222
|
doodle warns; the PNG is the deliverable.
|
|
194
223
|
|
|
224
|
+
SKETCH (a comic or quick doodle in a compact text format: file.c2m or file.sketch)
|
|
225
|
+
One statement per line; indent = inside the preceding panel. # starts a comment.
|
|
226
|
+
Use it for strips and small explainers: it lays everything out for you (no
|
|
227
|
+
coordinates), so a 3-panel comic is about 20 lines instead of 150 of JSON.
|
|
228
|
+
strip [N cols] optional first line: panel grid width (default 2)
|
|
229
|
+
title "text" optional heading above the strip
|
|
230
|
+
panel "Title" [note "caption"] starts a panel; the statements below belong to it
|
|
231
|
+
grid R x C optional: lay the panel's boxes in R rows x C columns
|
|
232
|
+
id: figure [sad|happy] [@left|@right] ["Label"] stick figure with a name tag
|
|
233
|
+
id: box "Text" [marker] rectangle; \\n breaks a line
|
|
234
|
+
a -> b ["label"] [marker] arrow bound to two ids (labels are placed apart)
|
|
235
|
+
id says "text" [marker] speech bubble above that figure/box
|
|
236
|
+
id thinks "text" [marker] thought bubble (cloud tail)
|
|
237
|
+
stat "text" [marker] bold callout line at the panel bottom
|
|
238
|
+
note "text" small caption line inside the panel
|
|
239
|
+
markers: accent (blue), bad (red), good (green); anything else stays white.
|
|
240
|
+
Keep to <= 3 filled shapes and 2 colours per panel (lint g warns beyond that).
|
|
241
|
+
Errors name the line number and say how to fix it. Put the picture in the PNG:
|
|
242
|
+
c2m excalidraw --png <dir> --strict comic.c2m
|
|
243
|
+
|
|
195
244
|
NOT SUPPORTED
|
|
196
245
|
frames, freedraw, editing an existing link (use c2m diagrams edit for that),
|
|
197
246
|
writing .excalidraw files, pictures in share links.
|
|
@@ -238,20 +287,21 @@ function toScene(input) {
|
|
|
238
287
|
var built = buildSkeleton(input.elements);
|
|
239
288
|
if (input.appState) built.scene.appState = input.appState;
|
|
240
289
|
if (input.files) built.scene.files = input.files;
|
|
241
|
-
return built;
|
|
290
|
+
return Object.assign({ fromSkeleton: true }, built);
|
|
242
291
|
}
|
|
243
|
-
return buildSkeleton(input);
|
|
292
|
+
return Object.assign({ fromSkeleton: true }, buildSkeleton(input));
|
|
244
293
|
}
|
|
245
294
|
|
|
246
295
|
// One input -> { scene, preview, warnings, fence }. A .mmd file is Mermaid; a
|
|
247
296
|
// JSON object with "image" and "notes" is a doodle; anything else is the
|
|
248
297
|
// element array or scene described in the help.
|
|
249
|
-
async function
|
|
298
|
+
async function buildInputRaw(target, io) {
|
|
250
299
|
var text = readInput(target, io.stdin);
|
|
251
300
|
if (/\.(mmd|mermaid)$/i.test(target)) {
|
|
252
301
|
var mermaid = await import('../src/mermaid-input.js');
|
|
253
302
|
return Object.assign({ fence: 'mermaid' }, await mermaid.mermaidToScene(text));
|
|
254
303
|
}
|
|
304
|
+
if (SKETCH_EXT.test(target)) return Object.assign({ fence: 'mermaid' }, toScene(sketchToSkeleton(text, target)));
|
|
255
305
|
var input = parseJson(text);
|
|
256
306
|
var doodle = await import('../src/doodle.js');
|
|
257
307
|
if (doodle.isDoodleSpec(input)) {
|
|
@@ -264,6 +314,20 @@ async function buildInput(target, io) {
|
|
|
264
314
|
return Object.assign({ fence: 'mermaid' }, toScene(input));
|
|
265
315
|
}
|
|
266
316
|
|
|
317
|
+
// Lint the finished scene, whatever input it came from. Element arrays and
|
|
318
|
+
// shorthand scenes already get "overlap" and "label does not fit" warnings from
|
|
319
|
+
// the skeleton builder, so those two classes are skipped for them unless the
|
|
320
|
+
// caller wants every finding (--strict, lint-only).
|
|
321
|
+
async function buildInput(target, io, opts) {
|
|
322
|
+
var built = await buildInputRaw(target, io);
|
|
323
|
+
var classes = built.fromSkeleton && !opts.all ? ALL_CLASSES.filter(function (c) { return c !== 'b' && c !== 'e'; }) : ALL_CLASSES;
|
|
324
|
+
var result = lintScene(built.scene, { pagePt: opts.pagePt, classes: classes });
|
|
325
|
+
built.findings = result.findings;
|
|
326
|
+
built.meta = result.meta;
|
|
327
|
+
built.warnings = built.warnings.concat(result.findings.map(formatFinding));
|
|
328
|
+
return built;
|
|
329
|
+
}
|
|
330
|
+
|
|
267
331
|
function parseJson(text) {
|
|
268
332
|
try {
|
|
269
333
|
return JSON.parse(text);
|
|
@@ -273,19 +337,19 @@ function parseJson(text) {
|
|
|
273
337
|
}
|
|
274
338
|
|
|
275
339
|
function sceneName(target) {
|
|
276
|
-
return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw|mmd|mermaid)$/i, '');
|
|
340
|
+
return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw|mmd|mermaid|c2m|sketch)$/i, '');
|
|
277
341
|
}
|
|
278
342
|
|
|
279
343
|
// `--png` takes an optional folder: the next argument is the folder unless it
|
|
280
344
|
// looks like an input (-, *.json, *.excalidraw) or an option.
|
|
281
345
|
function looksLikeInput(a) {
|
|
282
|
-
return a === '-' || a.startsWith('--') || /\.(json|excalidraw|mmd|mermaid)$/i.test(a);
|
|
346
|
+
return a === '-' || a.startsWith('--') || /\.(json|excalidraw|mmd|mermaid|c2m|sketch)$/i.test(a);
|
|
283
347
|
}
|
|
284
348
|
|
|
285
349
|
// Returns the exit code. `io.fetch`, `io.stdin` and `io.env` exist for tests.
|
|
286
350
|
export async function runExcalidraw(argv, io) {
|
|
287
351
|
var stdout = io.stdout, stderr = io.stderr;
|
|
288
|
-
var noUpload = false;
|
|
352
|
+
var noUpload = false, strict = false, lintOnly = false, pagePt = PAGE_PT;
|
|
289
353
|
var png = false, pngDir = null, outDir = null, review = false;
|
|
290
354
|
var targets = [];
|
|
291
355
|
for (var i = 0; i < argv.length; i++) {
|
|
@@ -301,19 +365,29 @@ export async function runExcalidraw(argv, io) {
|
|
|
301
365
|
png = true; outDir = argv[++i];
|
|
302
366
|
} else if (a.startsWith('--out=')) { png = true; outDir = a.slice(6); }
|
|
303
367
|
else if (a === '--review') review = true;
|
|
368
|
+
else if (a === '--strict') strict = true;
|
|
369
|
+
else if (a === '--lint-only') lintOnly = true;
|
|
370
|
+
else if (a === '--page-pt' || a.startsWith('--page-pt=')) {
|
|
371
|
+
var raw = a === '--page-pt' ? argv[++i] : a.slice(10);
|
|
372
|
+
pagePt = Number(raw);
|
|
373
|
+
if (!(pagePt > 0)) { stderr.write('c2m excalidraw: --page-pt needs a number of points, e.g. 468\n'); return 1; }
|
|
374
|
+
}
|
|
304
375
|
else if (a.startsWith('--')) { stderr.write('c2m excalidraw: unknown option ' + a + '\n'); return 1; }
|
|
305
376
|
else targets.push(a);
|
|
306
377
|
}
|
|
307
|
-
if (png ? targets.length < 1 : targets.length !== 1) {
|
|
378
|
+
if (lintOnly ? targets.length < 1 : png ? targets.length < 1 : targets.length !== 1) {
|
|
308
379
|
stderr.write('c2m excalidraw: expected ' + (png ? 'one or more <file.json>' : 'one <file.json>') +
|
|
309
380
|
' or - for stdin. See c2m excalidraw --help.\n');
|
|
310
381
|
return 1;
|
|
311
382
|
}
|
|
312
383
|
|
|
384
|
+
var lintOpts = { pagePt: pagePt, all: strict || lintOnly };
|
|
313
385
|
try {
|
|
386
|
+
if (lintOnly) return await runLint(targets, lintOpts, io);
|
|
314
387
|
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);
|
|
388
|
+
if (png) return await runPng(targets, { dir: outDir !== null ? outDir : pngDir, folder: outDir !== null, review: review, noUpload: noUpload, strict: strict, lint: lintOpts }, io);
|
|
389
|
+
var built = await buildInput(targets[0], io, lintOpts);
|
|
390
|
+
refuseOnErrors([{ name: targets[0], built: built }], strict);
|
|
317
391
|
var url = noUpload ? null : await upload(built.scene, io.fetch);
|
|
318
392
|
if (url) stdout.write(url + '\n');
|
|
319
393
|
stdout.write('```' + built.fence + '\n' + built.preview + '\n```\n');
|
|
@@ -325,6 +399,37 @@ export async function runExcalidraw(argv, io) {
|
|
|
325
399
|
}
|
|
326
400
|
}
|
|
327
401
|
|
|
402
|
+
// --strict: any error-level finding stops the run before a PNG or a link is
|
|
403
|
+
// made. Every input is reported, not just the first, so one pass shows the
|
|
404
|
+
// whole list.
|
|
405
|
+
function refuseOnErrors(items, strict) {
|
|
406
|
+
if (!strict) return;
|
|
407
|
+
var lines = [];
|
|
408
|
+
items.forEach(function (it) {
|
|
409
|
+
var errs = it.built.findings.filter(function (f) { return f.level === 'error'; });
|
|
410
|
+
if (errs.length) lines.push(it.name + ': ' + errs.length + ' error' + (errs.length === 1 ? '' : 's') + '\n' + errs.map(function (f) { return ' ' + formatFinding(f); }).join('\n'));
|
|
411
|
+
});
|
|
412
|
+
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.');
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// `c2m lint <file>...`: check only. One header line per input, then its
|
|
416
|
+
// findings; exit 1 if any input has an error-level finding.
|
|
417
|
+
async function runLint(targets, lintOpts, io) {
|
|
418
|
+
var failed = false;
|
|
419
|
+
for (var t = 0; t < targets.length; t++) {
|
|
420
|
+
var built = await buildInput(targets[t], io, lintOpts);
|
|
421
|
+
var m = built.meta;
|
|
422
|
+
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') +
|
|
423
|
+
', ' + built.findings.length + ' finding' + (built.findings.length === 1 ? '' : 's') + '\n');
|
|
424
|
+
built.warnings.forEach(function (w) {
|
|
425
|
+
if (!/^lint /.test(w)) io.stdout.write(' warning: ' + w + '\n');
|
|
426
|
+
});
|
|
427
|
+
built.findings.forEach(function (f) { io.stdout.write(' ' + formatFinding(f) + '\n'); });
|
|
428
|
+
if (hasErrors(built.findings)) failed = true;
|
|
429
|
+
}
|
|
430
|
+
return failed ? 1 : 0;
|
|
431
|
+
}
|
|
432
|
+
|
|
328
433
|
async function runPng(targets, opts, io) {
|
|
329
434
|
var stdout = io.stdout;
|
|
330
435
|
var names = targets.map(sceneName);
|
|
@@ -336,9 +441,10 @@ async function runPng(targets, opts, io) {
|
|
|
336
441
|
// last file costs no renders.
|
|
337
442
|
var items = [];
|
|
338
443
|
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 });
|
|
444
|
+
var built = await buildInput(targets[t], io, opts.lint);
|
|
445
|
+
items.push({ name: names[t], scene: built.scene, preview: built.preview, warnings: built.warnings, fence: built.fence, built: built });
|
|
341
446
|
}
|
|
447
|
+
refuseOnErrors(items, opts.strict);
|
|
342
448
|
|
|
343
449
|
var render = await import('../src/excalidraw-png.js');
|
|
344
450
|
var dir;
|
package/package.json
CHANGED
package/src/diagrams/skeleton.js
CHANGED
|
@@ -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
|
|
84
|
-
|
|
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
|
|
89
|
-
var
|
|
90
|
-
|
|
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
|
+
}
|
package/src/mermaid-input.js
CHANGED
|
@@ -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
|
-
//
|
|
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
|
|
38
|
-
var
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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 =
|
|
59
|
+
t.height = h;
|
|
45
60
|
t.x = box.x + (box.width - w) / 2;
|
|
46
|
-
t.y = box.y + (box.height -
|
|
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(
|
|
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 || {} },
|
package/src/sketch.js
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
// Compact comic / doodle format -> element array for the skeleton builder.
|
|
2
|
+
//
|
|
3
|
+
// An agent writes a few lines of text (see SKETCH in bin/excalidraw.js); this
|
|
4
|
+
// module parses them, lays everything out (no coordinates are ever written) and
|
|
5
|
+
// returns the same shorthand element array `c2m excalidraw` already accepts.
|
|
6
|
+
// From there the normal path runs unchanged: skeleton builder, lint, PNG, link.
|
|
7
|
+
//
|
|
8
|
+
// Look: everything is a white fill with a black stroke. Colour comes only from
|
|
9
|
+
// the markers `accent` (one blue, "look here"), `bad` (red) and `good` (green).
|
|
10
|
+
// Pure: no file or network access.
|
|
11
|
+
|
|
12
|
+
const FS = 16; // every text is 16 px; the scene is about 540 px wide, so it prints at about 14.5 pt
|
|
13
|
+
const CW = 0.68; // px per char per font px, equal to TEXT_METRICS.charWidth in diagrams/edit.js
|
|
14
|
+
const LH = 1.25; // line height
|
|
15
|
+
const PW = 256; // panel width
|
|
16
|
+
const PGAP = 32; // gap between panels
|
|
17
|
+
const M = 12; // margin inside a panel
|
|
18
|
+
const TAIL = 34; // gap between a bubble and its speaker's head
|
|
19
|
+
const SECTION = 18; // gap between sections of a panel
|
|
20
|
+
const INK = '#1e1e1e';
|
|
21
|
+
export const MARKERS = {
|
|
22
|
+
accent: { fill: '#a5d8ff', ink: '#1971c2' },
|
|
23
|
+
bad: { fill: '#ffc9c9', ink: '#e03131' },
|
|
24
|
+
good: { fill: '#b2f2bb', ink: '#2f9e44' },
|
|
25
|
+
};
|
|
26
|
+
const MOODS = ['ok', 'sad', 'happy'];
|
|
27
|
+
const SLOTS = ['@left', '@right', '@center'];
|
|
28
|
+
|
|
29
|
+
export const SKETCH_EXT = /\.(c2m|sketch)$/i;
|
|
30
|
+
|
|
31
|
+
function fail(file, line, text, msg, fix) {
|
|
32
|
+
var where = (file || 'input') + ':' + line;
|
|
33
|
+
throw new Error(where + ': ' + msg + (text ? '\n ' + String(text).trim() : '') + (fix ? '\n fix: ' + fix : ''));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ---- parser ---------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
function tokenize(src) {
|
|
39
|
+
var out = [], re = /"((?:[^"\\]|\\.)*)"|->|:|#.*|[^\s":]+/g, m;
|
|
40
|
+
while ((m = re.exec(src))) {
|
|
41
|
+
if (m[0][0] === '#') break;
|
|
42
|
+
if (m[1] !== undefined) out.push({ q: true, v: m[1].replace(/\\(.)/g, function (_, c) { return c === 'n' ? '\n' : c; }) });
|
|
43
|
+
else out.push({ q: false, v: m[0] });
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function parseSketch(source, file) {
|
|
49
|
+
var doc = { cols: 2, title: null, body: [], panels: [], bodyGrid: 0 };
|
|
50
|
+
var panel = null;
|
|
51
|
+
String(source).split(/\r?\n/).forEach(function (raw, idx) {
|
|
52
|
+
var line = idx + 1;
|
|
53
|
+
var tk = tokenize(raw);
|
|
54
|
+
if (!tk.length) return;
|
|
55
|
+
var indented = /^\s/.test(raw);
|
|
56
|
+
var err = function (msg, fix) { fail(file, line, raw, msg, fix); };
|
|
57
|
+
var word = function (i) { return tk[i] && !tk[i].q ? tk[i].v : null; };
|
|
58
|
+
var str = function (i, what) {
|
|
59
|
+
if (!tk[i] || !tk[i].q) err('expected a quoted ' + what + ' here', 'write the text in double quotes, e.g. "Report"');
|
|
60
|
+
return tk[i].v;
|
|
61
|
+
};
|
|
62
|
+
// trailing markers and slots, in any order
|
|
63
|
+
var rest = function (from, allow) {
|
|
64
|
+
var o = { marker: null, slot: null, mood: null, words: [] };
|
|
65
|
+
for (var i = from; i < tk.length; i++) {
|
|
66
|
+
var w = word(i);
|
|
67
|
+
if (w && MARKERS[w]) { if (o.marker) err('two colour markers on one line (' + o.marker + ', ' + w + ')', 'use only one of accent, bad, good'); o.marker = w; }
|
|
68
|
+
else if (w && SLOTS.indexOf(w) >= 0 && allow.slot) o.slot = w.slice(1);
|
|
69
|
+
else if (w && MOODS.indexOf(w) >= 0 && allow.mood) o.mood = w;
|
|
70
|
+
else o.words.push(tk[i]);
|
|
71
|
+
}
|
|
72
|
+
return o;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
var first = word(0);
|
|
76
|
+
if (!indented || !panel) {
|
|
77
|
+
if (indented && !panel && first !== 'strip' && first !== 'panel') {
|
|
78
|
+
// an indented line before any panel is just a body line
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
var target = indented && panel ? panel.stmts : doc.body;
|
|
82
|
+
if (!indented) panel = null;
|
|
83
|
+
|
|
84
|
+
if (first === 'strip') {
|
|
85
|
+
var n = Number(word(1));
|
|
86
|
+
if (!(n >= 1 && n <= 4)) err('strip needs a column count from 1 to 4', 'write: strip 2 cols (2 columns fit a 468 pt page at 14 pt text)');
|
|
87
|
+
doc.cols = n; return;
|
|
88
|
+
}
|
|
89
|
+
if (first === 'title') { doc.title = str(1, 'title'); return; }
|
|
90
|
+
if (first === 'panel') {
|
|
91
|
+
var r = rest(2, {});
|
|
92
|
+
panel = { title: str(1, 'panel title'), note: null, stmts: [], line: line };
|
|
93
|
+
if (r.words.length) {
|
|
94
|
+
if (r.words[0].v !== 'note' || !r.words[1] || !r.words[1].q || r.words.length > 2) err('after the panel title only note "caption" is allowed', 'write: panel "Title" note "One-line caption."');
|
|
95
|
+
panel.note = r.words[1].v;
|
|
96
|
+
}
|
|
97
|
+
doc.panels.push(panel); return;
|
|
98
|
+
}
|
|
99
|
+
if (first === 'grid') {
|
|
100
|
+
var g = Number(word(1));
|
|
101
|
+
if (!(g >= 1 && g <= 4)) err('grid needs a column count from 1 to 4', 'write: grid 2 cols');
|
|
102
|
+
(panel && indented ? panel : doc).grid = g; return;
|
|
103
|
+
}
|
|
104
|
+
if (first === 'stat' || first === 'text' || first === 'note') {
|
|
105
|
+
var rs = rest(2, {});
|
|
106
|
+
if (rs.words.length) err('unexpected text after the quoted string: ' + rs.words.map(function (t) { return t.v; }).join(' '), 'quote the whole text once; add \\n for a line break');
|
|
107
|
+
target.push({ kind: first === 'note' ? 'note' : 'stat', text: str(1, 'text'), marker: rs.marker, line: line }); return;
|
|
108
|
+
}
|
|
109
|
+
if (tk.some(function (t) { return !t.q && /->./.test(t.v) || !t.q && /.->/.test(t.v); })) err('write -> with a space on each side', 'e.g. a -> b "label"');
|
|
110
|
+
var ai = tk.findIndex(function (t) { return !t.q && t.v === '->'; });
|
|
111
|
+
if (ai >= 0) {
|
|
112
|
+
if (ai !== 1 || !word(0) || !word(2)) err('an arrow is written: from -> to ["label"] [accent|bad|good]', 'e.g. rpt -> db "query"');
|
|
113
|
+
var re = rest(3, {}), label = '';
|
|
114
|
+
if (re.words.length) {
|
|
115
|
+
var ws = re.words;
|
|
116
|
+
if (ws[0].v === ':' && !ws[0].q) label = ws.slice(1).map(function (t) { return t.v; }).join(' ');
|
|
117
|
+
else if (ws.length === 1 && ws[0].q) label = ws[0].v;
|
|
118
|
+
else err('unexpected text after the arrow target', 'label an arrow with : text or "text"');
|
|
119
|
+
}
|
|
120
|
+
target.push({ kind: 'edge', from: word(0), to: word(2), label: label, marker: re.marker, line: line }); return;
|
|
121
|
+
}
|
|
122
|
+
var w0 = word(0), w1 = word(1);
|
|
123
|
+
if (w1 === 'says' || w1 === 'thinks') {
|
|
124
|
+
var rb = rest(3, {});
|
|
125
|
+
if (rb.words.length) err('unexpected text after the quoted string', 'one quoted string, \\n for line breaks');
|
|
126
|
+
target.push({ kind: 'bubble', who: w0, think: w1 === 'thinks', text: str(2, 'speech'), marker: rb.marker, line: line }); return;
|
|
127
|
+
}
|
|
128
|
+
if (w0 && tk[1] && !tk[1].q && tk[1].v === ':') {
|
|
129
|
+
var kind = word(2);
|
|
130
|
+
if (kind === 'figure') {
|
|
131
|
+
var rf = rest(3, { slot: true, mood: true });
|
|
132
|
+
var name = '';
|
|
133
|
+
if (rf.words.length) { if (rf.words.length > 1 || !rf.words[0].q) err('a figure takes at most one quoted name', 'write: me: figure happy @left "You"'); name = rf.words[0].v; }
|
|
134
|
+
target.push({ kind: 'figure', id: w0, mood: rf.mood || 'ok', slot: rf.slot, name: name, marker: rf.marker, line: line }); return;
|
|
135
|
+
}
|
|
136
|
+
if (kind === 'box') {
|
|
137
|
+
var rx = rest(3, {});
|
|
138
|
+
if (rx.words.length !== 1 || !rx.words[0].q) err('a box needs one quoted label', 'write: db: box "Source\\nDB" good');
|
|
139
|
+
target.push({ kind: 'box', id: w0, label: rx.words[0].v, marker: rx.marker, line: line }); return;
|
|
140
|
+
}
|
|
141
|
+
err('unknown kind "' + kind + '" after "' + w0 + ':"', 'use figure or box');
|
|
142
|
+
}
|
|
143
|
+
err('cannot read this line', 'statements: strip N cols | title "t" | panel "t" [note "c"] | id: figure | id: box "l" | id says "t" | a -> b "l" | stat "t" | note "t" | grid N cols');
|
|
144
|
+
});
|
|
145
|
+
doc.panels.forEach(function (p) {
|
|
146
|
+
if (!p.stmts.length) fail(file, p.line, '', 'panel "' + p.title + '" has no statements', 'indent its figures, boxes and bubbles under the panel line with two spaces');
|
|
147
|
+
});
|
|
148
|
+
if (!doc.panels.length && !doc.body.length) fail(file, 1, '', 'nothing to draw', 'start with: strip 2 cols then panel "Title"');
|
|
149
|
+
return doc;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---- layout ---------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
function wrap(text, maxChars) {
|
|
155
|
+
return String(text).split('\n').map(function (para) {
|
|
156
|
+
var lines = [], cur = '';
|
|
157
|
+
para.split(/\s+/).filter(Boolean).forEach(function (w) {
|
|
158
|
+
if (!cur) cur = w;
|
|
159
|
+
else if ((cur + ' ' + w).length <= maxChars) cur += ' ' + w;
|
|
160
|
+
else { lines.push(cur); cur = w; }
|
|
161
|
+
});
|
|
162
|
+
lines.push(cur);
|
|
163
|
+
return lines.join('\n');
|
|
164
|
+
}).join('\n');
|
|
165
|
+
}
|
|
166
|
+
function chars(px) { return Math.max(4, Math.floor(px / (CW * FS))); }
|
|
167
|
+
function size(text) {
|
|
168
|
+
var ls = String(text).split('\n');
|
|
169
|
+
return { w: Math.ceil(Math.max.apply(null, ls.map(function (l) { return l.length; })) * CW * FS), h: Math.ceil(ls.length * LH * FS), n: ls.length };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function Maker(prefix) {
|
|
173
|
+
var n = 0, els = [];
|
|
174
|
+
return {
|
|
175
|
+
els: els,
|
|
176
|
+
id: function (p) { n++; return prefix + p + n; },
|
|
177
|
+
push: function (e) { els.push(e); return e; },
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function shift(els, dx, dy) {
|
|
182
|
+
els.forEach(function (e) { if (typeof e.x === 'number') { e.x += dx; e.y += dy; } });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function layoutBody(stmts, W, scope, grid, file) {
|
|
186
|
+
var mk = Maker(scope + 'e');
|
|
187
|
+
var P = function (id) { return scope + id; };
|
|
188
|
+
var figs = stmts.filter(function (s) { return s.kind === 'figure'; });
|
|
189
|
+
var bubbles = stmts.filter(function (s) { return s.kind === 'bubble'; });
|
|
190
|
+
var boxes = stmts.filter(function (s) { return s.kind === 'box'; });
|
|
191
|
+
var edges = stmts.filter(function (s) { return s.kind === 'edge'; });
|
|
192
|
+
var stats = stmts.filter(function (s) { return s.kind === 'stat'; });
|
|
193
|
+
var notes = stmts.filter(function (s) { return s.kind === 'note'; });
|
|
194
|
+
var ids = {};
|
|
195
|
+
stmts.forEach(function (s) {
|
|
196
|
+
if (s.id) {
|
|
197
|
+
if (ids[s.id]) fail(file, s.line, '', 'id "' + s.id + '" is declared twice in this ' + (scope ? 'panel' : 'file'), 'rename one; ids only need to be unique inside their panel');
|
|
198
|
+
ids[s.id] = s;
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
// figure slots
|
|
203
|
+
var used = {};
|
|
204
|
+
figs.forEach(function (f) { if (f.slot) { if (used[f.slot]) fail(file, f.line, '', 'two figures in @' + f.slot, 'give each figure its own @left, @right or @center'); used[f.slot] = 1; } });
|
|
205
|
+
var order = figs.length === 3 ? ['left', 'center', 'right'] : ['left', 'right', 'center'];
|
|
206
|
+
figs.forEach(function (f) { if (!f.slot) { f.slot = order.filter(function (s) { return !used[s]; })[0]; if (!f.slot) fail(file, f.line, '', 'more than 3 figures in one panel', 'split the scene into two panels'); used[f.slot] = 1; } });
|
|
207
|
+
figs.forEach(function (f) {
|
|
208
|
+
f.nameText = f.name ? wrap(f.name, 12) : '';
|
|
209
|
+
f.hw = Math.max(40, f.nameText ? Math.ceil(size(f.nameText).w / 2) + 2 : 0);
|
|
210
|
+
f.cx = f.slot === 'left' ? M + f.hw : f.slot === 'right' ? W - M - f.hw : W / 2;
|
|
211
|
+
});
|
|
212
|
+
var speakers = {};
|
|
213
|
+
bubbles.forEach(function (b) {
|
|
214
|
+
var f = ids[b.who];
|
|
215
|
+
if (!f || f.kind !== 'figure') fail(file, b.line, '', '"' + b.who + '" is not a figure here', 'declare it first: ' + b.who + ': figure @left "Name" (declared here: ' + (Object.keys(ids).join(', ') || 'nothing') + ')');
|
|
216
|
+
if (speakers[b.who]) fail(file, b.line, '', '"' + b.who + '" already has a bubble in this panel', 'one bubble per figure; merge the two into one with \\n');
|
|
217
|
+
speakers[b.who] = 1; b.fig = f;
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
var y = 0, bw, ink;
|
|
221
|
+
// 1. bubbles, stacked in statement order, each leaning toward its speaker
|
|
222
|
+
var two = bubbles.length > 1;
|
|
223
|
+
var maxBW = two ? W - 80 : W - 2 * M;
|
|
224
|
+
bubbles.forEach(function (b) {
|
|
225
|
+
var f = b.fig, k = b.think ? Math.SQRT2 : 1;
|
|
226
|
+
var text = wrap(b.text, chars((maxBW / k) - 20));
|
|
227
|
+
var s = size(text);
|
|
228
|
+
b.text2 = text;
|
|
229
|
+
b.w = Math.ceil((s.w + 20) * k) + (b.think ? 8 : 0);
|
|
230
|
+
b.h = Math.ceil((s.h + 20) * k);
|
|
231
|
+
b.x = f.slot === 'left' ? M : f.slot === 'right' ? W - M - b.w : Math.round((W - b.w) / 2);
|
|
232
|
+
b.y = y;
|
|
233
|
+
y += b.h + 30;
|
|
234
|
+
});
|
|
235
|
+
if (bubbles.length) y = y - 30 + TAIL;
|
|
236
|
+
var figTop = y;
|
|
237
|
+
|
|
238
|
+
// 2. figures and their tails
|
|
239
|
+
bubbles.forEach(function (b) {
|
|
240
|
+
var f = b.fig, col = b.marker && MARKERS[b.marker];
|
|
241
|
+
var by = b.y + b.h, tx = Math.max(b.x + 14, Math.min(b.x + b.w - 14, f.cx)), tipY = figTop - 6;
|
|
242
|
+
mk.push({ id: P(b.who + '_' + (b.think ? 'thinks' : 'says')), type: b.think ? 'ellipse' : 'rectangle', x: b.x, y: b.y, width: b.w, height: b.h,
|
|
243
|
+
backgroundColor: col ? col.fill : '#ffffff', label: { text: b.text2, fontSize: FS } });
|
|
244
|
+
if (b.think) {
|
|
245
|
+
[[0.62, 9], [0.8, 6], [0.95, 4]].forEach(function (d) {
|
|
246
|
+
var py = by + (tipY - by) * d[0];
|
|
247
|
+
mk.push({ id: mk.id('dot'), type: 'line', x: tx + (f.cx - tx) * d[0], y: py, points: [[0, 0], [1, 0]], strokeWidth: d[1] });
|
|
248
|
+
});
|
|
249
|
+
} else {
|
|
250
|
+
mk.push({ id: mk.id('tail'), type: 'line', x: tx - 9, y: by, points: [[0, 0], [f.cx - tx + 9, tipY - by], [18, 0]], strokeWidth: 2 });
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
var figH = 0;
|
|
254
|
+
figs.forEach(function (f) {
|
|
255
|
+
var col = f.marker && MARKERS[f.marker], cx = f.cx, t = figTop, sw = 3;
|
|
256
|
+
mk.push({ id: P(f.id + '_head'), type: 'ellipse', x: cx - 17, y: t, width: 34, height: 34, strokeWidth: sw, backgroundColor: col ? col.fill : '#ffffff' });
|
|
257
|
+
[-6, 6].forEach(function (dx) { mk.push({ id: mk.id('eye'), type: 'line', x: cx + dx, y: t + 14, points: [[0, 0], [1, 0]], strokeWidth: 5 }); });
|
|
258
|
+
var mouth = f.mood === 'happy' ? [[0, 0], [8, 7], [16, 0]] : f.mood === 'sad' ? [[0, 7], [8, 0], [16, 7]] : [[0, 0], [16, 0]];
|
|
259
|
+
mk.push({ id: mk.id('mouth'), type: 'line', x: cx - 8, y: t + 23, points: mouth, strokeWidth: 2 });
|
|
260
|
+
mk.push({ id: mk.id('torso'), type: 'line', x: cx, y: t + 34, points: [[0, 0], [0, 44]], strokeWidth: sw });
|
|
261
|
+
mk.push({ id: mk.id('arm'), type: 'line', x: cx, y: t + 46, points: [[0, 0], [-30, 22]], strokeWidth: sw });
|
|
262
|
+
mk.push({ id: mk.id('arm'), type: 'line', x: cx, y: t + 46, points: [[0, 0], [30, -14]], strokeWidth: sw });
|
|
263
|
+
mk.push({ id: mk.id('leg'), type: 'line', x: cx, y: t + 78, points: [[0, 0], [-22, 38]], strokeWidth: sw });
|
|
264
|
+
mk.push({ id: mk.id('leg'), type: 'line', x: cx, y: t + 78, points: [[0, 0], [22, 38]], strokeWidth: sw });
|
|
265
|
+
var h = 120;
|
|
266
|
+
if (f.nameText) {
|
|
267
|
+
var s = size(f.nameText);
|
|
268
|
+
mk.push({ id: mk.id('name'), type: 'text', x: cx - s.w / 2, y: t + 122, text: f.nameText, fontSize: FS, textAlign: 'center' });
|
|
269
|
+
h = 122 + s.h;
|
|
270
|
+
}
|
|
271
|
+
figH = Math.max(figH, h);
|
|
272
|
+
});
|
|
273
|
+
if (figs.length) y = figTop + figH + SECTION;
|
|
274
|
+
else if (bubbles.length) y = figTop;
|
|
275
|
+
|
|
276
|
+
// 3. boxes and the arrows between them
|
|
277
|
+
if (boxes.length) {
|
|
278
|
+
boxes.forEach(function (b) {
|
|
279
|
+
var s = size(b.label);
|
|
280
|
+
b.w = Math.max(80, s.w + 24); b.h = Math.max(52, s.h + 24);
|
|
281
|
+
});
|
|
282
|
+
var bwMax = Math.max.apply(null, boxes.map(function (b) { return b.w; }));
|
|
283
|
+
var bhMax = Math.max.apply(null, boxes.map(function (b) { return b.h; }));
|
|
284
|
+
var rx = M, rw = W - 2 * M, side = null;
|
|
285
|
+
var sides = figs.map(function (f) { return f.slot; }).filter(function (s, i, a) { return a.indexOf(s) === i; });
|
|
286
|
+
if (figs.length && sides.length === 1 && sides[0] !== 'center' && !grid) {
|
|
287
|
+
var edgeL = Math.max.apply(null, figs.map(function (f) { return f.cx + f.hw; })) + 10;
|
|
288
|
+
var edgeR = Math.min.apply(null, figs.map(function (f) { return f.cx - f.hw; })) - 10;
|
|
289
|
+
var r0 = sides[0] === 'left' ? edgeL : M, r1 = sides[0] === 'left' ? W - M : edgeR;
|
|
290
|
+
var room = (r1 - r0) - bwMax / 2 - 10;
|
|
291
|
+
var labelsFit = edges.every(function (e) { var s = size(wrap(e.label || 'x', chars(room))); return s.n <= 3; });
|
|
292
|
+
if (bwMax <= r1 - r0 && labelsFit) { side = sides[0]; rx = r0; rw = r1 - r0; }
|
|
293
|
+
}
|
|
294
|
+
var n = boxes.length, cols = grid || (side ? 1 : (n * bwMax + (n - 1) * 90 <= rw ? n : 1));
|
|
295
|
+
cols = Math.min(cols, n);
|
|
296
|
+
var labelH = 0;
|
|
297
|
+
edges.forEach(function (e) { if (e.label) labelH = Math.max(labelH, size(wrap(e.label, chars(side ? rw - bwMax / 2 - 10 : 130))).h); });
|
|
298
|
+
var gy = Math.max(64, labelH ? labelH + 28 : 0);
|
|
299
|
+
var gx = cols > 1 ? Math.max(90, Math.min(130, (rw - cols * bwMax) / (cols - 1))) : 0;
|
|
300
|
+
var totalW = cols * bwMax + (cols - 1) * gx;
|
|
301
|
+
var x0 = side === 'left' ? rx : side === 'right' ? rx + rw - totalW : rx + (rw - totalW) / 2;
|
|
302
|
+
boxes.forEach(function (b, i) {
|
|
303
|
+
var c = i % cols, r = Math.floor(i / cols), col = b.marker && MARKERS[b.marker];
|
|
304
|
+
b.w = bwMax; b.h = bhMax;
|
|
305
|
+
b.x = Math.round(x0 + c * (bwMax + gx)); b.y = Math.round(y + r * (bhMax + gy));
|
|
306
|
+
mk.push({ id: P(b.id), type: 'rectangle', x: b.x, y: b.y, width: b.w, height: b.h, backgroundColor: col ? col.fill : '#ffffff', label: { text: b.label, fontSize: FS } });
|
|
307
|
+
});
|
|
308
|
+
var rows = Math.ceil(n / cols);
|
|
309
|
+
edges.forEach(function (e) {
|
|
310
|
+
var a = ids[e.from], b = ids[e.to];
|
|
311
|
+
[[e.from, a], [e.to, b]].forEach(function (p) {
|
|
312
|
+
if (!p[1] || p[1].kind !== 'box') fail(file, e.line, '', '"' + p[0] + '" is not a box here', 'arrows join boxes; declared boxes here: ' + (boxes.map(function (x) { return x.id; }).join(', ') || 'none'));
|
|
313
|
+
});
|
|
314
|
+
var col = e.marker && MARKERS[e.marker];
|
|
315
|
+
mk.push({ id: P(e.from + '_to_' + e.to), type: 'arrow', start: { id: P(e.from) }, end: { id: P(e.to) }, strokeColor: col ? col.ink : INK, strokeWidth: 2 });
|
|
316
|
+
if (e.label) {
|
|
317
|
+
var ax = (a.x + a.w / 2 + b.x + b.w / 2) / 2, ay = (a.y + a.h / 2 + b.y + b.h / 2) / 2;
|
|
318
|
+
var vertical = Math.abs(a.x - b.x) < 4, horizontal = Math.abs(a.y - b.y) < 4;
|
|
319
|
+
var txt, s;
|
|
320
|
+
if (horizontal) {
|
|
321
|
+
var gapW = Math.abs(b.x - a.x) - bwMax;
|
|
322
|
+
txt = wrap(e.label, chars(Math.max(gapW - 8, 60))); s = size(txt);
|
|
323
|
+
mk.push({ id: mk.id('lbl'), type: 'text', x: ax - s.w / 2, y: ay - 8 - s.h, text: txt, fontSize: FS, strokeColor: col ? col.ink : INK, textAlign: 'center' });
|
|
324
|
+
} else {
|
|
325
|
+
var rightRoom = (rx + rw) - (ax + 8), leftRoom = (ax - 8) - rx;
|
|
326
|
+
var onRight = side === 'right' ? false : rightRoom >= leftRoom;
|
|
327
|
+
txt = wrap(e.label, chars(onRight ? rightRoom : leftRoom)); s = size(txt);
|
|
328
|
+
mk.push({ id: mk.id('lbl'), type: 'text', x: onRight ? ax + 14 : ax - 14 - s.w, y: ay - s.h / 2 - (vertical ? 0 : 6), text: txt, fontSize: FS, strokeColor: col ? col.ink : INK, textAlign: onRight ? 'left' : 'right' });
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
y += rows * bhMax + (rows - 1) * gy + SECTION;
|
|
333
|
+
} else if (edges.length) {
|
|
334
|
+
fail(file, edges[0].line, '', 'arrow with no boxes in this ' + (scope ? 'panel' : 'file'), 'declare the boxes first: a: box "A"');
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// 4. free text and the caption, centred
|
|
338
|
+
stats.concat(notes).forEach(function (t) {
|
|
339
|
+
var col = t.marker && MARKERS[t.marker], txt = wrap(t.text, chars(W - 2 * M)), s = size(txt);
|
|
340
|
+
mk.push({ id: mk.id('txt'), type: 'text', x: Math.round((W - s.w) / 2), y: y, text: txt, fontSize: FS, strokeColor: col ? col.ink : INK, textAlign: 'center' });
|
|
341
|
+
y += s.h + 10;
|
|
342
|
+
});
|
|
343
|
+
return { els: mk.els, h: Math.max(0, y - SECTION + 10) };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Parsed document -> element array.
|
|
347
|
+
export function sketchToElements(doc, file) {
|
|
348
|
+
var out = [];
|
|
349
|
+
var cols = Math.min(doc.cols, Math.max(1, doc.panels.length));
|
|
350
|
+
var width = doc.panels.length ? cols * PW + (cols - 1) * PGAP : 520;
|
|
351
|
+
var y = 0;
|
|
352
|
+
if (doc.title) {
|
|
353
|
+
var t = wrap(doc.title, chars(width)), s = size(t);
|
|
354
|
+
out.push({ id: 'title', type: 'text', x: Math.round((width - s.w) / 2), y: 0, text: t, fontSize: FS, textAlign: 'center' });
|
|
355
|
+
y = s.h + 18;
|
|
356
|
+
}
|
|
357
|
+
if (doc.body.length) {
|
|
358
|
+
var body = layoutBody(doc.body, width, '', doc.grid, file);
|
|
359
|
+
shift(body.els, 0, y); out = out.concat(body.els); y += body.h + 24;
|
|
360
|
+
}
|
|
361
|
+
var rows = [];
|
|
362
|
+
doc.panels.forEach(function (p, i) { (rows[Math.floor(i / cols)] = rows[Math.floor(i / cols)] || []).push(i); });
|
|
363
|
+
rows.forEach(function (row) {
|
|
364
|
+
var laid = row.map(function (i) {
|
|
365
|
+
var p = doc.panels[i];
|
|
366
|
+
var head = wrap(p.title, chars(PW - 2 * M)), hs = size(head);
|
|
367
|
+
var stmts = p.stmts.slice();
|
|
368
|
+
if (p.note) stmts.push({ kind: 'note', text: p.note, marker: null, line: p.line });
|
|
369
|
+
var body = layoutBody(stmts, PW, 'p' + (i + 1) + '_', p.grid, file);
|
|
370
|
+
return { head: head, hs: hs, body: body, top: hs.h + 22, num: i };
|
|
371
|
+
});
|
|
372
|
+
var H = Math.max.apply(null, laid.map(function (l) { return l.top + l.body.h + 16; }));
|
|
373
|
+
laid.forEach(function (l, c) {
|
|
374
|
+
var ox = c * (PW + PGAP), p = 'p' + (l.num + 1) + '_';
|
|
375
|
+
out.push({ id: p + 'frame', type: 'rectangle', x: ox, y: y, width: PW, height: H, strokeWidth: 3 });
|
|
376
|
+
out.push({ id: p + 'title', type: 'text', x: ox + Math.round((PW - l.hs.w) / 2), y: y + 9, text: l.head, fontSize: FS, textAlign: 'center' });
|
|
377
|
+
out.push({ id: p + 'rule', type: 'line', x: ox, y: y + l.top - 4, points: [[0, 0], [PW, 0]], strokeWidth: 2 });
|
|
378
|
+
shift(l.body.els, ox, y + l.top + 8);
|
|
379
|
+
out = out.concat(l.body.els);
|
|
380
|
+
});
|
|
381
|
+
y += H + PGAP;
|
|
382
|
+
});
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export function sketchToSkeleton(source, file) {
|
|
387
|
+
return sketchToElements(parseSketch(source, file), file);
|
|
388
|
+
}
|