flowfig 0.3.0 → 0.4.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 +71 -14
- package/dist/browser.d.ts +33 -0
- package/dist/browser.js +201 -0
- package/dist/check.js +60 -3
- package/dist/cli.js +176 -6
- package/dist/diff.js +1 -1
- package/dist/draw.js +20 -3
- package/dist/geometry.d.ts +4 -1
- package/dist/geometry.js +39 -12
- package/dist/gif.d.ts +12 -0
- package/dist/gif.js +245 -0
- package/dist/guide.d.ts +3 -3
- package/dist/guide.js +25 -10
- package/dist/index.d.ts +1 -1
- package/dist/index.js +209 -13
- package/dist/init.d.ts +5 -0
- package/dist/init.js +58 -22
- package/dist/model.d.ts +89 -0
- package/dist/model.js +171 -7
- package/dist/open.d.ts +15 -0
- package/dist/open.js +82 -0
- package/dist/page.d.ts +2 -0
- package/dist/page.js +16 -0
- package/dist/picker.d.ts +33 -0
- package/dist/picker.js +148 -0
- package/dist/png.d.ts +7 -0
- package/dist/png.js +70 -0
- package/dist/scene.d.ts +2 -0
- package/dist/svg.js +205 -15
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -21,24 +21,34 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
21
21
|
* flowfig mcp # serve check, render, verify, diff and docs over MCP (stdio)
|
|
22
22
|
* flowfig init [dir] # write flowfig instructions for the coding agents of a repo
|
|
23
23
|
* flowfig draw "<question>" [--out out.svg] # ask Claude Code for a figure, then check it
|
|
24
|
+
* flowfig open figure.svg # show the figure in the default browser
|
|
25
|
+
* flowfig gif figure.svg [out.gif] # write an animated GIF of the figure (needs Chrome, Edge, Chromium or Brave)
|
|
24
26
|
*
|
|
25
27
|
* A render checks first and writes nothing on an error (--no-check skips that). --strict makes warnings errors; --width and
|
|
26
28
|
* --min-text set the page width and the smallest text the reader should get.
|
|
29
|
+
* --open opens the rendered SVG in the default browser (render and draw).
|
|
27
30
|
*
|
|
28
31
|
* Every rendered SVG carries its own spec in <metadata>, so a figure is editable later without anyone having to keep the JSON.
|
|
29
32
|
*/
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
33
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
34
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
35
|
+
import { tmpdir } from 'node:os';
|
|
36
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
32
37
|
import { pathToFileURL } from 'node:url';
|
|
38
|
+
import { captureFrames, findBrowser, launch } from './browser.js';
|
|
39
|
+
import { delays, encodeGif } from './gif.js';
|
|
33
40
|
import { GUIDE } from './guide.js';
|
|
34
41
|
import { runDraw } from './draw.js';
|
|
35
42
|
import { runInit } from './init.js';
|
|
36
43
|
import { serve } from './mcp.js';
|
|
44
|
+
import { openedLine, openSvg, runOpen } from './open.js';
|
|
45
|
+
import { pageHtml } from './page.js';
|
|
46
|
+
import { decodePng } from './png.js';
|
|
37
47
|
import { diff, formatDiff } from './diff.js';
|
|
38
48
|
import { loadSpec, reportLines, sortFindings, specOf, svgWithSpec } from './load.js';
|
|
39
|
-
import { check } from './svg.js';
|
|
49
|
+
import { check, toSvg } from './svg.js';
|
|
40
50
|
import { links, verify } from './verify.js';
|
|
41
|
-
const USAGE = `usage: flowfig <-|spec.json|figure.ts> [out.svg] render a figure; a spec on stdin with -
|
|
51
|
+
const USAGE = `usage: flowfig <-|spec.json|figure.ts> [out.svg] [--open] render a figure; a spec on stdin with -
|
|
42
52
|
flowfig check <-|spec.json|figure.ts|figure.svg> list the faults; the input can be an SVG this wrote
|
|
43
53
|
flowfig --spec figure.svg print the spec the SVG carries
|
|
44
54
|
flowfig verify <input>... [--root <dir>] [--json] [--strict] check the code links of one or more figures
|
|
@@ -46,7 +56,9 @@ const USAGE = `usage: flowfig <-|spec.json|figure.ts> [out.svg] render a figur
|
|
|
46
56
|
flowfig docs print the guide (Markdown)
|
|
47
57
|
flowfig mcp serve check, render, verify, diff and docs over MCP (stdio)
|
|
48
58
|
flowfig init [dir] [--agents <ids>] [-y] [--global] [--dry-run] [--no-mcp] write flowfig instructions for the coding agents of a repo
|
|
49
|
-
flowfig draw "<question>" [--out <path>] [--model <alias>] [--max-turns <n>] [--json] ask Claude Code for a figure, then check it
|
|
59
|
+
flowfig draw "<question>" [--out <path>] [--model <alias>] [--max-turns <n>] [--json] [--open] ask Claude Code for a figure, then check it
|
|
60
|
+
flowfig open <figure.svg> [--html <path>] show the figure in the default browser
|
|
61
|
+
flowfig gif <figure.svg> [out.gif] [--step <n>] [--dark] [--fps <n>] [--scale <n>] [--mp4] write an animated GIF
|
|
50
62
|
flags for render and check: --strict (warnings are errors), --json, --width <px>, --min-text <px>, --no-check (render only)`;
|
|
51
63
|
/** Bad use, not a bad figure: exit 2 with a message, not a stack trace. A declaration, so TypeScript narrows after a call. */
|
|
52
64
|
function usage(message) {
|
|
@@ -86,6 +98,8 @@ if (args[0] === 'init')
|
|
|
86
98
|
process.exit(await runInit(args.slice(1)));
|
|
87
99
|
if (args[0] === 'draw')
|
|
88
100
|
process.exit(await runDraw(args.slice(1)));
|
|
101
|
+
if (args[0] === 'open')
|
|
102
|
+
process.exit(await runOpen(args.slice(1)));
|
|
89
103
|
if (args[0] === '--spec') {
|
|
90
104
|
if (!args[1])
|
|
91
105
|
usage('--spec needs the path of an SVG');
|
|
@@ -159,8 +173,155 @@ if (args[0] === 'diff') {
|
|
|
159
173
|
console.log(json ? JSON.stringify(changes, null, 2) : formatDiff(changes, md ? 'md' : 'text'));
|
|
160
174
|
process.exit(0);
|
|
161
175
|
}
|
|
176
|
+
if (args[0] === 'gif') {
|
|
177
|
+
args.shift();
|
|
178
|
+
const dark = flag('--dark'), mp4 = flag('--mp4');
|
|
179
|
+
const fps = value('--fps') ?? 20, scale = value('--scale') ?? 2, step = value('--step');
|
|
180
|
+
if (!Number.isInteger(fps) || fps > 50)
|
|
181
|
+
usage('--fps needs a whole number from 1 to 50');
|
|
182
|
+
const unknown = args.find((a) => a.startsWith('-'));
|
|
183
|
+
if (unknown)
|
|
184
|
+
usage(`unknown flag ${unknown}`);
|
|
185
|
+
const [path, outArg] = args;
|
|
186
|
+
if (!path)
|
|
187
|
+
usage('usage: flowfig gif <figure.svg> [out.gif] [--step <n>] [--dark] [--fps <n>] [--scale <n>] [--mp4]');
|
|
188
|
+
if (!path.endsWith('.svg'))
|
|
189
|
+
usage(`${path}: expected a .svg path`);
|
|
190
|
+
let svg = '';
|
|
191
|
+
try {
|
|
192
|
+
svg = readFileSync(path, 'utf8');
|
|
193
|
+
}
|
|
194
|
+
catch (e) {
|
|
195
|
+
usage(`${path}: ${e.message}`);
|
|
196
|
+
}
|
|
197
|
+
if (step !== undefined) {
|
|
198
|
+
// One step only: render the spec again with that step, so the loop holds that step alone.
|
|
199
|
+
const props = (() => {
|
|
200
|
+
try {
|
|
201
|
+
return loadSpec(path);
|
|
202
|
+
}
|
|
203
|
+
catch (e) {
|
|
204
|
+
return usage(e.message);
|
|
205
|
+
}
|
|
206
|
+
})();
|
|
207
|
+
const count = props.steps?.length ?? 0;
|
|
208
|
+
if (!count)
|
|
209
|
+
usage(`${path}: --step needs a figure with steps; this figure has 0`);
|
|
210
|
+
if (!Number.isInteger(step) || step > count)
|
|
211
|
+
usage(`--step needs a whole number from 1 to ${count}`);
|
|
212
|
+
svg = toSvg({ ...props, steps: [props.steps[step - 1]] });
|
|
213
|
+
}
|
|
214
|
+
const out = outArg ?? path.replace(/\.svg$/, step === undefined ? '.gif' : `-step${step}.gif`);
|
|
215
|
+
const size = /<svg\b[^>]*?\swidth="([\d.]+)"[^>]*?\sheight="([\d.]+)"/.exec(svg);
|
|
216
|
+
if (!size)
|
|
217
|
+
usage(`${path}: no width and height on the <svg> element`);
|
|
218
|
+
if (!existsSync(dirname(resolve(out))))
|
|
219
|
+
usage(`${out}: the folder does not exist`);
|
|
220
|
+
const found = findBrowser({ platform: process.platform, env: process.env, exists: existsSync });
|
|
221
|
+
if (!found.path)
|
|
222
|
+
usage(['gif needs Chrome, Edge, Chromium or Brave. Checked:', ...found.checked, 'Set CHROME_PATH to the browser program.'].join('\n'));
|
|
223
|
+
const line = (file, frames, bytes) => `${file} — ${frames} frame${frames === 1 ? '' : 's'}, ${(frames / fps).toFixed(1)} s, ${(bytes / 1048576).toFixed(1)} MB`;
|
|
224
|
+
const temp = mkdtempSync(join(tmpdir(), 'flowfig-gif-'));
|
|
225
|
+
// A Ctrl-C can come while the browser starts, so cleanup waits for the start before it stops the browser.
|
|
226
|
+
let launching;
|
|
227
|
+
let cleaning;
|
|
228
|
+
const cleanup = () => (cleaning ??= (async () => {
|
|
229
|
+
await (await launching?.catch(() => undefined))?.close();
|
|
230
|
+
try {
|
|
231
|
+
// The retries cover Windows, where the browser can hold a file lock for a short time after the exit.
|
|
232
|
+
rmSync(temp, { recursive: true, force: true, maxRetries: 3 });
|
|
233
|
+
}
|
|
234
|
+
catch (e) {
|
|
235
|
+
console.error(`warning: could not remove ${temp}: ${e.message}`);
|
|
236
|
+
}
|
|
237
|
+
})());
|
|
238
|
+
// The output files of this run: a stop removes them, so no partial file stays.
|
|
239
|
+
const written = [];
|
|
240
|
+
let ffmpeg, ffmpegDone = Promise.resolve(), stopped = 0;
|
|
241
|
+
const yieldLoop = () => new Promise((done) => setImmediate(done));
|
|
242
|
+
// The handlers stay for the whole run: a second signal during the cleanup must not end the process before the cleanup ends.
|
|
243
|
+
const onSignal = (signal) => {
|
|
244
|
+
if (stopped)
|
|
245
|
+
return;
|
|
246
|
+
stopped = signal === 'SIGINT' ? 130 : 143;
|
|
247
|
+
ffmpeg?.kill('SIGKILL');
|
|
248
|
+
void ffmpegDone
|
|
249
|
+
.then(() => written.forEach((f) => rmSync(f, { force: true })))
|
|
250
|
+
.then(cleanup)
|
|
251
|
+
.finally(() => process.exit(stopped));
|
|
252
|
+
};
|
|
253
|
+
process.on('SIGINT', onSignal);
|
|
254
|
+
process.on('SIGTERM', onSignal);
|
|
255
|
+
// The encode and the ffmpeg run give the event loop a turn, so a signal handler can run. A write comes straight after this check.
|
|
256
|
+
const proceed = async () => {
|
|
257
|
+
await yieldLoop();
|
|
258
|
+
if (stopped)
|
|
259
|
+
throw new Error('stopped');
|
|
260
|
+
};
|
|
261
|
+
let code = 0;
|
|
262
|
+
try {
|
|
263
|
+
launching = launch(found.path, join(temp, 'profile'));
|
|
264
|
+
const browser = await launching;
|
|
265
|
+
const viewport = { width: Math.ceil(Number(size[1])), height: Math.ceil(Number(size[2])) };
|
|
266
|
+
const { pngs } = await captureFrames(browser.cdp, pageHtml(svg, basename(path)), { ...viewport, scale, fps, dark });
|
|
267
|
+
const wait = delays(pngs.length, fps);
|
|
268
|
+
// The GIF keeps the PNG bytes, not the pixels: a decoded 2400 x 1600 frame is 15 MB.
|
|
269
|
+
const gif = await encodeGif(pngs.map((png, i) => ({ load: () => decodePng(png), delay: wait[i], same: i > 0 && png.equals(pngs[i - 1]) })));
|
|
270
|
+
await proceed();
|
|
271
|
+
written.push(out);
|
|
272
|
+
writeFileSync(out, gif);
|
|
273
|
+
console.log(line(out, pngs.length, gif.length));
|
|
274
|
+
if (gif.length > 10485760)
|
|
275
|
+
console.error(`warning: ${out} is ${(gif.length / 1048576).toFixed(1)} MB, over 10 MB. Try --step <n>, a lower --fps or a lower --scale.`);
|
|
276
|
+
if (mp4) {
|
|
277
|
+
const mp4Path = out.replace(/(\.gif)?$/, '.mp4');
|
|
278
|
+
// FLOWFIG_FFMPEG replaces the PATH lookup, so a test can hide ffmpeg and keep the full PATH.
|
|
279
|
+
const ffmpegBin = process.env.FLOWFIG_FFMPEG ?? 'ffmpeg';
|
|
280
|
+
if (spawnSync(ffmpegBin, ['-version']).error)
|
|
281
|
+
console.error('gif: no ffmpeg on the PATH, so no MP4. The GIF is written.');
|
|
282
|
+
else {
|
|
283
|
+
await proceed();
|
|
284
|
+
written.push(mp4Path);
|
|
285
|
+
// yuv420p needs an even width and height, so the pad filter adds a pixel where needed.
|
|
286
|
+
ffmpeg = spawn(ffmpegBin, [
|
|
287
|
+
...['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'png', '-i', '-'],
|
|
288
|
+
...['-vf', 'pad=ceil(iw/2)*2:ceil(ih/2)*2', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', mp4Path],
|
|
289
|
+
]);
|
|
290
|
+
let stderr = '';
|
|
291
|
+
ffmpeg.stderr.on('data', (d) => (stderr += d));
|
|
292
|
+
ffmpeg.stdin.on('error', () => { }); // ffmpeg can exit before it reads all the input; the exit code reports that
|
|
293
|
+
ffmpeg.stdin.end(Buffer.concat(pngs));
|
|
294
|
+
const status = await (ffmpegDone = new Promise((done) => {
|
|
295
|
+
ffmpeg.once('error', () => done(-1));
|
|
296
|
+
ffmpeg.once('close', done);
|
|
297
|
+
}));
|
|
298
|
+
await proceed();
|
|
299
|
+
if (status !== 0) {
|
|
300
|
+
rmSync(mp4Path, { force: true });
|
|
301
|
+
throw new Error(`ffmpeg failed: ${stderr.trim()}`);
|
|
302
|
+
}
|
|
303
|
+
console.log(line(mp4Path, pngs.length, statSync(mp4Path).size));
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
catch (e) {
|
|
308
|
+
if (!stopped)
|
|
309
|
+
console.error(`gif: ${e.message}`);
|
|
310
|
+
code = 1;
|
|
311
|
+
}
|
|
312
|
+
finally {
|
|
313
|
+
await cleanup();
|
|
314
|
+
}
|
|
315
|
+
// A signal that came in the last turn runs its handler here, before the exit.
|
|
316
|
+
await yieldLoop();
|
|
317
|
+
if (stopped)
|
|
318
|
+
written.forEach((f) => rmSync(f, { force: true }));
|
|
319
|
+
process.exit(stopped || code);
|
|
320
|
+
}
|
|
162
321
|
const command = args[0] === 'check' ? args.shift() : 'render';
|
|
163
|
-
const json = flag('--json'), strict = flag('--strict'), skip = flag('--no-check');
|
|
322
|
+
const json = flag('--json'), strict = flag('--strict'), skip = flag('--no-check'), open = flag('--open');
|
|
323
|
+
if (command === 'check' && open)
|
|
324
|
+
usage('--open works with a render, not with check');
|
|
164
325
|
const opts = { width: value('--width'), minText: value('--min-text') };
|
|
165
326
|
const unknown = args.find((a) => a.startsWith('-') && a !== '-');
|
|
166
327
|
if (unknown)
|
|
@@ -194,3 +355,12 @@ const dest = out ?? (input === '-' ? 'figure.svg' : input.replace(/\.[^./\\]+$/,
|
|
|
194
355
|
const withSpec = svgWithSpec(props);
|
|
195
356
|
writeFileSync(dest, withSpec);
|
|
196
357
|
console.log(`${dest} — ${(withSpec.length / 1024).toFixed(1)} kB`);
|
|
358
|
+
if (open) {
|
|
359
|
+
try {
|
|
360
|
+
console.log(openedLine((await openSvg(dest))[0]));
|
|
361
|
+
}
|
|
362
|
+
catch (e) {
|
|
363
|
+
console.error(`open: ${e.message}`);
|
|
364
|
+
process.exit(1);
|
|
365
|
+
}
|
|
366
|
+
}
|
package/dist/diff.js
CHANGED
|
@@ -36,7 +36,7 @@ export function diff(before, after) {
|
|
|
36
36
|
const edges = (f) => new Map(f.edges.map((e) => [edgeId(e), e]));
|
|
37
37
|
const steps = (f) => new Map((f.steps ?? []).map((s) => [str(s.label), s]));
|
|
38
38
|
const out = [
|
|
39
|
-
...compare('box', boxes(before), boxes(after), (a, b) => fields(a, b, ['label', 'sub', 'shape', 'tone', 'source', 'group'])),
|
|
39
|
+
...compare('box', boxes(before), boxes(after), (a, b) => fields(a, b, ['label', 'sub', 'shape', 'tone', 'mark', 'from', 'to', 'source', 'group'])),
|
|
40
40
|
...compare('edge', edges(before), edges(after), (a, b) => fields(a, b, ['from', 'to', 'label', 'source'])),
|
|
41
41
|
...compare('step', steps(before), steps(after), () => []),
|
|
42
42
|
...compare('message', messages(before), messages(after), () => []),
|
package/dist/draw.js
CHANGED
|
@@ -4,11 +4,12 @@ import { existsSync, mkdirSync, rmSync, statSync } from 'node:fs';
|
|
|
4
4
|
import { dirname, resolve } from 'node:path';
|
|
5
5
|
import { AGENT_TEXT } from './guide.js';
|
|
6
6
|
import { loadSpec, reportLines, sortFindings } from './load.js';
|
|
7
|
+
import { openedLine, openSvg } from './open.js';
|
|
7
8
|
import { check } from './svg.js';
|
|
8
9
|
import { verify } from './verify.js';
|
|
9
10
|
const ALLOWED = 'Read,Glob,Grep,Bash(npx flowfig *)';
|
|
10
11
|
const DISALLOWED = 'Edit,MultiEdit,NotebookEdit';
|
|
11
|
-
const USAGE = 'usage: flowfig draw "<question>" [--out <path>] [--model <alias>] [--max-turns <n>] [--json]';
|
|
12
|
+
const USAGE = 'usage: flowfig draw "<question>" [--out <path>] [--model <alias>] [--max-turns <n>] [--json] [--open]';
|
|
12
13
|
/** A file name from the question: lower case, letters and digits, joined by -, at most 60 characters. */
|
|
13
14
|
export function slug(question) {
|
|
14
15
|
const s = question
|
|
@@ -63,9 +64,10 @@ export async function runDraw(argv) {
|
|
|
63
64
|
throw new Bad(`${n} needs a value`);
|
|
64
65
|
return v;
|
|
65
66
|
};
|
|
66
|
-
let json, outArg, model, turns;
|
|
67
|
+
let json, open, outArg, model, turns;
|
|
67
68
|
try {
|
|
68
69
|
json = flag('--json');
|
|
70
|
+
open = flag('--open');
|
|
69
71
|
outArg = value('--out');
|
|
70
72
|
model = value('--model');
|
|
71
73
|
turns = value('--max-turns');
|
|
@@ -174,5 +176,20 @@ export async function runDraw(argv) {
|
|
|
174
176
|
console.log(`agent: claude, $${cost === null ? '?' : cost.toFixed(4)}, session ${session ?? '?'}`);
|
|
175
177
|
}
|
|
176
178
|
stop();
|
|
177
|
-
|
|
179
|
+
let code = errors || stopped !== undefined ? 1 : 0;
|
|
180
|
+
// The SVG is on disk also with findings, so the user can look at it.
|
|
181
|
+
if (open) {
|
|
182
|
+
try {
|
|
183
|
+
const line = openedLine((await openSvg(full))[0]);
|
|
184
|
+
if (json)
|
|
185
|
+
console.error(line);
|
|
186
|
+
else
|
|
187
|
+
console.log(line);
|
|
188
|
+
}
|
|
189
|
+
catch (e) {
|
|
190
|
+
console.error(`open: ${e.message}`);
|
|
191
|
+
code = 1;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return code;
|
|
178
195
|
}
|
package/dist/geometry.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export type Rect = {
|
|
|
4
4
|
w: number;
|
|
5
5
|
h: number;
|
|
6
6
|
};
|
|
7
|
+
export type Side = 'l' | 'r' | 't' | 'b';
|
|
7
8
|
export type Pt = {
|
|
8
9
|
x: number;
|
|
9
10
|
y: number;
|
|
@@ -20,5 +21,7 @@ export declare function route(edges: {
|
|
|
20
21
|
from: string;
|
|
21
22
|
to: string;
|
|
22
23
|
around?: Around;
|
|
23
|
-
|
|
24
|
+
sides?: [Side, Side];
|
|
25
|
+
elbow?: boolean;
|
|
26
|
+
}[], rects: Record<string, Rect>, tips?: Set<string>, avoid?: Rect[]): Routed[];
|
|
24
27
|
export {};
|
package/dist/geometry.js
CHANGED
|
@@ -4,25 +4,29 @@ const cy = (r) => r.y + r.h / 2;
|
|
|
4
4
|
// Boxes stacked on top of each other connect bottom->top, otherwise side->side.
|
|
5
5
|
// Several edges leaving the same side of a box are spread out so they don't overlap,
|
|
6
6
|
// except on `tips` boxes (diamonds), where they all meet at the point.
|
|
7
|
+
// `elbow` draws a right-angle path, from a right end to a left end: its four curve points are the corners.
|
|
8
|
+
// `sides` fixes the two sides an edge uses (a timeline uses right to left).
|
|
7
9
|
// `around` makes an edge leave and enter from the top or bottom, arcing over whatever sits between.
|
|
8
|
-
export function route(edges, rects, tips = new Set()) {
|
|
10
|
+
export function route(edges, rects, tips = new Set(), avoid = []) {
|
|
9
11
|
const picks = [];
|
|
10
12
|
for (const e of edges) {
|
|
11
13
|
const a = rects[e.from], b = rects[e.to];
|
|
12
14
|
if (!a || !b)
|
|
13
15
|
continue;
|
|
14
16
|
const stacked = a.x < b.x + b.w && b.x < a.x + a.w;
|
|
15
|
-
const [sa, sb] = e.
|
|
16
|
-
? e.
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
:
|
|
17
|
+
const [sa, sb] = e.sides
|
|
18
|
+
? e.sides
|
|
19
|
+
: e.around
|
|
20
|
+
? e.around === 'above'
|
|
21
|
+
? ['t', 't']
|
|
22
|
+
: ['b', 'b']
|
|
23
|
+
: stacked
|
|
24
|
+
? a.y < b.y
|
|
25
|
+
? ['b', 't']
|
|
26
|
+
: ['t', 'b']
|
|
27
|
+
: a.x < b.x
|
|
28
|
+
? ['r', 'l']
|
|
29
|
+
: ['l', 'r'];
|
|
26
30
|
picks.push({ ...e, a, b, sa, sb });
|
|
27
31
|
}
|
|
28
32
|
// For every (box, side), list the edge ends that sit there, sorted by where the other end is.
|
|
@@ -65,6 +69,29 @@ export function route(edges, rects, tips = new Set()) {
|
|
|
65
69
|
};
|
|
66
70
|
return picks.map((p) => {
|
|
67
71
|
const s = anchor.get(p.id + ':s'), e = anchor.get(p.id + ':e');
|
|
72
|
+
if (p.elbow) {
|
|
73
|
+
// The vertical run sits at the midpoint x. Under 16 px of gap, it detours: out 8 px past the start, back to 8 px
|
|
74
|
+
// before the end, then forward into the target. A gap of 0 px or less takes the same detour.
|
|
75
|
+
// Over 16 px, it tries the midpoint, then 8 px before the end, then 8 px after the start, and takes the first that clears `avoid`.
|
|
76
|
+
const y0 = Math.min(s.y, e.y), y1 = Math.max(s.y, e.y);
|
|
77
|
+
const clear = (x) => !avoid.some((r) => x > r.x - 2 && x < r.x + r.w + 2 && y1 > r.y && y0 < r.y + r.h);
|
|
78
|
+
const mx = e.x - s.x >= 16 ? ([(s.x + e.x) / 2, e.x - 8, s.x + 8].find(clear) ?? (s.x + e.x) / 2) : s.x + 8;
|
|
79
|
+
const c1 = { x: mx, y: s.y }, c2 = { x: mx, y: e.y };
|
|
80
|
+
if (e.x - s.x < 16 && s.y === e.y) {
|
|
81
|
+
// One row: a straight line, since a detour would only double back.
|
|
82
|
+
return { id: p.id, d: `M ${s.x} ${s.y} H ${e.x}`, mid: { x: (s.x + e.x) / 2, y: s.y }, curve: [s, s, e, e] };
|
|
83
|
+
}
|
|
84
|
+
if (e.x - s.x < 16) {
|
|
85
|
+
const ex = e.x - 8, my = (s.y + e.y) / 2;
|
|
86
|
+
return {
|
|
87
|
+
id: p.id,
|
|
88
|
+
d: `M ${s.x} ${s.y} H ${mx} V ${my} H ${ex} V ${e.y} H ${e.x}`,
|
|
89
|
+
mid: { x: (mx + ex) / 2, y: my },
|
|
90
|
+
curve: [s, { x: mx, y: my }, { x: ex, y: my }, e],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
return { id: p.id, d: `M ${s.x} ${s.y} H ${mx} V ${e.y} H ${e.x}`, mid: { x: mx, y: (s.y + e.y) / 2 }, curve: [s, c1, c2, e] };
|
|
94
|
+
}
|
|
68
95
|
if (p.around) {
|
|
69
96
|
// ponytail: arcs 50px past the two ends' boxes; a taller box in between can still be crossed.
|
|
70
97
|
const y = p.around === 'above' ? Math.min(p.a.y, p.b.y) - 50 : Math.max(p.a.y + p.a.h, p.b.y + p.b.h) + 50;
|
package/dist/gif.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Image } from './png.ts';
|
|
2
|
+
/** One frame: `load` returns the pixels (called twice per frame); `delay` is in centiseconds.
|
|
3
|
+
* `same` says the pixels equal the frame before: the encoder then never calls `load`. */
|
|
4
|
+
export type GifFrame = {
|
|
5
|
+
load: () => Image;
|
|
6
|
+
delay: number;
|
|
7
|
+
same?: boolean;
|
|
8
|
+
};
|
|
9
|
+
/** The delay of each of `count` frames in cs. The sum is round(count * 100 / fps). */
|
|
10
|
+
export declare function delays(count: number, fps: number): number[];
|
|
11
|
+
/** An animated GIF that loops forever. All frames have the size of the first frame. */
|
|
12
|
+
export declare function encodeGif(frames: GifFrame[]): Promise<Uint8Array>;
|
package/dist/gif.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/** The delay of each of `count` frames in cs. The sum is round(count * 100 / fps). */
|
|
2
|
+
export function delays(count, fps) {
|
|
3
|
+
// Each delay is a whole cs: the rounding error moves between frames and does not add up.
|
|
4
|
+
return Array.from({ length: count }, (_, i) => Math.round(((i + 1) * 100) / fps) - Math.round((i * 100) / fps));
|
|
5
|
+
}
|
|
6
|
+
// A color bin: 5 bits per channel, 32768 bins.
|
|
7
|
+
const binOf = (rgb) => ((rgb >> 9) & 0x7c00) | ((rgb >> 6) & 0x3e0) | ((rgb >> 3) & 0x1f);
|
|
8
|
+
const channel = (bin, c) => (bin >> (10 - 5 * c)) & 31;
|
|
9
|
+
/** Median cut: split the box with the widest channel range at its weighted median, until 256 boxes or one bin per box. */
|
|
10
|
+
function medianCut(bins, counts) {
|
|
11
|
+
const boxes = [bins];
|
|
12
|
+
while (boxes.length < 256) {
|
|
13
|
+
let pick = -1, widest = 0, axis = 0;
|
|
14
|
+
boxes.forEach((box, i) => {
|
|
15
|
+
for (let c = 0; c < 3; c++) {
|
|
16
|
+
let lo = 31, hi = 0;
|
|
17
|
+
for (const b of box) {
|
|
18
|
+
const v = channel(b, c);
|
|
19
|
+
if (v < lo)
|
|
20
|
+
lo = v;
|
|
21
|
+
if (v > hi)
|
|
22
|
+
hi = v;
|
|
23
|
+
}
|
|
24
|
+
if (hi - lo > widest)
|
|
25
|
+
[widest, pick, axis] = [hi - lo, i, c];
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
if (pick === -1)
|
|
29
|
+
break;
|
|
30
|
+
const box = boxes[pick].sort((a, b) => channel(a, axis) - channel(b, axis));
|
|
31
|
+
const half = box.reduce((s, b) => s + counts[b], 0) / 2;
|
|
32
|
+
let at = 1, seen = counts[box[0]];
|
|
33
|
+
while (at < box.length - 1 && seen + counts[box[at]] <= half)
|
|
34
|
+
seen += counts[box[at++]];
|
|
35
|
+
boxes.splice(pick, 1, box.slice(0, at), box.slice(at));
|
|
36
|
+
}
|
|
37
|
+
return boxes;
|
|
38
|
+
}
|
|
39
|
+
/** The palette: the exact colors if there are 256 or fewer, else median cut over the bins. No dither. */
|
|
40
|
+
function palette(exact, counts, sums) {
|
|
41
|
+
const colors = new Uint8Array(768);
|
|
42
|
+
if (exact) {
|
|
43
|
+
for (const [rgb, k] of exact)
|
|
44
|
+
colors.set([rgb >> 16, (rgb >> 8) & 255, rgb & 255], k * 3);
|
|
45
|
+
return { colors, index: (rgb) => exact.get(rgb) };
|
|
46
|
+
}
|
|
47
|
+
const bins = [];
|
|
48
|
+
for (let b = 0; b < 32768; b++)
|
|
49
|
+
if (counts[b])
|
|
50
|
+
bins.push(b);
|
|
51
|
+
const boxes = medianCut(bins, counts);
|
|
52
|
+
boxes.forEach((box, k) => {
|
|
53
|
+
let n = 0, r = 0, g = 0, b = 0;
|
|
54
|
+
for (const x of box) {
|
|
55
|
+
n += counts[x];
|
|
56
|
+
r += sums[x * 3];
|
|
57
|
+
g += sums[x * 3 + 1];
|
|
58
|
+
b += sums[x * 3 + 2];
|
|
59
|
+
}
|
|
60
|
+
colors.set([Math.round(r / n), Math.round(g / n), Math.round(b / n)], k * 3);
|
|
61
|
+
});
|
|
62
|
+
// Each bin maps to the palette color nearest to the mean color of the bin.
|
|
63
|
+
const table = new Uint8Array(32768);
|
|
64
|
+
for (const x of bins) {
|
|
65
|
+
const r = sums[x * 3] / counts[x], g = sums[x * 3 + 1] / counts[x], b = sums[x * 3 + 2] / counts[x];
|
|
66
|
+
let best = 0, dist = Infinity;
|
|
67
|
+
for (let k = 0; k < boxes.length; k++) {
|
|
68
|
+
const d = (colors[k * 3] - r) ** 2 + (colors[k * 3 + 1] - g) ** 2 + (colors[k * 3 + 2] - b) ** 2;
|
|
69
|
+
if (d < dist)
|
|
70
|
+
[dist, best] = [d, k];
|
|
71
|
+
}
|
|
72
|
+
table[x] = best;
|
|
73
|
+
}
|
|
74
|
+
return { colors, index: (rgb) => table[binOf(rgb)] };
|
|
75
|
+
}
|
|
76
|
+
/** GIF LZW: minimum code size 8, a clear code first, codes up to 12 bits, data in sub-blocks of 255 bytes or fewer. */
|
|
77
|
+
function lzw(px, width, rect, byte) {
|
|
78
|
+
const [x0, y0, x1, y1] = rect;
|
|
79
|
+
const CLEAR = 256, END = 257;
|
|
80
|
+
const block = new Uint8Array(255);
|
|
81
|
+
const dict = new Map();
|
|
82
|
+
let blen = 0, acc = 0, bits = 0, size = 9, next = 258, prefix = -1;
|
|
83
|
+
const flush = () => {
|
|
84
|
+
byte(blen);
|
|
85
|
+
for (let i = 0; i < blen; i++)
|
|
86
|
+
byte(block[i]);
|
|
87
|
+
blen = 0;
|
|
88
|
+
};
|
|
89
|
+
const emit = (code) => {
|
|
90
|
+
acc |= code << bits;
|
|
91
|
+
for (bits += size; bits >= 8; bits -= 8, acc >>>= 8) {
|
|
92
|
+
block[blen++] = acc & 255;
|
|
93
|
+
if (blen === 255)
|
|
94
|
+
flush();
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
byte(8);
|
|
98
|
+
emit(CLEAR);
|
|
99
|
+
for (let y = y0; y <= y1; y++)
|
|
100
|
+
for (let x = x0; x <= x1; x++) {
|
|
101
|
+
const k = px[y * width + x];
|
|
102
|
+
if (prefix < 0) {
|
|
103
|
+
prefix = k;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
const code = dict.get((prefix << 8) | k);
|
|
107
|
+
if (code !== undefined) {
|
|
108
|
+
prefix = code;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
emit(prefix);
|
|
112
|
+
if (next === 4096) {
|
|
113
|
+
emit(CLEAR);
|
|
114
|
+
dict.clear();
|
|
115
|
+
[next, size] = [258, 9];
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
// The decoder runs one code behind: grow the size when the new code no longer fits.
|
|
119
|
+
if (next >= 1 << size)
|
|
120
|
+
size++;
|
|
121
|
+
dict.set((prefix << 8) | k, next++);
|
|
122
|
+
}
|
|
123
|
+
prefix = k;
|
|
124
|
+
}
|
|
125
|
+
emit(prefix);
|
|
126
|
+
emit(END);
|
|
127
|
+
if (bits > 0) {
|
|
128
|
+
block[blen++] = acc & 255;
|
|
129
|
+
if (blen === 255)
|
|
130
|
+
flush();
|
|
131
|
+
}
|
|
132
|
+
if (blen)
|
|
133
|
+
flush();
|
|
134
|
+
byte(0);
|
|
135
|
+
}
|
|
136
|
+
/** An animated GIF that loops forever. All frames have the size of the first frame. */
|
|
137
|
+
// It yields to the event loop between frames, so a signal handler can run while the encode goes on.
|
|
138
|
+
export async function encodeGif(frames) {
|
|
139
|
+
if (!frames.length)
|
|
140
|
+
throw new Error('a GIF needs at least one frame');
|
|
141
|
+
// Pass 1: count the colors of all frames.
|
|
142
|
+
const counts = new Uint32Array(32768), sums = new Float64Array(32768 * 3);
|
|
143
|
+
let exact = new Map(), width = 0, height = 0;
|
|
144
|
+
for (let f = 0; f < frames.length; f++) {
|
|
145
|
+
if (frames[f].same && f > 0)
|
|
146
|
+
continue;
|
|
147
|
+
// A run of equal frames counts once, with the weight of the run.
|
|
148
|
+
let weight = 1;
|
|
149
|
+
while (f + weight < frames.length && frames[f + weight].same)
|
|
150
|
+
weight++;
|
|
151
|
+
await new Promise(setImmediate);
|
|
152
|
+
const { width: w, height: h, data } = frames[f].load();
|
|
153
|
+
if (f === 0)
|
|
154
|
+
[width, height] = [w, h];
|
|
155
|
+
else if (w !== width || h !== height)
|
|
156
|
+
throw new Error(`frame ${f + 1} is ${w} x ${h}; the first frame is ${width} x ${height}`);
|
|
157
|
+
let last = -1, bin = 0;
|
|
158
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
159
|
+
const rgb = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2];
|
|
160
|
+
if (rgb !== last) {
|
|
161
|
+
last = rgb;
|
|
162
|
+
bin = binOf(rgb);
|
|
163
|
+
if (exact && !exact.has(rgb))
|
|
164
|
+
exact = exact.size < 256 ? exact.set(rgb, exact.size) : null;
|
|
165
|
+
}
|
|
166
|
+
counts[bin] += weight;
|
|
167
|
+
sums[bin * 3] += data[i] * weight;
|
|
168
|
+
sums[bin * 3 + 1] += data[i + 1] * weight;
|
|
169
|
+
sums[bin * 3 + 2] += data[i + 2] * weight;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const { colors, index } = palette(exact, counts, sums);
|
|
173
|
+
let buf = new Uint8Array(1 << 20), len = 0;
|
|
174
|
+
const byte = (v) => {
|
|
175
|
+
if (len === buf.length) {
|
|
176
|
+
const grown = new Uint8Array(buf.length * 2);
|
|
177
|
+
grown.set(buf);
|
|
178
|
+
buf = grown;
|
|
179
|
+
}
|
|
180
|
+
buf[len++] = v;
|
|
181
|
+
};
|
|
182
|
+
const word = (v) => {
|
|
183
|
+
byte(v & 255);
|
|
184
|
+
byte(v >> 8);
|
|
185
|
+
};
|
|
186
|
+
const bytes = (...vs) => vs.forEach(byte);
|
|
187
|
+
const text = (s) => {
|
|
188
|
+
for (const c of s)
|
|
189
|
+
byte(c.charCodeAt(0));
|
|
190
|
+
};
|
|
191
|
+
text('GIF89a');
|
|
192
|
+
word(width);
|
|
193
|
+
word(height);
|
|
194
|
+
bytes(0xf7, 0, 0); // a global color table of 256 colors; background color 0; no aspect ratio
|
|
195
|
+
colors.forEach(byte);
|
|
196
|
+
bytes(0x21, 0xff, 11);
|
|
197
|
+
text('NETSCAPE2.0');
|
|
198
|
+
bytes(3, 1, 0, 0, 0); // loop count 0: loop forever
|
|
199
|
+
// Pass 2: each frame as palette indices. A later frame sends only the rectangle that changed.
|
|
200
|
+
let prev = null;
|
|
201
|
+
for (const frame of frames) {
|
|
202
|
+
await new Promise(setImmediate);
|
|
203
|
+
let cur = prev;
|
|
204
|
+
if (!(frame.same && prev)) {
|
|
205
|
+
const { data } = frame.load();
|
|
206
|
+
cur = new Uint8Array(width * height);
|
|
207
|
+
let last = -1, k = 0;
|
|
208
|
+
for (let p = 0, i = 0; p < cur.length; p++, i += 4) {
|
|
209
|
+
const rgb = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2];
|
|
210
|
+
if (rgb !== last)
|
|
211
|
+
[last, k] = [rgb, index(rgb)];
|
|
212
|
+
cur[p] = k;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
let rect = [0, 0, width - 1, height - 1];
|
|
216
|
+
if (cur === prev)
|
|
217
|
+
rect = [0, 0, -1, -1];
|
|
218
|
+
else if (prev) {
|
|
219
|
+
rect = [width, height, -1, -1];
|
|
220
|
+
for (let y = 0, p = 0; y < height; y++)
|
|
221
|
+
for (let x = 0; x < width; x++, p++)
|
|
222
|
+
if (cur[p] !== prev[p]) {
|
|
223
|
+
if (x < rect[0])
|
|
224
|
+
rect[0] = x;
|
|
225
|
+
if (x > rect[2])
|
|
226
|
+
rect[2] = x;
|
|
227
|
+
if (y < rect[1])
|
|
228
|
+
rect[1] = y;
|
|
229
|
+
rect[3] = y;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
// No change: a 1 x 1 frame that paints the old color keeps the frame and its delay.
|
|
233
|
+
if (rect[2] < 0)
|
|
234
|
+
rect = [0, 0, 0, 0];
|
|
235
|
+
bytes(0x21, 0xf9, 4, 1 << 2); // disposal method 1: the next frame draws over this frame
|
|
236
|
+
word(frame.delay);
|
|
237
|
+
bytes(0, 0, 0x2c);
|
|
238
|
+
[rect[0], rect[1], rect[2] - rect[0] + 1, rect[3] - rect[1] + 1].forEach(word);
|
|
239
|
+
byte(0);
|
|
240
|
+
lzw(cur, width, rect, byte);
|
|
241
|
+
prev = cur;
|
|
242
|
+
}
|
|
243
|
+
byte(0x3b);
|
|
244
|
+
return buf.slice(0, len);
|
|
245
|
+
}
|