blockout-editor 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 CHANGED
@@ -73,12 +73,24 @@ The **Edit** button sits in the page's bottom right corner. It opens the panel:
73
73
  - Hold **Space** to use the page as usual for a moment. Links, buttons and hover looks hold still while editing (the
74
74
  settings change that).
75
75
 
76
- **Send to Claude Code** saves a note in `.notes/blockout-notes.json`: your words, the element you picked (its CSS path and, in
77
- a React dev build, its components), and every style you changed on the page, from → to.
76
+ **Comment mode** (the speech bubble in the panel's header): click anything on the page and a box opens beside it; type
77
+ what should change and press Enter. Each comment gets a numbered pin on its element and waits in the panel.
78
78
 
79
- ## Claude Code: `sc`
79
+ **Send to Claude** sends your message, the comments and every style you changed on the page (from → to, against your
80
+ tokens) to the panel's **Claude** tab. Your dev server runs your own Claude Code in the project's folder
81
+ (`claude -p`, with your login, settings, CLAUDE.md and skills), so it makes the changes in your code and the page
82
+ reloads with them; the tab shows each step as Claude takes it (read, search, edit, run), then its answer. A chat is one
83
+ Claude Code session: reply to carry on, and Claude remembers the thread and its own edits ("undo that" works). Chats
84
+ are kept in `.notes/blockout-chats.json`; New chat starts a fresh one.
80
85
 
81
- Put this line in your project's instructions (CLAUDE.md, AGENTS.md or the like):
86
+ Claude may read, search and edit your files, run commands (Bash) and use your skills, without asking (there is no one
87
+ to ask in `-p`). It starts only on the dev server, and only from your app's own page on this computer's own address
88
+ (`localhost`, `127.0.0.1`, `*.localhost`): another site can't start it, by a rebound DNS name either. `claude` must be
89
+ on the PATH of the terminal the dev server runs in (or set `BLOCKOUT_CLAUDE` to its path).
90
+
91
+ ## Without the chat: `sc`
92
+
93
+ The notes route also keeps notes in `.notes/blockout-notes.json` for Claude Code to work through itself. Put this line in your project's instructions (CLAUDE.md, AGENTS.md or the like):
82
94
 
83
95
  ```text
84
96
  When I say "sc": read .notes/blockout-notes.json, make each open note's changes in the code (with the project's own tokens and
@@ -102,7 +114,8 @@ colours (any token whose value is a colour) and type styles (classes like `.text
102
114
  ## What leaves your computer
103
115
 
104
116
  Nothing of your page. The panel loads from Blockout (`startEditor({ blockout })` points it elsewhere), and your page
105
- tells it what to draw in the browser: values, token names and element labels. Notes go to your own dev server. Only a
117
+ tells it what to draw in the browser: values, token names and element labels. Comments, messages and notes go to your
118
+ own dev server, and Claude runs there with your own Claude Code. Only a
106
119
  page on your own computer (localhost) can show Blockout's panel.
107
120
 
108
121
  ## Options
@@ -68,6 +68,10 @@
68
68
  panelOn = !!on;
69
69
  if (!relay) setOn(!!on);
70
70
  };
71
+ // The element picked now, for the kit's comment box to sit beside.
72
+ window.__blockoutEditorPicked = function () {
73
+ return S.sel || null;
74
+ };
71
75
  window.__blockoutEditorRelay = function (w, changesThere) {
72
76
  relay = w || null;
73
77
  if (relay) return setOn(false);
@@ -1698,6 +1702,9 @@
1698
1702
  // Words styled in a text are part of it, not layers.
1699
1703
  while (t && t.hasAttribute && t.hasAttribute("data-bo-mark")) t = t.parentElement;
1700
1704
  if (!t || t === document.documentElement || t === document.body) return null;
1705
+ // The kit's comment mode: a click is on what is under the pointer, as a whole: a button or link rather than its
1706
+ // label, an icon rather than its paths.
1707
+ if (window.__blockoutEditorDeep) return (t.closest && t.closest("button,a,input,select,textarea,label,img,svg,[role=button]")) || t;
1701
1708
  if (deep) return t;
1702
1709
  if (S.sel && S.sel.isConnected && (S.sel === t || S.sel.contains(t))) return S.sel;
1703
1710
  var scope = S.sel && S.sel.isConnected ? S.sel.parentElement : null;
@@ -2848,8 +2855,11 @@
2848
2855
  * Blockout's editor in a project's own dev page. startEditor() puts the editor's engine (engine.js, the same one
2849
2856
  * Blockout's file view uses) in this page and docks Blockout's editor panel beside it, in a frame from Blockout
2850
2857
  * (/editor), behind a small Edit button in the corner. Pick anything on the page and change it live against the page's
2851
- * own tokens; Send to Claude Code saves what changed, with a note, through the dev server into .notes/blockout-notes.json
2852
- * (server/next.js, server/vite.js), where Claude Code picks it up (`sc`, or `npx blockout-editor mcp`).
2858
+ * own tokens, or comment on it (comment mode: a box beside what is picked, a numbered pin on it); Send to Claude goes
2859
+ * to the panel's Claude chat, which the dev server's route runs as the person's own Claude Code in the project
2860
+ * (server/claude.js), so it writes the changes into the code and hot reload shows them. With no Claude Code there,
2861
+ * a send is saved as a note in .notes/blockout-notes.json instead (server/next.js, server/vite.js), for Claude Code to
2862
+ * pick up (`sc`, or `npx blockout-editor mcp`).
2853
2863
  *
2854
2864
  * Development only: call it from a dev build (react.js does). Nothing here reaches Blockout but what the panel needs
2855
2865
  * to draw: values, token names and labels from the page, never its content.
@@ -2935,6 +2945,15 @@ function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-notes", op
2935
2945
  "box-shadow:0 4px 14px rgba(16,16,16,.24)";
2936
2946
 
2937
2947
  let isOpen = false;
2948
+ // Open across a reload: Claude's edits reload the page through the dev server, and the chat goes on in the panel.
2949
+ const remember = (on) => {
2950
+ try {
2951
+ sessionStorage.setItem("blockout-editor:open", on ? "1" : "");
2952
+ } catch {}
2953
+ };
2954
+ try {
2955
+ open = open || sessionStorage.getItem("blockout-editor:open") === "1";
2956
+ } catch {}
2938
2957
  const toPanel = (msg) => frame.contentWindow?.postMessage({ ...msg, blockoutEditorKit: 1 }, origin);
2939
2958
  // On a phone the panels are a sheet at the bottom, the page above them; Layers take the sheet's place when shown.
2940
2959
  const place = (el, sheet, side) => {
@@ -2944,6 +2963,8 @@ function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-notes", op
2944
2963
  };
2945
2964
  const setOpen = (on) => {
2946
2965
  isOpen = on;
2966
+ remember(on);
2967
+ if (!on) comments.pins([]);
2947
2968
  host.style.display = on ? "block" : "none";
2948
2969
  const narrow = window.innerWidth < 640;
2949
2970
  const room = narrow || window.innerWidth >= 900;
@@ -2972,6 +2993,33 @@ function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-notes", op
2972
2993
  if (m.type === "ready") toPanel({ type: "open", open: isOpen });
2973
2994
  // Blockout's theme, so the canvas around the frames matches the panels.
2974
2995
  if (m.type === "theme") canvas.setDark(m.dark === true);
2996
+ // The chat's calls to the dev server's route (server/claude.js), made from this page, its own origin.
2997
+ if (m.type === "api" && typeof m.id === "string") {
2998
+ const query = new URLSearchParams();
2999
+ for (const k of ["claude", "id"]) if (typeof m.query?.[k] === "string") query.set(k, m.query[k]);
3000
+ const method = m.method === "POST" ? "POST" : "GET";
3001
+ try {
3002
+ const res = await fetch(`${notesApi}?${query}`, {
3003
+ method,
3004
+ headers: { "content-type": "application/json" },
3005
+ ...(method === "POST" ? { body: JSON.stringify(m.body ?? {}) } : {}),
3006
+ });
3007
+ toPanel({ type: "api", id: m.id, status: res.status, body: await res.json().catch(() => ({})) });
3008
+ } catch {
3009
+ toPanel({ type: "api", id: m.id, status: 0, body: { error: "The dev server didn't answer." } });
3010
+ }
3011
+ return;
3012
+ }
3013
+ // Comment mode: a box beside what is picked, and the numbered pins of the comments not sent yet.
3014
+ if (m.type === "comment-mode") {
3015
+ // A click picks exactly what is under the pointer, not a layer at a time as when designing.
3016
+ window.__blockoutEditorDeep = m.on === true;
3017
+ if (!m.on) comments.close();
3018
+ return;
3019
+ }
3020
+ if (m.type === "comment-box") return comments.open(m.n, String(m.label ?? ""));
3021
+ if (m.type === "comment-close") return comments.close();
3022
+ if (m.type === "pins") return comments.pins(Array.isArray(m.pins) ? m.pins : []);
2975
3023
  if (m.type === "send") {
2976
3024
  try {
2977
3025
  const res = await fetch(notesApi, {
@@ -2989,6 +3037,7 @@ function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-notes", op
2989
3037
  }
2990
3038
  }
2991
3039
  };
3040
+ const comments = makeComments({ toPanel });
2992
3041
  window.addEventListener("message", onMessage);
2993
3042
  document.body.append(left, tab, host, pill);
2994
3043
  setOpen(open);
@@ -3002,6 +3051,7 @@ function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-notes", op
3002
3051
  window.removeEventListener("message", onMessage);
3003
3052
  window.__blockoutEditorSetOn?.(false);
3004
3053
  canvas.remove();
3054
+ comments.remove();
3005
3055
  host.remove();
3006
3056
  left.remove();
3007
3057
  tab.remove();
@@ -3010,6 +3060,158 @@ function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-notes", op
3010
3060
  };
3011
3061
  }
3012
3062
 
3063
+ /*
3064
+ * Comments on the page, as Agentation's: in comment mode the panel asks for a box beside what the engine picked (the
3065
+ * engine leaves anything marked data-blockout-editor alone, so the box takes clicks and keys); Enter adds the comment
3066
+ * and the panel numbers it, Esc or Cancel lets it go. Each comment not sent yet has a numbered pin on its element,
3067
+ * kept in place as the page scrolls.
3068
+ */
3069
+ const INK = "#101010";
3070
+ const ACCENT = "#e12c05";
3071
+ const FONT = "ui-sans-serif,system-ui,-apple-system,sans-serif";
3072
+
3073
+ function makeComments({ toPanel }) {
3074
+ const els = new Map();
3075
+ let shown = [];
3076
+ let box = null;
3077
+ const layer = document.createElement("div");
3078
+ layer.setAttribute("data-blockout-editor", "");
3079
+ layer.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:2147483645";
3080
+ document.body.append(layer);
3081
+
3082
+ const pin = (n) => {
3083
+ const el = document.createElement("span");
3084
+ el.textContent = String(n);
3085
+ el.style.cssText =
3086
+ `position:absolute;display:flex;align-items:center;justify-content:center;min-width:22px;height:22px;padding:0 6px;box-sizing:border-box;` +
3087
+ `border-radius:11px 11px 11px 3px;background:${ACCENT};color:#fff;font:700 11px/1 ${FONT};` +
3088
+ "box-shadow:0 0 0 2px #fff,0 4px 12px rgba(16,16,16,.22);font-variant-numeric:tabular-nums";
3089
+ return el;
3090
+ };
3091
+ let frame = 0;
3092
+ const place = () => {
3093
+ frame = 0;
3094
+ for (const p of layer.children) {
3095
+ const el = els.get(Number(p.dataset.n));
3096
+ const r = el?.isConnected ? el.getBoundingClientRect() : null;
3097
+ p.style.display = r ? "flex" : "none";
3098
+ if (r) Object.assign(p.style, { left: `${Math.max(4, r.left - 6)}px`, top: `${Math.max(4, r.top - 16)}px` });
3099
+ }
3100
+ if (box?.el) {
3101
+ const r = box.el.isConnected ? box.el.getBoundingClientRect() : null;
3102
+ if (!r) return close();
3103
+ // Beside the element, clear of the panel on the right; above the fold.
3104
+ const room = window.innerWidth - (window.innerWidth < 640 ? 8 : 376);
3105
+ const w = 288;
3106
+ let x = r.right + 10;
3107
+ if (x + w > room) x = r.left - w - 10;
3108
+ if (x < 8) x = Math.min(Math.max(8, r.left), room - w);
3109
+ const y = Math.min(Math.max(8, r.top), window.innerHeight - box.node.offsetHeight - 8);
3110
+ Object.assign(box.node.style, { left: `${x}px`, top: `${y}px` });
3111
+ }
3112
+ };
3113
+ const soon = () => (frame ||= requestAnimationFrame(place));
3114
+ window.addEventListener("scroll", soon, true);
3115
+ window.addEventListener("resize", soon);
3116
+
3117
+ function close() {
3118
+ box?.node.remove();
3119
+ box = null;
3120
+ }
3121
+
3122
+ return {
3123
+ open(n, label) {
3124
+ close();
3125
+ const el = window.__blockoutEditorPicked?.();
3126
+ if (!el) return;
3127
+ const node = document.createElement("div");
3128
+ node.setAttribute("data-blockout-editor", "");
3129
+ node.setAttribute("role", "dialog");
3130
+ node.setAttribute("aria-label", `Comment on ${label}`);
3131
+ node.style.cssText =
3132
+ `position:fixed;z-index:2147483646;width:288px;box-sizing:border-box;padding:10px;border-radius:16px;background:#fff;color:${INK};` +
3133
+ `font:400 13px/1.45 ${FONT};box-shadow:0 0 0 1px rgba(16,16,16,.08),0 16px 40px rgba(16,16,16,.18);text-align:left`;
3134
+ const head = document.createElement("div");
3135
+ head.style.cssText = "display:flex;align-items:center;gap:8px;margin:0 2px 8px";
3136
+ const mark = pin(n);
3137
+ mark.style.position = "static";
3138
+ mark.style.boxShadow = "none";
3139
+ const name = document.createElement("span");
3140
+ name.textContent = label;
3141
+ name.style.cssText = "min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#6b665f;font-size:12px";
3142
+ head.append(mark, name);
3143
+ const field = document.createElement("textarea");
3144
+ field.rows = 3;
3145
+ field.placeholder = "What should change here?";
3146
+ field.setAttribute("aria-label", `Comment on ${label}`);
3147
+ field.style.cssText =
3148
+ `display:block;width:100%;box-sizing:border-box;margin:0;padding:8px 10px;border:0;border-radius:10px;background:#f5f2ec;color:${INK};` +
3149
+ `font:inherit;resize:none;outline:none;box-shadow:none`;
3150
+ const foot = document.createElement("div");
3151
+ foot.style.cssText = "display:flex;align-items:center;gap:6px;margin:8px 2px 0";
3152
+ const hint = document.createElement("span");
3153
+ hint.textContent = "Enter to add";
3154
+ hint.style.cssText = "flex:1;color:#6b665f;font-size:11px";
3155
+ const button = (text, primary) => {
3156
+ const b = document.createElement("button");
3157
+ b.type = "button";
3158
+ b.textContent = text;
3159
+ b.style.cssText =
3160
+ `padding:6px 12px;border:0;border-radius:999px;font:600 12px/1 ${FONT};cursor:pointer;` +
3161
+ (primary ? `background:${INK};color:#fff` : `background:transparent;color:${INK}`);
3162
+ return b;
3163
+ };
3164
+ const cancel = button("Cancel", false);
3165
+ const add = button("Add", true);
3166
+ foot.append(hint, cancel, add);
3167
+ node.append(head, field, foot);
3168
+ document.body.append(node);
3169
+ box = { node, el };
3170
+ const submit = () => {
3171
+ const text = field.value.trim();
3172
+ if (!text) return field.focus();
3173
+ els.set(n, el);
3174
+ close();
3175
+ toPanel({ type: "comment", n, text });
3176
+ };
3177
+ const dismiss = () => {
3178
+ close();
3179
+ toPanel({ type: "comment-cancel" });
3180
+ };
3181
+ add.addEventListener("click", submit);
3182
+ cancel.addEventListener("click", dismiss);
3183
+ field.addEventListener("keydown", (e) => {
3184
+ if (e.key === "Enter" && !e.shiftKey) {
3185
+ e.preventDefault();
3186
+ submit();
3187
+ }
3188
+ if (e.key === "Escape") dismiss();
3189
+ });
3190
+ place();
3191
+ field.focus();
3192
+ },
3193
+ close,
3194
+ pins(list) {
3195
+ shown = list.filter((p) => Number.isInteger(p?.n) && els.has(p.n)).map((p) => p.n);
3196
+ for (const n of [...els.keys()]) if (!shown.includes(n)) els.delete(n);
3197
+ layer.replaceChildren(
3198
+ ...shown.map((n) => {
3199
+ const p = pin(n);
3200
+ p.dataset.n = String(n);
3201
+ return p;
3202
+ }),
3203
+ );
3204
+ place();
3205
+ },
3206
+ remove() {
3207
+ close();
3208
+ layer.remove();
3209
+ window.removeEventListener("scroll", soon, true);
3210
+ window.removeEventListener("resize", soon);
3211
+ },
3212
+ };
3213
+ }
3214
+
3013
3215
  /*
3014
3216
  * The canvas, as Figma's: zoomed out (a pinch, Cmd-scroll, Cmd-, Shift+1; from inside the page too), the page is a frame
3015
3217
  * on a canvas over it, and frames at tablet and phone widths can join it, each this page loaded again at that width
package/engine.js CHANGED
@@ -56,6 +56,10 @@
56
56
  panelOn = !!on;
57
57
  if (!relay) setOn(!!on);
58
58
  };
59
+ // The element picked now, for the kit's comment box to sit beside.
60
+ window.__blockoutEditorPicked = function () {
61
+ return S.sel || null;
62
+ };
59
63
  window.__blockoutEditorRelay = function (w, changesThere) {
60
64
  relay = w || null;
61
65
  if (relay) return setOn(false);
@@ -1686,6 +1690,9 @@
1686
1690
  // Words styled in a text are part of it, not layers.
1687
1691
  while (t && t.hasAttribute && t.hasAttribute("data-bo-mark")) t = t.parentElement;
1688
1692
  if (!t || t === document.documentElement || t === document.body) return null;
1693
+ // The kit's comment mode: a click is on what is under the pointer, as a whole: a button or link rather than its
1694
+ // label, an icon rather than its paths.
1695
+ if (window.__blockoutEditorDeep) return (t.closest && t.closest("button,a,input,select,textarea,label,img,svg,[role=button]")) || t;
1689
1696
  if (deep) return t;
1690
1697
  if (S.sel && S.sel.isConnected && (S.sel === t || S.sel.contains(t))) return S.sel;
1691
1698
  var scope = S.sel && S.sel.isConnected ? S.sel.parentElement : null;
package/index.js CHANGED
@@ -2,8 +2,11 @@
2
2
  * Blockout's editor in a project's own dev page. startEditor() puts the editor's engine (engine.js, the same one
3
3
  * Blockout's file view uses) in this page and docks Blockout's editor panel beside it, in a frame from Blockout
4
4
  * (/editor), behind a small Edit button in the corner. Pick anything on the page and change it live against the page's
5
- * own tokens; Send to Claude Code saves what changed, with a note, through the dev server into .notes/blockout-notes.json
6
- * (server/next.js, server/vite.js), where Claude Code picks it up (`sc`, or `npx blockout-editor mcp`).
5
+ * own tokens, or comment on it (comment mode: a box beside what is picked, a numbered pin on it); Send to Claude goes
6
+ * to the panel's Claude chat, which the dev server's route runs as the person's own Claude Code in the project
7
+ * (server/claude.js), so it writes the changes into the code and hot reload shows them. With no Claude Code there,
8
+ * a send is saved as a note in .notes/blockout-notes.json instead (server/next.js, server/vite.js), for Claude Code to
9
+ * pick up (`sc`, or `npx blockout-editor mcp`).
7
10
  *
8
11
  * Development only: call it from a dev build (react.js does). Nothing here reaches Blockout but what the panel needs
9
12
  * to draw: values, token names and labels from the page, never its content.
@@ -89,6 +92,15 @@ export function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-not
89
92
  "box-shadow:0 4px 14px rgba(16,16,16,.24)";
90
93
 
91
94
  let isOpen = false;
95
+ // Open across a reload: Claude's edits reload the page through the dev server, and the chat goes on in the panel.
96
+ const remember = (on) => {
97
+ try {
98
+ sessionStorage.setItem("blockout-editor:open", on ? "1" : "");
99
+ } catch {}
100
+ };
101
+ try {
102
+ open = open || sessionStorage.getItem("blockout-editor:open") === "1";
103
+ } catch {}
92
104
  const toPanel = (msg) => frame.contentWindow?.postMessage({ ...msg, blockoutEditorKit: 1 }, origin);
93
105
  // On a phone the panels are a sheet at the bottom, the page above them; Layers take the sheet's place when shown.
94
106
  const place = (el, sheet, side) => {
@@ -98,6 +110,8 @@ export function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-not
98
110
  };
99
111
  const setOpen = (on) => {
100
112
  isOpen = on;
113
+ remember(on);
114
+ if (!on) comments.pins([]);
101
115
  host.style.display = on ? "block" : "none";
102
116
  const narrow = window.innerWidth < 640;
103
117
  const room = narrow || window.innerWidth >= 900;
@@ -126,6 +140,33 @@ export function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-not
126
140
  if (m.type === "ready") toPanel({ type: "open", open: isOpen });
127
141
  // Blockout's theme, so the canvas around the frames matches the panels.
128
142
  if (m.type === "theme") canvas.setDark(m.dark === true);
143
+ // The chat's calls to the dev server's route (server/claude.js), made from this page, its own origin.
144
+ if (m.type === "api" && typeof m.id === "string") {
145
+ const query = new URLSearchParams();
146
+ for (const k of ["claude", "id"]) if (typeof m.query?.[k] === "string") query.set(k, m.query[k]);
147
+ const method = m.method === "POST" ? "POST" : "GET";
148
+ try {
149
+ const res = await fetch(`${notesApi}?${query}`, {
150
+ method,
151
+ headers: { "content-type": "application/json" },
152
+ ...(method === "POST" ? { body: JSON.stringify(m.body ?? {}) } : {}),
153
+ });
154
+ toPanel({ type: "api", id: m.id, status: res.status, body: await res.json().catch(() => ({})) });
155
+ } catch {
156
+ toPanel({ type: "api", id: m.id, status: 0, body: { error: "The dev server didn't answer." } });
157
+ }
158
+ return;
159
+ }
160
+ // Comment mode: a box beside what is picked, and the numbered pins of the comments not sent yet.
161
+ if (m.type === "comment-mode") {
162
+ // A click picks exactly what is under the pointer, not a layer at a time as when designing.
163
+ window.__blockoutEditorDeep = m.on === true;
164
+ if (!m.on) comments.close();
165
+ return;
166
+ }
167
+ if (m.type === "comment-box") return comments.open(m.n, String(m.label ?? ""));
168
+ if (m.type === "comment-close") return comments.close();
169
+ if (m.type === "pins") return comments.pins(Array.isArray(m.pins) ? m.pins : []);
129
170
  if (m.type === "send") {
130
171
  try {
131
172
  const res = await fetch(notesApi, {
@@ -143,6 +184,7 @@ export function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-not
143
184
  }
144
185
  }
145
186
  };
187
+ const comments = makeComments({ toPanel });
146
188
  window.addEventListener("message", onMessage);
147
189
  document.body.append(left, tab, host, pill);
148
190
  setOpen(open);
@@ -156,6 +198,7 @@ export function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-not
156
198
  window.removeEventListener("message", onMessage);
157
199
  window.__blockoutEditorSetOn?.(false);
158
200
  canvas.remove();
201
+ comments.remove();
159
202
  host.remove();
160
203
  left.remove();
161
204
  tab.remove();
@@ -164,6 +207,158 @@ export function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-not
164
207
  };
165
208
  }
166
209
 
210
+ /*
211
+ * Comments on the page, as Agentation's: in comment mode the panel asks for a box beside what the engine picked (the
212
+ * engine leaves anything marked data-blockout-editor alone, so the box takes clicks and keys); Enter adds the comment
213
+ * and the panel numbers it, Esc or Cancel lets it go. Each comment not sent yet has a numbered pin on its element,
214
+ * kept in place as the page scrolls.
215
+ */
216
+ const INK = "#101010";
217
+ const ACCENT = "#e12c05";
218
+ const FONT = "ui-sans-serif,system-ui,-apple-system,sans-serif";
219
+
220
+ function makeComments({ toPanel }) {
221
+ const els = new Map();
222
+ let shown = [];
223
+ let box = null;
224
+ const layer = document.createElement("div");
225
+ layer.setAttribute("data-blockout-editor", "");
226
+ layer.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:2147483645";
227
+ document.body.append(layer);
228
+
229
+ const pin = (n) => {
230
+ const el = document.createElement("span");
231
+ el.textContent = String(n);
232
+ el.style.cssText =
233
+ `position:absolute;display:flex;align-items:center;justify-content:center;min-width:22px;height:22px;padding:0 6px;box-sizing:border-box;` +
234
+ `border-radius:11px 11px 11px 3px;background:${ACCENT};color:#fff;font:700 11px/1 ${FONT};` +
235
+ "box-shadow:0 0 0 2px #fff,0 4px 12px rgba(16,16,16,.22);font-variant-numeric:tabular-nums";
236
+ return el;
237
+ };
238
+ let frame = 0;
239
+ const place = () => {
240
+ frame = 0;
241
+ for (const p of layer.children) {
242
+ const el = els.get(Number(p.dataset.n));
243
+ const r = el?.isConnected ? el.getBoundingClientRect() : null;
244
+ p.style.display = r ? "flex" : "none";
245
+ if (r) Object.assign(p.style, { left: `${Math.max(4, r.left - 6)}px`, top: `${Math.max(4, r.top - 16)}px` });
246
+ }
247
+ if (box?.el) {
248
+ const r = box.el.isConnected ? box.el.getBoundingClientRect() : null;
249
+ if (!r) return close();
250
+ // Beside the element, clear of the panel on the right; above the fold.
251
+ const room = window.innerWidth - (window.innerWidth < 640 ? 8 : 376);
252
+ const w = 288;
253
+ let x = r.right + 10;
254
+ if (x + w > room) x = r.left - w - 10;
255
+ if (x < 8) x = Math.min(Math.max(8, r.left), room - w);
256
+ const y = Math.min(Math.max(8, r.top), window.innerHeight - box.node.offsetHeight - 8);
257
+ Object.assign(box.node.style, { left: `${x}px`, top: `${y}px` });
258
+ }
259
+ };
260
+ const soon = () => (frame ||= requestAnimationFrame(place));
261
+ window.addEventListener("scroll", soon, true);
262
+ window.addEventListener("resize", soon);
263
+
264
+ function close() {
265
+ box?.node.remove();
266
+ box = null;
267
+ }
268
+
269
+ return {
270
+ open(n, label) {
271
+ close();
272
+ const el = window.__blockoutEditorPicked?.();
273
+ if (!el) return;
274
+ const node = document.createElement("div");
275
+ node.setAttribute("data-blockout-editor", "");
276
+ node.setAttribute("role", "dialog");
277
+ node.setAttribute("aria-label", `Comment on ${label}`);
278
+ node.style.cssText =
279
+ `position:fixed;z-index:2147483646;width:288px;box-sizing:border-box;padding:10px;border-radius:16px;background:#fff;color:${INK};` +
280
+ `font:400 13px/1.45 ${FONT};box-shadow:0 0 0 1px rgba(16,16,16,.08),0 16px 40px rgba(16,16,16,.18);text-align:left`;
281
+ const head = document.createElement("div");
282
+ head.style.cssText = "display:flex;align-items:center;gap:8px;margin:0 2px 8px";
283
+ const mark = pin(n);
284
+ mark.style.position = "static";
285
+ mark.style.boxShadow = "none";
286
+ const name = document.createElement("span");
287
+ name.textContent = label;
288
+ name.style.cssText = "min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#6b665f;font-size:12px";
289
+ head.append(mark, name);
290
+ const field = document.createElement("textarea");
291
+ field.rows = 3;
292
+ field.placeholder = "What should change here?";
293
+ field.setAttribute("aria-label", `Comment on ${label}`);
294
+ field.style.cssText =
295
+ `display:block;width:100%;box-sizing:border-box;margin:0;padding:8px 10px;border:0;border-radius:10px;background:#f5f2ec;color:${INK};` +
296
+ `font:inherit;resize:none;outline:none;box-shadow:none`;
297
+ const foot = document.createElement("div");
298
+ foot.style.cssText = "display:flex;align-items:center;gap:6px;margin:8px 2px 0";
299
+ const hint = document.createElement("span");
300
+ hint.textContent = "Enter to add";
301
+ hint.style.cssText = "flex:1;color:#6b665f;font-size:11px";
302
+ const button = (text, primary) => {
303
+ const b = document.createElement("button");
304
+ b.type = "button";
305
+ b.textContent = text;
306
+ b.style.cssText =
307
+ `padding:6px 12px;border:0;border-radius:999px;font:600 12px/1 ${FONT};cursor:pointer;` +
308
+ (primary ? `background:${INK};color:#fff` : `background:transparent;color:${INK}`);
309
+ return b;
310
+ };
311
+ const cancel = button("Cancel", false);
312
+ const add = button("Add", true);
313
+ foot.append(hint, cancel, add);
314
+ node.append(head, field, foot);
315
+ document.body.append(node);
316
+ box = { node, el };
317
+ const submit = () => {
318
+ const text = field.value.trim();
319
+ if (!text) return field.focus();
320
+ els.set(n, el);
321
+ close();
322
+ toPanel({ type: "comment", n, text });
323
+ };
324
+ const dismiss = () => {
325
+ close();
326
+ toPanel({ type: "comment-cancel" });
327
+ };
328
+ add.addEventListener("click", submit);
329
+ cancel.addEventListener("click", dismiss);
330
+ field.addEventListener("keydown", (e) => {
331
+ if (e.key === "Enter" && !e.shiftKey) {
332
+ e.preventDefault();
333
+ submit();
334
+ }
335
+ if (e.key === "Escape") dismiss();
336
+ });
337
+ place();
338
+ field.focus();
339
+ },
340
+ close,
341
+ pins(list) {
342
+ shown = list.filter((p) => Number.isInteger(p?.n) && els.has(p.n)).map((p) => p.n);
343
+ for (const n of [...els.keys()]) if (!shown.includes(n)) els.delete(n);
344
+ layer.replaceChildren(
345
+ ...shown.map((n) => {
346
+ const p = pin(n);
347
+ p.dataset.n = String(n);
348
+ return p;
349
+ }),
350
+ );
351
+ place();
352
+ },
353
+ remove() {
354
+ close();
355
+ layer.remove();
356
+ window.removeEventListener("scroll", soon, true);
357
+ window.removeEventListener("resize", soon);
358
+ },
359
+ };
360
+ }
361
+
167
362
  /*
168
363
  * The canvas, as Figma's: zoomed out (a pinch, Cmd-scroll, Cmd-, Shift+1; from inside the page too), the page is a frame
169
364
  * on a canvas over it, and frames at tablet and phone widths can join it, each this page loaded again at that width
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blockout-editor",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Blockout's editor in your app's dev page: pick anything, change its spacing, type, colour and layout against your own tokens, and send it to Claude Code to write into your code.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "author": "Yash Gidwani (https://github.com/ux-yash)",
@@ -0,0 +1,334 @@
1
+ /*
2
+ * The editor's Claude chat: the dev server runs the person's own Claude Code (`claude -p`) in the project's folder, so
3
+ * what they change and comment on in the dev page goes straight to Claude, which writes it into the code; the dev
4
+ * server's hot reload shows it. Each chat is one Claude Code session, resumed message to message (`--resume`), so
5
+ * Claude remembers the thread and its own edits; when the session can't be resumed, the chat's last exchanges go ahead
6
+ * of the message instead.
7
+ *
8
+ * Chats are kept in .notes/blockout-chats.json beside the notes:
9
+ * { "chats": [ { "id", "title", "createdAt", "updatedAt", "sessionId",
10
+ * "messages": [ { "id", "at", "from": "you", "text", "comments": [ { "n", "label", "text" } ], "changed" }
11
+ * | { "id", "at", "from": "claude", "status": "running" | "done" | "failed" | "stopped",
12
+ * "steps": [ { "at", "kind", "text", "done", "failed" } ], "said", "reply", "error",
13
+ * "endedAt" } ] } ] }
14
+ *
15
+ * Claude may read, search and edit the project's files, run commands (Bash), and use the person's skills, with their
16
+ * own settings and CLAUDE.md. Only the dev server runs it, and only for the app's own page on this computer's own
17
+ * address (claudeRefusal): a page another site serves can't start it, by a rebound DNS name either.
18
+ */
19
+ import { spawn } from "node:child_process";
20
+ import { randomUUID } from "node:crypto";
21
+ import { promises as fs, realpathSync } from "node:fs";
22
+ import path from "node:path";
23
+ import { createInterface } from "node:readline";
24
+
25
+ /** Claude Code's tools a run may use without asking: there is no one to ask in `-p`. */
26
+ export const TOOLS = ["Read", "Edit", "MultiEdit", "Write", "Glob", "Grep", "Bash", "Skill", "TodoWrite"];
27
+
28
+ const SYSTEM = [
29
+ "You are working from Blockout's editor, which runs in this project's dev page. Each message is what the person changed or commented on there, for you to make in the code.",
30
+ "Make each change in the project's source, the way the project writes things: its tokens, classes and components, not inline styles. When an element is a shared component, say whether your change reaches every use of it or only this one.",
31
+ "The dev server reloads the page as you save, so there is no need to start it.",
32
+ "Before each step, say what you are about to do in one short sentence. End with one or two lines on what you changed.",
33
+ ].join(" ");
34
+
35
+ /** A run that goes quiet for this long is stopped. */
36
+ const RUN_LIMIT_MS = 15 * 60 * 1000;
37
+ const MAX_CHATS = 50;
38
+ const MAX_MESSAGES = 200;
39
+ /** How much of the chat goes ahead of a message when its session can't be resumed. */
40
+ const MEMORY = 10;
41
+
42
+ const str = (v, max) => (typeof v === "string" ? v.slice(0, max) : "");
43
+
44
+ // Kept on globalThis: a dev server reloads its route modules as files change (Claude's own edits among them), and a
45
+ // run must outlive that.
46
+ const shared = (globalThis.__blockoutEditorClaude ??= { stores: new Map(), runs: new Map() });
47
+
48
+ /** The chats of the project in `dir`'s parent folder, read once and kept in memory, written on each change. */
49
+ export function createChats({ dir = path.join(process.cwd(), ".notes"), cwd = path.dirname(dir), bin = process.env.BLOCKOUT_CLAUDE || "claude" } = {}) {
50
+ const file = path.join(dir, "blockout-chats.json");
51
+ const known = shared.stores.get(file);
52
+ if (known) return known;
53
+ let all = null;
54
+ let writing = Promise.resolve();
55
+ const load = async () => {
56
+ if (all) return all;
57
+ try {
58
+ const read = JSON.parse(await fs.readFile(file, "utf8"));
59
+ all = Array.isArray(read?.chats) ? read : { chats: [] };
60
+ } catch {
61
+ all = { chats: [] };
62
+ }
63
+ // A run the server lost (it restarted) is over.
64
+ for (const chat of all.chats) for (const m of chat.messages) if (m.status === "running" && !shared.runs.has(chat.id)) Object.assign(m, { status: "failed", error: "The dev server restarted during this run." });
65
+ return all;
66
+ };
67
+ // One write at a time, each whole: written aside, then moved into place.
68
+ const save = () => {
69
+ writing = writing.then(async () => {
70
+ await fs.mkdir(dir, { recursive: true });
71
+ const tmp = `${file}.${process.pid}.tmp`;
72
+ await fs.writeFile(tmp, `${JSON.stringify(all, null, 2)}\n`);
73
+ await fs.rename(tmp, file);
74
+ }).catch(() => {});
75
+ return writing;
76
+ };
77
+ // Its real path: Claude Code names files by it (on a Mac, /var is /private/var).
78
+ let real = cwd;
79
+ try {
80
+ real = realpathSync(cwd);
81
+ } catch {}
82
+ const store = { file, cwd: real, bin, load, save, running: (id) => shared.runs.has(id) };
83
+ shared.stores.set(file, store);
84
+ return store;
85
+ }
86
+
87
+ /** Each chat in a line, newest first, for the chat list. */
88
+ export async function listChats(store) {
89
+ const { chats } = await store.load();
90
+ return [...chats]
91
+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
92
+ .map((c) => ({ id: c.id, title: c.title, updatedAt: c.updatedAt, messages: c.messages.length, running: store.running(c.id) }));
93
+ }
94
+
95
+ export async function getChat(store, id) {
96
+ const { chats } = await store.load();
97
+ return chats.find((c) => c.id === id) ?? null;
98
+ }
99
+
100
+ /**
101
+ * Sends a message: `prompt` is what Claude gets (the change request the panel wrote), `shown` what the chat shows of
102
+ * it. A new chat without `chatId`. One run at a time in a project: Claude edits the same files.
103
+ */
104
+ export async function sendMessage(store, { chatId, prompt, shown }) {
105
+ const all = await store.load();
106
+ const text = str(prompt, 60000).trim();
107
+ if (!text) return { status: 400, body: { error: "Nothing to send." } };
108
+ if (shared.runs.size) return { status: 409, body: { error: "Claude is still on the last message. Wait for it, or stop it." } };
109
+ let chat = chatId ? all.chats.find((c) => c.id === chatId) : null;
110
+ if (chatId && !chat) return { status: 404, body: { error: "There's no chat with that id." } };
111
+ const now = new Date().toISOString();
112
+ const you = {
113
+ id: randomUUID(),
114
+ at: now,
115
+ from: "you",
116
+ text: str(shown?.text, 4000).trim(),
117
+ comments: (Array.isArray(shown?.comments) ? shown.comments.slice(0, 50) : []).map((c, i) => ({
118
+ n: Number.isInteger(c?.n) ? c.n : i + 1,
119
+ label: str(c?.label, 200),
120
+ text: str(c?.text, 2000),
121
+ })),
122
+ changed: Number.isInteger(shown?.changed) ? shown.changed : 0,
123
+ };
124
+ if (!chat) {
125
+ chat = { id: randomUUID(), title: titleOf(you), createdAt: now, updatedAt: now, sessionId: null, messages: [] };
126
+ all.chats.push(chat);
127
+ all.chats.sort((a, b) => a.updatedAt.localeCompare(b.updatedAt));
128
+ while (all.chats.length > MAX_CHATS) all.chats.shift();
129
+ }
130
+ const reply = { id: randomUUID(), at: now, from: "claude", status: "running", steps: [], said: "", reply: "", error: "" };
131
+ const history = memoryOf(chat);
132
+ chat.messages.push(you, reply);
133
+ chat.messages.splice(0, Math.max(0, chat.messages.length - MAX_MESSAGES));
134
+ chat.updatedAt = now;
135
+ await store.save();
136
+ run(store, chat, reply, text, history);
137
+ return { status: 201, body: { chat } };
138
+ }
139
+
140
+ /** Stops the chat's run, if one is out. */
141
+ export async function stopRun(store, chatId) {
142
+ const live = shared.runs.get(chatId);
143
+ if (!live) return { status: 404, body: { error: "Nothing is running in that chat." } };
144
+ live.stopped = true;
145
+ live.child.kill("SIGTERM");
146
+ return { status: 200, body: {} };
147
+ }
148
+
149
+ function titleOf(you) {
150
+ const words = you.text || you.comments[0]?.text || (you.changed ? `${you.changed} design ${you.changed === 1 ? "change" : "changes"}` : "Design changes");
151
+ const line = words.replace(/\s+/g, " ").trim();
152
+ return line.length > 60 ? `${line.slice(0, 59)}…` : line;
153
+ }
154
+
155
+ /** The chat so far, for a run whose session can't be resumed. */
156
+ function memoryOf(chat) {
157
+ const lines = [];
158
+ for (const m of chat.messages.slice(-MEMORY * 2)) {
159
+ if (m.from === "you") lines.push(`The person: ${m.text || "(design changes and comments)"}${m.comments?.length ? ` [${m.comments.length} comments]` : ""}`);
160
+ else if (m.reply || m.said) lines.push(`You: ${(m.reply || m.said).slice(0, 1500)}`);
161
+ }
162
+ return lines.length ? `This chat so far, for context (your earlier session isn't available):\n${lines.join("\n")}\n\nNow:\n` : "";
163
+ }
164
+
165
+ /** Claude Code's arguments for a run. */
166
+ export function argsFor(resume) {
167
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--permission-mode", "acceptEdits", "--allowedTools", TOOLS.join(","), "--append-system-prompt", SYSTEM];
168
+ return resume ? [...args, "--resume", resume] : args;
169
+ }
170
+
171
+ function run(store, chat, msg, prompt, history, resume = chat.sessionId) {
172
+ const live = { child: null, stopped: false, sawInit: false };
173
+ shared.runs.set(chat.id, live);
174
+ let ended = false;
175
+ let saveTimer = null;
176
+ const saveSoon = () => {
177
+ saveTimer ??= setTimeout(() => {
178
+ saveTimer = null;
179
+ void store.save();
180
+ }, 2000);
181
+ };
182
+ const child = spawn(store.bin, argsFor(resume), { cwd: store.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
183
+ live.child = child;
184
+ let quiet = setTimeout(() => child.kill("SIGTERM"), RUN_LIMIT_MS);
185
+ let stderr = "";
186
+ child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-2000)));
187
+ const finish = (fields) => {
188
+ if (ended) return;
189
+ ended = true;
190
+ clearTimeout(quiet);
191
+ clearTimeout(saveTimer);
192
+ shared.runs.delete(chat.id);
193
+ for (const s of msg.steps) if (!s.done) s.done = Date.now();
194
+ Object.assign(msg, fields, { endedAt: new Date().toISOString() });
195
+ chat.updatedAt = msg.endedAt;
196
+ void store.save();
197
+ };
198
+ child.on("error", (err) =>
199
+ finish({
200
+ status: "failed",
201
+ error: err.code === "ENOENT" ? "Claude Code isn't on this dev server's PATH. Start the dev server from a terminal where `claude` works." : String(err.message),
202
+ code: err.code === "ENOENT" ? "no-claude" : undefined,
203
+ }),
204
+ );
205
+ child.stdin.on("error", () => {});
206
+ child.stdin.end(resume ? prompt : history + prompt);
207
+ createInterface({ input: child.stdout }).on("line", (line) => {
208
+ clearTimeout(quiet);
209
+ quiet = setTimeout(() => child.kill("SIGTERM"), RUN_LIMIT_MS);
210
+ let event;
211
+ try {
212
+ event = JSON.parse(line);
213
+ } catch {
214
+ return;
215
+ }
216
+ if (event.type === "system" && event.subtype === "init") {
217
+ live.sawInit = true;
218
+ if (event.session_id) chat.sessionId = event.session_id;
219
+ }
220
+ if (read(event, msg, store.cwd)) saveSoon();
221
+ });
222
+ child.on("close", (code) => {
223
+ if (ended) return;
224
+ // The session wasn't there (another computer, or Claude Code cleared it): once more, fresh, with the chat so far.
225
+ if (resume && !live.sawInit && !live.stopped) {
226
+ clearTimeout(quiet);
227
+ shared.runs.delete(chat.id);
228
+ chat.sessionId = null;
229
+ ended = true;
230
+ return run(store, chat, msg, prompt, history, null);
231
+ }
232
+ if (live.stopped) return finish({ status: "stopped" });
233
+ if (msg.status === "running") finish(code === 0 ? { status: "done" } : { status: "failed", error: msg.error || stderr.trim().split("\n").pop() || `Claude Code stopped (${code}).` });
234
+ else finish({});
235
+ });
236
+ }
237
+
238
+ /** Puts one line of Claude Code's stream into the message; true when it changed something. */
239
+ export function read(event, msg, cwd) {
240
+ if (event.type === "assistant") {
241
+ let changed = false;
242
+ for (const block of event.message?.content ?? []) {
243
+ if (block.type === "text" && block.text?.trim()) {
244
+ msg.said = block.text.trim().slice(0, 4000);
245
+ changed = true;
246
+ }
247
+ if (block.type === "tool_use") {
248
+ msg.steps.push({ id: block.id, at: Date.now(), ...stepOf(block.name, block.input ?? {}, cwd) });
249
+ msg.steps.splice(0, Math.max(0, msg.steps.length - 200));
250
+ changed = true;
251
+ }
252
+ }
253
+ return changed;
254
+ }
255
+ if (event.type === "user") {
256
+ let changed = false;
257
+ for (const block of event.message?.content ?? []) {
258
+ if (block.type !== "tool_result") continue;
259
+ const step = msg.steps.find((s) => s.id === block.tool_use_id);
260
+ if (!step) continue;
261
+ step.done = Date.now();
262
+ if (block.is_error) step.failed = str(typeof block.content === "string" ? block.content : block.content?.[0]?.text, 200) || "It didn't work.";
263
+ changed = true;
264
+ }
265
+ return changed;
266
+ }
267
+ if (event.type === "result") {
268
+ msg.reply = str(event.result, 8000).trim();
269
+ if (event.is_error) Object.assign(msg, { status: "failed", error: msg.reply || "Claude Code stopped with an error." });
270
+ else msg.status = "done";
271
+ return true;
272
+ }
273
+ return false;
274
+ }
275
+
276
+ /** A tool call as the chat says it. */
277
+ export function stepOf(name, input, cwd) {
278
+ const file = (p) => (typeof p === "string" ? path.relative(cwd, p) || p : "a file");
279
+ const quote = (s) => `“${str(s, 60)}”`;
280
+ switch (name) {
281
+ case "Read":
282
+ return { kind: "read", text: `Read ${file(input.file_path)}` };
283
+ case "Edit":
284
+ case "MultiEdit":
285
+ return { kind: "edit", text: `Edited ${file(input.file_path)}` };
286
+ case "Write":
287
+ return { kind: "edit", text: `Wrote ${file(input.file_path)}` };
288
+ case "Grep":
289
+ return { kind: "find", text: `Searched for ${quote(input.pattern)}` };
290
+ case "Glob":
291
+ return { kind: "find", text: `Looked for ${str(input.pattern, 80)}` };
292
+ case "Bash":
293
+ return { kind: "run", text: str(input.description, 100) || `Ran ${str(input.command, 80)}` };
294
+ case "Skill":
295
+ return { kind: "skill", text: `Used the ${str(input.skill || input.command || input.name, 60) || "a"} skill` };
296
+ case "TodoWrite":
297
+ return { kind: "plan", text: "Planned the steps" };
298
+ default:
299
+ return { kind: "tool", text: `Used ${str(name, 60)}` };
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Claude may start only from the app's own page on this computer's own address. The notes route's own check
305
+ * (same-origin) passes a rebound DNS name, whose page and route share the attacker's host: this one also wants the
306
+ * host to be this computer. Returns why not, or null.
307
+ */
308
+ export function claudeRefusal(get) {
309
+ const host = get("host") || "";
310
+ let name = "";
311
+ try {
312
+ name = new URL(`http://${host}`).hostname;
313
+ } catch {
314
+ name = "";
315
+ }
316
+ const local = name === "localhost" || name === "127.0.0.1" || name === "[::1]" || name.endsWith(".localhost");
317
+ if (!local) return "Claude runs only from the dev page on this computer's own address (localhost or 127.0.0.1).";
318
+ if (get("sec-fetch-site") !== "same-origin") return "Only this app's own pages can talk to Claude.";
319
+ return null;
320
+ }
321
+
322
+ /** One request to the route's Claude ops (`?claude=`): answers { status, body }. */
323
+ export async function handleClaude(store, method, url, body) {
324
+ const params = new URL(url, "http://localhost").searchParams;
325
+ const op = params.get("claude");
326
+ if (method === "GET" && op === "chats") return { status: 200, body: { chats: await listChats(store) } };
327
+ if (method === "GET" && op === "chat") {
328
+ const chat = await getChat(store, params.get("id") || "");
329
+ return chat ? { status: 200, body: { chat, running: store.running(chat.id) } } : { status: 404, body: { error: "There's no chat with that id." } };
330
+ }
331
+ if (method === "POST" && op === "send") return sendMessage(store, { chatId: str(body?.chatId, 100) || null, prompt: body?.prompt, shown: body?.shown });
332
+ if (method === "POST" && op === "stop") return stopRun(store, str(body?.chatId, 100));
333
+ return { status: 400, body: { error: "Ask for chats, chat, send or stop." } };
334
+ }
package/server/next.js CHANGED
@@ -1,11 +1,14 @@
1
1
  /*
2
2
  * The notes route for a Next.js app (App Router). Add app/api/blockout-notes/route.js with:
3
3
  * export { GET, POST, PATCH, DELETE } from "blockout-editor/next";
4
- * It works on the dev server only: in production every method answers 404.
4
+ * It works on the dev server only: in production every method answers 404. With ?claude= it is the editor's Claude
5
+ * chat (claude.js).
5
6
  */
7
+ import { claudeRefusal, createChats, handleClaude } from "./claude.js";
6
8
  import { createStore, handle, refusal } from "./store.js";
7
9
 
8
10
  const store = createStore();
11
+ const chats = createChats();
9
12
 
10
13
  async function respond(request) {
11
14
  if (process.env.NODE_ENV !== "development") return Response.json({ error: "Blockout's editor notes only work on the dev server." }, { status: 404 });
@@ -13,6 +16,12 @@ async function respond(request) {
13
16
  if (no) return Response.json({ error: no }, { status: 403 });
14
17
  if (Number(request.headers.get("content-length") || 0) > 1 << 20) return Response.json({ error: "That's too much for one note." }, { status: 413 });
15
18
  const body = request.method === "GET" || request.method === "DELETE" ? null : await request.json().catch(() => null);
19
+ if (new URL(request.url).searchParams.has("claude")) {
20
+ const not = claudeRefusal((name) => request.headers.get(name));
21
+ if (not) return Response.json({ error: not }, { status: 403 });
22
+ const { status, body: out } = await handleClaude(chats, request.method, request.url, body);
23
+ return Response.json(out, { status });
24
+ }
16
25
  const { status, body: out } = await handle(store, request.method, request.url, body);
17
26
  return Response.json(out, { status });
18
27
  }
package/server/vite.js CHANGED
@@ -4,10 +4,12 @@
4
4
  * export default { plugins: [blockoutNotes()] };
5
5
  * The dev server only: `vite build` leaves it out.
6
6
  */
7
+ import { claudeRefusal, createChats, handleClaude } from "./claude.js";
7
8
  import { ROUTE, createStore, handle, refusal } from "./store.js";
8
9
 
9
10
  export function blockoutNotes({ route = ROUTE } = {}) {
10
11
  const store = createStore();
12
+ const chats = createChats();
11
13
  return {
12
14
  name: "blockout-editor-notes",
13
15
  apply: "serve",
@@ -32,6 +34,13 @@ export function blockoutNotes({ route = ROUTE } = {}) {
32
34
  } catch {
33
35
  return send(400, { error: "That isn't JSON." });
34
36
  }
37
+ if (new URL(req.url, "http://localhost").searchParams.has("claude")) {
38
+ // The editor's Claude chat (claude.js).
39
+ const not = claudeRefusal((name) => req.headers[name]);
40
+ if (not) return send(403, { error: not });
41
+ const { status, body: out } = await handleClaude(chats, req.method, req.url, body);
42
+ return send(status, out);
43
+ }
35
44
  const { status, body: out } = await handle(store, req.method, req.url, body);
36
45
  send(status, out);
37
46
  });