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/server/boards.mjs CHANGED
@@ -6,12 +6,14 @@ import path from "node:path";
6
6
  import { formatBoard } from "./boardFormat.mjs";
7
7
  import { writeAtomic } from "./fsutil.mjs";
8
8
  import { readBody, safeJoin, sendJson } from "./index.mjs";
9
+ import { freeSpot, GAP_X, placeNew } from "./place.mjs";
10
+ import { SYSTEM_FONT } from "./tokens.mjs";
9
11
 
10
12
  const read = (p) => fs.readFile(p, "utf8").catch(() => null);
11
13
  const FILE_RE = /^[a-z0-9][a-z0-9._-]*\.html$/i;
12
14
 
13
- const FONT = `@font-face{font-family:"Pretendard Variable";font-weight:45 920;font-style:normal;font-display:swap;src:url(https://cdn.jsdelivr.net/npm/pretendard@1.3.9/dist/web/variable/woff2/PretendardVariable.woff2) format("woff2-variations")}
14
- body{margin:0;color-scheme:light;font-family:"Pretendard Variable",Pretendard,-apple-system,"Apple SD Gothic Neo","Noto Sans KR",sans-serif;color:#111111;background:#FFFFFF;-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}`;
15
+ // System font stack only (the same as the default tokens): no web font download, nothing language- or brand-specific
16
+ const BASE_CSS = `body{margin:0;color-scheme:light;font-family:${SYSTEM_FONT.replace(/, /g, ",")};color:#111111;background:#FFFFFF;-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}`;
15
17
 
16
18
  /** New board templates. The size is written both in the board-size meta and on the outermost div */
17
19
  export const TEMPLATES = {
@@ -21,9 +23,10 @@ export const TEMPLATES = {
21
23
  doc: { label: "Document", w: 800, h: 1000 },
22
24
  };
23
25
 
24
- export function newBoardHtml({ title, w, h, template = "blank" }) {
26
+ export function newBoardHtml({ title, w, h, template = "blank", brand = "" }) {
25
27
  const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;");
26
28
  const t = esc(title);
29
+ const name = esc(brand || "Title");
27
30
  const bodies = {
28
31
  blank: `<div style="width:${w}px;min-height:${h}px;box-sizing:border-box;padding:20px;display:flex;flex-direction:column;gap:16px">
29
32
  </div>`,
@@ -41,7 +44,7 @@ export function newBoardHtml({ title, w, h, template = "blank" }) {
41
44
  </div>`,
42
45
  desktop: `<div style="width:${w}px;min-height:${h}px;box-sizing:border-box;background:#FFFFFF;display:flex;flex-direction:column">
43
46
  <header style="height:64px;display:flex;align-items:center;gap:24px;padding:0 40px;border-bottom:1px solid #E8E8E6;flex:none">
44
- <strong style="font-size:20px">farmclub</strong>
47
+ <strong style="font-size:20px">${name}</strong>
45
48
  </header>
46
49
  <main style="flex:1;max-width:1120px;width:100%;margin:0 auto;padding:40px;box-sizing:border-box;display:flex;flex-direction:column;gap:24px">
47
50
  <h1 style="margin:0;font-size:40px;font-weight:700;letter-spacing:-0.02em">${t}</h1>
@@ -53,14 +56,14 @@ export function newBoardHtml({ title, w, h, template = "blank" }) {
53
56
  </div>`,
54
57
  };
55
58
  return `<!doctype html>
56
- <html lang="ko">
59
+ <html lang="en">
57
60
  <head>
58
61
  <meta charset="utf-8">
59
62
  <meta name="viewport" content="width=device-width, initial-scale=1">
60
63
  <meta name="board-size" content="${w}x${h}">
61
64
  <title>${t}</title>
62
65
  <style>
63
- ${FONT}
66
+ ${BASE_CSS}
64
67
  </style>
65
68
  </head>
66
69
  <body>
@@ -73,7 +76,7 @@ ${bodies[template] ?? bodies.blank}
73
76
  }
74
77
 
75
78
  /** A file name that does not collide */
76
- async function uniqueName(screensDir, base) {
79
+ export async function uniqueName(screensDir, base) {
77
80
  const stem = base.replace(/\.html$/i, "");
78
81
  for (let i = 0; i < 1000; i++) {
79
82
  const name = `${stem}${i ? `-${i + 1}` : ""}.html`;
@@ -108,7 +111,7 @@ function repage(board, pages, map = (pid) => pid) {
108
111
  if (board.launch?.page && !pages.some((p) => p.id === board.launch.page)) delete board.launch.page;
109
112
  }
110
113
 
111
- /** Creates several boards as one history step. items: [{file, html, x, y, w, h, title, page}] → list of actual file names */
114
+ /** Creates several boards as one history step. items: [{file, html, x, y, w, h, title, page, origin}] → list of actual file names */
112
115
  export async function createBoards(ctx, items, label) {
113
116
  const changes = [];
114
117
  const made = [];
@@ -124,7 +127,7 @@ export async function createBoards(ctx, items, label) {
124
127
  label,
125
128
  (board) => {
126
129
  for (const it of made) {
127
- board.boards[it.file] = { x: Math.round(it.x ?? 0), y: Math.round(it.y ?? 0), w: it.w, h: it.h, title: it.title, ...(it.page ? { page: it.page } : {}) };
130
+ board.boards[it.file] = { x: Math.round(it.x ?? 0), y: Math.round(it.y ?? 0), w: it.w, h: it.h, title: it.title, ...(it.page ? { page: it.page } : {}), ...(it.origin ? { origin: it.origin } : {}) };
128
131
  board.order = [...board.order.filter((f) => f !== it.file), it.file];
129
132
  }
130
133
  },
@@ -146,6 +149,31 @@ export async function commitBoard(ctx, label, mutate, fileChanges = []) {
146
149
  return after;
147
150
  }
148
151
 
152
+ /**
153
+ * Moves board files to the trash (<design dir>/.trash/<time>/, gitignored) and deletes them; Undo brings them back from the history.
154
+ * Returns the history changes for the files that were there
155
+ */
156
+ export async function trashFiles(ctx, files) {
157
+ const trash = path.join(ctx.dir, ".trash", new Date().toISOString().replace(/[:.]/g, "-"));
158
+ await fs.mkdir(trash, { recursive: true });
159
+ await fs.writeFile(path.join(ctx.dir, ".trash", ".gitignore"), "*\n").catch(() => {});
160
+ const changes = [];
161
+ for (const f of files) {
162
+ const p = safeJoin(ctx.store.screensDir, f);
163
+ const html = p && (await read(p));
164
+ if (html == null) continue;
165
+ await fs.writeFile(path.join(trash, path.basename(f)), html);
166
+ await fs.rm(p);
167
+ changes.push({ path: p, before: html, after: null });
168
+ }
169
+ return { changes, trash };
170
+ }
171
+
172
+ /** Boards that came from a deleted board (its variants and forks) become ordinary boards: the link would point at nothing */
173
+ export function unlinkOrigins(board, gone) {
174
+ for (const b of Object.values(board.boards)) if (b.origin && gone.includes(b.origin.of)) delete b.origin;
175
+ }
176
+
149
177
  export function boardRoutes() {
150
178
  return [
151
179
  [
@@ -177,8 +205,11 @@ export function boardRoutes() {
177
205
  const h = Math.max(40, Math.min(8000, Math.round(b.h ?? TEMPLATES[tpl].h)));
178
206
  const wanted = b.file && FILE_RE.test(b.file) ? b.file : `${tpl === "blank" ? "board" : tpl}.html`;
179
207
  const title = b.title || (tpl === "blank" ? wanted.replace(/\.html$/, "") : TEMPLATES[tpl].label);
180
- const html = b.html ?? newBoardHtml({ title, w, h, template: tpl });
181
- const [file] = await createBoards(ctx, [{ file: wanted, html, x: b.x, y: b.y, w, h, title, page: b.page }], `Create board ${wanted}`);
208
+ const board0 = await ctx.store.readBoard();
209
+ const html = b.html ?? newBoardHtml({ title, w, h, template: tpl, brand: board0.title });
210
+ // No position given (an agent's create_board): the first free spot, never on top of a board or a note
211
+ const at = Number.isFinite(b.x) && Number.isFinite(b.y) ? { x: b.x, y: b.y } : placeNew(board0, { w, h }, b.page);
212
+ const [file] = await createBoards(ctx, [{ file: wanted, html, x: at.x, y: at.y, w, h, title, page: b.page }], `Create board ${wanted}`);
182
213
  sendJson(res, 200, { file });
183
214
  },
184
215
  ],
@@ -191,27 +222,18 @@ export function boardRoutes() {
191
222
  const files = (b.files ?? []).filter((f) => FILE_RE.test(path.basename(f)));
192
223
  if (!files.length) return sendJson(res, 400, { error: "files is required" });
193
224
  // Also copy to the trash (docs/design/.trash/). Undo restores from the history
194
- const trash = path.join(ctx.dir, ".trash", new Date().toISOString().replace(/[:.]/g, "-"));
195
- await fs.mkdir(trash, { recursive: true });
196
- await fs.writeFile(path.join(ctx.dir, ".trash", ".gitignore"), "*\n").catch(() => {});
197
- const changes = [];
198
- for (const f of files) {
199
- const p = safeJoin(ctx.store.screensDir, f);
200
- const html = p && (await read(p));
201
- if (html == null) continue;
202
- await fs.writeFile(path.join(trash, path.basename(f)), html);
203
- await fs.rm(p);
204
- changes.push({ path: p, before: html, after: null });
205
- }
225
+ const { changes, trash } = await trashFiles(ctx, files);
206
226
  await commitBoard(
207
227
  ctx,
208
228
  `Delete board ${files.join(", ")}`,
209
229
  (board) => {
210
230
  for (const f of files) delete board.boards[f];
211
231
  board.order = board.order.filter((f) => !files.includes(f));
232
+ unlinkOrigins(board, files);
212
233
  },
213
234
  changes,
214
235
  );
236
+ for (const f of files) ctx.occupancy?.forget(f);
215
237
  sendJson(res, 200, { ok: true, trash: path.relative(ctx.dir, trash) });
216
238
  },
217
239
  ],
@@ -227,12 +249,14 @@ export function boardRoutes() {
227
249
  const p = path.join(ctx.store.screensDir, file);
228
250
  await writeAtomic(p, html);
229
251
  const board0 = await ctx.store.readBoard();
230
- const it = board0.boards[b.file] ?? { x: 0, y: 0, w: 390, h: 844 };
252
+ // The copy is an ordinary board: it is not a variant or fork of anything
253
+ const { origin, autoPlaced, ...it } = board0.boards[b.file] ?? { x: 0, y: 0, w: 390, h: 844 };
254
+ const at = freeSpot(board0, { x: it.x + it.w + GAP_X, y: it.y, w: it.w, h: it.h }, { page: it.page });
231
255
  await commitBoard(
232
256
  ctx,
233
257
  `Duplicate board ${b.file}`,
234
258
  (board) => {
235
- board.boards[file] = { ...it, x: it.x + it.w + 80, title: `${it.title ?? b.file.replace(/\.html$/, "")} copy` };
259
+ board.boards[file] = { ...it, x: at.x, y: at.y, title: `${it.title ?? b.file.replace(/\.html$/, "")} copy` };
236
260
  const i = board.order.indexOf(b.file);
237
261
  board.order.splice(i < 0 ? board.order.length : i + 1, 0, file);
238
262
  },
@@ -292,6 +316,8 @@ export function boardRoutes() {
292
316
  board.boards[b.newFile] = { ...board.boards[b.file], ...(b.title ? { title: b.title } : {}) };
293
317
  delete board.boards[b.file];
294
318
  board.order = board.order.map((f) => (f === b.file ? b.newFile : f));
319
+ // Its variants and forks follow the new name
320
+ for (const o of Object.values(board.boards)) if (o.origin?.of === b.file) o.origin = { ...o.origin, of: b.newFile };
295
321
  },
296
322
  changes,
297
323
  );
@@ -0,0 +1,68 @@
1
+ // AI-generated with Claude Code, 2026-11-11, reviewed by Hyun Park
2
+ // The one shared headless Chromium (playwright, an optional dependency) behind screenshots, thumbnails and PDF/PNG export.
3
+ import { existsSync } from "node:fs";
4
+
5
+ let browserPromise = null;
6
+ /** Close the Chromium used for screenshots/thumbnails when the server stops (otherwise it becomes an orphan process) */
7
+ export async function closeBrowser() {
8
+ const b = await browserPromise?.catch(() => null);
9
+ browserPromise = null;
10
+ await b?.close().catch(() => {});
11
+ }
12
+
13
+ const loadPlaywright = () =>
14
+ import("playwright").catch(() => {
15
+ throw Object.assign(new Error("Screenshots are unavailable because playwright is not installed (npm run design:install)"), { status: 501 });
16
+ });
17
+
18
+ export async function getBrowser() {
19
+ // A browser that exited behind our back (crash, killed, sleep) must not stay cached, or every thumbnail fails until a restart
20
+ const pending = browserPromise;
21
+ const cached = pending && (await pending.catch(() => null));
22
+ if (cached && !cached.isConnected() && browserPromise === pending) browserPromise = null;
23
+ if (!browserPromise) {
24
+ const p = (browserPromise = (async () => {
25
+ const { chromium } = await loadPlaywright();
26
+ // Fall back to the installed Chrome if no downloaded Chromium exists
27
+ const b = await chromium.launch().catch(() => chromium.launch({ channel: "chrome" }));
28
+ b.on("disconnected", () => {
29
+ if (browserPromise === p) browserPromise = null;
30
+ });
31
+ return b;
32
+ })());
33
+ p.catch(() => {
34
+ if (browserPromise === p) browserPromise = null;
35
+ });
36
+ }
37
+ return browserPromise;
38
+ }
39
+
40
+ /** New page on the shared browser; if the browser died since it was cached, launch a fresh one and try once more */
41
+ export async function newPage(opts) {
42
+ const browser = await getBrowser();
43
+ try {
44
+ return await browser.newPage(opts);
45
+ } catch (e) {
46
+ if (browser.isConnected()) throw e;
47
+ return (await getBrowser()).newPage(opts); // getBrowser drops the dead one and launches again
48
+ }
49
+ }
50
+
51
+ /** For tests: the browser currently cached for screenshots, if any */
52
+ export const cachedBrowser = () => browserPromise?.catch(() => null) ?? Promise.resolve(null);
53
+
54
+ /** Can PDF/PNG export run here? { ok } or { ok: false, reason } in one line, without launching when the downloaded Chromium is on disk */
55
+ export async function browserStatus() {
56
+ let chromium;
57
+ try {
58
+ ({ chromium } = await import("playwright"));
59
+ } catch {
60
+ return { ok: false, reason: "Needs Playwright: npm i playwright" };
61
+ }
62
+ if (existsSync(chromium.executablePath())) return { ok: true };
63
+ // No downloaded Chromium: the installed Chrome may still work (getBrowser falls back to it)
64
+ return getBrowser().then(
65
+ () => ({ ok: true }),
66
+ () => ({ ok: false, reason: "Needs Chromium: npx playwright install chromium" }),
67
+ );
68
+ }