@luutuankiet/clipboard2markdown 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/bin/cli.js +6 -0
- package/bin/excalidraw.js +151 -17
- package/package.json +1 -1
- package/src/diagrams/skeleton.js +10 -5
- package/src/doodle.js +225 -0
- package/src/excalidraw-png.js +92 -5
- package/src/lint.js +239 -0
- package/src/mermaid-input.js +178 -0
- package/vendor/excalidraw/excalidraw.bundle.mjs +285 -285
package/README.md
CHANGED
|
@@ -73,6 +73,25 @@ c2m excalidraw --out work/images/ a.json # into a working copy: , 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.
|
|
75
75
|
|
|
76
|
+
**Mermaid in, Excalidraw out** (`c2m excalidraw <file>.mmd`): a Mermaid file goes through the same command and gives the same outputs (link, PNG, paste block), drawn by Mermaid's layout as Excalidraw shapes in the house style. Flowcharts and sequence diagrams become editable boxes and arrows; other diagram types come out as one picture, with a warning.
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
c2m excalidraw --png flow.mmd # PNG + link + paste block
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**Lint and `--strict`** (every input): the finished scene is checked for a node sticking out of its subgraph frame, overlapping nodes, a literal `<br>` shown as text, unbound or floating arrows, text wider than its box, and text that would print under 8 pt at page width (468 pt, change with `--page-pt`). Findings print as `warning: lint ...` lines. `--strict` turns any error into exit 1 with no PNG and no link; `c2m lint <file>...` (or `c2m excalidraw --lint-only`) only checks. Mermaid input also turns `<br>` into line breaks, redraws `flowchart LR` / `graph LR` as TD (with a warning) and fits subgraph frames around their nodes.
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
c2m lint flow.mmd shot.json # check only; exit 1 on an error
|
|
86
|
+
c2m excalidraw --png --strict flow.mmd # draw only if the lint is clean
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
**Annotated screenshots** (doodles): a JSON object naming a PNG or JPEG and a list of notes, each with a `target` point `[x, y]` or box `[x, y, w, h]` in the image's pixels and an optional `side`. Notes go in the margins in Excalidraw's hand font, never on the picture or on each other, with a curved arrow to each target. The share link opens without the picture (excalidraw.com stores pictures apart from the link); the PNG is complete. Full spec in `c2m excalidraw --help`, section DOODLE.
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
c2m excalidraw --png shot.doodle.json # {"image": "shot.png", "notes": [{"text": "...", "target": [10, 20, 300, 40]}]}
|
|
93
|
+
```
|
|
94
|
+
|
|
76
95
|
## Demo
|
|
77
96
|
|
|
78
97
|
**Live:** https://luutuankiet.github.io/clipboard2markdown/
|
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
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
// step with src/diagrams/skeleton.js.
|
|
6
6
|
|
|
7
7
|
import { mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
8
|
-
import { basename, resolve } from 'path';
|
|
8
|
+
import { basename, dirname, resolve } from 'path';
|
|
9
9
|
import { buildSkeleton } from '../src/diagrams/skeleton.js';
|
|
10
10
|
import { saveScene } from '../src/diagrams/share-link.js';
|
|
11
11
|
import { sceneToMermaid } from '../src/diagrams/scene-to-mermaid.js';
|
|
12
|
+
import { lintScene, formatFinding, hasErrors, ALL_CLASSES, PAGE_PT } from '../src/lint.js';
|
|
12
13
|
|
|
13
14
|
export const EXCALIDRAW_HELP = `c2m excalidraw - turn a JSON diagram description into an excalidraw.com share link
|
|
14
15
|
|
|
@@ -20,6 +21,11 @@ Usage:
|
|
|
20
21
|
also draw each diagram as PNG (see PNG below)
|
|
21
22
|
c2m excalidraw --out <folder>/images/ <file.json>...
|
|
22
23
|
draw into a working copy's images folder
|
|
24
|
+
c2m excalidraw <file.mmd> a Mermaid diagram instead (see MERMAID below)
|
|
25
|
+
c2m excalidraw <shot.json> an annotated screenshot (see DOODLE below)
|
|
26
|
+
c2m excalidraw --strict ... refuse to draw or upload when the lint finds an error
|
|
27
|
+
c2m lint <file>... check only, any input: exit 1 on an error finding
|
|
28
|
+
(same as c2m excalidraw --lint-only <file>...)
|
|
23
29
|
c2m excalidraw --help show this help
|
|
24
30
|
|
|
25
31
|
OUTPUT (stdout, in this order)
|
|
@@ -121,6 +127,25 @@ PREVIEW
|
|
|
121
127
|
larger labelled shape -> subgraph. Free text -> "%% note:" line. The preview
|
|
122
128
|
shows structure only; Mermaid's layout is not your drawing's layout.
|
|
123
129
|
|
|
130
|
+
LINT (every input: .mmd, element array, whole scene)
|
|
131
|
+
After the diagram is built, the finished scene is checked. Each finding is a
|
|
132
|
+
line "warning: lint <class> (error|warn): <what, and how to fix it>".
|
|
133
|
+
a a node sticks out of its frame / subgraph, or straddles its edge
|
|
134
|
+
b two nodes overlap (full nesting is fine)
|
|
135
|
+
c a label shows a literal <br> or backslash-n instead of a line break
|
|
136
|
+
d an arrow end is unbound, bound to a missing shape, or far off its outline
|
|
137
|
+
e a label is wider or taller than its shape
|
|
138
|
+
f text prints under 8 pt (warn under 10 pt) once the scene is scaled to the
|
|
139
|
+
page width: 468 pt, or --page-pt <n>
|
|
140
|
+
g (warn) more than 3 filled shapes or 2 fill colours; white, transparent and
|
|
141
|
+
greys are free, frames are skipped. Everything white, colour only the point.
|
|
142
|
+
--strict any error-level finding exits 1, prints the findings to stderr and
|
|
143
|
+
writes no PNG and makes no link. Use it in the loop: fix until clean.
|
|
144
|
+
c2m lint <file>... (or --lint-only) prints one summary line and the findings
|
|
145
|
+
per file, draws and uploads nothing, exits 1 on any error.
|
|
146
|
+
Text widths are estimated (0.6 em per character), so lint can still miss real
|
|
147
|
+
clipping; look at --review for the first diagram of a document.
|
|
148
|
+
|
|
124
149
|
WARNINGS
|
|
125
150
|
overlap two shapes partly overlap
|
|
126
151
|
label does not fit the label's estimated size exceeds its shape minus padding
|
|
@@ -163,9 +188,40 @@ PNG (for pasting into a Google Doc): one command, then one write
|
|
|
163
188
|
Text uses Excalidraw's fonts; CJK text is not drawn (the CJK font is not
|
|
164
189
|
shipped) and gets a warning.
|
|
165
190
|
|
|
191
|
+
MERMAID (input file ending .mmd or .mermaid)
|
|
192
|
+
c2m excalidraw --png flow.mmd seq.mmd
|
|
193
|
+
Authoring limits: <br>, <br/> and <br /> in a label become line breaks.
|
|
194
|
+
"flowchart LR" and "graph LR" are redrawn as TD, with a warning: left-to-right
|
|
195
|
+
layouts come out wider than a page and print too small. Subgraph frames are
|
|
196
|
+
fitted tightly around their nodes. Prefer TD chains; run with --strict.
|
|
197
|
+
Mermaid's own layout, drawn as Excalidraw shapes in the house style's plan
|
|
198
|
+
pass (white nodes, dark stroke, Excalifont). Flowcharts and sequence
|
|
199
|
+
diagrams become editable shapes; other types (class, state, gantt ...) come
|
|
200
|
+
out as one picture and get a warning. The preview is your Mermaid source.
|
|
201
|
+
Colour a node afterwards with c2m diagrams edit (style op).
|
|
202
|
+
|
|
203
|
+
DOODLE (annotated screenshot: a JSON object with "image" and "notes")
|
|
204
|
+
{"image": "shot.png", PNG or JPEG, relative to this JSON file
|
|
205
|
+
"width": 1100, optional: drawn width in px (default the
|
|
206
|
+
image's own, at most 1400); targets stay
|
|
207
|
+
in the image's own pixels
|
|
208
|
+
"color": "#1971c2", optional: pen colour for notes and arrows
|
|
209
|
+
"notes": [
|
|
210
|
+
{"text": "honest about gaps", "target": [100, 150, 370, 45]},
|
|
211
|
+
{"text": "green = in the warehouse", "target": [1662, 341], "side": "right"}]}
|
|
212
|
+
target [x, y] a point, or [x, y, width, height] a box (gets an outline),
|
|
213
|
+
in the image's pixels, measured from its top-left corner
|
|
214
|
+
side left, right, top or bottom; default: the image edge nearest the
|
|
215
|
+
target. Notes stack in the margin on that side, never on the
|
|
216
|
+
image or on each other, wrapped at ~28 characters ("\n" breaks).
|
|
217
|
+
Each note gets a curved arrow from its edge to the target, in Excalidraw's
|
|
218
|
+
hand font. The preview lists the notes. The share link opens WITHOUT the
|
|
219
|
+
picture (excalidraw.com stores pictures apart from the link), so every
|
|
220
|
+
doodle warns; the PNG is the deliverable.
|
|
221
|
+
|
|
166
222
|
NOT SUPPORTED
|
|
167
|
-
|
|
168
|
-
|
|
223
|
+
frames, freedraw, editing an existing link (use c2m diagrams edit for that),
|
|
224
|
+
writing .excalidraw files, pictures in share links.
|
|
169
225
|
`;
|
|
170
226
|
|
|
171
227
|
function readInput(target, stdin) {
|
|
@@ -209,9 +265,44 @@ function toScene(input) {
|
|
|
209
265
|
var built = buildSkeleton(input.elements);
|
|
210
266
|
if (input.appState) built.scene.appState = input.appState;
|
|
211
267
|
if (input.files) built.scene.files = input.files;
|
|
212
|
-
return built;
|
|
268
|
+
return Object.assign({ fromSkeleton: true }, built);
|
|
213
269
|
}
|
|
214
|
-
return buildSkeleton(input);
|
|
270
|
+
return Object.assign({ fromSkeleton: true }, buildSkeleton(input));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// One input -> { scene, preview, warnings, fence }. A .mmd file is Mermaid; a
|
|
274
|
+
// JSON object with "image" and "notes" is a doodle; anything else is the
|
|
275
|
+
// element array or scene described in the help.
|
|
276
|
+
async function buildInputRaw(target, io) {
|
|
277
|
+
var text = readInput(target, io.stdin);
|
|
278
|
+
if (/\.(mmd|mermaid)$/i.test(target)) {
|
|
279
|
+
var mermaid = await import('../src/mermaid-input.js');
|
|
280
|
+
return Object.assign({ fence: 'mermaid' }, await mermaid.mermaidToScene(text));
|
|
281
|
+
}
|
|
282
|
+
var input = parseJson(text);
|
|
283
|
+
var doodle = await import('../src/doodle.js');
|
|
284
|
+
if (doodle.isDoodleSpec(input)) {
|
|
285
|
+
var base = target === '-' ? process.cwd() : dirname(resolve(target));
|
|
286
|
+
var bytes;
|
|
287
|
+
try { bytes = readFileSync(resolve(base, input.image)); } catch (e) { throw new Error('cannot read image ' + input.image + ': ' + e.message); }
|
|
288
|
+
var render = await import('../src/excalidraw-png.js');
|
|
289
|
+
return Object.assign({ fence: 'text' }, await doodle.doodleToScene(input, bytes, render.loadExcalidraw));
|
|
290
|
+
}
|
|
291
|
+
return Object.assign({ fence: 'mermaid' }, toScene(input));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// Lint the finished scene, whatever input it came from. Element arrays and
|
|
295
|
+
// shorthand scenes already get "overlap" and "label does not fit" warnings from
|
|
296
|
+
// the skeleton builder, so those two classes are skipped for them unless the
|
|
297
|
+
// caller wants every finding (--strict, lint-only).
|
|
298
|
+
async function buildInput(target, io, opts) {
|
|
299
|
+
var built = await buildInputRaw(target, io);
|
|
300
|
+
var classes = built.fromSkeleton && !opts.all ? ALL_CLASSES.filter(function (c) { return c !== 'b' && c !== 'e'; }) : ALL_CLASSES;
|
|
301
|
+
var result = lintScene(built.scene, { pagePt: opts.pagePt, classes: classes });
|
|
302
|
+
built.findings = result.findings;
|
|
303
|
+
built.meta = result.meta;
|
|
304
|
+
built.warnings = built.warnings.concat(result.findings.map(formatFinding));
|
|
305
|
+
return built;
|
|
215
306
|
}
|
|
216
307
|
|
|
217
308
|
function parseJson(text) {
|
|
@@ -223,19 +314,19 @@ function parseJson(text) {
|
|
|
223
314
|
}
|
|
224
315
|
|
|
225
316
|
function sceneName(target) {
|
|
226
|
-
return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw)$/i, '');
|
|
317
|
+
return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw|mmd|mermaid)$/i, '');
|
|
227
318
|
}
|
|
228
319
|
|
|
229
320
|
// `--png` takes an optional folder: the next argument is the folder unless it
|
|
230
321
|
// looks like an input (-, *.json, *.excalidraw) or an option.
|
|
231
322
|
function looksLikeInput(a) {
|
|
232
|
-
return a === '-' || a.startsWith('--') || /\.(json|excalidraw)$/i.test(a);
|
|
323
|
+
return a === '-' || a.startsWith('--') || /\.(json|excalidraw|mmd|mermaid)$/i.test(a);
|
|
233
324
|
}
|
|
234
325
|
|
|
235
326
|
// Returns the exit code. `io.fetch`, `io.stdin` and `io.env` exist for tests.
|
|
236
327
|
export async function runExcalidraw(argv, io) {
|
|
237
328
|
var stdout = io.stdout, stderr = io.stderr;
|
|
238
|
-
var noUpload = false;
|
|
329
|
+
var noUpload = false, strict = false, lintOnly = false, pagePt = PAGE_PT;
|
|
239
330
|
var png = false, pngDir = null, outDir = null, review = false;
|
|
240
331
|
var targets = [];
|
|
241
332
|
for (var i = 0; i < argv.length; i++) {
|
|
@@ -251,22 +342,32 @@ export async function runExcalidraw(argv, io) {
|
|
|
251
342
|
png = true; outDir = argv[++i];
|
|
252
343
|
} else if (a.startsWith('--out=')) { png = true; outDir = a.slice(6); }
|
|
253
344
|
else if (a === '--review') review = true;
|
|
345
|
+
else if (a === '--strict') strict = true;
|
|
346
|
+
else if (a === '--lint-only') lintOnly = true;
|
|
347
|
+
else if (a === '--page-pt' || a.startsWith('--page-pt=')) {
|
|
348
|
+
var raw = a === '--page-pt' ? argv[++i] : a.slice(10);
|
|
349
|
+
pagePt = Number(raw);
|
|
350
|
+
if (!(pagePt > 0)) { stderr.write('c2m excalidraw: --page-pt needs a number of points, e.g. 468\n'); return 1; }
|
|
351
|
+
}
|
|
254
352
|
else if (a.startsWith('--')) { stderr.write('c2m excalidraw: unknown option ' + a + '\n'); return 1; }
|
|
255
353
|
else targets.push(a);
|
|
256
354
|
}
|
|
257
|
-
if (png ? targets.length < 1 : targets.length !== 1) {
|
|
355
|
+
if (lintOnly ? targets.length < 1 : png ? targets.length < 1 : targets.length !== 1) {
|
|
258
356
|
stderr.write('c2m excalidraw: expected ' + (png ? 'one or more <file.json>' : 'one <file.json>') +
|
|
259
357
|
' or - for stdin. See c2m excalidraw --help.\n');
|
|
260
358
|
return 1;
|
|
261
359
|
}
|
|
262
360
|
|
|
361
|
+
var lintOpts = { pagePt: pagePt, all: strict || lintOnly };
|
|
263
362
|
try {
|
|
363
|
+
if (lintOnly) return await runLint(targets, lintOpts, io);
|
|
264
364
|
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);
|
|
266
|
-
var built =
|
|
365
|
+
if (png) return await runPng(targets, { dir: outDir !== null ? outDir : pngDir, folder: outDir !== null, review: review, noUpload: noUpload, strict: strict, lint: lintOpts }, io);
|
|
366
|
+
var built = await buildInput(targets[0], io, lintOpts);
|
|
367
|
+
refuseOnErrors([{ name: targets[0], built: built }], strict);
|
|
267
368
|
var url = noUpload ? null : await upload(built.scene, io.fetch);
|
|
268
369
|
if (url) stdout.write(url + '\n');
|
|
269
|
-
stdout.write('```
|
|
370
|
+
stdout.write('```' + built.fence + '\n' + built.preview + '\n```\n');
|
|
270
371
|
built.warnings.forEach(function (w) { stdout.write('warning: ' + w + '\n'); });
|
|
271
372
|
return 0;
|
|
272
373
|
} catch (e) {
|
|
@@ -275,6 +376,37 @@ export async function runExcalidraw(argv, io) {
|
|
|
275
376
|
}
|
|
276
377
|
}
|
|
277
378
|
|
|
379
|
+
// --strict: any error-level finding stops the run before a PNG or a link is
|
|
380
|
+
// made. Every input is reported, not just the first, so one pass shows the
|
|
381
|
+
// whole list.
|
|
382
|
+
function refuseOnErrors(items, strict) {
|
|
383
|
+
if (!strict) return;
|
|
384
|
+
var lines = [];
|
|
385
|
+
items.forEach(function (it) {
|
|
386
|
+
var errs = it.built.findings.filter(function (f) { return f.level === 'error'; });
|
|
387
|
+
if (errs.length) lines.push(it.name + ': ' + errs.length + ' error' + (errs.length === 1 ? '' : 's') + '\n' + errs.map(function (f) { return ' ' + formatFinding(f); }).join('\n'));
|
|
388
|
+
});
|
|
389
|
+
if (lines.length) throw new Error('--strict: lint found errors; nothing was drawn or uploaded\n' + lines.join('\n') + '\nFix the diagram and rerun, or drop --strict to accept the findings as warnings.');
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// `c2m lint <file>...`: check only. One header line per input, then its
|
|
393
|
+
// findings; exit 1 if any input has an error-level finding.
|
|
394
|
+
async function runLint(targets, lintOpts, io) {
|
|
395
|
+
var failed = false;
|
|
396
|
+
for (var t = 0; t < targets.length; t++) {
|
|
397
|
+
var built = await buildInput(targets[t], io, lintOpts);
|
|
398
|
+
var m = built.meta;
|
|
399
|
+
io.stdout.write(targets[t] + ': ' + m.width + 'x' + m.height + ' px, min text ' + (m.minPt === null ? 'n/a' : m.minPt + ' pt at ' + lintOpts.pagePt + ' pt page width') +
|
|
400
|
+
', ' + built.findings.length + ' finding' + (built.findings.length === 1 ? '' : 's') + '\n');
|
|
401
|
+
built.warnings.forEach(function (w) {
|
|
402
|
+
if (!/^lint /.test(w)) io.stdout.write(' warning: ' + w + '\n');
|
|
403
|
+
});
|
|
404
|
+
built.findings.forEach(function (f) { io.stdout.write(' ' + formatFinding(f) + '\n'); });
|
|
405
|
+
if (hasErrors(built.findings)) failed = true;
|
|
406
|
+
}
|
|
407
|
+
return failed ? 1 : 0;
|
|
408
|
+
}
|
|
409
|
+
|
|
278
410
|
async function runPng(targets, opts, io) {
|
|
279
411
|
var stdout = io.stdout;
|
|
280
412
|
var names = targets.map(sceneName);
|
|
@@ -284,10 +416,12 @@ async function runPng(targets, opts, io) {
|
|
|
284
416
|
|
|
285
417
|
// Read and build every input before drawing anything, so a typo in the
|
|
286
418
|
// last file costs no renders.
|
|
287
|
-
var items =
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
419
|
+
var items = [];
|
|
420
|
+
for (var t = 0; t < targets.length; t++) {
|
|
421
|
+
var built = await buildInput(targets[t], io, opts.lint);
|
|
422
|
+
items.push({ name: names[t], scene: built.scene, preview: built.preview, warnings: built.warnings, fence: built.fence, built: built });
|
|
423
|
+
}
|
|
424
|
+
refuseOnErrors(items, opts.strict);
|
|
291
425
|
|
|
292
426
|
var render = await import('../src/excalidraw-png.js');
|
|
293
427
|
var dir;
|
|
@@ -320,7 +454,7 @@ async function runPng(targets, opts, io) {
|
|
|
320
454
|
// which is how a working copy's push finds a new image.
|
|
321
455
|
var target = opts.folder ? './' + basename(dir) + '/' + it.name + '.png' : 'attach:' + it.name;
|
|
322
456
|
var lines = [];
|
|
323
|
-
if (it.preview) lines.push('```
|
|
457
|
+
if (it.preview) lines.push('```' + it.fence + '\n' + it.preview + '\n```');
|
|
324
458
|
lines.push('');
|
|
325
459
|
// The share link sits as a plain text line under the image, so it shows in
|
|
326
460
|
// the doc: no API request sets an image's alt text, and a link hidden
|
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/doodle.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// Annotated screenshot ("doodle") spec -> Excalidraw scene for `c2m excalidraw`.
|
|
2
|
+
// The picture sits in the middle, handwritten notes in the margins around it,
|
|
3
|
+
// and a curved arrow runs from each note to the spot it explains. Notes never
|
|
4
|
+
// sit on the picture or on each other: each side is a column (left, right) or
|
|
5
|
+
// a row (top, bottom) stacked outward from the target, then a final pass
|
|
6
|
+
// pushes apart anything that still touches.
|
|
7
|
+
//
|
|
8
|
+
// Pure layout: the caller hands in the image bytes, so tests need no files.
|
|
9
|
+
|
|
10
|
+
export const DOODLE_DEFAULTS = { fontSize: 20, color: '#1971c2', maxWidth: 1400, wrap: 28 };
|
|
11
|
+
const GAP = 90; // picture edge -> note
|
|
12
|
+
const STACK = 24; // note -> note
|
|
13
|
+
const PAD = 8; // note edge -> arrow start
|
|
14
|
+
const SIDES = ['left', 'right', 'top', 'bottom'];
|
|
15
|
+
|
|
16
|
+
export function isDoodleSpec(input) {
|
|
17
|
+
return !!input && !Array.isArray(input) && typeof input === 'object' &&
|
|
18
|
+
typeof input.image === 'string' && Array.isArray(input.notes);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// PNG width and height from the IHDR chunk; JPEG from its first SOFn marker.
|
|
22
|
+
export function imageInfo(buf) {
|
|
23
|
+
if (buf.length > 24 && buf.readUInt32BE(0) === 0x89504e47) {
|
|
24
|
+
return { mimeType: 'image/png', width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
|
|
25
|
+
}
|
|
26
|
+
if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {
|
|
27
|
+
for (var i = 2; i + 9 < buf.length;) {
|
|
28
|
+
if (buf[i] !== 0xff) { i++; continue; }
|
|
29
|
+
var marker = buf[i + 1], len = buf.readUInt16BE(i + 2);
|
|
30
|
+
if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
|
|
31
|
+
return { mimeType: 'image/jpeg', width: buf.readUInt16BE(i + 7), height: buf.readUInt16BE(i + 5) };
|
|
32
|
+
}
|
|
33
|
+
i += 2 + len;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
throw new Error('the image is not a PNG or JPEG');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Greedy word wrap; the writer's own "\n" always breaks.
|
|
40
|
+
export function wrapText(text, width) {
|
|
41
|
+
return String(text).split('\n').map(function (para) {
|
|
42
|
+
var out = [], line = '';
|
|
43
|
+
para.split(/\s+/).filter(Boolean).forEach(function (w) {
|
|
44
|
+
if (line && (line + ' ' + w).length > width) { out.push(line); line = w; } else line = line ? line + ' ' + w : w;
|
|
45
|
+
});
|
|
46
|
+
out.push(line);
|
|
47
|
+
return out.join('\n');
|
|
48
|
+
}).join('\n');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// 0.55 em per character, the width Excalidraw's own text measure gives here
|
|
52
|
+
// (see the canvas stand-in in src/excalidraw-png.js); 1.25 em per line.
|
|
53
|
+
function textSize(text, fontSize) {
|
|
54
|
+
var lines = text.split('\n');
|
|
55
|
+
var longest = lines.reduce(function (m, l) { return Math.max(m, l.length); }, 0);
|
|
56
|
+
return { w: Math.ceil(longest * fontSize * 0.55), h: Math.ceil(lines.length * fontSize * 1.25) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function parseTarget(t, k, info) {
|
|
60
|
+
if (!Array.isArray(t) || (t.length !== 2 && t.length !== 4) || t.some(function (v) { return typeof v !== 'number' || !isFinite(v); })) {
|
|
61
|
+
throw new Error('note ' + (k + 1) + ': "target" must be [x, y] (a point) or [x, y, width, height] (a box), in image pixels');
|
|
62
|
+
}
|
|
63
|
+
var box = { x: t[0], y: t[1], w: t[2] || 0, h: t[3] || 0, isBox: t.length === 4 };
|
|
64
|
+
if (box.x < 0 || box.y < 0 || box.x + box.w > info.width || box.y + box.h > info.height) {
|
|
65
|
+
throw new Error('note ' + (k + 1) + ': target ' + JSON.stringify(t) + ' lies outside the ' + info.width + 'x' + info.height + ' image');
|
|
66
|
+
}
|
|
67
|
+
return box;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// The side whose image edge is nearest the target's centre.
|
|
71
|
+
function nearestSide(c, W, H) {
|
|
72
|
+
var d = { left: c.x, right: W - c.x, top: c.y, bottom: H - c.y };
|
|
73
|
+
return SIDES.reduce(function (best, s) { return d[s] < d[best] ? s : best; }, 'left');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function overlaps(a, b, pad) {
|
|
77
|
+
return a.x < b.x + b.w + pad && b.x < a.x + a.w + pad && a.y < b.y + b.h + pad && b.y < a.y + a.h + pad;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Stack one side's notes along its axis, each as close to its target as the
|
|
81
|
+
// notes before it allow.
|
|
82
|
+
function stack(notes, axis) {
|
|
83
|
+
var pos = axis === 'y' ? 'y' : 'x', size = axis === 'y' ? 'h' : 'w';
|
|
84
|
+
notes.sort(function (a, b) { return a[pos] - b[pos]; });
|
|
85
|
+
for (var i = 1; i < notes.length; i++) {
|
|
86
|
+
var min = notes[i - 1][pos] + notes[i - 1][size] + STACK;
|
|
87
|
+
if (notes[i][pos] < min) notes[i][pos] = min;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Returns { notes: [{text, x, y, w, h, side, target, start, end}], W, H }:
|
|
92
|
+
// the layout in scene pixels with the picture at (0, 0) to (W, H).
|
|
93
|
+
export function layoutDoodle(spec, info) {
|
|
94
|
+
var opt = Object.assign({}, DOODLE_DEFAULTS, spec);
|
|
95
|
+
var natural = info.width;
|
|
96
|
+
var W = spec.width ? Number(spec.width) : Math.min(natural, opt.maxWidth);
|
|
97
|
+
if (!(W > 0)) throw new Error('"width" must be a positive number of pixels');
|
|
98
|
+
var s = W / natural, H = Math.round(info.height * s);
|
|
99
|
+
if (!spec.notes.length) throw new Error('"notes" is empty: give at least one {"text", "target"}');
|
|
100
|
+
|
|
101
|
+
var notes = spec.notes.map(function (n, k) {
|
|
102
|
+
if (!n || typeof n.text !== 'string' || !n.text.trim()) throw new Error('note ' + (k + 1) + ': needs "text"');
|
|
103
|
+
var t = parseTarget(n.target, k, info);
|
|
104
|
+
var target = { x: t.x * s, y: t.y * s, w: t.w * s, h: t.h * s, isBox: t.isBox };
|
|
105
|
+
var c = { x: target.x + target.w / 2, y: target.y + target.h / 2 };
|
|
106
|
+
var side = n.side || nearestSide(c, W, H);
|
|
107
|
+
if (SIDES.indexOf(side) < 0) throw new Error('note ' + (k + 1) + ': "side" must be one of ' + SIDES.join(', '));
|
|
108
|
+
var fontSize = n.fontSize || opt.fontSize;
|
|
109
|
+
var text = wrapText(n.text.trim(), opt.wrap);
|
|
110
|
+
var sz = textSize(text, fontSize);
|
|
111
|
+
var note = { k: k, text: text, textAlign: side === 'left' ? 'right' : side === 'right' ? 'left' : 'center', fontSize: fontSize, color: n.color || opt.color, side: side, target: target, c: c, w: sz.w, h: sz.h };
|
|
112
|
+
if (side === 'left') { note.x = -GAP - sz.w; note.y = c.y - sz.h / 2; }
|
|
113
|
+
if (side === 'right') { note.x = W + GAP; note.y = c.y - sz.h / 2; }
|
|
114
|
+
if (side === 'top') { note.y = -GAP - sz.h; note.x = Math.max(0, Math.min(W - sz.w, c.x - sz.w / 2)); }
|
|
115
|
+
if (side === 'bottom') { note.y = H + GAP; note.x = Math.max(0, Math.min(W - sz.w, c.x - sz.w / 2)); }
|
|
116
|
+
return note;
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
stack(notes.filter(function (n) { return n.side === 'left'; }), 'y');
|
|
120
|
+
stack(notes.filter(function (n) { return n.side === 'right'; }), 'y');
|
|
121
|
+
stack(notes.filter(function (n) { return n.side === 'top'; }), 'x');
|
|
122
|
+
stack(notes.filter(function (n) { return n.side === 'bottom'; }), 'x');
|
|
123
|
+
|
|
124
|
+
// Corners: a long column can reach a row's notes. Push the later note
|
|
125
|
+
// outward (columns away from the picture sideways, rows up or down) until
|
|
126
|
+
// nothing touches; outward moves never bring a note onto the picture.
|
|
127
|
+
for (var pass = 0; pass < 50; pass++) {
|
|
128
|
+
var moved = false;
|
|
129
|
+
for (var i = 0; i < notes.length; i++) {
|
|
130
|
+
for (var j = i + 1; j < notes.length; j++) {
|
|
131
|
+
var a = notes[i], b = notes[j];
|
|
132
|
+
if (!overlaps(a, b, STACK / 2)) continue;
|
|
133
|
+
if (b.side === 'left') b.x = a.x - STACK - b.w;
|
|
134
|
+
else if (b.side === 'right') b.x = a.x + a.w + STACK;
|
|
135
|
+
else if (b.side === 'top') b.y = a.y - STACK - b.h;
|
|
136
|
+
else b.y = a.y + a.h + STACK;
|
|
137
|
+
moved = true;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (!moved) break;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
notes.forEach(function (n) {
|
|
144
|
+
var mid = { x: n.x + n.w / 2, y: n.y + n.h / 2 };
|
|
145
|
+
if (n.side === 'left') n.start = { x: n.x + n.w + PAD, y: mid.y };
|
|
146
|
+
if (n.side === 'right') n.start = { x: n.x - PAD, y: mid.y };
|
|
147
|
+
if (n.side === 'top') n.start = { x: mid.x, y: n.y + n.h + PAD };
|
|
148
|
+
if (n.side === 'bottom') n.start = { x: mid.x, y: n.y - PAD };
|
|
149
|
+
n.end = arrowEnd(n.target, n.start);
|
|
150
|
+
});
|
|
151
|
+
notes.sort(function (a, b) { return a.k - b.k; });
|
|
152
|
+
return { notes: notes, W: W, H: H, scale: s };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// A point target: the point. A box: the point on its outline nearest the
|
|
156
|
+
// note, pulled 4 px off the line so the arrowhead does not hide the box.
|
|
157
|
+
function arrowEnd(t, from) {
|
|
158
|
+
if (!t.isBox) return { x: t.x, y: t.y };
|
|
159
|
+
var x = Math.max(t.x, Math.min(t.x + t.w, from.x));
|
|
160
|
+
var y = Math.max(t.y, Math.min(t.y + t.h, from.y));
|
|
161
|
+
if (x > t.x && x < t.x + t.w && y > t.y && y < t.y + t.h) return { x: x, y: y };
|
|
162
|
+
var dx = from.x - x, dy = from.y - y, len = Math.hypot(dx, dy) || 1;
|
|
163
|
+
return { x: x + dx / len * 4, y: y + dy / len * 4 };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Excalidraw element skeletons (for convertToExcalidrawElements) plus files.
|
|
167
|
+
export function doodleSkeleton(spec, bytes, now) {
|
|
168
|
+
var info = imageInfo(bytes);
|
|
169
|
+
var lay = layoutDoodle(spec, info);
|
|
170
|
+
var fileId = 'doodle-image';
|
|
171
|
+
var els = [
|
|
172
|
+
{ type: 'image', id: 'image', fileId: fileId, x: 0, y: 0, width: lay.W, height: lay.H, status: 'saved' },
|
|
173
|
+
{ type: 'rectangle', id: 'image-frame', x: 0, y: 0, width: lay.W, height: lay.H, strokeColor: '#868e96', strokeWidth: 1, roughness: 0, backgroundColor: 'transparent' },
|
|
174
|
+
];
|
|
175
|
+
lay.notes.forEach(function (n, k) {
|
|
176
|
+
var id = 'note-' + (k + 1);
|
|
177
|
+
if (n.target.isBox) {
|
|
178
|
+
els.push({ type: 'rectangle', id: id + '-box', x: n.target.x - 4, y: n.target.y - 4, width: n.target.w + 8, height: n.target.h + 8,
|
|
179
|
+
strokeColor: n.color, strokeWidth: 2, backgroundColor: 'transparent', roundness: { type: 3 } });
|
|
180
|
+
}
|
|
181
|
+
els.push({ type: 'text', id: id, x: n.x, y: n.y, text: n.text, fontSize: n.fontSize, fontFamily: 5, strokeColor: n.color,
|
|
182
|
+
textAlign: n.textAlign });
|
|
183
|
+
// Curve: one bend point off the straight line, alternating sides so
|
|
184
|
+
// neighbouring arrows do not mirror each other.
|
|
185
|
+
var dx = n.end.x - n.start.x, dy = n.end.y - n.start.y, len = Math.hypot(dx, dy) || 1;
|
|
186
|
+
var bend = Math.min(40, len * 0.18) * (k % 2 ? -1 : 1);
|
|
187
|
+
var mid = [dx / 2 - dy / len * bend, dy / 2 + dx / len * bend];
|
|
188
|
+
els.push({ type: 'arrow', id: id + '-arrow', x: n.start.x, y: n.start.y, points: [[0, 0], mid, [dx, dy]],
|
|
189
|
+
strokeColor: n.color, strokeWidth: 2, roundness: { type: 2 }, endArrowhead: 'arrow' });
|
|
190
|
+
});
|
|
191
|
+
var b64 = Buffer.from(bytes).toString('base64');
|
|
192
|
+
var files = {};
|
|
193
|
+
files[fileId] = { id: fileId, mimeType: info.mimeType, dataURL: 'data:' + info.mimeType + ';base64,' + b64, created: now || 0 };
|
|
194
|
+
return { elements: els, files: files, layout: lay };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// The preview for a doodle: one line per note, so an agent can check which
|
|
198
|
+
// note points where without opening the picture.
|
|
199
|
+
export function doodlePreview(spec, lay) {
|
|
200
|
+
return ['%% doodle: ' + spec.image + ' (' + Math.round(lay.W) + 'x' + Math.round(lay.H) + ' px)'].concat(lay.notes.map(function (n, k) {
|
|
201
|
+
var t = n.target;
|
|
202
|
+
return '%% note ' + (k + 1) + ' (' + n.side + ') -> ' + (t.isBox ? 'box' : 'point') + ': ' + n.text.replace(/\n/g, ' ');
|
|
203
|
+
})).join('\n');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export async function doodleToScene(spec, bytes, loadExcalidraw) {
|
|
207
|
+
var built = doodleSkeleton(spec, bytes, Date.now());
|
|
208
|
+
var m = await loadExcalidraw();
|
|
209
|
+
var elements = m.convertToExcalidrawElements(built.elements, { regenerateIds: false });
|
|
210
|
+
// The converter shifts a right- or centre-aligned text left by its width,
|
|
211
|
+
// as if x were its anchor. Put each note back on the box the layout chose.
|
|
212
|
+
var placed = {};
|
|
213
|
+
built.layout.notes.forEach(function (n, k) { placed['note-' + (k + 1)] = n; });
|
|
214
|
+
elements.forEach(function (e) {
|
|
215
|
+
var n = e.type === 'text' && placed[e.id];
|
|
216
|
+
if (!n) return;
|
|
217
|
+
e.x = n.textAlign === 'right' ? n.x + n.w - e.width : n.textAlign === 'center' ? n.x + (n.w - e.width) / 2 : n.x;
|
|
218
|
+
e.y = n.y;
|
|
219
|
+
});
|
|
220
|
+
return {
|
|
221
|
+
scene: { type: 'excalidraw', version: 2, source: 'c2m', elements: elements, appState: { viewBackgroundColor: '#ffffff' }, files: built.files },
|
|
222
|
+
preview: doodlePreview(spec, built.layout),
|
|
223
|
+
warnings: ['the share link opens without the picture: excalidraw.com stores images apart from the link (see c2m excalidraw --help, DOODLE); the PNG is complete'],
|
|
224
|
+
};
|
|
225
|
+
}
|