blockout-editor 0.0.0-stage → 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/index.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export interface EditorOptions {
2
+ /** Where Blockout is: its editor panel loads from there. Default https://blockout-cyan.vercel.app. */
3
+ blockout?: string;
4
+ /** The dev server's notes route. Default /api/blockout-notes. */
5
+ notesApi?: string;
6
+ /** Start with the panel open. */
7
+ open?: boolean;
8
+ /** How far the Edit button sits from the bottom right corner, in px. Default 16 each. */
9
+ button?: { right?: number; bottom?: number };
10
+ }
11
+ /** Starts Blockout's editor in this page (development only). Returns a function that takes it out again. */
12
+ export function startEditor(options?: EditorOptions): () => void;
13
+ export default startEditor;
package/index.js ADDED
@@ -0,0 +1,606 @@
1
+ /*
2
+ * Blockout's editor in a project's own dev page. startEditor() puts the editor's engine (engine.js, the same one
3
+ * Blockout's file view uses) in this page and docks Blockout's editor panel beside it, in a frame from Blockout
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, 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`).
10
+ *
11
+ * Development only: call it from a dev build (react.js does). Nothing here reaches Blockout but what the panel needs
12
+ * to draw: values, token names and labels from the page, never its content.
13
+ */
14
+
15
+ const BLOCKOUT = "https://blockout-cyan.vercel.app";
16
+ const FRAME = "blockout-frame-";
17
+ const MARK =
18
+ "M25.65 4.81 39.34 7.72C42.04 8.29 43.77 10.95 43.19 13.65L40.28 27.34C39.71 30.04 37.05 31.77 34.35 31.19L20.66 28.28C17.96 27.71 16.23 25.05 16.81 22.35L19.72 8.66C20.29 5.96 22.95 4.23 25.65 4.81ZM11 15H15.81L14.75 20H12C10.9 20 10 20.9 10 22V36C10 37.1 10.9 38 12 38H26C27.1 38 28 37.1 28 36V32.4L33 33.46V37C33 40.31 30.31 43 27 43H11C7.69 43 5 40.31 5 37V21C5 17.69 7.69 15 11 15Z";
19
+
20
+ /**
21
+ * Starts the editor in this page. Returns a function that takes it out again.
22
+ * @param {{ blockout?: string, notesApi?: string, open?: boolean, button?: { right?: number, bottom?: number } }} [options]
23
+ * blockout: where Blockout is (its panel loads from there); notesApi: the dev server's notes route; open: start open;
24
+ * button: how far the Edit button sits from the bottom right corner, in px, clear of the app's own corner buttons.
25
+ */
26
+ export function startEditor({ blockout = BLOCKOUT, notesApi = "/api/blockout-notes", open = false, button = {} } = {}) {
27
+ if (typeof window === "undefined" || window.__blockoutEditorKit) return () => {};
28
+ window.__blockoutEditorKit = true;
29
+ const origin = new URL(blockout).origin;
30
+ // A frame of the canvas (below): the page at another width. Only the engine, talking to the page around it.
31
+ if (window.name.startsWith(FRAME)) {
32
+ window.__blockoutEditorConfig = { origin, frame: true };
33
+ import("./engine.js");
34
+ return () => {
35
+ window.__blockoutEditorKit = false;
36
+ };
37
+ }
38
+ // The engine reads where its panel is before it starts.
39
+ window.__blockoutEditorConfig = { origin };
40
+ import("./engine.js");
41
+
42
+ const host = document.createElement("div");
43
+ host.setAttribute("data-blockout-editor", "");
44
+ host.style.cssText =
45
+ "position:fixed;top:8px;right:8px;bottom:8px;width:360px;max-width:calc(100vw - 16px);z-index:2147483646;display:none;" +
46
+ "border-radius:16px;overflow:hidden;background:#fff;box-shadow:0 0 0 1px rgba(16,16,16,.1),0 12px 40px rgba(16,16,16,.18)";
47
+ const frame = document.createElement("iframe");
48
+ frame.src = `${origin}/editor`;
49
+ frame.title = "Blockout editor";
50
+ frame.allow = "clipboard-write";
51
+ frame.style.cssText = "display:block;width:100%;height:100%;border:0";
52
+ host.appendChild(frame);
53
+ // The page's layers, as Figma's left panel, docked on the other side (not on a narrow window).
54
+ const left = document.createElement("div");
55
+ left.setAttribute("data-blockout-editor", "");
56
+ left.style.cssText = host.style.cssText;
57
+ left.style.right = "auto";
58
+ left.style.left = "8px";
59
+ left.style.width = "264px";
60
+ const layers = document.createElement("iframe");
61
+ layers.src = `${origin}/editor?panel=layers`;
62
+ layers.title = "Blockout layers";
63
+ layers.style.cssText = frame.style.cssText;
64
+ left.appendChild(layers);
65
+ // Layers hidden (its own button): a small tab on the left brings them back. Remembered on this page's origin.
66
+ let layersShown = (localStorage.getItem("blockout-editor:layers") ?? (window.innerWidth >= 900 ? "shown" : "hidden")) !== "hidden";
67
+ const tab = document.createElement("button");
68
+ tab.type = "button";
69
+ tab.setAttribute("data-blockout-editor", "");
70
+ tab.textContent = "Layers";
71
+ tab.style.cssText =
72
+ "position:fixed;top:8px;left:8px;z-index:2147483646;display:none;padding:7px 12px;border:0;border-radius:12px;background:#fff;color:#101010;" +
73
+ "font:500 13px/1 ui-sans-serif,system-ui,sans-serif;cursor:pointer;box-shadow:0 0 0 1px rgba(16,16,16,.1),0 6px 20px rgba(16,16,16,.14)";
74
+ const showLayers = (on) => {
75
+ layersShown = on;
76
+ try {
77
+ localStorage.setItem("blockout-editor:layers", on ? "shown" : "hidden");
78
+ } catch {}
79
+ setOpen(isOpen);
80
+ };
81
+ tab.addEventListener("click", () => showLayers(true));
82
+
83
+ const pill = document.createElement("button");
84
+ pill.type = "button";
85
+ pill.setAttribute("data-blockout-editor", "");
86
+ pill.setAttribute("aria-label", "Open Blockout's editor");
87
+ pill.innerHTML = `<svg viewBox="5 4.7 38.3 38.3" width="14" height="14" fill="currentColor" aria-hidden="true"><path d="${MARK}"/></svg><span>Edit</span>`;
88
+ pill.style.cssText =
89
+ `position:fixed;right:${button.right ?? 16}px;bottom:${button.bottom ?? 16}px;z-index:2147483646;` +
90
+ "display:flex;align-items:center;gap:6px;padding:8px 14px;border:0;" +
91
+ "border-radius:999px;background:#101010;color:#fff;font:600 13px/1 ui-sans-serif,system-ui,sans-serif;cursor:pointer;" +
92
+ "box-shadow:0 4px 14px rgba(16,16,16,.24)";
93
+
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 {}
104
+ const toPanel = (msg) => frame.contentWindow?.postMessage({ ...msg, blockoutEditorKit: 1 }, origin);
105
+ // On a phone the panels are a sheet at the bottom, the page above them; Layers take the sheet's place when shown.
106
+ const place = (el, sheet, side) => {
107
+ Object.assign(el.style, sheet
108
+ ? { top: "auto", left: "8px", right: "8px", bottom: "8px", width: "auto", height: "55vh" }
109
+ : { top: "8px", bottom: "8px", height: "auto", left: side === "left" ? "8px" : "auto", right: side === "left" ? "auto" : "8px", width: side === "left" ? "264px" : "360px" });
110
+ };
111
+ const setOpen = (on) => {
112
+ isOpen = on;
113
+ remember(on);
114
+ if (!on) comments.pins([]);
115
+ host.style.display = on ? "block" : "none";
116
+ const narrow = window.innerWidth < 640;
117
+ const room = narrow || window.innerWidth >= 900;
118
+ place(host, narrow, "right");
119
+ place(left, narrow, "left");
120
+ // Above the page's outlines (the engine's, 2147483645); on a phone the Layers panel sits over the Design one.
121
+ left.style.zIndex = narrow ? "2147483647" : "2147483646";
122
+ left.style.display = on && room && layersShown ? "block" : "none";
123
+ tab.style.display = on && room && !layersShown ? "block" : "none";
124
+ pill.style.display = on ? "none" : "flex";
125
+ toPanel({ type: "open", open: on });
126
+ if (!on) window.__blockoutEditorSetOn?.(false);
127
+ };
128
+ pill.addEventListener("click", () => setOpen(true));
129
+ window.addEventListener("resize", () => isOpen && setOpen(true));
130
+ frame.addEventListener("load", () => toPanel({ type: "open", open: isOpen }));
131
+
132
+ const onMessage = async (event) => {
133
+ if (event.origin !== origin) return;
134
+ const m = event.data;
135
+ if (!m || m.blockoutEditorKit !== 1) return;
136
+ if (event.source === layers.contentWindow && m.type === "layers") return showLayers(!!m.open);
137
+ if (event.source !== frame.contentWindow) return;
138
+ if (m.type === "close") setOpen(false);
139
+ // The panel listens now: it is told whether it is open (a word sent at its frame's load may have come too soon).
140
+ if (m.type === "ready") toPanel({ type: "open", open: isOpen });
141
+ // Blockout's theme, so the canvas around the frames matches the panels.
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 : []);
170
+ if (m.type === "send") {
171
+ try {
172
+ const res = await fetch(notesApi, {
173
+ method: "POST",
174
+ headers: { "content-type": "application/json" },
175
+ body: JSON.stringify({ page: location.href, width: window.innerWidth, notes: m.notes }),
176
+ });
177
+ // No notes route here (a static page's server answers 404, 405 or 501): the panel puts the request on the
178
+ // clipboard instead, to paste into Claude Code.
179
+ if ([404, 405, 501].includes(res.status)) return toPanel({ type: "sent", ok: false, copy: true });
180
+ const said = res.ok ? {} : await res.json().catch(() => ({}));
181
+ toPanel({ type: "sent", ok: res.ok, error: res.ok ? undefined : said.error || `The notes route answered ${res.status}.` });
182
+ } catch {
183
+ toPanel({ type: "sent", ok: false, copy: true });
184
+ }
185
+ }
186
+ };
187
+ const comments = makeComments({ toPanel });
188
+ window.addEventListener("message", onMessage);
189
+ document.body.append(left, tab, host, pill);
190
+ setOpen(open);
191
+ const canvas = makeCanvas({
192
+ isOpen: () => isOpen,
193
+ insets: () => (window.innerWidth < 640 ? { left: 0, right: 0 } : { left: layersShown && window.innerWidth >= 900 ? 280 : 0, right: 376 }),
194
+ });
195
+ // Taken out (React's development mount runs an effect, undoes it and runs it again), it can start afresh; the engine
196
+ // stays in the page and the new panel greets it.
197
+ return () => {
198
+ window.removeEventListener("message", onMessage);
199
+ window.__blockoutEditorSetOn?.(false);
200
+ canvas.remove();
201
+ comments.remove();
202
+ host.remove();
203
+ left.remove();
204
+ tab.remove();
205
+ pill.remove();
206
+ window.__blockoutEditorKit = false;
207
+ };
208
+ }
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
+
362
+ /*
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
364
+ * on a canvas over it, and frames at tablet and phone widths can join it, each this page loaded again at that width
365
+ * (its own engine, started by the kit in frame mode). The frame pressed in is the one the panels work on: the page's
366
+ * engine passes their messages to it, and its changes are made the same in the other frames by CSS path. Back at 100%
367
+ * with the desktop frame alone, the canvas goes and the page has what was changed there.
368
+ */
369
+ const DEVICES = [
370
+ { id: "desktop", name: "Desktop", w: 0, h: 0 },
371
+ { id: "tablet", name: "Tablet", w: 768, h: 1024 },
372
+ { id: "phone", name: "Phone", w: 390, h: 844 },
373
+ ];
374
+ const GAP = 80;
375
+
376
+ function makeCanvas({ isOpen, insets }) {
377
+ let shell = null;
378
+ let world = null;
379
+ let bar = null;
380
+ let zoomLabel = null;
381
+ const frames = {};
382
+ let devices = ["desktop"];
383
+ let active = "desktop";
384
+ let view = { z: 1, x: 0, y: 0 };
385
+ let lastChanges = [];
386
+ // The canvas in Blockout's light or dark colours (paper and ink, as the panels have them), as the panel says.
387
+ const THEMES = {
388
+ light: { canvas: "#ece8e1", bar: "#fff", ring: "rgba(16,16,16,.1)", ink: "#101010", pressed: "#efebe4", label: "#6b665f", active: "#e12c05" },
389
+ dark: { canvas: "#101010", bar: "#131211", ring: "rgba(245,242,236,.12)", ink: "#f5f2ec", pressed: "#282522", label: "#948d84", active: "#ff6b4f" },
390
+ };
391
+ let theme = THEMES.light;
392
+ const paint = () => {
393
+ if (!shell) return;
394
+ for (const [k, v] of Object.entries(theme)) shell.style.setProperty(`--bo-${k}`, v);
395
+ };
396
+ window.__blockoutEditorFrames = [];
397
+
398
+ const size = () => ({ w: window.innerWidth, h: window.innerHeight });
399
+ const layout = () => {
400
+ let x = 0;
401
+ return DEVICES.filter((d) => devices.includes(d.id)).map((d) => {
402
+ const w = d.id === "desktop" ? size().w : d.w;
403
+ const h = d.id === "desktop" ? size().h : d.h;
404
+ const f = { ...d, x, w, h };
405
+ x += w + GAP;
406
+ return f;
407
+ });
408
+ };
409
+ const draw = () => {
410
+ if (!shell) return;
411
+ world.style.transform = `translate(${view.x}px, ${view.y}px) scale(${view.z})`;
412
+ for (const f of layout()) {
413
+ const el = frames[f.id];
414
+ if (!el) continue;
415
+ el.box.style.left = `${f.x}px`;
416
+ el.frame.style.width = `${f.w}px`;
417
+ el.frame.style.height = `${f.h}px`;
418
+ el.label.textContent = `${f.name} · ${f.w}`;
419
+ el.label.style.fontSize = `${12 / view.z}px`;
420
+ el.label.style.paddingBottom = `${6 / view.z}px`;
421
+ el.label.style.color = f.id === active ? "var(--bo-active)" : "var(--bo-label)";
422
+ el.frame.style.outline = f.id === active ? `${2 / view.z}px solid #ff4d2e` : "none";
423
+ }
424
+ zoomLabel.textContent = `${Math.round(view.z * 100)}%`;
425
+ for (const b of bar.querySelectorAll("[data-device]")) b.setAttribute("aria-pressed", String(devices.includes(b.dataset.device)));
426
+ };
427
+ const relayTo = (id) => {
428
+ active = id;
429
+ const w = frames[id]?.frame.contentWindow;
430
+ window.__blockoutEditorRelay?.(w);
431
+ w?.postMessage({ blockoutEditor: 1, type: "hello" }, location.origin);
432
+ draw();
433
+ };
434
+ const addFrame = (d) => {
435
+ const box = document.createElement("div");
436
+ box.style.cssText = "position:absolute;top:0";
437
+ const label = document.createElement("p");
438
+ label.style.cssText = "position:absolute;bottom:100%;left:0;margin:0;white-space:nowrap;font:500 12px/1.4 ui-sans-serif,system-ui,sans-serif";
439
+ const frame = document.createElement("iframe");
440
+ frame.name = FRAME + d.id;
441
+ frame.title = `${d.name} width`;
442
+ frame.src = location.href;
443
+ frame.style.cssText = "display:block;border:0;background:#fff;box-shadow:0 0 0 1px rgba(16,16,16,.08),0 12px 40px rgba(16,16,16,.12)";
444
+ // The frame's engine says it has started (it loads after the frame does): it is turned on, and either worked in or
445
+ // given the changes made so far.
446
+ box.append(label, frame);
447
+ world.appendChild(box);
448
+ frames[d.id] = { box, frame, label };
449
+ window.__blockoutEditorFrames = Object.values(frames).map((f) => f.frame.contentWindow);
450
+ };
451
+ const fit = () => {
452
+ const list = layout();
453
+ const all = { w: Math.max(...list.map((f) => f.x + f.w)), h: Math.max(...list.map((f) => f.h)) };
454
+ const ins = insets();
455
+ const room = { w: size().w - ins.left - ins.right - 96, h: size().h - 160 };
456
+ const z = Math.min(1, room.w / all.w, room.h / all.h);
457
+ view = { z, x: ins.left + 48 + (room.w - all.w * z) / 2, y: 96 + (room.h - all.h * z) / 2 };
458
+ draw();
459
+ };
460
+ const zoomAt = (factor, cx, cy) => {
461
+ if (!shell) open();
462
+ const z = Math.min(4, Math.max(0.05, view.z * factor));
463
+ view = { z, x: cx - ((cx - view.x) / view.z) * z, y: cy - ((cy - view.y) / view.z) * z };
464
+ // Back at 100%, the desktop frame alone, where the page is: the canvas goes.
465
+ if (Math.abs(z - 1) < 0.02 && devices.length === 1 && Math.abs(view.x) < 40 && Math.abs(view.y) < 40) return close();
466
+ draw();
467
+ };
468
+ const key = (k) => {
469
+ const ins = insets();
470
+ const cx = ins.left + (size().w - ins.left - ins.right) / 2;
471
+ if (k === "=") zoomAt(1.25, cx, size().h / 2);
472
+ else if (k === "-") zoomAt(0.8, cx, size().h / 2);
473
+ else if (k === "0") close();
474
+ else {
475
+ if (!shell) open();
476
+ fit();
477
+ }
478
+ };
479
+ const toggle = (id) => {
480
+ const next = devices.includes(id) ? devices.filter((x) => x !== id) : DEVICES.map((d) => d.id).filter((x) => x === id || devices.includes(x));
481
+ if (!next.length) return;
482
+ for (const d of DEVICES)
483
+ if (devices.includes(d.id) && !next.includes(d.id)) {
484
+ frames[d.id].box.remove();
485
+ delete frames[d.id];
486
+ }
487
+ devices = next;
488
+ for (const d of DEVICES) if (devices.includes(d.id) && !frames[d.id]) addFrame(d);
489
+ window.__blockoutEditorFrames = Object.values(frames).map((f) => f.frame.contentWindow);
490
+ if (!devices.includes(active)) relayTo(devices[0]);
491
+ fit();
492
+ };
493
+ const button = (text, label, onClick) => {
494
+ const b = document.createElement("button");
495
+ b.type = "button";
496
+ b.textContent = text;
497
+ b.setAttribute("aria-label", label);
498
+ b.title = label;
499
+ b.style.cssText =
500
+ "border:0;border-radius:8px;background:transparent;color:var(--bo-ink);padding:5px 9px;font:500 12px/1 ui-sans-serif,system-ui,sans-serif;cursor:pointer";
501
+ b.addEventListener("click", onClick);
502
+ return b;
503
+ };
504
+ const open = () => {
505
+ if (shell) return;
506
+ shell = document.createElement("div");
507
+ shell.setAttribute("data-blockout-editor", "");
508
+ shell.style.cssText = "position:fixed;inset:0;z-index:2147483644;overflow:hidden;background:var(--bo-canvas)";
509
+ world = document.createElement("div");
510
+ world.style.cssText = "position:absolute;left:0;top:0;transform-origin:0 0";
511
+ bar = document.createElement("div");
512
+ bar.style.cssText =
513
+ "position:absolute;top:12px;left:50%;transform:translateX(-50%);display:flex;gap:2px;align-items:center;padding:4px;border-radius:14px;background:var(--bo-bar);" +
514
+ "box-shadow:0 0 0 1px var(--bo-ring),0 8px 24px rgba(16,16,16,.14)";
515
+ for (const d of DEVICES) {
516
+ const b = button(d.name, `${d.name} frame`, () => toggle(d.id));
517
+ b.dataset.device = d.id;
518
+ bar.appendChild(b);
519
+ }
520
+ bar.append(button("−", "Zoom out", () => key("-")));
521
+ zoomLabel = button("100%", "Zoom to fit", () => key("fit"));
522
+ bar.append(zoomLabel, button("+", "Zoom in", () => key("=")), button("100%", "Back to the page", () => key("0")));
523
+ const style = document.createElement("style");
524
+ style.textContent = '[data-blockout-editor] [aria-pressed="true"]{background:var(--bo-pressed)}';
525
+ shell.append(style, world, bar);
526
+ shell.addEventListener(
527
+ "wheel",
528
+ (e) => {
529
+ e.preventDefault();
530
+ if (e.ctrlKey || e.metaKey) zoomAt(Math.exp(-e.deltaY * 0.01), e.clientX, e.clientY);
531
+ else {
532
+ view = { ...view, x: view.x - e.deltaX, y: view.y - e.deltaY };
533
+ draw();
534
+ }
535
+ },
536
+ { passive: false },
537
+ );
538
+ paint();
539
+ document.body.appendChild(shell);
540
+ for (const d of DEVICES) if (devices.includes(d.id)) addFrame(d);
541
+ draw();
542
+ };
543
+ const close = () => {
544
+ if (!shell) return;
545
+ shell.remove();
546
+ shell = null;
547
+ for (const k of Object.keys(frames)) delete frames[k];
548
+ window.__blockoutEditorFrames = [];
549
+ devices = ["desktop"];
550
+ active = "desktop";
551
+ view = { z: 1, x: 0, y: 0 };
552
+ window.__blockoutEditorRelay?.(null, lastChanges);
553
+ };
554
+
555
+ // Zooms from the page (its engine) and from the frames; which frame is pressed in; its changes, for the others.
556
+ const onZoom = (e) => {
557
+ if (!isOpen()) return;
558
+ const m = e.detail;
559
+ if (m.type === "zoomKey") key(m.key);
560
+ else zoomAt(Math.exp(-m.dy * 0.01), m.x, m.y);
561
+ };
562
+ const onFrame = (e) => {
563
+ const { msg, from } = e.detail;
564
+ const id = Object.keys(frames).find((k) => frames[k].frame.contentWindow === from);
565
+ if (!id) return;
566
+ if (msg.type === "boot") {
567
+ from.postMessage({ blockoutEditor: 1, type: "on", on: true }, location.origin);
568
+ if (id === active) relayTo(id);
569
+ else from.postMessage({ blockoutEditor: 1, type: "mirror", changes: lastChanges }, location.origin);
570
+ } else if (msg.type === "focus" && id !== active) relayTo(id);
571
+ else if (msg.type === "zoomKey") key(msg.key);
572
+ else if (msg.type === "zoom") {
573
+ const f = layout().find((l) => l.id === id);
574
+ if (f) zoomAt(Math.exp(-msg.dy * 0.01), view.x + (f.x + msg.x) * view.z, view.y + msg.y * view.z);
575
+ } else if (msg.type === "changes" && id === active) {
576
+ lastChanges = msg.changes || [];
577
+ for (const k of Object.keys(frames))
578
+ if (k !== id) frames[k].frame.contentWindow?.postMessage({ blockoutEditor: 1, type: "mirror", changes: lastChanges }, location.origin);
579
+ }
580
+ };
581
+ // With the canvas open the page's engine stands still, so the zoom keys are heard here.
582
+ const onKey = (e) => {
583
+ if (!shell) return;
584
+ const k = (e.metaKey || e.ctrlKey) && /^(=|\+|-|0)$/.test(e.key) ? (e.key === "+" ? "=" : e.key) : e.shiftKey && e.code === "Digit1" ? "fit" : null;
585
+ if (!k) return;
586
+ e.preventDefault();
587
+ key(k);
588
+ };
589
+ window.addEventListener("keydown", onKey, true);
590
+ window.addEventListener("blockout-editor:zoom", onZoom);
591
+ window.addEventListener("blockout-editor:frame", onFrame);
592
+ return {
593
+ setDark(dark) {
594
+ theme = dark ? THEMES.dark : THEMES.light;
595
+ paint();
596
+ },
597
+ remove() {
598
+ close();
599
+ window.removeEventListener("keydown", onKey, true);
600
+ window.removeEventListener("blockout-editor:zoom", onZoom);
601
+ window.removeEventListener("blockout-editor:frame", onFrame);
602
+ },
603
+ };
604
+ }
605
+
606
+ export default startEditor;