easel-canvas 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/server/routes.mjs CHANGED
@@ -16,6 +16,7 @@ import { easelDir, rootOf, toPosix, writeAtomic } from "./fsutil.mjs";
16
16
  import { inspect, outline } from "./html.mjs";
17
17
  import { contentHash, livePatch } from "./livePatch.mjs";
18
18
  import { readBody, safeJoin, sendJson } from "./index.mjs";
19
+ import { requestRoutes, undoState } from "./requests.mjs";
19
20
  import { watchDesign } from "./watch.mjs";
20
21
 
21
22
  const OUTER_LIMIT = 4096;
@@ -97,6 +98,14 @@ export function createThumbQueue(limit = 2) {
97
98
  }
98
99
  const thumbQueue = createThumbQueue(2);
99
100
 
101
+ /** The newest thumbnail of a board on disk (any version, this size first), for when a new one cannot be made */
102
+ async function previousThumb(dir, base, px) {
103
+ const names = (await fs.readdir(dir).catch(() => [])).filter((n) => n.startsWith(base + ".") && n.endsWith(".jpg"));
104
+ const dated = await Promise.all(names.map(async (n) => ({ n, t: (await fs.stat(path.join(dir, n)).catch(() => null))?.mtimeMs ?? 0, same: n.endsWith(`.${px}.jpg`) })));
105
+ dated.sort((a, b) => b.same - a.same || b.t - a.t);
106
+ return dated.length ? fs.readFile(path.join(dir, dated[0].n)).catch(() => null) : null;
107
+ }
108
+
100
109
  export async function screenshot(ctx, port, file, elPath) {
101
110
  const board = (await ctx.store.readBoard()).boards[file];
102
111
  return withPage({ viewport: { width: board?.w ?? 390, height: board?.h ?? 844 }, deviceScaleFactor: 2 }, async (page) => {
@@ -142,7 +151,9 @@ export const extraRoutes = [
142
151
  }
143
152
  if (next === html) return sendJson(res, 200, { ok: true, changed: false, ...fork });
144
153
  await writeScreen(ctx, p, next);
145
- ctx.history.push(`${to.file} ${b.op}`, [{ path: p, before: html, after: next }]);
154
+ // What a style step changed (its human name says "colour", "fill", "radius"…): the property, or a batch's when they agree
155
+ const props = b.op === "setStyle" ? [b.prop] : b.op === "batch" && Array.isArray(b.ops) ? [...new Set(b.ops.filter((o) => o.op === "setStyle").map((o) => o.prop))] : [];
156
+ ctx.history.push(`${to.file} ${b.op}`, [{ path: p, before: html, after: next }], props.length === 1 && props[0] ? { prop: props[0] } : {});
146
157
  ctx.broadcast({ type: "history-changed" });
147
158
  // base/hash: the file's content hash before and after; live: the DOM change that turns a board showing base into one showing
148
159
  // hash, when that is proven (server/livePatch.mjs). Never for a fork: the caller's board is not the file written
@@ -164,8 +175,11 @@ export const extraRoutes = [
164
175
  ...forkRoutes(),
165
176
  ...activityRoutes(),
166
177
  ...chat.routes,
178
+ ...requestRoutes({ chatState: chat.state, getSelection: () => selection }),
167
179
  ...tokenRoutes(),
168
- // Zoomed-out thumbnails: small images shown below 25% instead of empty frames. Stored per modification time in docs/design/.thumbs/ (gitignored)
180
+ // Zoomed-out thumbnails: small images shown below 25% instead of empty frames. Stored per render stamp (server/stamps.mjs: the
181
+ // board's HTML and every local file it loads) in docs/design/.thumbs/ (gitignored). The app asks with the stamp it was told
182
+ // (s=), so that URL is cached for good; without it, or with a stamp that is no longer current, the answer is revalidated
169
183
  [
170
184
  "GET",
171
185
  "/api/thumb",
@@ -173,17 +187,19 @@ export const extraRoutes = [
173
187
  const f = url.searchParams.get("f") ?? "";
174
188
  const src = safeJoin(ctx.store.screensDir, f);
175
189
  const st = src && (await fs.stat(src).catch(() => null));
176
- if (!st) return sendJson(res, 404, { error: "File not found" });
190
+ if (!st?.isFile()) return sendJson(res, 404, { error: "File not found" });
177
191
  const px = thumbPx(url.searchParams.get("px"));
178
192
  const dir = path.join(ctx.dir, ".thumbs");
179
193
  const base = f.replace(/[\\/]/g, "_");
180
- const stamp = `${base}.${Math.round(st.mtimeMs)}.`;
194
+ const cur = (await ctx.stamps.stamp(f)) ?? `m${Math.round(st.mtimeMs)}`;
195
+ const stamp = `${base}.${cur}.`;
181
196
  const out = path.join(dir, `${stamp}${px}.jpg`);
182
197
  // Read the port now: a job that waits in the queue runs after its request may have closed, and a closed socket has no localPort
183
198
  const port = req.socket.localPort;
184
199
  let gone = false;
185
200
  res.on("close", () => (gone = true));
186
201
  let buf = await fs.readFile(out).catch(() => null);
202
+ let fresh = true;
187
203
  if (!buf) {
188
204
  buf = await thumbQueue.push(async () => {
189
205
  await fs.mkdir(dir, { recursive: true });
@@ -196,18 +212,23 @@ export const extraRoutes = [
196
212
  await page.goto(`http://127.0.0.1:${port}/screens/${encodeURI(f)}`, { waitUntil: "load", timeout: 15000 });
197
213
  await page.waitForTimeout(150);
198
214
  const b = await page.screenshot({ type: "jpeg", quality: 80 });
199
- // Remove thumbnails of older versions (other sizes of this version stay)
215
+ // Remove thumbnails of older versions (other sizes of this version stay); only once the new one is made
200
216
  for (const n of await fs.readdir(dir)) if (n.startsWith(base + ".") && !n.startsWith(stamp)) await fs.rm(path.join(dir, n), { force: true });
201
217
  await fs.writeFile(out, b);
202
218
  return b;
203
219
  });
204
- }, () => gone).catch((e) => {
220
+ }, () => gone).catch(async (e) => {
205
221
  if (e.dropped) return null;
206
- throw e;
222
+ // The render failed: the last picture of this board, if there is one, beats no picture (and is asked for again next time)
223
+ const old = await previousThumb(dir, base, px);
224
+ if (!old) throw e;
225
+ fresh = false;
226
+ return old;
207
227
  });
208
228
  if (!buf) return; // nobody is waiting for it any more
209
229
  }
210
- res.writeHead(200, { "Content-Type": "image/jpeg", "Content-Length": buf.length, "Cache-Control": "max-age=31536000, immutable" });
230
+ const cache = fresh && url.searchParams.get("s") === cur ? "max-age=31536000, immutable" : "no-cache";
231
+ res.writeHead(200, { "Content-Type": "image/jpeg", "Content-Length": buf.length, "Cache-Control": cache });
211
232
  res.end(buf);
212
233
  },
213
234
  ],
@@ -334,6 +355,10 @@ export const extraRoutes = [
334
355
  const f = url.searchParams.get("file");
335
356
  if (f) list = list.filter((c) => c.file === f);
336
357
  if (url.searchParams.get("unresolved") === "1") list = list.filter((c) => !c.resolved);
358
+ // for_agent=1: only comments marked For AI (requests for the agent the person is talking to)
359
+ if (url.searchParams.get("for_agent") === "1") list = list.filter((c) => c.forAgent);
360
+ // A done request says whether its own undo steps can still be undone (not stored: read from this server's history)
361
+ list = list.map((c) => (c.request?.state === "done" && c.request.steps?.length ? { ...c, request: { ...c.request, undo: undoState(ctx.history, c.request.steps) } } : c));
337
362
  sendJson(res, 200, { comments: list });
338
363
  },
339
364
  ],
@@ -354,6 +379,23 @@ export const extraRoutes = [
354
379
  ctx.broadcast({ type: "comments-changed" });
355
380
  return sendJson(res, 200, { comment: c, reply: r });
356
381
  }
382
+ if (b.action === "edit") {
383
+ const c = list.find((x) => x.id === b.id);
384
+ if (!c) return sendJson(res, 404, { error: "Comment not found" });
385
+ if (!String(b.text ?? "").trim()) return sendJson(res, 400, { error: "text is required" });
386
+ c.text = String(b.text).trim();
387
+ await writeComments(ctx, list);
388
+ ctx.broadcast({ type: "comments-changed" });
389
+ return sendJson(res, 200, { comment: c });
390
+ }
391
+ if (b.action === "delete") {
392
+ const i = list.findIndex((x) => x.id === b.id);
393
+ if (i < 0) return sendJson(res, 404, { error: "Comment not found" });
394
+ const [c] = list.splice(i, 1);
395
+ await writeComments(ctx, list);
396
+ ctx.broadcast({ type: "comments-changed" });
397
+ return sendJson(res, 200, { comment: c });
398
+ }
357
399
  if (b.action === "resolve") {
358
400
  const c = list.find((x) => x.id === b.id);
359
401
  if (!c) return sendJson(res, 404, { error: "Comment not found" });
@@ -0,0 +1,134 @@
1
+ // AI-generated with Claude Code, 2026-11-29
2
+ // A board's render stamp: a short hash of the modification time and size of its HTML and of every local file the page loads
3
+ // (stylesheets and what they import, scripts, images, fonts, media, embedded boards and what those load). It changes whenever
4
+ // the rendered board can change, so the zoomed-out thumbnail is keyed by it on disk and in its URL (cached for a year by the
5
+ // browser). Not followed: what scripts fetch at run time, and remote URLs (both rarely change what a board looks like).
6
+ import { createHash } from "node:crypto";
7
+ import fs from "node:fs/promises";
8
+ import path from "node:path";
9
+
10
+ /** Tags whose attributes load something into the page (an <a href> only links, so it is not one) */
11
+ const LOADING_TAG = /<(link|script|img|source|video|audio|track|iframe|frame|object|embed|image|use|feimage|input)\b([^>]*)>/gi;
12
+ const LOADING_ATTR = /(?:^|\s)(src|href|srcset|poster|data|xlink:href)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi;
13
+ const CSS_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]+))\s*\)/gi;
14
+ const CSS_IMPORT = /@import\s+(?:"([^"]*)"|'([^']*)')/gi;
15
+ /** A board's page loads at most this many local files that count (a runaway page still gets a stamp) */
16
+ const MAX_FILES = 400;
17
+
18
+ const kindOf = (p) => (/\.html?$/i.test(p) ? "html" : /\.css$/i.test(p) ? "css" : "leaf");
19
+
20
+ /** The local references in an HTML page or a stylesheet, as written */
21
+ export function refsIn(text, kind) {
22
+ const out = [];
23
+ const css = (s) => {
24
+ for (const m of s.matchAll(CSS_URL)) out.push(m[1] ?? m[2] ?? m[3]);
25
+ for (const m of s.matchAll(CSS_IMPORT)) out.push(m[1] ?? m[2]);
26
+ };
27
+ if (kind === "css") {
28
+ css(text);
29
+ return out;
30
+ }
31
+ for (const t of text.matchAll(LOADING_TAG)) {
32
+ for (const a of t[2].matchAll(LOADING_ATTR)) {
33
+ const v = a[2] ?? a[3] ?? a[4] ?? "";
34
+ if (a[1].toLowerCase() === "srcset") for (const part of v.split(",")) out.push(part.trim().split(/\s+/)[0]);
35
+ else out.push(v);
36
+ }
37
+ }
38
+ // Inline <style> blocks and style="" attributes (a url() inside a script only adds a needless dependency)
39
+ css(text);
40
+ return out;
41
+ }
42
+
43
+ export function createStamps(dir) {
44
+ const root = path.resolve(dir);
45
+ const screensDir = path.join(root, "screens");
46
+ const parsed = new Map(); // abs → { key, refs: abs[] }
47
+ const depsOf = new Map(); // board file → Set(abs) its last stamp covered
48
+
49
+ /** Where the server finds what a page at `fromAbs` asks for with `ref` (the same mapping as the static routes), or null */
50
+ async function resolve(fromAbs, ref) {
51
+ ref = String(ref ?? "").trim();
52
+ if (!ref || ref.startsWith("#") || ref.startsWith("//") || /^[a-z][\w+.-]*:/i.test(ref)) return null;
53
+ let pathname;
54
+ try {
55
+ const base = new URL("http://x/" + path.relative(root, fromAbs).split(path.sep).map(encodeURIComponent).join("/"));
56
+ pathname = decodeURIComponent(new URL(ref, base).pathname);
57
+ } catch {
58
+ return null;
59
+ }
60
+ const inside = (p) => (p === root || p.startsWith(root + path.sep) ? p : null);
61
+ if (pathname.startsWith("/screens/") || pathname.startsWith("/assets/")) return inside(path.join(root, pathname));
62
+ // Other root paths: the server sends them to screens/ when the file is there, else serves them from the design folder
63
+ const inScreens = inside(path.join(screensDir, pathname));
64
+ if (inScreens && (await fs.stat(inScreens).catch(() => null))) return inScreens;
65
+ return inside(path.join(root, pathname));
66
+ }
67
+
68
+ async function refsOf(abs, key) {
69
+ const hit = parsed.get(abs);
70
+ if (hit?.key === key) return hit.refs;
71
+ const kind = kindOf(abs);
72
+ let refs = [];
73
+ if (kind !== "leaf") {
74
+ const text = await fs.readFile(abs, "utf8").catch(() => "");
75
+ refs = (await Promise.all(refsIn(text, kind).map((r) => resolve(abs, r)))).filter((p) => p && p !== abs);
76
+ }
77
+ parsed.set(abs, { key, refs });
78
+ return refs;
79
+ }
80
+
81
+ /**
82
+ * The stamp of a board (path under screens/), or null when its file is missing. memo: stats shared by several stamps made
83
+ * together (a hundred boards using the same fonts stat them once)
84
+ */
85
+ async function stamp(file, memo = new Map()) {
86
+ const start = path.join(screensDir, file);
87
+ const statOf = (p) => {
88
+ if (!memo.has(p)) memo.set(p, fs.stat(p).then((s) => (s.isFile() ? `${Math.round(s.mtimeMs)}:${s.size}` : "-"), () => "-"));
89
+ return memo.get(p);
90
+ };
91
+ const first = await statOf(start);
92
+ if (first === "-") {
93
+ depsOf.delete(file);
94
+ return null;
95
+ }
96
+ const seen = new Map([[start, first]]);
97
+ let level = [start];
98
+ while (level.length && seen.size < MAX_FILES) {
99
+ const next = [];
100
+ for (const refs of await Promise.all(level.map(async (p) => (kindOf(p) === "leaf" || seen.get(p) === "-" ? [] : refsOf(p, seen.get(p)))))) {
101
+ for (const r of refs) if (!seen.has(r) && seen.size < MAX_FILES) {
102
+ seen.set(r, null);
103
+ next.push(r);
104
+ }
105
+ }
106
+ await Promise.all(next.map(async (p) => seen.set(p, await statOf(p))));
107
+ level = next;
108
+ }
109
+ depsOf.set(file, new Set(seen.keys()));
110
+ const h = createHash("sha1");
111
+ for (const [p, s] of [...seen].sort((a, b) => (a[0] < b[0] ? -1 : 1))) h.update(`${path.relative(root, p)}\0${s}\n`);
112
+ return h.digest("hex").slice(0, 12);
113
+ }
114
+
115
+ /** Stamps of many boards at once */
116
+ async function stampAll(files) {
117
+ const memo = new Map();
118
+ const out = {};
119
+ await Promise.all(files.map(async (f) => {
120
+ const s = await stamp(f, memo);
121
+ if (s) out[f] = s;
122
+ }));
123
+ return out;
124
+ }
125
+
126
+ /** Boards whose last stamp covered abs (a file they load, directly or through a stylesheet or an embedded board) */
127
+ function users(abs) {
128
+ const out = [];
129
+ for (const [f, set] of depsOf) if (set.has(abs)) out.push(f);
130
+ return out;
131
+ }
132
+
133
+ return { stamp, stampAll, users, forget: (file) => depsOf.delete(file) };
134
+ }
package/server/watch.mjs CHANGED
@@ -7,12 +7,14 @@ import path from "node:path";
7
7
  import chokidar from "chokidar";
8
8
 
9
9
  import { createDeps } from "./deps.mjs";
10
+ import { createStamps } from "./stamps.mjs";
10
11
  import { toPosix } from "./fsutil.mjs";
11
12
  import { contentHash } from "./livePatch.mjs";
12
13
 
13
- export function watchDesign({ dir, store, broadcast, history }) {
14
+ export function watchDesign({ dir, store, broadcast, history, stamps = createStamps(dir) }) {
14
15
  const screensDir = store.screensDir;
15
- const watcher = chokidar.watch([screensDir, store.boardPath], {
16
+ // The whole design folder: a stylesheet, image or font a board loads may sit anywhere in it (assets/ mostly)
17
+ const watcher = chokidar.watch([dir, screensDir, store.boardPath], {
16
18
  ignoreInitial: true,
17
19
  // Ignore iCloud placeholders (.icloud) and hidden files (PLAN.md ch. 9)
18
20
  ignored: (p) => {
@@ -31,6 +33,8 @@ export function watchDesign({ dir, store, broadcast, history }) {
31
33
  for (const f of files) hashes.set(f, sha(await fs.readFile(path.join(screensDir, f), "utf8").catch(() => "")));
32
34
  });
33
35
  store.listScreenFiles().then((files) => deps.init(files));
36
+ // Which files each board loads, so a change to a shared one finds its boards
37
+ store.listScreenFiles().then((files) => stamps.stampAll(files)).catch(() => {});
34
38
  let syncTimer = null;
35
39
  const scheduleSync = () => {
36
40
  clearTimeout(syncTimer);
@@ -79,7 +83,15 @@ export function watchDesign({ dir, store, broadcast, history }) {
79
83
  broadcast({ type: "board-changed", source: "server:external" });
80
84
  return;
81
85
  }
82
- if (!abs.endsWith(".html")) return;
86
+ const inScreens = abs.startsWith(screensDir + path.sep);
87
+ if (!abs.endsWith(".html") || !inScreens) {
88
+ // A file boards load (a stylesheet, an image, a font, a page outside screens/): redraw those boards and their thumbnails
89
+ for (const host of stamps.users(abs)) {
90
+ const stamp = await stamps.stamp(host);
91
+ broadcast({ type: "file-changed", file: host, kind: "change", via: toPosix(path.relative(dir, abs)), ...(stamp ? { stamp } : {}) });
92
+ }
93
+ return;
94
+ }
83
95
  const file = toPosix(path.relative(screensDir, abs));
84
96
  const kind = event === "add" ? "add" : event === "unlink" ? "unlink" : "change";
85
97
  void track(path.join(screensDir, file));
@@ -102,10 +114,16 @@ export function watchDesign({ dir, store, broadcast, history }) {
102
114
  }
103
115
  }
104
116
  }
105
- // hash: the content read now. A tab whose board already shows exactly this content (it patched its own edit in place) keeps it
106
- broadcast({ type: "file-changed", file, kind, ...(hash ? { hash } : {}) });
107
- // Also redraw boards that embed this screen (flow diagrams etc.)
108
- for (const host of deps.dependents(file)) broadcast({ type: "file-changed", file: host, kind: "change", via: file });
117
+ // hash: the content read now. A tab whose board already shows exactly this content (it patched its own edit in place) keeps it.
118
+ // stamp: the board's render stamp now, the version of its thumbnail
119
+ const stamp = kind === "unlink" ? (stamps.forget(file), null) : await stamps.stamp(file);
120
+ broadcast({ type: "file-changed", file, kind, ...(hash ? { hash } : {}), ...(stamp ? { stamp } : {}) });
121
+ // Also redraw boards that embed this screen (flow diagrams etc.), or load it some other way
122
+ for (const host of new Set([...deps.dependents(file), ...stamps.users(abs)])) {
123
+ if (host === file) continue;
124
+ const s = await stamps.stamp(host);
125
+ broadcast({ type: "file-changed", file: host, kind: "change", via: file, ...(s ? { stamp: s } : {}) });
126
+ }
109
127
  if (kind !== "change") scheduleSync();
110
128
  });
111
129