@luutuankiet/clipboard2markdown 0.5.0 → 0.6.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 +9 -3
- package/bin/diagrams.js +22 -4
- package/bin/excalidraw.js +61 -33
- package/package.json +1 -1
- package/src/diagrams/edit.js +89 -1
- package/src/diagrams/skeleton.js +51 -1
package/README.md
CHANGED
|
@@ -44,11 +44,16 @@ c2m diagrams expand doc.md [--write] # same output as the page
|
|
|
44
44
|
c2m diagrams strip doc.md [--write]
|
|
45
45
|
c2m diagrams show '<share url>' # or a local .excalidraw file
|
|
46
46
|
c2m diagrams edit '<share url>' --ops '[{"op":"rename","node":"auth","label":"Identity"}]'
|
|
47
|
+
c2m diagrams edit '<share url>' --ops '[{"op":"style","nodes":["auth"],"set":{"backgroundColor":"#ffec99"}}]' --out auth.png
|
|
47
48
|
```
|
|
48
49
|
|
|
49
|
-
`edit` patches the existing canvas (rename, add, connect, disconnect, relabel-edge, remove), keeps every untouched element exactly as it was, uploads the result and prints exactly one new share link. The old link keeps working. Node ids are the ones `show` prints. Uploading exists only in the CLI.
|
|
50
|
+
`edit` patches the existing canvas (rename, add, connect, disconnect, relabel-edge, remove, style), keeps every untouched element exactly as it was, uploads the result and prints exactly one new share link. The old link keeps working. Node ids are the ones `show` prints. Uploading exists only in the CLI.
|
|
50
51
|
|
|
51
|
-
|
|
52
|
+
`style` picks elements by `nodes` (Mermaid ids), `type` (`rectangle`, `arrow`, `text` and so on) or both, and applies `set`: `strokeColor`, `backgroundColor`, `strokeWidth`, `strokeStyle`, `fillStyle`, `roughness` and `opacity` go on the shape or arrow; `textColor`, `fontFamily` and `fontSize` go on its label, which is refitted in its box. Unknown keys, and a filter that matches nothing, are refused.
|
|
53
|
+
|
|
54
|
+
`--out <file>.png` draws the edited diagram as a doc-ready PNG (same renderer and scale as `c2m excalidraw --png`); any other `--out` path gets the edited scene JSON. Stdout is still the new link.
|
|
55
|
+
|
|
56
|
+
**New diagram from JSON** (`c2m excalidraw`, Node 20+, any OS): an agent describes boxes, labels and arrows in a short JSON array and gets back a share link, a Mermaid preview of what it drew, and layout warnings (overlaps, labels that do not fit, crowded shapes, crossing arrows, loose arrows). `c2m excalidraw --help` is the full manual: input format, worked example, sizing rules and the check-fix-upload loop.
|
|
52
57
|
|
|
53
58
|
```bash
|
|
54
59
|
c2m excalidraw diagram.json --no-upload # check: preview + warnings only
|
|
@@ -63,9 +68,10 @@ The Mermaid is deliberately lossy: positions, colours, fonts and arrow curves ar
|
|
|
63
68
|
```bash
|
|
64
69
|
c2m excalidraw --png a.json b.json # PNGs in ~/.cache/c2m/renders/
|
|
65
70
|
c2m excalidraw --png out/ a.json # PNGs in out/
|
|
71
|
+
c2m excalidraw --out work/images/ a.json # into a working copy: 
|
|
66
72
|
```
|
|
67
73
|
|
|
68
|
-
Per diagram it writes `<name>.png` (scale 3, lowered until the image has at most 25,000,000 pixels, Google Docs' limit)
|
|
74
|
+
Per diagram it writes `<name>.png` (scale 3, lowered until the image has at most 25,000,000 pixels, Google Docs' limit), then prints the Mermaid preview, any warnings, an image line ``, an `Edit: <share link>` line (the link as plain text under the image, so it shows in the doc) and the images map entry `"<name>": "@file64:/abs/path/<name>.png"`. With `--out <folder>/images/` instead of `--png`, the PNG goes into that folder and the image line reads ``, ready for a working copy. No review PNG is written unless you pass `--review`; the preview and warnings are the check. Each run first deletes PNGs older than 24 hours in the default cache folder; a folder you name is never cleaned. CJK text is not drawn, because the 13 MB CJK font is left out of the package; such diagrams get a warning.
|
|
69
75
|
|
|
70
76
|
## Demo
|
|
71
77
|
|
package/bin/diagrams.js
CHANGED
|
@@ -21,13 +21,22 @@ const USAGE = `usage: c2m diagrams <command> [options]
|
|
|
21
21
|
strip <file.md> [--write] remove every generated block
|
|
22
22
|
show <url|file.excalidraw> print the Mermaid for one diagram
|
|
23
23
|
edit <url|file.excalidraw> (--ops '<json>' | --ops-file <path>)
|
|
24
|
-
[--show-mermaid] [--out file.excalidraw] [--no-upload]
|
|
24
|
+
[--show-mermaid] [--out file.excalidraw|file.png] [--no-upload]
|
|
25
25
|
apply edit ops, upload, print the new link
|
|
26
|
-
(--no-upload prints the resulting Mermaid instead
|
|
26
|
+
(--no-upload prints the resulting Mermaid instead;
|
|
27
|
+
--out *.png draws the edited diagram, doc-ready)
|
|
27
28
|
|
|
28
29
|
ops: [{"op":"rename","node","label"}, {"op":"add","id","label","near","side"?},
|
|
29
30
|
{"op":"connect","from","to","label"?,"dashed"?}, {"op":"disconnect","from","to"},
|
|
30
|
-
{"op":"relabel-edge","from","to","label"}, {"op":"remove","node"}
|
|
31
|
+
{"op":"relabel-edge","from","to","label"}, {"op":"remove","node"},
|
|
32
|
+
{"op":"style","nodes"?:[ids],"type"?,"set":{...}}]
|
|
33
|
+
|
|
34
|
+
style: pick elements by "nodes" (Mermaid ids), "type" (rectangle, ellipse,
|
|
35
|
+
diamond, arrow, line, text, ...) or both. "set" keys: strokeColor,
|
|
36
|
+
backgroundColor, strokeWidth, strokeStyle (solid|dashed|dotted), fillStyle
|
|
37
|
+
(hachure|cross-hatch|solid|zigzag), roughness, opacity go on the shape or
|
|
38
|
+
arrow; textColor, fontFamily, fontSize go on its label. A larger font
|
|
39
|
+
refits the label in its box.
|
|
31
40
|
`;
|
|
32
41
|
|
|
33
42
|
// Test hook: a directory standing in for json.excalidraw.com. GET reads
|
|
@@ -133,7 +142,16 @@ export async function main(argv, io) {
|
|
|
133
142
|
stderr.write('warning: embedded images do not carry over to a new share link; excalidraw.com will show placeholders until they are re-inserted (docs/traps/EDITED_LINK_LOSES_IMAGES.md)\n');
|
|
134
143
|
}
|
|
135
144
|
edited.report.forEach(function (line) { stderr.write(line + '\n'); });
|
|
136
|
-
if (args.out
|
|
145
|
+
if (args.out && /\.png$/i.test(args.out)) {
|
|
146
|
+
// Lazy: the renderer loads jsdom and Excalidraw, which the other commands never need.
|
|
147
|
+
var render = await import('../src/excalidraw-png.js');
|
|
148
|
+
var drawn = await render.renderScene(edited.scene);
|
|
149
|
+
fs.mkdirSync(path.dirname(path.resolve(args.out)), { recursive: true });
|
|
150
|
+
fs.writeFileSync(args.out, drawn.png);
|
|
151
|
+
stderr.write('wrote ' + args.out + (drawn.scale < 3 ? ' (drawn at scale ' + drawn.scale + ' to stay under 25,000,000 pixels)' : '') + '\n');
|
|
152
|
+
} else if (args.out) {
|
|
153
|
+
fs.writeFileSync(args.out, JSON.stringify(edited.scene, null, 2) + '\n');
|
|
154
|
+
}
|
|
137
155
|
if (args['show-mermaid']) stderr.write(edited.mermaid + '\n');
|
|
138
156
|
stdout.write((args['no-upload'] ? edited.mermaid : edited.url) + '\n');
|
|
139
157
|
return 0;
|
package/bin/excalidraw.js
CHANGED
|
@@ -8,6 +8,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
|
8
8
|
import { basename, resolve } from 'path';
|
|
9
9
|
import { buildSkeleton } from '../src/diagrams/skeleton.js';
|
|
10
10
|
import { saveScene } from '../src/diagrams/share-link.js';
|
|
11
|
+
import { sceneToMermaid } from '../src/diagrams/scene-to-mermaid.js';
|
|
11
12
|
|
|
12
13
|
export const EXCALIDRAW_HELP = `c2m excalidraw - turn a JSON diagram description into an excalidraw.com share link
|
|
13
14
|
|
|
@@ -17,6 +18,8 @@ Usage:
|
|
|
17
18
|
c2m excalidraw --no-upload ... check only: print preview and warnings, no link
|
|
18
19
|
c2m excalidraw --png [<dir>] <file.json>...
|
|
19
20
|
also draw each diagram as PNG (see PNG below)
|
|
21
|
+
c2m excalidraw --out <folder>/images/ <file.json>...
|
|
22
|
+
draw into a working copy's images folder
|
|
20
23
|
c2m excalidraw --help show this help
|
|
21
24
|
|
|
22
25
|
OUTPUT (stdout, in this order)
|
|
@@ -30,7 +33,8 @@ LOOP
|
|
|
30
33
|
1. Write the diagram JSON to a file.
|
|
31
34
|
2. Run: c2m excalidraw diagram.json --no-upload
|
|
32
35
|
3. Read the preview: is every box, arrow and label what you meant?
|
|
33
|
-
Read the warnings: overlaps, labels that do not fit,
|
|
36
|
+
Read the warnings: overlaps, labels that do not fit, crowded shapes,
|
|
37
|
+
crossing arrows, loose arrows.
|
|
34
38
|
4. Fix the JSON and rerun until the preview is right and warnings are gone.
|
|
35
39
|
5. Run without --no-upload and paste the link into the document.
|
|
36
40
|
Every upload makes a new link; old links keep working. The encryption key
|
|
@@ -120,35 +124,42 @@ PREVIEW
|
|
|
120
124
|
WARNINGS
|
|
121
125
|
overlap two shapes partly overlap
|
|
122
126
|
label does not fit the label's estimated size exceeds its shape minus padding
|
|
127
|
+
px apart two shapes sit closer than 30 px, edge to edge
|
|
128
|
+
cross two arrows cross that share no shape
|
|
123
129
|
not attached an arrow end has no "start"/"end"
|
|
124
130
|
points at "<id>" an arrow end names an id that is not a shape here
|
|
125
131
|
duplicate id bindings attach to the first element with that id
|
|
126
132
|
dropped unsupported type, or an MCP-only command such as
|
|
127
133
|
cameraUpdate, delete, restoreCheckpoint
|
|
128
134
|
|
|
129
|
-
PNG (for pasting into a Google Doc)
|
|
135
|
+
PNG (for pasting into a Google Doc): one command, then one write
|
|
130
136
|
c2m excalidraw --png [<dir>] a.json b.json ...
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
(
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
<dir> defaults to ~/.cache/c2m/renders/ ($XDG_CACHE_HOME/c2m/renders/);
|
|
141
|
-
each run first deletes PNGs there older than 24 h. A <dir> you name
|
|
142
|
-
never cleaned. --png=<dir> also
|
|
143
|
-
Then, per diagram:
|
|
144
|
-
|
|
145
|
-
[
|
|
146
|
-
|
|
147
|
-
|
|
137
|
+
c2m excalidraw --out <folder>/images/ a.json b.json ...
|
|
138
|
+
Builds and checks each diagram, draws it locally (no browser; the drawing
|
|
139
|
+
itself makes no network request) and uploads it for its share link as
|
|
140
|
+
above. Each input is either the element array described here or a whole
|
|
141
|
+
scene ({"elements": [...]}, e.g. a .excalidraw file). A scene's elements
|
|
142
|
+
may use the same shorthand (label, start/end, arrows without points); a
|
|
143
|
+
scene without it is drawn and uploaded as is. For each input <name>.json
|
|
144
|
+
it writes <name>.png: scale 3, lowered until the image has at most
|
|
145
|
+
25,000,000 pixels (Google Docs' limit).
|
|
146
|
+
--png <dir> defaults to ~/.cache/c2m/renders/ ($XDG_CACHE_HOME/c2m/renders/);
|
|
147
|
+
each run first deletes PNGs there older than 24 h. A <dir> you name, and
|
|
148
|
+
the --out folder, are never cleaned. --png=<dir> and --out=<dir> also work.
|
|
149
|
+
Then, per diagram, a block to paste:
|
|
150
|
+
\`\`\`mermaid ...\`\`\` the preview, as above
|
|
151
|
+
 the image line (--png)
|
|
152
|
+
 the image line (--out .../images/)
|
|
153
|
+
Edit: <share link> the link line, shown as text under
|
|
154
|
+
the image; omitted with --no-upload
|
|
155
|
+
"<name>": "@file64:/abs/path/<name>.png" the images map entry (--png only)
|
|
148
156
|
warning: ... as above, if any
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
the
|
|
157
|
+
--png: write the image line with edit_doc or create_doc, mapping <name> to
|
|
158
|
+
its @file64: pointer in "images". --out: the image line goes in the tab
|
|
159
|
+
file, and the push inserts the PNG. Check the drawing by its preview and
|
|
160
|
+
warnings; there is no picture to look at unless a human asks for one:
|
|
161
|
+
--review also write <name>.review.png (at most 1000 px on the long side)
|
|
162
|
+
and print "review: <path>" in its block.
|
|
152
163
|
Text uses Excalidraw's fonts; CJK text is not drawn (the CJK font is not
|
|
153
164
|
shipped) and gets a warning.
|
|
154
165
|
|
|
@@ -191,7 +202,10 @@ function usesShorthand(el) {
|
|
|
191
202
|
// an element array, keeping the scene's own appState and files.
|
|
192
203
|
function toScene(input) {
|
|
193
204
|
if (input && !Array.isArray(input) && Array.isArray(input.elements)) {
|
|
194
|
-
if (!input.elements.some(usesShorthand))
|
|
205
|
+
if (!input.elements.some(usesShorthand)) {
|
|
206
|
+
var read = sceneToMermaid(input);
|
|
207
|
+
return { scene: input, preview: read.text, warnings: read.warnings };
|
|
208
|
+
}
|
|
195
209
|
var built = buildSkeleton(input.elements);
|
|
196
210
|
if (input.appState) built.scene.appState = input.appState;
|
|
197
211
|
if (input.files) built.scene.files = input.files;
|
|
@@ -222,7 +236,7 @@ function looksLikeInput(a) {
|
|
|
222
236
|
export async function runExcalidraw(argv, io) {
|
|
223
237
|
var stdout = io.stdout, stderr = io.stderr;
|
|
224
238
|
var noUpload = false;
|
|
225
|
-
var png = false, pngDir = null;
|
|
239
|
+
var png = false, pngDir = null, outDir = null, review = false;
|
|
226
240
|
var targets = [];
|
|
227
241
|
for (var i = 0; i < argv.length; i++) {
|
|
228
242
|
var a = argv[i];
|
|
@@ -232,6 +246,11 @@ export async function runExcalidraw(argv, io) {
|
|
|
232
246
|
png = true;
|
|
233
247
|
if (i + 1 < argv.length && !looksLikeInput(argv[i + 1])) pngDir = argv[++i];
|
|
234
248
|
} else if (a.startsWith('--png=')) { png = true; pngDir = a.slice(6); }
|
|
249
|
+
else if (a === '--out') {
|
|
250
|
+
if (i + 1 >= argv.length) { stderr.write('c2m excalidraw: --out needs a folder\n'); return 1; }
|
|
251
|
+
png = true; outDir = argv[++i];
|
|
252
|
+
} else if (a.startsWith('--out=')) { png = true; outDir = a.slice(6); }
|
|
253
|
+
else if (a === '--review') review = true;
|
|
235
254
|
else if (a.startsWith('--')) { stderr.write('c2m excalidraw: unknown option ' + a + '\n'); return 1; }
|
|
236
255
|
else targets.push(a);
|
|
237
256
|
}
|
|
@@ -242,7 +261,8 @@ export async function runExcalidraw(argv, io) {
|
|
|
242
261
|
}
|
|
243
262
|
|
|
244
263
|
try {
|
|
245
|
-
if (png)
|
|
264
|
+
if (png && pngDir !== null && outDir !== null) throw new Error('use --png <dir> or --out <dir>, not both');
|
|
265
|
+
if (png) return await runPng(targets, { dir: outDir !== null ? outDir : pngDir, folder: outDir !== null, review: review, noUpload: noUpload }, io);
|
|
246
266
|
var built = buildSkeleton(parseJson(readInput(targets[0], io.stdin)));
|
|
247
267
|
var url = noUpload ? null : await upload(built.scene, io.fetch);
|
|
248
268
|
if (url) stdout.write(url + '\n');
|
|
@@ -266,7 +286,7 @@ async function runPng(targets, opts, io) {
|
|
|
266
286
|
// last file costs no renders.
|
|
267
287
|
var items = targets.map(function (t, k) {
|
|
268
288
|
var built = toScene(parseJson(readInput(t, io.stdin)));
|
|
269
|
-
return { name: names[k], scene: built.scene, warnings: built.warnings };
|
|
289
|
+
return { name: names[k], scene: built.scene, preview: built.preview, warnings: built.warnings };
|
|
270
290
|
});
|
|
271
291
|
|
|
272
292
|
var render = await import('../src/excalidraw-png.js');
|
|
@@ -288,21 +308,29 @@ async function runPng(targets, opts, io) {
|
|
|
288
308
|
throw new Error(it.name + ': ' + (e && e.message ? e.message : e));
|
|
289
309
|
}
|
|
290
310
|
var file = resolve(dir, it.name + '.png');
|
|
291
|
-
var reviewFile = resolve(dir, it.name + '.review.png');
|
|
311
|
+
var reviewFile = opts.review ? resolve(dir, it.name + '.review.png') : null;
|
|
292
312
|
writeFileSync(file, out.png);
|
|
293
|
-
writeFileSync(reviewFile, out.review);
|
|
313
|
+
if (reviewFile) writeFileSync(reviewFile, out.review);
|
|
294
314
|
var url = opts.noUpload ? null : await upload(it.scene, io.fetch);
|
|
295
315
|
var warnings = it.warnings.slice();
|
|
296
316
|
if (out.scale < 3) warnings.push('drawn at scale ' + out.scale + ' to stay under 25,000,000 pixels');
|
|
297
317
|
if (render.hasCjkText(it.scene)) warnings.push('CJK text is not drawn: the CJK font is not shipped');
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
318
|
+
// Folder path: the image line points into the folder the PNG sits in,
|
|
319
|
+
// relative to its parent (./images/<name>.png for --out work/images/),
|
|
320
|
+
// which is how a working copy's push finds a new image.
|
|
321
|
+
var target = opts.folder ? './' + basename(dir) + '/' + it.name + '.png' : 'attach:' + it.name;
|
|
322
|
+
var lines = [];
|
|
323
|
+
if (it.preview) lines.push('```mermaid\n' + it.preview + '\n```');
|
|
324
|
+
lines.push('');
|
|
325
|
+
// The share link sits as a plain text line under the image, so it shows in
|
|
326
|
+
// the doc: no API request sets an image's alt text, and a link hidden
|
|
327
|
+
// behind words is easy to miss.
|
|
328
|
+
if (url) lines.push('Edit: ' + url);
|
|
329
|
+
if (!opts.folder) lines.push(JSON.stringify(it.name) + ': ' + JSON.stringify('@file64:' + file));
|
|
330
|
+
if (reviewFile) lines.push('review: ' + reviewFile);
|
|
302
331
|
warnings.forEach(function (w) { lines.push('warning: ' + w); });
|
|
303
332
|
blocks.push(lines.join('\n') + '\n');
|
|
304
333
|
}
|
|
305
334
|
stdout.write(blocks.join('\n'));
|
|
306
|
-
stdout.write('\nCheck a drawing by its Mermaid preview first (c2m excalidraw <file> --no-upload, or c2m diagrams show <file> for a whole scene); open the review PNG only if that is not enough.\n');
|
|
307
335
|
return 0;
|
|
308
336
|
}
|
package/package.json
CHANGED
package/src/diagrams/edit.js
CHANGED
|
@@ -23,6 +23,7 @@ const OP_FIELDS = {
|
|
|
23
23
|
disconnect: ['from', 'to'],
|
|
24
24
|
'relabel-edge': ['from', 'to', 'label'],
|
|
25
25
|
remove: ['node'],
|
|
26
|
+
style: [],
|
|
26
27
|
};
|
|
27
28
|
|
|
28
29
|
function randomInt() { return Math.floor(Math.random() * 2 ** 31); }
|
|
@@ -469,7 +470,94 @@ function opRemove(scene, model, op) {
|
|
|
469
470
|
removeElements(scene, ids);
|
|
470
471
|
}
|
|
471
472
|
|
|
472
|
-
|
|
473
|
+
// Keys a style op may set. Shape keys go on the matched shape or arrow; label
|
|
474
|
+
// keys go on its label text (or on a matched text element itself). textColor
|
|
475
|
+
// is the label's strokeColor, named apart so it never collides with the shape's.
|
|
476
|
+
const STYLE_KEYS = {
|
|
477
|
+
strokeColor: 'shape', backgroundColor: 'shape', strokeWidth: 'shape', strokeStyle: 'shape',
|
|
478
|
+
fillStyle: 'shape', roughness: 'shape', opacity: 'shape',
|
|
479
|
+
textColor: 'label', fontFamily: 'label', fontSize: 'label',
|
|
480
|
+
};
|
|
481
|
+
const STYLE_ENUMS = {
|
|
482
|
+
strokeStyle: ['solid', 'dashed', 'dotted'],
|
|
483
|
+
fillStyle: ['hachure', 'cross-hatch', 'solid', 'zigzag'],
|
|
484
|
+
};
|
|
485
|
+
const STYLE_STRINGS = ['strokeColor', 'backgroundColor', 'textColor'];
|
|
486
|
+
|
|
487
|
+
function checkStyleSet(set) {
|
|
488
|
+
if (!set || typeof set !== 'object' || Array.isArray(set) || !Object.keys(set).length) {
|
|
489
|
+
throw new Error('"set" must be an object with at least one of: ' + Object.keys(STYLE_KEYS).join(', '));
|
|
490
|
+
}
|
|
491
|
+
Object.keys(set).forEach(function (k) {
|
|
492
|
+
var v = set[k];
|
|
493
|
+
if (!STYLE_KEYS[k]) throw new Error('unknown style key "' + k + '"; valid keys: ' + Object.keys(STYLE_KEYS).join(', '));
|
|
494
|
+
if (STYLE_ENUMS[k]) {
|
|
495
|
+
if (STYLE_ENUMS[k].indexOf(v) < 0) throw new Error(k + ' must be one of ' + STYLE_ENUMS[k].join(', '));
|
|
496
|
+
} else if (STYLE_STRINGS.indexOf(k) >= 0) {
|
|
497
|
+
if (typeof v !== 'string' || !v) throw new Error(k + ' must be a colour string such as "#e03131"');
|
|
498
|
+
} else if (typeof v !== 'number' || !isFinite(v) || v < 0) {
|
|
499
|
+
throw new Error(k + ' must be a non-negative number');
|
|
500
|
+
}
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// The label text elements of a shape or arrow, as the reader sees them.
|
|
505
|
+
function labelElsOf(model, el) {
|
|
506
|
+
var item = model.nodes.get(el.id) || model.groups.get(el.id);
|
|
507
|
+
if (item) return item.label ? item.label.els : [];
|
|
508
|
+
var edge = model.edges.find(function (e) { return e.el.id === el.id; });
|
|
509
|
+
return edge && edge.label ? edge.label.els : [];
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function opStyle(scene, model, op) {
|
|
513
|
+
checkStyleSet(op.set);
|
|
514
|
+
if (op.nodes == null && op.type == null) throw new Error('needs "nodes", "type" or both to pick elements');
|
|
515
|
+
if (op.nodes != null && (!Array.isArray(op.nodes) || !op.nodes.length || op.nodes.some(function (n) { return typeof n !== 'string'; }))) {
|
|
516
|
+
throw new Error('"nodes" must be a non-empty array of ids');
|
|
517
|
+
}
|
|
518
|
+
if (op.type != null && (typeof op.type !== 'string' || !op.type)) throw new Error('"type" must be an element type such as "rectangle" or "arrow"');
|
|
519
|
+
var matched = op.nodes
|
|
520
|
+
? op.nodes.map(function (id) { return resolve(model, id, 'nodes', true).el; })
|
|
521
|
+
: scene.elements.filter(function (el) { return !el.isDeleted; });
|
|
522
|
+
if (op.type) matched = matched.filter(function (el) { return el.type === op.type; });
|
|
523
|
+
if (!matched.length) throw new Error('the filter matches no element');
|
|
524
|
+
|
|
525
|
+
var keys = Object.keys(op.set);
|
|
526
|
+
var count = 0;
|
|
527
|
+
matched.forEach(function (el) {
|
|
528
|
+
var own = el.type === 'text';
|
|
529
|
+
var shapeKeys = keys.filter(function (k) { return own || STYLE_KEYS[k] === 'shape'; });
|
|
530
|
+
var labelKeys = keys.filter(function (k) { return STYLE_KEYS[k] === 'label'; });
|
|
531
|
+
if (!own && shapeKeys.length) {
|
|
532
|
+
shapeKeys.forEach(function (k) { el[k] = op.set[k]; });
|
|
533
|
+
touch(el);
|
|
534
|
+
count++;
|
|
535
|
+
}
|
|
536
|
+
var texts = own ? [el] : labelKeys.length ? labelElsOf(model, el) : [];
|
|
537
|
+
texts.forEach(function (t) {
|
|
538
|
+
(own ? keys : labelKeys).forEach(function (k) {
|
|
539
|
+
if (k === 'textColor') t.strokeColor = op.set[k];
|
|
540
|
+
else if (STYLE_KEYS[k] === 'label' || own) t[k] = op.set[k];
|
|
541
|
+
});
|
|
542
|
+
if (op.set.fontSize != null) {
|
|
543
|
+
var container = t.containerId ? scene.elements.find(function (c) { return c.id === t.containerId; }) : null;
|
|
544
|
+
if (container) fitBoundText(t, container);
|
|
545
|
+
else {
|
|
546
|
+
var c = center(t);
|
|
547
|
+
fitBoundText(t, null);
|
|
548
|
+
t.x = c[0] - t.width / 2;
|
|
549
|
+
t.y = c[1] - t.height / 2;
|
|
550
|
+
}
|
|
551
|
+
} else {
|
|
552
|
+
touch(t);
|
|
553
|
+
}
|
|
554
|
+
count++;
|
|
555
|
+
});
|
|
556
|
+
});
|
|
557
|
+
return 'styled ' + count + ' element' + (count === 1 ? '' : 's');
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
const OPS = { rename: opRename, add: opAdd, connect: opConnect, disconnect: opDisconnect, 'relabel-edge': opRelabelEdge, remove: opRemove, style: opStyle };
|
|
473
561
|
|
|
474
562
|
function checkShape(op, index) {
|
|
475
563
|
if (!op || typeof op !== 'object') throw new Error('op ' + index + ' is not an object');
|
package/src/diagrams/skeleton.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import { measureText, containerFactor, TEXT_METRICS } from './edit.js';
|
|
9
9
|
import { sceneToMermaid } from './scene-to-mermaid.js';
|
|
10
|
-
import { bounds, TUNING } from './scene-model.js';
|
|
10
|
+
import { absolutePoints, bounds, TUNING } from './scene-model.js';
|
|
11
11
|
|
|
12
12
|
const SHAPES = new Set(['rectangle', 'ellipse', 'diamond']);
|
|
13
13
|
const LINEAR = new Set(['arrow', 'line']);
|
|
@@ -324,6 +324,36 @@ function contains(outer, inner) {
|
|
|
324
324
|
return inner.x >= outer.x && inner.y >= outer.y && inner.x + inner.w <= outer.x + outer.w && inner.y + inner.h <= outer.y + outer.h;
|
|
325
325
|
}
|
|
326
326
|
|
|
327
|
+
// Shapes closer than this, edge to edge, read as one blob at document width.
|
|
328
|
+
// Well under the 120 px the help asks for between joined shapes, so only a
|
|
329
|
+
// layout that is clearly cramped is warned about.
|
|
330
|
+
export const CROWDED_GAP = 30;
|
|
331
|
+
|
|
332
|
+
// Edge-to-edge distance between two boxes that do not overlap.
|
|
333
|
+
function gapBetween(a, b) {
|
|
334
|
+
var dx = Math.max(0, Math.max(a.x, b.x) - Math.min(a.x + a.w, b.x + b.w));
|
|
335
|
+
var dy = Math.max(0, Math.max(a.y, b.y) - Math.min(a.y + a.h, b.y + b.h));
|
|
336
|
+
return Math.sqrt(dx * dx + dy * dy);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Do segments p1-p2 and q1-q2 cross at a point inside both? Touching or
|
|
340
|
+
// collinear segments do not count.
|
|
341
|
+
function segmentsCross(p1, p2, q1, q2) {
|
|
342
|
+
function side(a, b, c) { return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); }
|
|
343
|
+
var d1 = side(q1, q2, p1), d2 = side(q1, q2, p2), d3 = side(p1, p2, q1), d4 = side(p1, p2, q2);
|
|
344
|
+
return d1 * d2 < 0 && d3 * d4 < 0;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function pathsCross(a, b) {
|
|
348
|
+
var pa = absolutePoints(a), pb = absolutePoints(b);
|
|
349
|
+
for (var i = 0; i + 1 < pa.length; i++) {
|
|
350
|
+
for (var j = 0; j + 1 < pb.length; j++) {
|
|
351
|
+
if (segmentsCross(pa[i], pa[i + 1], pb[j], pb[j + 1])) return true;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return false;
|
|
355
|
+
}
|
|
356
|
+
|
|
327
357
|
export function lintSkeleton(normalized) {
|
|
328
358
|
var warnings = [];
|
|
329
359
|
var elements = normalized.scene.elements;
|
|
@@ -341,6 +371,12 @@ export function lintSkeleton(normalized) {
|
|
|
341
371
|
var a = box(shapes[i]), b = box(shapes[j]);
|
|
342
372
|
if (overlapArea(a, b) && !contains(a, b) && !contains(b, a)) {
|
|
343
373
|
warnings.push('"' + shapes[i].id + '" and "' + shapes[j].id + '" overlap; move them apart or nest one fully inside the other');
|
|
374
|
+
} else if (SHAPES.has(shapes[i].type) && SHAPES.has(shapes[j].type) && !overlapArea(a, b)) {
|
|
375
|
+
var gap = gapBetween(a, b);
|
|
376
|
+
if (gap < CROWDED_GAP) {
|
|
377
|
+
warnings.push('"' + shapes[i].id + '" and "' + shapes[j].id + '" are ' + Math.round(gap) + ' px apart; leave at least ' +
|
|
378
|
+
CROWDED_GAP + ' px (120 px if an arrow joins them)');
|
|
379
|
+
}
|
|
344
380
|
}
|
|
345
381
|
}
|
|
346
382
|
}
|
|
@@ -374,6 +410,20 @@ export function lintSkeleton(normalized) {
|
|
|
374
410
|
});
|
|
375
411
|
});
|
|
376
412
|
|
|
413
|
+
// Two arrows that share a shape meet there by design; only a crossing
|
|
414
|
+
// between unrelated arrows is a tangle.
|
|
415
|
+
var arrows = normalized.arrows.filter(function (a) { return a.el.type === 'arrow' || a.el.type === 'line'; });
|
|
416
|
+
for (var x = 0; x < arrows.length; x++) {
|
|
417
|
+
for (var y = x + 1; y < arrows.length; y++) {
|
|
418
|
+
var p = arrows[x], q = arrows[y];
|
|
419
|
+
var ends = [p.from, p.to].filter(Boolean);
|
|
420
|
+
if ([q.from, q.to].some(function (e) { return e && ends.indexOf(e) !== -1; })) continue;
|
|
421
|
+
if (pathsCross(p.el, q.el)) {
|
|
422
|
+
warnings.push('arrows "' + p.el.id + '" and "' + q.el.id + '" cross; move a shape or route one around with "points"');
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
377
427
|
return warnings;
|
|
378
428
|
}
|
|
379
429
|
|