excalideck 0.0.1 → 0.2.1

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.
@@ -0,0 +1,83 @@
1
+ // From cli-contract 1.0, reference/install-method.ts (https://github.com/edspencer/cli-contract), translated to JS
2
+ // and trimmed: excalideck has no `update` (AGENTS.md), so this detects how it was installed for `doctor` and leaves
3
+ // out `updateCommand`. Node built-ins only.
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ export const inDockerVar = (prefix) => `${prefix}_IN_DOCKER`;
9
+ export const updateHintVar = (prefix) => `${prefix}_UPDATE_HINT`;
10
+
11
+ const realpathOr = (p) => { try { return fs.realpathSync(p); } catch { return p; } };
12
+ const segments = (p) => p.split(/[/\\]/);
13
+
14
+ /** Walks up from `entry` to the folder whose `package.json` has our name. */
15
+ export function findPackageRoot(entry, packageName) {
16
+ let dir = path.dirname(realpathOr(entry));
17
+ let nearest;
18
+ for (;;) {
19
+ const manifest = path.join(dir, "package.json");
20
+ if (fs.existsSync(manifest)) {
21
+ nearest ??= dir;
22
+ try { if (JSON.parse(fs.readFileSync(manifest, "utf8")).name === packageName) return { root: dir, named: true }; }
23
+ catch { /* a broken package.json on the way up isn't ours; keep walking */ }
24
+ }
25
+ const parent = path.dirname(dir);
26
+ if (parent === dir) return { root: nearest, named: false };
27
+ dir = parent;
28
+ }
29
+ }
30
+
31
+ /** Whether a path is inside a `node_modules` folder: by segment, so `my-node_modules` isn't one. */
32
+ export const underNodeModules = (p) => segments(p).includes("node_modules");
33
+
34
+ /** The npx, pnpm dlx, bunx and yarn dlx caches (SPEC §6). */
35
+ export const isEphemeralCachePath = (p) =>
36
+ segments(p).some((s) => s === "_npx" || s === "dlx" || s.startsWith("dlx-") || s.startsWith("bunx-"));
37
+
38
+ function hasSegments(p, run) {
39
+ const parts = segments(p);
40
+ for (let i = 0; i + run.length <= parts.length; i++) if (run.every((s, j) => parts[i + j] === s)) return true;
41
+ return false;
42
+ }
43
+
44
+ const samePath = (a, b) => path.resolve(a) === path.resolve(b) || realpathOr(a) === realpathOr(b);
45
+
46
+ /** Which of SPEC §6's rows this install is, checked in the table's order. */
47
+ export function detectInstall(input) {
48
+ const env = input.env ?? process.env;
49
+ const { root, named } = findPackageRoot(input.entry, input.packageName);
50
+ const hintValue = env[updateHintVar(input.envPrefix)];
51
+ const hint = hintValue !== undefined && hintValue !== "" ? hintValue : undefined;
52
+ const base = { packageRoot: root, named, ...(hint !== undefined ? { hint } : {}) };
53
+
54
+ if (env[inDockerVar(input.envPrefix)] === "1") return { ...base, method: "docker", canUpdate: false };
55
+ if (hint !== undefined) return { ...base, method: "managed", canUpdate: false };
56
+ if (root === undefined) return { ...base, method: "checkout", canUpdate: false };
57
+ if (isEphemeralCachePath(root)) return { ...base, method: "npx", canUpdate: false };
58
+ if (!underNodeModules(root)) return { ...base, method: "checkout", canUpdate: false };
59
+ const globalRoot = input.npmGlobalRoot?.();
60
+ if (globalRoot !== undefined && samePath(root, path.join(globalRoot, input.packageName))) {
61
+ return { ...base, method: "npm-global", canUpdate: true, manager: "npm" };
62
+ }
63
+ if (hasSegments(root, ["pnpm", "global"])) return { ...base, method: "pnpm-global", canUpdate: true, manager: "pnpm" };
64
+ if (hasSegments(root, [".bun", "install", "global"])) return { ...base, method: "bun-global", canUpdate: true, manager: "bun" };
65
+ if (hasSegments(root, [".volta", "tools", "image", "packages"])) return { ...base, method: "volta", canUpdate: true, manager: "volta" };
66
+ if (hasSegments(root, ["yarn", "global", "node_modules"])) return { ...base, method: "yarn-global", canUpdate: false };
67
+ return { ...base, method: "dependency", canUpdate: false };
68
+ }
69
+
70
+ const DESCRIPTIONS = {
71
+ docker: "in a Docker image",
72
+ managed: "managed from outside (an Ansible role, say)",
73
+ npx: "from an npx, dlx or bunx cache",
74
+ checkout: "from a checkout (or npm link)",
75
+ "npm-global": "a global npm install",
76
+ "pnpm-global": "a global pnpm install",
77
+ "bun-global": "a global bun install",
78
+ volta: "installed by Volta",
79
+ "yarn-global": "a global yarn (classic) install",
80
+ dependency: "a dependency of another project",
81
+ };
82
+
83
+ export const describeInstall = (info) => DESCRIPTIONS[info.method] ?? info.method;
@@ -0,0 +1,83 @@
1
+ // From cli-contract 1.0, reference/output.ts (https://github.com/edspencer/cli-contract), translated to JS.
2
+ // A CLI's output, the way SPEC §2 and §3 say: errors as `<tool>: <message>` on stderr, colour only on a TTY
3
+ // (honouring NO_COLOR and FORCE_COLOR), and with `--json`, one JSON document on stdout and every word of prose
4
+ // on stderr. Node built-ins only.
5
+
6
+ import { EXIT } from "./exit-codes.js";
7
+
8
+ /**
9
+ * Whether to colour what goes to this stream (SPEC §3).
10
+ * - `NO_COLOR` set to anything but the empty string: never (https://no-color.org).
11
+ * - `FORCE_COLOR` set: `0` or `false` means never, anything else always.
12
+ * - Otherwise only on a TTY, and not when `TERM=dumb`.
13
+ */
14
+ export function useColor(stream, env = process.env) {
15
+ if (env.NO_COLOR !== undefined && env.NO_COLOR !== "") return false;
16
+ if (env.FORCE_COLOR !== undefined) return env.FORCE_COLOR !== "0" && env.FORCE_COLOR !== "false";
17
+ if (env.TERM === "dumb") return false;
18
+ return stream.isTTY === true;
19
+ }
20
+
21
+ const sgr = (open, close) => (s) => `\u001b[${open}m${s}\u001b[${close}m`;
22
+ const plain = (s) => s;
23
+
24
+ /** Colour functions that do nothing when `on` is false. */
25
+ export function paint(on) {
26
+ return on
27
+ ? { bold: sgr(1, 22), dim: sgr(2, 22), red: sgr(31, 39), green: sgr(32, 39), yellow: sgr(33, 39) }
28
+ : { bold: plain, dim: plain, red: plain, green: plain, yellow: plain };
29
+ }
30
+
31
+ /** One place for a command's output. Make it once per command, after the flags are parsed. */
32
+ export function createOutput(o) {
33
+ const stdout = o.stdout ?? process.stdout;
34
+ const stderr = o.stderr ?? process.stderr;
35
+ const env = o.env ?? process.env;
36
+ const json = o.json === true;
37
+ let printed = false;
38
+ const line = (s) => (s.endsWith("\n") ? s : `${s}\n`);
39
+ return {
40
+ json,
41
+ color: paint(!json && useColor(stdout, env)),
42
+ errColor: paint(useColor(stderr, env)),
43
+ /** Prose for a person: stdout, or stderr under `--json`. */
44
+ say(s) { (json ? stderr : stdout).write(line(s)); },
45
+ /** A warning on stderr, always. */
46
+ warn(s) { stderr.write(line(s)); },
47
+ /** `<tool>: <message>` on stderr. Returns `code` (default 1), for `return out.error(…)`. */
48
+ error(message, code = EXIT.FAILED) { stderr.write(line(`${o.tool}: ${message}`)); return code; },
49
+ /** The one JSON document `--json` promises. Prints nothing without `--json`. */
50
+ result(doc) {
51
+ if (!json) return;
52
+ if (printed) throw new Error("--json prints one document; result() was called twice");
53
+ printed = true;
54
+ stdout.write(`${JSON.stringify(doc, null, 2)}\n`);
55
+ },
56
+ };
57
+ }
58
+
59
+ /**
60
+ * A usage error (SPEC §2: exit 2, with the usage after the message). Throw it from argument parsing and let the
61
+ * top level print it with `reportUsageError`.
62
+ */
63
+ export class UsageError extends Error {
64
+ name = "UsageError";
65
+ }
66
+
67
+ /** Prints `<tool>: <message>`, then the usage, on stderr, and returns 2. */
68
+ export function reportUsageError(out, err, usage) {
69
+ out.error(err.message);
70
+ out.warn(`\n${usage.trimEnd()}`);
71
+ return EXIT.USAGE;
72
+ }
73
+
74
+ /**
75
+ * A closed pipe (`<tool> … | head -1`) exits quietly (SPEC §2): without this, Node throws EPIPE from a later write
76
+ * and prints a stack trace. Call once, at startup.
77
+ */
78
+ export function exitQuietlyOnEpipe(stream = process.stdout, exit = (c) => process.exit(c)) {
79
+ stream.on("error", (err) => {
80
+ if (err.code === "EPIPE") exit(typeof process.exitCode === "number" ? process.exitCode : 0);
81
+ else throw err;
82
+ });
83
+ }
@@ -0,0 +1,59 @@
1
+ // From cli-contract 1.0, reference/runtime-file.ts (https://github.com/edspencer/cli-contract), translated to JS.
2
+ // `<home>/runtime.json`: what a running instance tells its own CLI (SPEC §4). `serve` writes it once it's listening
3
+ // and removes it on a clean exit; `busy` reads it to find the instance. Node built-ins only.
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+
8
+ export const RUNTIME_FILE = "runtime.json";
9
+
10
+ export const runtimeFilePath = (home) => path.join(home, RUNTIME_FILE);
11
+
12
+ /** Writes the file atomically (a temporary file, then a rename), readable only by this user. */
13
+ export function writeRuntimeFile(home, info) {
14
+ const full = {
15
+ pid: info.pid, port: info.port, url: info.url, version: info.version,
16
+ startedAt: info.startedAt ?? new Date().toISOString(),
17
+ };
18
+ fs.mkdirSync(home, { recursive: true });
19
+ const file = runtimeFilePath(home);
20
+ const tmp = `${file}.${process.pid}.tmp`;
21
+ fs.writeFileSync(tmp, `${JSON.stringify(full, null, 2)}\n`, { mode: 0o600 });
22
+ try { fs.renameSync(tmp, file); } catch (err) { fs.rmSync(tmp, { force: true }); throw err; }
23
+ return full;
24
+ }
25
+
26
+ /** The file's contents, or null if it's missing or isn't a runtime file (a half-written or foreign file). */
27
+ export function readRuntimeFile(home) {
28
+ let raw;
29
+ try { raw = fs.readFileSync(runtimeFilePath(home), "utf8"); } catch { return null; }
30
+ try {
31
+ const v = JSON.parse(raw);
32
+ if (Number.isInteger(v.pid) && Number.isInteger(v.port) && typeof v.url === "string" &&
33
+ typeof v.version === "string" && typeof v.startedAt === "string") return v;
34
+ } catch { /* fall through */ }
35
+ return null;
36
+ }
37
+
38
+ /**
39
+ * Removes the file, but only if it's still ours: a second instance may have started since and written its own.
40
+ * Call it on a clean exit. Returns whether it removed anything.
41
+ */
42
+ export function removeRuntimeFile(home, pid = process.pid) {
43
+ const info = readRuntimeFile(home);
44
+ if (!info || info.pid !== pid) return false;
45
+ fs.rmSync(runtimeFilePath(home), { force: true });
46
+ return true;
47
+ }
48
+
49
+ /** Whether a process with this pid exists. EPERM means it exists but isn't ours, which still counts. */
50
+ export function isPidAlive(pid) {
51
+ if (!Number.isInteger(pid) || pid <= 0) return false;
52
+ try { process.kill(pid, 0); return true; } catch (err) { return err.code === "EPERM"; }
53
+ }
54
+
55
+ /** The runtime file, if the process it names is still alive. A crashed instance leaves a stale file behind. */
56
+ export function readLiveRuntimeFile(home) {
57
+ const info = readRuntimeFile(home);
58
+ return info && isPidAlive(info.pid) ? info : null;
59
+ }
@@ -0,0 +1,101 @@
1
+ // From cli-contract 1.0, reference/semver.ts (https://github.com/edspencer/cli-contract), translated to JS and
2
+ // trimmed to what `doctor` needs: does this Node satisfy the package's `engines`. Node built-ins only.
3
+ //
4
+ // A range it can't read is "can't tell" (undefined), not "fails".
5
+
6
+ const VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/;
7
+ const COMPARATOR_RE = /^(>=|<=|>|<|=|\^|~)?\s*v?(\d+)(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z.-]+))?$/;
8
+
9
+ const identifiers = (s) => s.split(".").map((id) => (/^\d+$/.test(id) ? Number(id) : id));
10
+
11
+ /** `1.2.3-rc.1` as a version, or undefined if it isn't one. */
12
+ export function parseVersion(raw) {
13
+ const m = VERSION_RE.exec(String(raw).trim());
14
+ if (m === null) return undefined;
15
+ return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), prerelease: m[4] === undefined ? [] : identifiers(m[4]) };
16
+ }
17
+
18
+ function compare(va, vb) {
19
+ for (const k of ["major", "minor", "patch"]) if (va[k] !== vb[k]) return va[k] < vb[k] ? -1 : 1;
20
+ if (va.prerelease.length === 0 && vb.prerelease.length === 0) return 0;
21
+ if (va.prerelease.length === 0) return 1;
22
+ if (vb.prerelease.length === 0) return -1;
23
+ const n = Math.max(va.prerelease.length, vb.prerelease.length);
24
+ for (let i = 0; i < n; i++) {
25
+ const x = va.prerelease[i], y = vb.prerelease[i];
26
+ if (x === undefined) return -1;
27
+ if (y === undefined) return 1;
28
+ if (x === y) continue;
29
+ if (typeof x === "number" && typeof y === "number") return x < y ? -1 : 1;
30
+ if (typeof x === "number") return -1;
31
+ if (typeof y === "number") return 1;
32
+ return x < y ? -1 : 1;
33
+ }
34
+ return 0;
35
+ }
36
+
37
+ /** -1, 0 or 1 by semver's rules. Something that isn't a version compares as equal rather than throwing. */
38
+ export function compareVersions(a, b) {
39
+ const va = parseVersion(a), vb = parseVersion(b);
40
+ if (va === undefined || vb === undefined) return 0;
41
+ return compare(va, vb);
42
+ }
43
+
44
+ /** One range atom as the comparators it means: `^22.1.0` is `>=22.1.0 <23.0.0`. Undefined for anything else. */
45
+ function comparatorsFor(atom) {
46
+ const m = COMPARATOR_RE.exec(atom);
47
+ if (m === null) return undefined;
48
+ const op = m[1] ?? "=";
49
+ const wild = (s) => s === undefined || s === "x" || s === "X" || s === "*";
50
+ const major = Number(m[2]);
51
+ const minorWild = wild(m[3]), patchWild = wild(m[4]);
52
+ const minor = minorWild ? 0 : Number(m[3]), patch = patchWild ? 0 : Number(m[4]);
53
+ const at = (ma, mi, pa) => ({ major: ma, minor: mi, patch: pa, prerelease: [] });
54
+ const lower = { major, minor, patch, prerelease: m[5] === undefined ? [] : identifiers(m[5]) };
55
+ const between = (upper) => [{ op: ">=", version: lower }, { op: "<", version: upper }];
56
+ if (op === "^") {
57
+ if (major > 0 || minorWild) return between(at(major + 1, 0, 0));
58
+ if (minor > 0 || patchWild) return between(at(0, minor + 1, 0));
59
+ return between(at(0, 0, patch + 1));
60
+ }
61
+ if (op === "~") return between(minorWild ? at(major + 1, 0, 0) : at(major, minor + 1, 0));
62
+ if (op === "=" && (minorWild || patchWild)) return between(minorWild ? at(major + 1, 0, 0) : at(major, minor + 1, 0));
63
+ return [{ op, version: lower }];
64
+ }
65
+
66
+ function satisfiesComparator(v, c) {
67
+ const cmp = compare(v, c.version);
68
+ return c.op === ">=" ? cmp >= 0 : c.op === "<=" ? cmp <= 0 : c.op === ">" ? cmp > 0 : c.op === "<" ? cmp < 0 : cmp === 0;
69
+ }
70
+
71
+ /**
72
+ * Whether `version` satisfies `range`; undefined when this file can't tell.
73
+ * Reads what `engines.node` uses in practice: `>=22`, `^22.1.0`, `~22.1`, `22`, `22.x`, `>=20 <23`, and `||`.
74
+ */
75
+ export function satisfies(version, range) {
76
+ const v = parseVersion(version);
77
+ if (v === undefined) return undefined;
78
+ const trimmed = String(range).trim();
79
+ if (trimmed === "" || trimmed === "*" || trimmed === "x") return true;
80
+ let known = false;
81
+ for (const alt of trimmed.split("||")) {
82
+ const comparators = [];
83
+ let parsed = true;
84
+ for (const atom of alt.trim().split(/\s+/).filter(Boolean)) {
85
+ const cs = comparatorsFor(atom);
86
+ if (cs === undefined) { parsed = false; break; }
87
+ comparators.push(...cs);
88
+ }
89
+ if (!parsed) continue;
90
+ known = true;
91
+ if (comparators.every((c) => satisfiesComparator(v, c))) return true;
92
+ }
93
+ return known ? false : undefined;
94
+ }
95
+
96
+ /** `{ ok, range }`. `ok: undefined` means the range couldn't be read, which callers treat as a pass. */
97
+ export function satisfiesEngines(nodeVersion, engines) {
98
+ const range = engines?.node;
99
+ if (range === undefined || String(range).trim() === "") return { ok: true, range: undefined };
100
+ return { ok: satisfies(nodeVersion, range), range };
101
+ }
package/src/metrics.js ADDED
@@ -0,0 +1,4 @@
1
+ // Advance widths (px at fontSize 100) measured in Chrome from the bundled fonts.
2
+ // Keys are Excalidraw fontFamily ids: 1 Virgil, 2 Helvetica, 3 Cascadia/monospace, 5 Excalifont.
3
+ // Regenerate by measuring with canvas.measureText if fonts change.
4
+ export const ADVANCE = {"1":{"0":68.8,"1":27.1,"2":71.2,"3":68.1,"4":64,"5":61.8,"6":64,"7":53.8,"8":76.5,"9":60.9," ":50,"!":29.6,"\"":32.8,"#":79.7,"$":80.3,"%":93.9,"&":71.9,"'":26.6,"(":41.5,")":33.8,"*":51.6,"+":62.5,",":25.7,"-":41.1,".":27.4,"/":50,":":24.2,";":25.8,"<":60.5,"=":61.7,">":48.5,"?":46.6,"@":80.5,"A":65.6,"B":72.7,"C":64.4,"D":78,"E":67.4,"F":57.4,"G":78.9,"H":55.1,"I":54.5,"J":63.4,"K":61.3,"L":59.9,"M":76.6,"N":64.4,"O":72.6,"P":66.1,"Q":70.5,"R":67.8,"S":60.8,"T":80.4,"U":71.4,"V":51.7,"W":74.6,"X":59.8,"Y":51.6,"Z":79.7,"[":49.1,"\\":50,"]":50,"^":54.4,"_":82.6,"`":43.7,"a":66.7,"b":50.8,"c":50.2,"d":56.9,"e":54.7,"f":48.6,"g":50.1,"h":49.4,"i":21.9,"j":32.8,"k":48.7,"l":26.3,"m":63.3,"n":46.7,"o":55.4,"p":49.3,"q":54.6,"r":43,"s":54.3,"t":56.5,"u":56.8,"v":52.3,"w":60.9,"x":56.2,"y":46.9,"z":57.2,"{":57.3,"|":16.8,"}":49.6,"~":84.1,"‘":49.4,"’":40.6,"“":48.7,"”":51.3,"–":68.8,"—":91.1,"…":67.7,"•":32.2,"→":100,"←":100,"↑":50,"↓":50,"×":44.6,"é":61.6},"2":{"0":55.6,"1":55.6,"2":55.6,"3":55.6,"4":55.6,"5":55.6,"6":55.6,"7":55.6,"8":55.6,"9":55.6," ":27.8,"!":27.8,"\"":35.5,"#":55.6,"$":55.6,"%":88.9,"&":66.7,"'":19.1,"(":33.3,")":33.3,"*":38.9,"+":58.4,",":27.8,"-":33.3,".":27.8,"/":27.8,":":27.8,";":27.8,"<":58.4,"=":58.4,">":58.4,"?":55.6,"@":101.5,"A":66.7,"B":66.7,"C":72.2,"D":72.2,"E":66.7,"F":61.1,"G":77.8,"H":72.2,"I":27.8,"J":50,"K":66.7,"L":55.6,"M":83.3,"N":72.2,"O":77.8,"P":66.7,"Q":77.8,"R":72.2,"S":66.7,"T":61.1,"U":72.2,"V":66.7,"W":94.4,"X":66.7,"Y":66.7,"Z":61.1,"[":27.8,"\\":27.8,"]":27.8,"^":46.9,"_":55.6,"`":33.3,"a":55.6,"b":55.6,"c":50,"d":55.6,"e":55.6,"f":27.8,"g":55.6,"h":55.6,"i":22.2,"j":22.2,"k":50,"l":22.2,"m":83.3,"n":55.6,"o":55.6,"p":55.6,"q":55.6,"r":33.3,"s":50,"t":27.8,"u":55.6,"v":50,"w":72.2,"x":50,"y":50,"z":50,"{":33.4,"|":26,"}":33.4,"~":58.4,"‘":22.2,"’":22.2,"“":33.3,"”":33.3,"–":55.6,"—":100,"…":100,"•":35,"→":100,"←":100,"↑":50,"↓":50,"×":58.4,"é":55.6},"3":{"0":60.2,"1":60.2,"2":60.2,"3":60.2,"4":60.2,"5":60.2,"6":60.2,"7":60.2,"8":60.2,"9":60.2," ":60.2,"!":60.2,"\"":60.2,"#":60.2,"$":60.2,"%":60.2,"&":60.2,"'":60.2,"(":60.2,")":60.2,"*":60.2,"+":60.2,",":60.2,"-":60.2,".":60.2,"/":60.2,":":60.2,";":60.2,"<":60.2,"=":60.2,">":60.2,"?":60.2,"@":60.2,"A":60.2,"B":60.2,"C":60.2,"D":60.2,"E":60.2,"F":60.2,"G":60.2,"H":60.2,"I":60.2,"J":60.2,"K":60.2,"L":60.2,"M":60.2,"N":60.2,"O":60.2,"P":60.2,"Q":60.2,"R":60.2,"S":60.2,"T":60.2,"U":60.2,"V":60.2,"W":60.2,"X":60.2,"Y":60.2,"Z":60.2,"[":60.2,"\\":60.2,"]":60.2,"^":60.2,"_":60.2,"`":60.2,"a":60.2,"b":60.2,"c":60.2,"d":60.2,"e":60.2,"f":60.2,"g":60.2,"h":60.2,"i":60.2,"j":60.2,"k":60.2,"l":60.2,"m":60.2,"n":60.2,"o":60.2,"p":60.2,"q":60.2,"r":60.2,"s":60.2,"t":60.2,"u":60.2,"v":60.2,"w":60.2,"x":60.2,"y":60.2,"z":60.2,"{":60.2,"|":60.2,"}":60.2,"~":60.2,"‘":60.2,"’":60.2,"“":60.2,"”":60.2,"–":60.2,"—":60.2,"…":60.2,"•":60.2,"→":60.2,"←":60.2,"↑":60.2,"↓":60.2,"×":60.2,"é":60.2},"5":{"0":66.4,"1":42.7,"2":70,"3":60.8,"4":58.5,"5":61.8,"6":64,"7":55.8,"8":63.6,"9":62.9," ":40,"!":31.4,"\"":37.1,"#":78.3,"$":72.1,"%":92.8,"&":71.8,"'":21.8,"(":44.1,")":40.2,"*":52.5,"+":55,",":25.7,"-":41.1,".":27.4,"/":56.1,":":26.4,";":29.8,"<":55,"=":55,">":55,"?":46.6,"@":82.9,"A":67.6,"B":76.1,"C":62.9,"D":78,"E":70.7,"F":66.1,"G":78,"H":57.3,"I":54.5,"J":56.9,"K":61.3,"L":54.3,"M":76.6,"N":63.2,"O":76.7,"P":69.8,"Q":76.8,"R":73.6,"S":62.2,"T":85.7,"U":73,"V":59.2,"W":78.6,"X":62.8,"Y":56.4,"Z":83.2,"[":47.2,"\\":58.9,"]":49.7,"^":51,"_":67,"`":60,"a":57.6,"b":55.5,"c":50.4,"d":60.5,"e":53.7,"f":49.7,"g":55.5,"h":56.7,"i":24.4,"j":32.8,"k":53.3,"l":22.5,"m":66.3,"n":52.6,"o":60,"p":53.7,"q":53.9,"r":41.2,"s":54.3,"t":55.3,"u":54.8,"v":52.5,"w":69.3,"x":59.1,"y":53,"z":57.2,"{":50.4,"|":29.9,"}":54.4,"~":66.9,"‘":26.7,"’":30.4,"“":41.2,"”":42.8,"–":70.2,"—":93.5,"…":70.9,"•":52.2,"→":100,"←":100,"↑":50,"↓":50,"×":55,"é":55.1}};
package/src/scene.js ADDED
@@ -0,0 +1,187 @@
1
+ // Shared by the browser player and the Node CLI: reading an .excalidraw file into slides,
2
+ // and deciding which shapes on one slide correspond to which shapes on the next.
3
+ import { ADVANCE } from "./metrics.js";
4
+
5
+ export const TRANSITIONS = ["morph", "zoom", "camera", "fade", "cut"];
6
+ export const APPEARS = ["fade", "pop", "draw", "rise"];
7
+ export const norm = (s) => String(s).toLowerCase().replace(/\s+/g, " ").trim();
8
+
9
+ /** Width in px of one line of text, from measured advance widths (no canvas needed). */
10
+ export function textWidth(line, fontSize, fontFamily = 5) {
11
+ const table = ADVANCE[fontFamily] || ADVANCE[5];
12
+ let w = 0;
13
+ for (const ch of line) w += table[ch] ?? table["M"] ?? 60;
14
+ return (w * fontSize) / 100;
15
+ }
16
+
17
+ /** "03 Opening the box [zoom pop]" → { num: 3, title, mode: "zoom", appear: "pop", … } */
18
+ export function parseFrameName(name = "", idx = 0) {
19
+ const tags = [...name.matchAll(/\[([^\]]*)\]/g)].flatMap((m) => m[1].toLowerCase().split(/[\s,]+/)).filter(Boolean);
20
+ let mode = null, appear = null, speed = 1, stagger = true;
21
+ const unknown = [];
22
+ for (const t of tags) {
23
+ if (TRANSITIONS.includes(t) && !mode) mode = t;
24
+ else if (APPEARS.includes(t)) appear = t;
25
+ else if (t === "slow") speed = 1.6;
26
+ else if (t === "fast") speed = 0.6;
27
+ else if (t === "nostagger") stagger = false;
28
+ else unknown.push(t);
29
+ }
30
+ const num = name.match(/^\s*(\d+(?:\.\d+)?)/);
31
+ const title = name.replace(/\[[^\]]*\]/g, "").replace(/^\s*\d+(\.\d+)?\s*[.:\-–—)]?\s*/, "").trim();
32
+ return { mode, appear, speed, stagger, unknownTags: unknown, num: num ? parseFloat(num[1]) : null, title: title || `Slide ${idx + 1}` };
33
+ }
34
+
35
+ /**
36
+ * Turn Excalidraw JSON into slides. Each slide: { title, mode, appear, x, y, w, h, items[] }.
37
+ * Item coordinates are relative to their frame. `opts.image(fileId, file)` may return a drawable image.
38
+ */
39
+ export function loadScene(data, opts = {}) {
40
+ const all = (data.elements || []).filter((e) => !e.isDeleted);
41
+ const byId = new Map(all.map((e) => [e.id, e]));
42
+ const zOf = new Map(all.map((e, i) => [e.id, i]));
43
+ const files = data.files || {};
44
+ const labelOf = new Map();
45
+ for (const e of all) if (e.type === "text" && e.containerId && byId.has(e.containerId)) labelOf.set(e.containerId, e);
46
+
47
+ let frames = all.filter((e) => e.type === "frame" || e.type === "magicframe").map((el, idx) => ({ el, idx, name: el.name || "", ...parseFrameName(el.name || "", idx) }));
48
+ frames.sort((a, b) => (a.num ?? 1e9) - (b.num ?? 1e9) || a.idx - b.idx);
49
+ if (!frames.length && all.length) { // no frames: the whole drawing is one slide
50
+ const xs = all.flatMap((e) => [e.x, e.x + e.width]), ys = all.flatMap((e) => [e.y, e.y + e.height]);
51
+ const x = Math.min(...xs) - 60, y = Math.min(...ys) - 60;
52
+ frames = [{ el: { id: null, x, y, width: Math.max(...xs) - x + 60, height: Math.max(...ys) - y + 60 }, idx: 0, name: "", ...parseFrameName("", 0), all: true }];
53
+ }
54
+
55
+ const slides = frames.map((fr) => {
56
+ const fx = fr.el.x, fy = fr.el.y;
57
+ const members = all.filter((e) => (fr.all ? e.type !== "frame" : e.frameId === fr.el.id) &&
58
+ !(e.type === "text" && e.containerId && byId.has(e.containerId)));
59
+ const items = members.map((e) => makeItem(e, fx, fy, labelOf.get(e.id), zOf.get(e.id), files, opts)).filter(Boolean);
60
+ const itemById = new Map(items.map((i) => [i.id, i]));
61
+ for (const it of items) if (it.pts && it.type !== "freedraw") {
62
+ it.startAttach = attachInfo(it, itemById.get(it.startId), 0);
63
+ it.endAttach = attachInfo(it, itemById.get(it.endId), it.pts.length - 1);
64
+ const s = itemById.get(it.startId)?.key || hitKey(items, it.pts[0]);
65
+ const t = itemById.get(it.endId)?.key || hitKey(items, it.pts.at(-1));
66
+ it.startKey = s; it.endKey = t;
67
+ it.key = s || t ? `A:${s || "?"}>${t || "?"}` : null;
68
+ }
69
+ return { ...fr, id: fr.el.id, x: fx, y: fy, w: fr.el.width, h: fr.el.height, items };
70
+ });
71
+ return { slides, bg: data.appState?.viewBackgroundColor || "#ffffff" };
72
+ }
73
+
74
+ function makeItem(e, fx, fy, label, z, files, opts) {
75
+ const it = {
76
+ id: e.id, type: e.type, z, x: e.x - fx, y: e.y - fy, w: e.width, h: e.height, angle: e.angle || 0,
77
+ stroke: e.strokeColor, bg: e.backgroundColor, fillStyle: e.fillStyle || "solid", sw: e.strokeWidth ?? 2,
78
+ strokeStyle: e.strokeStyle || "solid", rough: e.roughness ?? 1, op: (e.opacity ?? 100) / 100,
79
+ seed: e.seed || 1, round: !!e.roundness, roundValue: e.roundness?.value, key: null,
80
+ };
81
+ if (label) it.label = { id: label.id, text: label.text, fs: label.fontSize, fam: label.fontFamily, align: label.textAlign,
82
+ valign: label.verticalAlign, color: label.strokeColor, lh: label.lineHeight || 1.25, op: (label.opacity ?? 100) / 100 };
83
+ switch (e.type) {
84
+ case "rectangle": case "ellipse": case "diamond":
85
+ if (label) it.key = "L:" + norm(label.text);
86
+ break;
87
+ case "text":
88
+ it.text = { text: e.text, fs: e.fontSize, fam: e.fontFamily, align: e.textAlign || "left", lh: e.lineHeight || 1.25 };
89
+ it.key = "T:" + norm(e.text);
90
+ break;
91
+ case "arrow": case "line":
92
+ it.pts = (e.points || []).map(([px, py]) => [it.x + px, it.y + py]);
93
+ it.startId = e.startBinding?.elementId; it.endId = e.endBinding?.elementId;
94
+ it.heads = [e.startArrowhead, e.endArrowhead];
95
+ it.closed = e.type === "line" && it.pts.length > 2 && Math.hypot(it.pts[0][0] - it.pts.at(-1)[0], it.pts[0][1] - it.pts.at(-1)[1]) < 2;
96
+ break;
97
+ case "freedraw":
98
+ it.pts = (e.points || []).map(([px, py]) => [it.x + px, it.y + py]);
99
+ break;
100
+ case "image":
101
+ it.img = opts.image ? opts.image(e.fileId, files[e.fileId]) : null;
102
+ break;
103
+ default:
104
+ return null; // frames, embeds — not drawn
105
+ }
106
+ return it;
107
+ }
108
+
109
+ // remember where on its shape's outline an arrow end attaches, so it can stay glued while the shape moves
110
+ function attachInfo(arrow, target, i) {
111
+ if (!target || target.pts) return null;
112
+ const p = arrow.pts[i], cx = target.x + target.w / 2, cy = target.y + target.h / 2;
113
+ const rx = target.w / 2 || 1, ry = target.h / 2 || 1;
114
+ const nx = (p[0] - cx) / rx, ny = (p[1] - cy) / ry;
115
+ const d = target.type === "ellipse" ? Math.hypot(nx, ny) : target.type === "diamond" ? Math.abs(nx) + Math.abs(ny) : Math.max(Math.abs(nx), Math.abs(ny));
116
+ const q = d ? [nx / d, ny / d] : [0, 0];
117
+ return { id: target.id, q, off: [p[0] - (cx + q[0] * rx), p[1] - (cy + q[1] * ry)] };
118
+ }
119
+ export const attachPos = (a, st) => [st.x + st.w / 2 + (a.q[0] * st.w) / 2 + a.off[0], st.y + st.h / 2 + (a.q[1] * st.h) / 2 + a.off[1]];
120
+
121
+ function hitKey(items, p) {
122
+ let best = null, area = Infinity;
123
+ for (const it of items) {
124
+ if (it.pts || !it.key || it.type === "text") continue;
125
+ if (p[0] >= it.x - 14 && p[0] <= it.x + it.w + 14 && p[1] >= it.y - 14 && p[1] <= it.y + it.h + 14 && it.w * it.h < area) { best = it; area = it.w * it.h; }
126
+ }
127
+ return best?.key || null;
128
+ }
129
+
130
+ /**
131
+ * Pair up items of slide A with items of slide B.
132
+ * Returns [{a, b}] (morph), [{a, b:null}] (exit), [{a:null, b}] (enter), [{a:null, b, spawn}] (clone).
133
+ */
134
+ export function match(A, B) {
135
+ const pairs = [], usedA = new Set(), usedB = new Set();
136
+ const dist = (a, b) => Math.hypot(a.x + a.w / 2 - b.x - b.w / 2, a.y + a.h / 2 - b.y - b.h / 2);
137
+ const take = (a, b, how) => { usedA.add(a.id); usedB.add(b.id); pairs.push({ a, b, how }); };
138
+ const group = (items) => { const g = new Map(); for (const i of items) if (i.key) (g.get(i.key) || g.set(i.key, []).get(i.key)).push(i); return g; };
139
+ const ga = group(A.items), gb = group(B.items);
140
+ // 1. same label / same text / same arrow endpoints — nearest first
141
+ for (const [k, bs] of gb) {
142
+ const as = ga.get(k); if (!as) continue;
143
+ const cand = []; for (const a of as) for (const b of bs) cand.push([dist(a, b), a, b]);
144
+ cand.sort((x, y) => x[0] - y[0]);
145
+ for (const [, a, b] of cand) if (!usedA.has(a.id) && !usedB.has(b.id)) take(a, b, "key");
146
+ for (const b of bs) if (!usedB.has(b.id)) { // extra copies clone out of the nearest original
147
+ const src = as.slice().sort((x, y) => dist(x, b) - dist(y, b))[0];
148
+ usedB.add(b.id); pairs.push({ a: null, b, spawn: src, how: "clone" });
149
+ }
150
+ }
151
+ // 2. arrows that kept one end (e.g. "→ Snapline" becomes "→ API Gateway")
152
+ const ua = A.items.filter((i) => i.pts && i.type !== "freedraw" && !usedA.has(i.id));
153
+ const ub = B.items.filter((i) => i.pts && i.type !== "freedraw" && !usedB.has(i.id));
154
+ const cand = [];
155
+ for (const a of ua) for (const b of ub) {
156
+ const score = (a.startKey && a.startKey === b.startKey ? 1 : 0) + (a.endKey && a.endKey === b.endKey ? 1 : 0);
157
+ if (score) cand.push([-score * 1e6 + dist(a, b), a, b]);
158
+ }
159
+ cand.sort((x, y) => x[0] - y[0]);
160
+ for (const [, a, b] of cand) if (!usedA.has(a.id) && !usedB.has(b.id)) take(a, b, "reattach");
161
+ // 3. unlabeled shapes left exactly where they were
162
+ for (const a of A.items) if (!usedA.has(a.id) && !a.key) for (const b of B.items)
163
+ if (!usedB.has(b.id) && !b.key && a.type === b.type && Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + Math.abs(a.w - b.w) + Math.abs(a.h - b.h) < 12) { take(a, b, "position"); break; }
164
+ for (const a of A.items) if (!usedA.has(a.id)) pairs.push({ a, b: null });
165
+ for (const b of B.items) if (!usedB.has(b.id)) pairs.push({ a: null, b });
166
+ return pairs;
167
+ }
168
+
169
+ /** For zoom transitions: the matched shape whose size changes the most (ratio > 1.8), or null. */
170
+ export function zoomAnchor(pairs) {
171
+ let best = 1.8, anchor = null;
172
+ for (const p of pairs) if (p.a && p.b && !p.a.pts && p.a.type !== "text") {
173
+ const r = (p.b.w * p.b.h) / Math.max(1, p.a.w * p.a.h), ratio = Math.max(r, 1 / r);
174
+ if (ratio > best) { best = ratio; anchor = p; }
175
+ }
176
+ return anchor;
177
+ }
178
+
179
+ /** Human-readable name for an item, for reports. */
180
+ export function describe(it) {
181
+ if (!it) return "?";
182
+ if (it.label) return `${it.type} "${it.label.text.replace(/\n/g, " ")}"`;
183
+ if (it.text) return `text "${it.text.text.replace(/\n/g, " ").slice(0, 40)}"`;
184
+ if (it.pts && it.type !== "freedraw") return `${it.type} ${pretty(it.startKey)} → ${pretty(it.endKey)}`;
185
+ return `${it.type} at ${Math.round(it.x)},${Math.round(it.y)}`;
186
+ }
187
+ const pretty = (k) => (k ? `"${k.slice(2)}"` : "(unattached)");