@luutuankiet/clipboard2markdown 0.4.1 → 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 +84 -36
- package/package.json +1 -1
- package/src/diagrams/edit.js +89 -1
- package/src/diagrams/skeleton.js +130 -10
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
|
|
@@ -39,7 +43,7 @@ LOOP
|
|
|
39
43
|
INPUT: a JSON array of elements
|
|
40
44
|
[
|
|
41
45
|
{"id": "api", "type": "rectangle", "x": 0, "y": 0, "width": 160, "height": 70,
|
|
42
|
-
"label": {"text": "API"}
|
|
46
|
+
"label": {"text": "API"}},
|
|
43
47
|
{"id": "db", "type": "ellipse", "x": 300, "y": 0, "width": 200, "height": 80,
|
|
44
48
|
"label": {"text": "Postgres"}},
|
|
45
49
|
{"id": "ok", "type": "diamond", "x": 280, "y": 180, "width": 240, "height": 120,
|
|
@@ -67,7 +71,11 @@ ELEMENTS
|
|
|
67
71
|
FIELDS (all optional unless noted above)
|
|
68
72
|
label {"text": "...", "fontSize": 20} or just "..." on shapes and
|
|
69
73
|
arrows; rendered as text centred in the shape / on the arrow.
|
|
70
|
-
|
|
74
|
+
A group box (a shape fully containing another) puts its
|
|
75
|
+
label top-left instead. Override with "textAlign" (left,
|
|
76
|
+
center, right) and "verticalAlign" (top, middle, bottom)
|
|
77
|
+
inside label. Use "\\n" for line breaks; labels are not
|
|
78
|
+
wrapped for you.
|
|
71
79
|
start, end {"id": "<shape id>"} on arrows and lines. The arrow stays
|
|
72
80
|
attached when someone drags the shape in excalidraw.com.
|
|
73
81
|
MCP style also works: "startBinding": {"elementId": "<id>"}.
|
|
@@ -88,9 +96,25 @@ SIZING AND SPACING (rules of thumb, font size 20)
|
|
|
88
96
|
- Ellipse needs ~1.4x that, diamond ~2x, in both directions.
|
|
89
97
|
- Leave >= 120 px between shapes that an arrow joins, more if it has a label.
|
|
90
98
|
- A large rectangle drawn first and fully containing others works as a group
|
|
91
|
-
box: full containment is fine, partial overlap is warned about.
|
|
99
|
+
box: full containment is fine, partial overlap is warned about. Give it a
|
|
100
|
+
"label" for its title (drawn top-left); do not fake one with a text
|
|
101
|
+
element, or the preview loses the group's name. Leave ~40 px above the
|
|
102
|
+
first row inside for the title.
|
|
92
103
|
- Lay out on a grid: rows every ~150 px, columns every ~250 px.
|
|
93
104
|
|
|
105
|
+
STYLE (the default look; the user's own styling instructions win)
|
|
106
|
+
1. Plan all white: every node #ffffff solid fill, #1e1e1e stroke, default
|
|
107
|
+
width, roughness and font. Group boxes: thin grey stroke (#868e96, width
|
|
108
|
+
1) and a "label" title. Fix layout, text and arrows here; never deliver it.
|
|
109
|
+
2. Deliver a highlight pass: same positions, text and arrows. Change only
|
|
110
|
+
fill colour, fillStyle, dashed strokes or shape, to mark the point.
|
|
111
|
+
Colour means emphasis only, no fixed palette, at most 3 colours. One
|
|
112
|
+
highlighted node is fine. Add a key (labelled boxes no arrow touches, at the
|
|
113
|
+
top or right) whenever a colour or dash carries meaning.
|
|
114
|
+
Arrow labels: optional, at most 2 words, no ids, brackets or line breaks.
|
|
115
|
+
Full guide with examples:
|
|
116
|
+
https://github.com/luutuankiet/clipboard2markdown/blob/master/docs/reference/diagram-style.md
|
|
117
|
+
|
|
94
118
|
PREVIEW
|
|
95
119
|
rectangle -> id[label] ellipse -> id((label)) diamond -> id{label}
|
|
96
120
|
An arrow bound at both ends -> edge with its label. A shape fully inside a
|
|
@@ -100,35 +124,42 @@ PREVIEW
|
|
|
100
124
|
WARNINGS
|
|
101
125
|
overlap two shapes partly overlap
|
|
102
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
|
|
103
129
|
not attached an arrow end has no "start"/"end"
|
|
104
130
|
points at "<id>" an arrow end names an id that is not a shape here
|
|
105
131
|
duplicate id bindings attach to the first element with that id
|
|
106
132
|
dropped unsupported type, or an MCP-only command such as
|
|
107
133
|
cameraUpdate, delete, restoreCheckpoint
|
|
108
134
|
|
|
109
|
-
PNG (for pasting into a Google Doc)
|
|
135
|
+
PNG (for pasting into a Google Doc): one command, then one write
|
|
110
136
|
c2m excalidraw --png [<dir>] a.json b.json ...
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
(
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
<dir> defaults to ~/.cache/c2m/renders/ ($XDG_CACHE_HOME/c2m/renders/);
|
|
121
|
-
each run first deletes PNGs there older than 24 h. A <dir> you name
|
|
122
|
-
never cleaned. --png=<dir> also
|
|
123
|
-
Then, per diagram:
|
|
124
|
-
|
|
125
|
-
[
|
|
126
|
-
|
|
127
|
-
|
|
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)
|
|
128
156
|
warning: ... as above, if any
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
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.
|
|
132
163
|
Text uses Excalidraw's fonts; CJK text is not drawn (the CJK font is not
|
|
133
164
|
shipped) and gets a warning.
|
|
134
165
|
|
|
@@ -171,7 +202,10 @@ function usesShorthand(el) {
|
|
|
171
202
|
// an element array, keeping the scene's own appState and files.
|
|
172
203
|
function toScene(input) {
|
|
173
204
|
if (input && !Array.isArray(input) && Array.isArray(input.elements)) {
|
|
174
|
-
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
|
+
}
|
|
175
209
|
var built = buildSkeleton(input.elements);
|
|
176
210
|
if (input.appState) built.scene.appState = input.appState;
|
|
177
211
|
if (input.files) built.scene.files = input.files;
|
|
@@ -202,7 +236,7 @@ function looksLikeInput(a) {
|
|
|
202
236
|
export async function runExcalidraw(argv, io) {
|
|
203
237
|
var stdout = io.stdout, stderr = io.stderr;
|
|
204
238
|
var noUpload = false;
|
|
205
|
-
var png = false, pngDir = null;
|
|
239
|
+
var png = false, pngDir = null, outDir = null, review = false;
|
|
206
240
|
var targets = [];
|
|
207
241
|
for (var i = 0; i < argv.length; i++) {
|
|
208
242
|
var a = argv[i];
|
|
@@ -212,6 +246,11 @@ export async function runExcalidraw(argv, io) {
|
|
|
212
246
|
png = true;
|
|
213
247
|
if (i + 1 < argv.length && !looksLikeInput(argv[i + 1])) pngDir = argv[++i];
|
|
214
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;
|
|
215
254
|
else if (a.startsWith('--')) { stderr.write('c2m excalidraw: unknown option ' + a + '\n'); return 1; }
|
|
216
255
|
else targets.push(a);
|
|
217
256
|
}
|
|
@@ -222,7 +261,8 @@ export async function runExcalidraw(argv, io) {
|
|
|
222
261
|
}
|
|
223
262
|
|
|
224
263
|
try {
|
|
225
|
-
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);
|
|
226
266
|
var built = buildSkeleton(parseJson(readInput(targets[0], io.stdin)));
|
|
227
267
|
var url = noUpload ? null : await upload(built.scene, io.fetch);
|
|
228
268
|
if (url) stdout.write(url + '\n');
|
|
@@ -246,7 +286,7 @@ async function runPng(targets, opts, io) {
|
|
|
246
286
|
// last file costs no renders.
|
|
247
287
|
var items = targets.map(function (t, k) {
|
|
248
288
|
var built = toScene(parseJson(readInput(t, io.stdin)));
|
|
249
|
-
return { name: names[k], scene: built.scene, warnings: built.warnings };
|
|
289
|
+
return { name: names[k], scene: built.scene, preview: built.preview, warnings: built.warnings };
|
|
250
290
|
});
|
|
251
291
|
|
|
252
292
|
var render = await import('../src/excalidraw-png.js');
|
|
@@ -268,21 +308,29 @@ async function runPng(targets, opts, io) {
|
|
|
268
308
|
throw new Error(it.name + ': ' + (e && e.message ? e.message : e));
|
|
269
309
|
}
|
|
270
310
|
var file = resolve(dir, it.name + '.png');
|
|
271
|
-
var reviewFile = resolve(dir, it.name + '.review.png');
|
|
311
|
+
var reviewFile = opts.review ? resolve(dir, it.name + '.review.png') : null;
|
|
272
312
|
writeFileSync(file, out.png);
|
|
273
|
-
writeFileSync(reviewFile, out.review);
|
|
313
|
+
if (reviewFile) writeFileSync(reviewFile, out.review);
|
|
274
314
|
var url = opts.noUpload ? null : await upload(it.scene, io.fetch);
|
|
275
315
|
var warnings = it.warnings.slice();
|
|
276
316
|
if (out.scale < 3) warnings.push('drawn at scale ' + out.scale + ' to stay under 25,000,000 pixels');
|
|
277
317
|
if (render.hasCjkText(it.scene)) warnings.push('CJK text is not drawn: the CJK font is not shipped');
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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);
|
|
282
331
|
warnings.forEach(function (w) { lines.push('warning: ' + w); });
|
|
283
332
|
blocks.push(lines.join('\n') + '\n');
|
|
284
333
|
}
|
|
285
334
|
stdout.write(blocks.join('\n'));
|
|
286
|
-
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');
|
|
287
335
|
return 0;
|
|
288
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 } 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']);
|
|
@@ -16,15 +16,31 @@ const MCP_PSEUDO = new Set(['cameraUpdate', 'delete', 'restoreCheckpoint']);
|
|
|
16
16
|
// Skeleton-only fields that must not leak into the scene.
|
|
17
17
|
const SKELETON_FIELDS = ['label', 'start', 'end'];
|
|
18
18
|
const BINDING_GAP = 4;
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
// Excalidraw's own inset for bound text (BOUND_TEXT_PADDING); using the same
|
|
20
|
+
// value means the editor does not move a title when the scene is opened.
|
|
21
|
+
const BOUND_TEXT_PADDING = 5;
|
|
22
|
+
const TEXT_ALIGNS = new Set(['left', 'center', 'right']);
|
|
23
|
+
const VERTICAL_ALIGNS = new Set(['top', 'middle', 'bottom']);
|
|
24
|
+
|
|
25
|
+
// FNV-1a over the element id. `seed` drives the hand-drawn wobble, so deriving
|
|
26
|
+
// it from the id makes the same diagram draw the same way on every run; a
|
|
27
|
+
// random seed made two renders of one diagram not line up. Never 0: rough.js
|
|
28
|
+
// falls back to Math.random for a zero seed.
|
|
29
|
+
function seedFromId(id, salt) {
|
|
30
|
+
var s = salt + String(id), h = 0x811c9dc5;
|
|
31
|
+
for (var i = 0; i < s.length; i++) {
|
|
32
|
+
h ^= s.charCodeAt(i);
|
|
33
|
+
h = Math.imul(h, 0x01000193);
|
|
34
|
+
}
|
|
35
|
+
return ((h >>> 0) % 2147483646) + 1;
|
|
36
|
+
}
|
|
21
37
|
|
|
22
38
|
function base(type, id) {
|
|
23
39
|
return {
|
|
24
40
|
id: id, type: type, x: 0, y: 0, width: 0, height: 0, angle: 0,
|
|
25
41
|
strokeColor: '#1e1e1e', backgroundColor: 'transparent', fillStyle: 'solid', strokeWidth: 2,
|
|
26
42
|
strokeStyle: 'solid', roughness: 1, opacity: 100, groupIds: [], frameId: null, roundness: null,
|
|
27
|
-
seed:
|
|
43
|
+
seed: seedFromId(id, ''), version: 1, versionNonce: seedFromId(id, 'nonce:'), isDeleted: false, boundElements: null,
|
|
28
44
|
updated: Date.now(), link: null, locked: false,
|
|
29
45
|
};
|
|
30
46
|
}
|
|
@@ -102,6 +118,42 @@ function fitLinear(el) {
|
|
|
102
118
|
el.height = Math.max.apply(null, ys) - Math.min.apply(null, ys);
|
|
103
119
|
}
|
|
104
120
|
|
|
121
|
+
function pickAlign(fromLabel, fromShape, allowed) {
|
|
122
|
+
if (allowed.has(fromLabel)) return fromLabel;
|
|
123
|
+
if (allowed.has(fromShape)) return fromShape;
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Same test the Mermaid reader uses for a subgraph: the shape fully encloses
|
|
128
|
+
// another shape and is bigger than it.
|
|
129
|
+
function encloses(shape, shapes) {
|
|
130
|
+
var outer = { x: shape.x, y: shape.y, w: shape.width, h: shape.height };
|
|
131
|
+
return shapes.some(function (o) {
|
|
132
|
+
if (o === shape) return false;
|
|
133
|
+
var inner = { x: o.x, y: o.y, w: o.width, h: o.height };
|
|
134
|
+
var k = TUNING.containmentSlack;
|
|
135
|
+
return contains({ x: outer.x - k, y: outer.y - k, w: outer.w + 2 * k, h: outer.h + 2 * k }, inner) &&
|
|
136
|
+
outer.w * outer.h > inner.w * inner.h;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Excalidraw's computeBoundTextPosition, so the text sits where the editor
|
|
141
|
+
// itself would put it for this alignment.
|
|
142
|
+
function placeInShape(t, shape) {
|
|
143
|
+
var ox = BOUND_TEXT_PADDING, oy = BOUND_TEXT_PADDING;
|
|
144
|
+
if (shape.type === 'ellipse') {
|
|
145
|
+
ox += (shape.width / 2) * (1 - Math.SQRT1_2);
|
|
146
|
+
oy += (shape.height / 2) * (1 - Math.SQRT1_2);
|
|
147
|
+
} else if (shape.type === 'diamond') {
|
|
148
|
+
ox += shape.width / 4;
|
|
149
|
+
oy += shape.height / 4;
|
|
150
|
+
}
|
|
151
|
+
var availW = shape.width - 2 * ox, availH = shape.height - 2 * oy;
|
|
152
|
+
var x0 = shape.x + ox, y0 = shape.y + oy;
|
|
153
|
+
t.x = t.textAlign === 'left' ? x0 : t.textAlign === 'right' ? x0 + availW - t.width : x0 + (availW - t.width) / 2;
|
|
154
|
+
t.y = t.verticalAlign === 'top' ? y0 : t.verticalAlign === 'bottom' ? y0 + availH - t.height : y0 + (availH - t.height) / 2;
|
|
155
|
+
}
|
|
156
|
+
|
|
105
157
|
// Throws on input that cannot become a scene at all; everything recoverable is
|
|
106
158
|
// a warning instead, so the agent still gets a link.
|
|
107
159
|
export function normalizeSkeleton(input) {
|
|
@@ -175,7 +227,11 @@ export function normalizeSkeleton(input) {
|
|
|
175
227
|
|
|
176
228
|
var label = labelOf(raw);
|
|
177
229
|
if (label && (SHAPES.has(raw.type) || LINEAR.has(raw.type))) {
|
|
178
|
-
labels.push({
|
|
230
|
+
labels.push({
|
|
231
|
+
container: el, text: String(label.text), fontSize: label.fontSize || raw.fontSize || 20, strokeColor: label.strokeColor || raw.strokeColor,
|
|
232
|
+
textAlign: pickAlign(label.textAlign, raw.textAlign, TEXT_ALIGNS),
|
|
233
|
+
verticalAlign: pickAlign(label.verticalAlign, raw.verticalAlign, VERTICAL_ALIGNS),
|
|
234
|
+
});
|
|
179
235
|
}
|
|
180
236
|
elements.push(el);
|
|
181
237
|
if (!byId.has(id)) byId.set(id, el);
|
|
@@ -211,17 +267,31 @@ export function normalizeSkeleton(input) {
|
|
|
211
267
|
a.to = to;
|
|
212
268
|
});
|
|
213
269
|
|
|
214
|
-
// Labels become bound text
|
|
270
|
+
// Labels become bound text. A container (a shape that encloses another shape,
|
|
271
|
+
// which the Mermaid preview reads as a subgraph) gets its title in the top-left
|
|
272
|
+
// corner so it stays clear of the boxes inside; any other shape, and every
|
|
273
|
+
// arrow, gets its label centred. An explicit textAlign / verticalAlign wins.
|
|
274
|
+
var shapeEls = elements.filter(function (e) { return SHAPES.has(e.type); });
|
|
215
275
|
var usedIds = new Set(elements.map(function (e) { return e.id; }));
|
|
216
276
|
labels.forEach(function (l) {
|
|
217
277
|
var id = l.container.id + '-label';
|
|
218
278
|
for (var n = 2; usedIds.has(id); n++) id = l.container.id + '-label' + n;
|
|
219
279
|
usedIds.add(id);
|
|
220
|
-
var
|
|
280
|
+
var linear = LINEAR.has(l.container.type);
|
|
281
|
+
var isContainer = !linear && encloses(l.container, shapeEls);
|
|
282
|
+
var t = textElement(id, l.text, l.fontSize, {
|
|
283
|
+
textAlign: linear ? 'center' : l.textAlign || (isContainer ? 'left' : 'center'),
|
|
284
|
+
verticalAlign: linear ? 'middle' : l.verticalAlign || (isContainer ? 'top' : 'middle'),
|
|
285
|
+
containerId: l.container.id,
|
|
286
|
+
});
|
|
221
287
|
if (l.strokeColor) t.strokeColor = l.strokeColor;
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
288
|
+
if (linear) {
|
|
289
|
+
var c = arrowMidpoint(l.container);
|
|
290
|
+
t.x = c[0] - t.width / 2;
|
|
291
|
+
t.y = c[1] - t.height / 2;
|
|
292
|
+
} else {
|
|
293
|
+
placeInShape(t, l.container);
|
|
294
|
+
}
|
|
225
295
|
addBound(l.container, { id: id, type: 'text' });
|
|
226
296
|
elements.push(t);
|
|
227
297
|
});
|
|
@@ -254,6 +324,36 @@ function contains(outer, inner) {
|
|
|
254
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;
|
|
255
325
|
}
|
|
256
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
|
+
|
|
257
357
|
export function lintSkeleton(normalized) {
|
|
258
358
|
var warnings = [];
|
|
259
359
|
var elements = normalized.scene.elements;
|
|
@@ -271,6 +371,12 @@ export function lintSkeleton(normalized) {
|
|
|
271
371
|
var a = box(shapes[i]), b = box(shapes[j]);
|
|
272
372
|
if (overlapArea(a, b) && !contains(a, b) && !contains(b, a)) {
|
|
273
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
|
+
}
|
|
274
380
|
}
|
|
275
381
|
}
|
|
276
382
|
}
|
|
@@ -304,6 +410,20 @@ export function lintSkeleton(normalized) {
|
|
|
304
410
|
});
|
|
305
411
|
});
|
|
306
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
|
+
|
|
307
427
|
return warnings;
|
|
308
428
|
}
|
|
309
429
|
|