easel-canvas 0.1.0 → 0.2.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 +64 -20
- package/bin/mcp.mjs +151 -43
- package/bin/server.mjs +69 -6
- package/dist/assets/index-BZFSkKqU.css +1 -0
- package/dist/assets/index-BwyrrnkP.js +65 -0
- package/dist/index.html +3 -3
- package/dist/viewer/viewer.css +1 -0
- package/dist/viewer/viewer.js +49 -0
- package/package.json +2 -2
- package/server/activity.mjs +370 -0
- package/server/agents.mjs +20 -0
- package/server/args.mjs +22 -2
- package/server/board.mjs +33 -33
- package/server/boards.mjs +51 -25
- package/server/browser.mjs +68 -0
- package/server/chat.mjs +446 -51
- package/server/connect.mjs +94 -0
- package/server/copies.mjs +105 -0
- package/server/custom.mjs +101 -0
- package/server/edit.mjs +2 -2
- package/server/export.mjs +627 -0
- package/server/forks.mjs +214 -0
- package/server/fsutil.mjs +25 -0
- package/server/history.mjs +152 -24
- package/server/html.mjs +11 -1
- package/server/index.mjs +162 -17
- package/server/occupancy.mjs +183 -0
- package/server/permissions.mjs +141 -0
- package/server/place.mjs +87 -0
- package/server/registry.mjs +110 -0
- package/server/routes.mjs +37 -38
- package/server/runs.mjs +167 -0
- package/server/snapshot.mjs +21 -9
- package/server/tokens.mjs +15 -3
- package/server/update.mjs +63 -0
- package/server/watch.mjs +12 -1
- package/dist/assets/index-DbJY7lxA.css +0 -1
- package/dist/assets/index-O7RiYHEC.js +0 -55
package/server/forks.mjs
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// AI-generated with Claude Code, 2026-11-12, reviewed by Hyun Park
|
|
2
|
+
// One writer per board: a second agent writing a board another agent is editing gets a fork next to it, and its later writes to the
|
|
3
|
+
// original go there while the fork exists. Forks and the chat's variants record where they came from in board.json (origin), and
|
|
4
|
+
// "Use this" makes one version the board (file name, title, position and comments stay) and moves the others to trash in one step.
|
|
5
|
+
import { existsSync } from "node:fs";
|
|
6
|
+
import fs from "node:fs/promises";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
import { cleanAgent } from "./agents.mjs";
|
|
10
|
+
import { commitBoard, trashFiles, uniqueName, unlinkOrigins } from "./boards.mjs";
|
|
11
|
+
import { isTrackedRel } from "./copies.mjs";
|
|
12
|
+
import { rootOf, toPosix, writeAtomic } from "./fsutil.mjs";
|
|
13
|
+
import { requestScope } from "./history.mjs";
|
|
14
|
+
import { readBody, safeJoin, sendJson } from "./index.mjs";
|
|
15
|
+
import { besideSpot } from "./place.mjs";
|
|
16
|
+
|
|
17
|
+
const read = (p) => fs.readFile(p, "utf8").catch(() => null);
|
|
18
|
+
/** A board name a request may use: an .html under screens/, no dot segments */
|
|
19
|
+
export const boardFile = (f) => typeof f === "string" && isTrackedRel(`screens/${f}`);
|
|
20
|
+
const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 30) || "agent";
|
|
21
|
+
|
|
22
|
+
/** The fork an agent already has of a board, while its file exists */
|
|
23
|
+
export function forkOf(board, file, by, exists = () => true) {
|
|
24
|
+
return Object.entries(board.boards).find(([f, b]) => b.origin?.kind === "fork" && b.origin.of === file && b.origin.by === by && exists(f))?.[0] ?? null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Where a write to file goes: { action: "write" } to the board itself, { action: "redirect", file } to the writer's own fork, or
|
|
29
|
+
* { action: "fork", while } when another agent is editing it (holders: agents editing file now). People (no by) are never forked
|
|
30
|
+
*/
|
|
31
|
+
export function decideWrite({ board, file, by, holders = [], exists = () => true }) {
|
|
32
|
+
if (!by) return { action: "write", file };
|
|
33
|
+
const fork = forkOf(board, file, by, exists);
|
|
34
|
+
if (fork) return { action: "redirect", file: fork };
|
|
35
|
+
const other = holders.find((h) => h.by !== by);
|
|
36
|
+
return other ? { action: "fork", while: other.by } : { action: "write", file };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The versions "Use this" chooses between: a variant or fork and the others made from the same board, or a board with forks.
|
|
41
|
+
* { original, kind: "variant" | "fork", chosen, alts: the variants or forks (chosen included when it is one) } or null
|
|
42
|
+
*/
|
|
43
|
+
export function choiceGroup(board, file) {
|
|
44
|
+
const it = board.boards[file];
|
|
45
|
+
if (!it) return null;
|
|
46
|
+
const linked = (o, kind) => Object.keys(board.boards).filter((f) => f !== o && board.boards[f].origin?.of === o && board.boards[f].origin.kind === kind);
|
|
47
|
+
if (it.origin?.of && board.boards[it.origin.of]) return { original: it.origin.of, kind: it.origin.kind, chosen: file, alts: linked(it.origin.of, it.origin.kind) };
|
|
48
|
+
const alts = linked(file, "fork");
|
|
49
|
+
return alts.length ? { original: file, kind: "fork", chosen: file, alts } : null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Creates the fork of file for agent by (html: its first content) beside the original, as one history step; returns its file name */
|
|
53
|
+
export async function createFork(ctx, file, { by, whileBy, html }) {
|
|
54
|
+
const { board } = await ctx.store.syncBoardNow();
|
|
55
|
+
const { origin, autoPlaced, x, y, title, ...o } = board.boards[file] ?? { x: 0, y: 0, w: 390, h: 844 };
|
|
56
|
+
const stem = file.replace(/\.html$/, "");
|
|
57
|
+
const name = await uniqueName(ctx.store.screensDir, `${stem}-${slug(by)}.html`);
|
|
58
|
+
const p = safeJoin(ctx.store.screensDir, name);
|
|
59
|
+
await fs.mkdir(path.dirname(p), { recursive: true });
|
|
60
|
+
await writeAtomic(p, html);
|
|
61
|
+
const at = besideSpot(board, { ...o, x, y });
|
|
62
|
+
await commitBoard(
|
|
63
|
+
ctx,
|
|
64
|
+
`Fork ${file} for ${by}`,
|
|
65
|
+
(b) => {
|
|
66
|
+
b.boards[name] = { ...o, x: at.x, y: at.y, title: `${title ?? path.posix.basename(stem)} · ${by}`, origin: { kind: "fork", of: file, by, while: whileBy, at: new Date().toISOString() } };
|
|
67
|
+
const i = b.order.indexOf(file);
|
|
68
|
+
b.order = b.order.filter((f) => f !== name);
|
|
69
|
+
b.order.splice(i < 0 ? b.order.length : i + 1, 0, name);
|
|
70
|
+
},
|
|
71
|
+
[{ path: p, before: null, after: html }],
|
|
72
|
+
);
|
|
73
|
+
return name;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Where the calling agent's write to file goes (making its fork when another agent is editing the board). html: the content to
|
|
78
|
+
* start a new fork with (default: the board as it was when the other writer started). → { file, forked, created, while }
|
|
79
|
+
*/
|
|
80
|
+
export async function routeWrite(ctx, file, html = null) {
|
|
81
|
+
const by = requestScope.getStore()?.agent ?? null;
|
|
82
|
+
const board = await ctx.store.readBoard();
|
|
83
|
+
const d = decideWrite({ board, file, by, holders: ctx.occupancy?.agentsOn(file) ?? [], exists: (f) => existsSync(path.join(ctx.store.screensDir, f)) });
|
|
84
|
+
if (d.action === "fork") {
|
|
85
|
+
const start = html ?? ctx.occupancy.base(file) ?? (await read(safeJoin(ctx.store.screensDir, file))) ?? "";
|
|
86
|
+
return { file: await createFork(ctx, file, { by, whileBy: d.while, html: start }), forked: true, created: true, while: d.while };
|
|
87
|
+
}
|
|
88
|
+
if (d.action === "redirect") return { file: d.file, forked: true, created: false, while: board.boards[d.file]?.origin?.while ?? null };
|
|
89
|
+
return { file, forked: false, created: false, while: null };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** What the agent is told: plainly which file it is on now */
|
|
93
|
+
export function forkMessage(ctx, original, r, { claim = false } = {}) {
|
|
94
|
+
const dir = toPosix(path.relative(rootOf(ctx.dir), ctx.store.screensDir)) || "screens";
|
|
95
|
+
if (!r.forked) return claim ? `You are editing ${dir}/${original} now. Edit it with your own file tools; another agent that writes it meanwhile gets a fork.` : `Wrote ${dir}/${original}.`;
|
|
96
|
+
const why = r.while ? `${r.while} ${r.created ? "is" : "was"} editing ${original}` : `${original} has a fork of yours`;
|
|
97
|
+
const what = r.created ? (claim ? `a fork was made for you: ${dir}/${r.file} (a copy of the board as it was when ${r.while} started)` : `your change went to a fork next to it: ${dir}/${r.file}`) : `you are working on your fork ${dir}/${r.file}`;
|
|
98
|
+
return `${why}, so ${what}. Keep working on ${r.file}, not ${original}; your later writes to ${original} go to the fork too. The person picks one version later.`;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function forkRoutes() {
|
|
102
|
+
return [
|
|
103
|
+
// Who is on which board (also sent over the WebSocket as "occupancy" events)
|
|
104
|
+
["GET", "/api/boards/occupancy", async (req, res, url, ctx) => sendJson(res, 200, { boards: ctx.occupancy.snapshot() })],
|
|
105
|
+
// An agent writes a whole board through Easel: it holds the board, or works on a fork when another agent is editing it
|
|
106
|
+
[
|
|
107
|
+
"POST",
|
|
108
|
+
"/api/boards/write",
|
|
109
|
+
async (req, res, url, ctx) => {
|
|
110
|
+
const b = await readBody(req);
|
|
111
|
+
if (!boardFile(b.file) || typeof b.html !== "string") return sendJson(res, 400, { error: "file (a board .html in the screens folder) and html are required" });
|
|
112
|
+
const r = await routeWrite(ctx, b.file, b.html);
|
|
113
|
+
if (!r.created) {
|
|
114
|
+
const p = safeJoin(ctx.store.screensDir, r.file);
|
|
115
|
+
const before = await read(p);
|
|
116
|
+
if (before !== b.html) {
|
|
117
|
+
await fs.mkdir(path.dirname(p), { recursive: true });
|
|
118
|
+
await writeAtomic(p, b.html);
|
|
119
|
+
ctx.history.push(`Write board ${r.file}`, [{ path: p, before, after: b.html }]);
|
|
120
|
+
ctx.broadcast({ type: "history-changed" });
|
|
121
|
+
if (before == null) {
|
|
122
|
+
await ctx.store.syncBoardNow();
|
|
123
|
+
ctx.broadcast({ type: "board-changed", source: "server:write" });
|
|
124
|
+
}
|
|
125
|
+
} else holdForCaller(ctx, r.file, before);
|
|
126
|
+
}
|
|
127
|
+
sendJson(res, 200, { file: r.file, forked: r.forked, ...(r.forked ? { original: b.file } : {}), message: forkMessage(ctx, b.file, r) });
|
|
128
|
+
},
|
|
129
|
+
],
|
|
130
|
+
// An agent is about to edit a board with its own file tools: which file to edit (the board, or its fork when another agent is on it)
|
|
131
|
+
[
|
|
132
|
+
"POST",
|
|
133
|
+
"/api/boards/claim",
|
|
134
|
+
async (req, res, url, ctx) => {
|
|
135
|
+
const b = await readBody(req);
|
|
136
|
+
if (!boardFile(b.file)) return sendJson(res, 400, { error: "file (a board .html in the screens folder) is required" });
|
|
137
|
+
const now = await read(safeJoin(ctx.store.screensDir, b.file));
|
|
138
|
+
if (now == null) return sendJson(res, 404, { error: "File not found" });
|
|
139
|
+
const r = await routeWrite(ctx, b.file);
|
|
140
|
+
if (!r.created) holdForCaller(ctx, r.file, r.file === b.file ? now : await read(safeJoin(ctx.store.screensDir, r.file)));
|
|
141
|
+
sendJson(res, 200, { file: r.file, forked: r.forked, ...(r.forked ? { original: b.file } : {}), message: forkMessage(ctx, b.file, r, { claim: true }) });
|
|
142
|
+
},
|
|
143
|
+
],
|
|
144
|
+
// An MCP server's client disconnected: the boards it kept busy are done
|
|
145
|
+
[
|
|
146
|
+
"POST",
|
|
147
|
+
"/api/boards/release",
|
|
148
|
+
async (req, res, url, ctx) => {
|
|
149
|
+
const client = cleanAgent((await readBody(req)).client);
|
|
150
|
+
if (client) ctx.occupancy.clientGone(client);
|
|
151
|
+
sendJson(res, 200, { ok: true });
|
|
152
|
+
},
|
|
153
|
+
],
|
|
154
|
+
// Use this (one): the chosen version becomes the original board and the others go to trash, as one history step
|
|
155
|
+
[
|
|
156
|
+
"POST",
|
|
157
|
+
"/api/boards/use",
|
|
158
|
+
async (req, res, url, ctx) => {
|
|
159
|
+
const b = await readBody(req);
|
|
160
|
+
const board = await ctx.store.readBoard();
|
|
161
|
+
const g = boardFile(b.file) ? choiceGroup(board, b.file) : null;
|
|
162
|
+
if (!g) return sendJson(res, 400, { error: "That board is not a variant or fork of another board" });
|
|
163
|
+
const busy = [g.original, ...g.alts].flatMap((f) => ctx.occupancy.agentsOn(f).map((h) => ({ file: f, by: h.by })));
|
|
164
|
+
if (busy.length) return sendJson(res, 409, { error: `${busy[0].by} is still editing ${board.boards[busy[0].file]?.title ?? busy[0].file}`, busy });
|
|
165
|
+
const changes = [];
|
|
166
|
+
if (g.chosen !== g.original) {
|
|
167
|
+
const src = await read(safeJoin(ctx.store.screensDir, g.chosen));
|
|
168
|
+
if (src == null) return sendJson(res, 404, { error: "File not found" });
|
|
169
|
+
const op = safeJoin(ctx.store.screensDir, g.original);
|
|
170
|
+
const before = await read(op);
|
|
171
|
+
if (before !== src) {
|
|
172
|
+
await writeAtomic(op, src);
|
|
173
|
+
changes.push({ path: op, before, after: src });
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const gone = await trashFiles(ctx, g.alts);
|
|
177
|
+
const label = g.chosen === g.original ? `Keep ${g.original}, trash ${g.alts.join(", ")}` : `Use ${g.chosen} for ${g.original}`;
|
|
178
|
+
await commitBoard(
|
|
179
|
+
ctx,
|
|
180
|
+
label,
|
|
181
|
+
(bd) => {
|
|
182
|
+
for (const f of g.alts) delete bd.boards[f];
|
|
183
|
+
bd.order = bd.order.filter((f) => !g.alts.includes(f));
|
|
184
|
+
unlinkOrigins(bd, g.alts);
|
|
185
|
+
},
|
|
186
|
+
[...changes, ...gone.changes],
|
|
187
|
+
);
|
|
188
|
+
for (const f of g.alts) ctx.occupancy.forget(f);
|
|
189
|
+
sendJson(res, 200, { ok: true, kind: g.kind, original: g.original, chosen: g.chosen, trashed: g.alts, step: ctx.history.peek().undo?.id ?? null });
|
|
190
|
+
},
|
|
191
|
+
],
|
|
192
|
+
// Keep all: the variants (or forks) stay as ordinary boards; only the link to the original goes
|
|
193
|
+
[
|
|
194
|
+
"POST",
|
|
195
|
+
"/api/boards/keep",
|
|
196
|
+
async (req, res, url, ctx) => {
|
|
197
|
+
const b = await readBody(req);
|
|
198
|
+
const board = await ctx.store.readBoard();
|
|
199
|
+
const g = boardFile(b.file) ? choiceGroup(board, b.file) : null;
|
|
200
|
+
if (!g) return sendJson(res, 400, { error: "That board is not a variant or fork of another board" });
|
|
201
|
+
await commitBoard(ctx, `Keep all ${g.kind === "variant" ? "variants" : "versions"} of ${g.original}`, (bd) => {
|
|
202
|
+
for (const f of g.alts) if (bd.boards[f]) delete bd.boards[f].origin;
|
|
203
|
+
});
|
|
204
|
+
sendJson(res, 200, { ok: true, kind: g.kind, original: g.original, kept: g.alts, step: ctx.history.peek().undo?.id ?? null });
|
|
205
|
+
},
|
|
206
|
+
],
|
|
207
|
+
];
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The calling agent holds file (a claim, or a write that changed nothing); people hold boards by selecting an element on them instead */
|
|
211
|
+
function holdForCaller(ctx, file, before) {
|
|
212
|
+
const s = requestScope.getStore();
|
|
213
|
+
if (s?.agent) ctx.occupancy.agentWrite(file, s.agent, { run: s.run && ctx.history.running(s.run) ? s.run : undefined, client: s.client, before });
|
|
214
|
+
}
|
package/server/fsutil.mjs
CHANGED
|
@@ -31,5 +31,30 @@ async function renameRetry(from, to, tries = 6) {
|
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
+
/** <design dir>/.easel: Easel's own files in the project (screenshots, run copies, snapshot copies), kept out of git by its .gitignore */
|
|
35
|
+
export async function easelDir(dir) {
|
|
36
|
+
const d = path.join(dir, ".easel");
|
|
37
|
+
await fs.mkdir(d, { recursive: true });
|
|
38
|
+
await fs.writeFile(path.join(d, ".gitignore"), "*\n", { flag: "wx" }).catch(() => {});
|
|
39
|
+
return d;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Repo root: two levels up for docs/design, otherwise (temp folders in tests) the folder itself */
|
|
43
|
+
export const rootOf = (dir) => (dir.endsWith(path.join("docs", "design")) ? path.resolve(dir, "../..") : dir);
|
|
44
|
+
|
|
45
|
+
/** Canvas name: the project folder (relay for /x/relay/docs/design), else the design folder's own name */
|
|
46
|
+
export const projectName = (dir) => path.basename(rootOf(dir));
|
|
47
|
+
|
|
48
|
+
/** <title> of an HTML file, trimmed and unescaped; null when missing or empty */
|
|
49
|
+
export function htmlTitle(html) {
|
|
50
|
+
const m = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(String(html ?? ""));
|
|
51
|
+
const t = m?.[1]
|
|
52
|
+
.replace(/<[^>]*>/g, "")
|
|
53
|
+
.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, (_, e) => ({ amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'", apos: "'", nbsp: " " })[e])
|
|
54
|
+
.replace(/\s+/g, " ")
|
|
55
|
+
.trim();
|
|
56
|
+
return t ? t.slice(0, 120) : null;
|
|
57
|
+
}
|
|
58
|
+
|
|
34
59
|
/** OS path (\\ or /) → / path for URLs and board.json */
|
|
35
60
|
export const toPosix = (rel, sep = path.sep) => rel.split(sep).join("/");
|
package/server/history.mjs
CHANGED
|
@@ -1,24 +1,50 @@
|
|
|
1
|
-
// AI-generated with Claude Code, 2026-10-09, reviewed by Hyun Park
|
|
1
|
+
// AI-generated with Claude Code, 2026-10-09, 2026-11-10 and 2026-11-12, reviewed by Hyun Park
|
|
2
2
|
// One chronological undo history: canvas operations (board.json), HTML edits and board file create/delete share the same stack.
|
|
3
|
-
// step = { label, changes: [{ path, before, after }] } — before/after null means the file does not exist.
|
|
3
|
+
// step = { id, label, changes: [{ path, before, after }], by?, client?, person? } — before/after null means the file does not exist.
|
|
4
|
+
// by: the agent (X-Easel-Agent or the in-app run), client/person: the browser and the person's name that made it (X-Easel-Client, X-Easel-Author).
|
|
5
|
+
// Outside changes (an agent's own file tools, an editor) become steps too: the last known content of every tracked file is kept,
|
|
6
|
+
// and anything that differs from it is recorded, grouped per in-app chat run or per burst of edits.
|
|
7
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
8
|
import fs from "node:fs/promises";
|
|
9
|
+
import path from "node:path";
|
|
5
10
|
|
|
6
11
|
import { writeAtomic } from "./fsutil.mjs";
|
|
7
12
|
|
|
8
13
|
const LIMIT = 100;
|
|
14
|
+
/** Outside changes this close together (no run active) merge into one step */
|
|
15
|
+
export const GROUP_MS = 10000;
|
|
9
16
|
|
|
10
|
-
|
|
17
|
+
/** Per-request values set by the HTTP server: { agent } from X-Easel-Agent, { run } from X-Easel-Run, { client, person } from X-Easel-Client / X-Easel-Author */
|
|
18
|
+
export const requestScope = new AsyncLocalStorage();
|
|
19
|
+
|
|
20
|
+
/** "a.html, b.html, c.html +2" */
|
|
21
|
+
export const fileList = (names, max = 3) => names.slice(0, max).join(", ") + (names.length > max ? ` +${names.length - max}` : "");
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* list: async () => absolute paths of the tracked files on disk now; isTracked(path) for paths seen earlier;
|
|
25
|
+
* name(path) → short name for labels; onStep(step, changes) after changes are recorded in a step (who is editing which board)
|
|
26
|
+
*/
|
|
27
|
+
export function createHistory({ onWrite, list = async () => [], isTracked = () => true, name = (p) => path.basename(p), onStep } = {}) {
|
|
11
28
|
let undo = [];
|
|
12
29
|
let redo = [];
|
|
30
|
+
const known = new Map(); // path → last known content (null: absent)
|
|
31
|
+
const runs = new Map(); // id → { id, label, by } for each in-app chat run that is going, oldest first
|
|
32
|
+
let seq = 0;
|
|
33
|
+
/** Step ids are unique for this server session only (the history is not kept across restarts) */
|
|
34
|
+
const nextId = () => `s${++seq}`;
|
|
35
|
+
// Disk changes nobody reported cannot be told apart between overlapping runs: they go to the one started last
|
|
36
|
+
const current = () => [...runs.values()].at(-1) ?? null;
|
|
13
37
|
|
|
14
38
|
const read = (p) => fs.readFile(p, "utf8").catch(() => null);
|
|
39
|
+
const trim = () => undo.length > LIMIT && undo.shift();
|
|
15
40
|
|
|
16
41
|
async function apply(changes, dir) {
|
|
17
|
-
// Do not overwrite if the file changed outside in the meantime
|
|
42
|
+
// Do not overwrite if the file changed outside in the meantime. Content the app itself wrote without a step
|
|
43
|
+
// (board.json auto-placement, position saves) is known, so it is replaced instead of blocking the undo
|
|
18
44
|
for (const c of changes) {
|
|
19
45
|
const now = await read(c.path);
|
|
20
46
|
const expect = dir === "undo" ? c.after : c.before;
|
|
21
|
-
if (now !== expect) {
|
|
47
|
+
if (now !== expect && now !== (known.get(c.path) ?? null)) {
|
|
22
48
|
undo = [];
|
|
23
49
|
redo = [];
|
|
24
50
|
throw Object.assign(new Error("A file changed outside the app, so the undo history was cleared"), { status: 409 });
|
|
@@ -28,36 +54,138 @@ export function createHistory({ onWrite } = {}) {
|
|
|
28
54
|
const target = dir === "undo" ? c.before : c.after;
|
|
29
55
|
if (target == null) await fs.rm(c.path, { force: true });
|
|
30
56
|
else await writeAtomic(c.path, target);
|
|
57
|
+
known.set(c.path, target);
|
|
31
58
|
onWrite?.(c.path, target);
|
|
32
59
|
}
|
|
33
60
|
}
|
|
34
61
|
|
|
62
|
+
/** Adds changes to the current group (the step of run, or a recent outside step), or opens a new one. Clears redo */
|
|
63
|
+
function group(changes, run = current(), now = Date.now()) {
|
|
64
|
+
if (!changes.length) return null;
|
|
65
|
+
const top = undo[undo.length - 1];
|
|
66
|
+
const fits = top?.outside && (run ? top.run === run.id : !top.run && now - top.lastAt < GROUP_MS);
|
|
67
|
+
let step = fits ? top : null;
|
|
68
|
+
if (!step) {
|
|
69
|
+
step = { id: nextId(), label: run?.label ?? "", changes: [], at: now, outside: true, ...(run ? { run: run.id, by: run.by } : {}) };
|
|
70
|
+
undo.push(step);
|
|
71
|
+
trim();
|
|
72
|
+
}
|
|
73
|
+
for (const c of changes) {
|
|
74
|
+
const prev = step.changes.find((x) => x.path === c.path);
|
|
75
|
+
if (prev) prev.after = c.after;
|
|
76
|
+
else step.changes.push({ path: c.path, before: c.before, after: c.after });
|
|
77
|
+
}
|
|
78
|
+
step.changes = step.changes.filter((c) => c.before !== c.after);
|
|
79
|
+
step.lastAt = now;
|
|
80
|
+
step.rev = (step.rev ?? 0) + 1; // grouped steps change in place: lets readers cache what they derive from a step
|
|
81
|
+
if (!step.run) step.label = `Changed outside the app: ${fileList(step.changes.map((c) => name(c.path)))}`;
|
|
82
|
+
if (!step.changes.length) undo.splice(undo.indexOf(step), 1);
|
|
83
|
+
redo = [];
|
|
84
|
+
onStep?.(step, changes);
|
|
85
|
+
return step;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Tracked files whose content differs from the last known → one outside step (or merged into the current group) */
|
|
89
|
+
async function observe(paths) {
|
|
90
|
+
const all = paths ?? [...new Set([...(await list()), ...[...known.keys()].filter(isTracked)])];
|
|
91
|
+
const changes = [];
|
|
92
|
+
for (const p of all) {
|
|
93
|
+
const now = await read(p);
|
|
94
|
+
const before = known.get(p) ?? null;
|
|
95
|
+
if (now === before) continue;
|
|
96
|
+
known.set(p, now);
|
|
97
|
+
changes.push({ path: p, before, after: now });
|
|
98
|
+
}
|
|
99
|
+
return group(changes);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function undoOne() {
|
|
103
|
+
await observe(); // pending outside changes first, so undo takes back the latest change instead of tripping the safety check
|
|
104
|
+
const step = undo[undo.length - 1];
|
|
105
|
+
if (!step) return null;
|
|
106
|
+
await apply([...step.changes].reverse(), "undo");
|
|
107
|
+
undo.pop();
|
|
108
|
+
redo.push(step);
|
|
109
|
+
return step;
|
|
110
|
+
}
|
|
111
|
+
async function redoOne() {
|
|
112
|
+
await observe();
|
|
113
|
+
const step = redo[redo.length - 1];
|
|
114
|
+
if (!step) return null;
|
|
115
|
+
await apply(step.changes, "redo");
|
|
116
|
+
redo.pop();
|
|
117
|
+
undo.push(step);
|
|
118
|
+
return step;
|
|
119
|
+
}
|
|
120
|
+
|
|
35
121
|
return {
|
|
36
|
-
/** Records a change that has already been written
|
|
37
|
-
|
|
122
|
+
/** Records a change that has already been written. Inside a request from the running in-app agent (X-Easel-Run) it joins the run's step.
|
|
123
|
+
* mark: extra fields kept on the step (undoOf / redoOf: the run an undo-run step belongs to) */
|
|
124
|
+
push(label, changes, mark = {}) {
|
|
125
|
+
for (const c of changes) known.set(c.path, c.after);
|
|
38
126
|
const real = changes.filter((c) => c.before !== c.after);
|
|
39
127
|
if (!real.length) return;
|
|
40
|
-
|
|
41
|
-
|
|
128
|
+
const scope = requestScope.getStore();
|
|
129
|
+
const run = scope?.run ? runs.get(scope.run) : null;
|
|
130
|
+
if (run) return void group(real, run);
|
|
131
|
+
const who = scope?.agent ? { by: scope.agent } : scope?.person ? { person: scope.person } : {};
|
|
132
|
+
const step = { id: nextId(), label, changes: real, at: Date.now(), ...who, ...(scope?.client ? { client: scope.client } : {}), ...mark };
|
|
133
|
+
undo.push(step);
|
|
134
|
+
trim();
|
|
42
135
|
redo = [];
|
|
136
|
+
onStep?.(step, real);
|
|
43
137
|
},
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
await apply([...step.changes].reverse(), "undo");
|
|
48
|
-
undo.pop();
|
|
49
|
-
redo.push(step);
|
|
50
|
-
return step;
|
|
138
|
+
/** The app wrote this content without a history step (auto-placement, positions): not an outside change */
|
|
139
|
+
note(p, content) {
|
|
140
|
+
known.set(p, content);
|
|
51
141
|
},
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
await
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
142
|
+
/** Reads every tracked file as the starting point */
|
|
143
|
+
async seed() {
|
|
144
|
+
known.clear();
|
|
145
|
+
for (const p of await list()) known.set(p, await read(p));
|
|
146
|
+
},
|
|
147
|
+
observe,
|
|
148
|
+
beginRun(r) {
|
|
149
|
+
runs.set(r.id, r);
|
|
150
|
+
},
|
|
151
|
+
endRun(id) {
|
|
152
|
+
runs.delete(id);
|
|
153
|
+
},
|
|
154
|
+
/** Whether an in-app run with this id is going */
|
|
155
|
+
running: (id) => runs.has(id),
|
|
156
|
+
/** Undo steps made by a run (normally one) */
|
|
157
|
+
runSteps: (id) => undo.filter((s) => s.run === id),
|
|
158
|
+
/** The newest undo and redo steps: undo-run is a plain undo/redo when its step is on top */
|
|
159
|
+
peek: () => ({ undo: undo[undo.length - 1] ?? null, redo: redo[redo.length - 1] ?? null }),
|
|
160
|
+
/** Both stacks as they are (oldest first; the redo stack's last entry is the next redo). For reading only */
|
|
161
|
+
entries: () => ({ undo: [...undo], redo: [...redo] }),
|
|
162
|
+
/** Last content the history knows for a tracked file (what is on disk unless an outside change is still pending) */
|
|
163
|
+
current: (p) => known.get(p) ?? null,
|
|
164
|
+
undo: undoOne,
|
|
165
|
+
redo: redoOne,
|
|
166
|
+
/** History › Go back to here: undo (or redo) one step at a time until step id is the newest applied one. Returns the steps moved */
|
|
167
|
+
async goTo(id) {
|
|
168
|
+
await observe();
|
|
169
|
+
const dir = undo.some((s) => s.id === id) ? "undo" : redo.some((s) => s.id === id) ? "redo" : null;
|
|
170
|
+
if (!dir) throw Object.assign(new Error("That step is no longer in the history"), { status: 404 });
|
|
171
|
+
let moved = 0;
|
|
172
|
+
while (undo[undo.length - 1]?.id !== id) {
|
|
173
|
+
if (!(await (dir === "undo" ? undoOne() : redoOne()))) break;
|
|
174
|
+
moved++;
|
|
175
|
+
}
|
|
176
|
+
return moved;
|
|
177
|
+
},
|
|
178
|
+
state: () => {
|
|
179
|
+
const brief = (s) => ({ id: s.id, label: s.label, ...(s.by ? { by: s.by } : {}), at: s.at });
|
|
180
|
+
return {
|
|
181
|
+
undo: undo.map((s) => s.label).slice(-20),
|
|
182
|
+
redo: redo.map((s) => s.label).slice(-20),
|
|
183
|
+
canUndo: undo.length > 0,
|
|
184
|
+
canRedo: redo.length > 0,
|
|
185
|
+
steps: undo.slice(-20).map(brief),
|
|
186
|
+
redoSteps: redo.slice(-20).map(brief),
|
|
187
|
+
};
|
|
59
188
|
},
|
|
60
|
-
state: () => ({ undo: undo.map((s) => s.label).slice(-20), redo: redo.map((s) => s.label).slice(-20), canUndo: undo.length > 0, canRedo: redo.length > 0 }),
|
|
61
189
|
clear() {
|
|
62
190
|
undo = [];
|
|
63
191
|
redo = [];
|
package/server/html.mjs
CHANGED
|
@@ -57,6 +57,16 @@ export function textOf(node) {
|
|
|
57
57
|
return (node.childNodes ?? []).map(textOf).join("");
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
// Block elements read as separate words in a label: "Meditate" + "10 min" is "Meditate 10 min", not "Meditate10 min"
|
|
61
|
+
const BLOCK = new Set("address article aside blockquote dd div dl dt figcaption figure footer form h1 h2 h3 h4 h5 h6 header li main nav ol p pre section table td th tr ul".split(" "));
|
|
62
|
+
|
|
63
|
+
/** Text for showing an element by name (layers list): like textOf, with a space between block children */
|
|
64
|
+
export function labelOf(node) {
|
|
65
|
+
if (node.nodeName === "#text") return node.value;
|
|
66
|
+
if (node.tagName === "script" || node.tagName === "style") return "";
|
|
67
|
+
return (node.childNodes ?? []).map((c) => (BLOCK.has(c.tagName) ? ` ${labelOf(c)} ` : labelOf(c))).join("");
|
|
68
|
+
}
|
|
69
|
+
|
|
60
70
|
/** Tree for the layers list (depth-limited) */
|
|
61
71
|
export function outline(html, maxDepth = 12) {
|
|
62
72
|
const doc = parseHtml(html);
|
|
@@ -65,7 +75,7 @@ export function outline(html, maxDepth = 12) {
|
|
|
65
75
|
elementChildren(node).map((c, i) => {
|
|
66
76
|
const p = path ? `${path}/${i}` : String(i);
|
|
67
77
|
const cls = c.attrs?.find((a) => a.name === "class")?.value;
|
|
68
|
-
const text =
|
|
78
|
+
const text = labelOf(c).replace(/\s+/g, " ").trim().slice(0, 40);
|
|
69
79
|
return {
|
|
70
80
|
path: p,
|
|
71
81
|
tag: c.tagName,
|