verso-cms 0.0.0-stage → 0.1.3

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.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/bin/verso.js +16 -0
  4. package/editor/door.js +139 -0
  5. package/editor/editor.js +1880 -0
  6. package/editor/elevate.css +2158 -0
  7. package/editor/ext-attrs.js +87 -0
  8. package/editor/ext-blocks.js +422 -0
  9. package/editor/ext-builder.js +819 -0
  10. package/editor/ext-channels.js +574 -0
  11. package/editor/ext-components.js +160 -0
  12. package/editor/ext-history.js +242 -0
  13. package/editor/ext-palette.js +307 -0
  14. package/editor/ext-people.js +345 -0
  15. package/editor/ext-repeaters.js +143 -0
  16. package/editor/ext-screens.js +94 -0
  17. package/editor/ext-site-settings.js +318 -0
  18. package/editor/ext-site-view.js +632 -0
  19. package/editor/ext-tokens.js +1195 -0
  20. package/editor/new-page.js +252 -0
  21. package/editor/rich.js +23 -0
  22. package/package.json +69 -4
  23. package/src/blocks.js +269 -0
  24. package/src/box.js +339 -0
  25. package/src/build.js +210 -0
  26. package/src/cli.js +161 -0
  27. package/src/color.js +137 -0
  28. package/src/components.js +223 -0
  29. package/src/elevate.js +74 -0
  30. package/src/errors.js +46 -0
  31. package/src/extensions/README.md +70 -0
  32. package/src/extensions/blocks.js +294 -0
  33. package/src/extensions/builder.js +734 -0
  34. package/src/extensions/channels.js +341 -0
  35. package/src/extensions/components.js +141 -0
  36. package/src/extensions/history.js +169 -0
  37. package/src/extensions/palette.js +31 -0
  38. package/src/extensions/people.js +113 -0
  39. package/src/extensions/site-settings.js +251 -0
  40. package/src/extensions/site-view.js +381 -0
  41. package/src/extensions/tags.js +15 -0
  42. package/src/extensions/tokens.js +587 -0
  43. package/src/fonts.js +139 -0
  44. package/src/git.js +419 -0
  45. package/src/html-edit.js +942 -0
  46. package/src/images.js +116 -0
  47. package/src/people.js +286 -0
  48. package/src/rich.js +124 -0
  49. package/src/scaffold.js +185 -0
  50. package/src/screens.js +65 -0
  51. package/src/server.js +693 -0
  52. package/src/site.js +618 -0
  53. package/src/template.js +915 -0
  54. package/src/video.js +29 -0
  55. package/starter/Dockerfile +20 -0
  56. package/starter/README.md +49 -0
  57. package/starter/blocks/call-to-action.html +6 -0
  58. package/starter/blocks/features.html +15 -0
  59. package/starter/blocks/hero.html +8 -0
  60. package/starter/blocks/image-and-text.html +8 -0
  61. package/starter/blocks/latest-posts.html +20 -0
  62. package/starter/blocks/post-index.html +30 -0
  63. package/starter/blocks/quote.html +9 -0
  64. package/starter/blocks/site-footer.html +8 -0
  65. package/starter/blocks/site-nav.html +8 -0
  66. package/starter/blocks/tag-list.html +10 -0
  67. package/starter/blocks/tagged-posts.html +19 -0
  68. package/starter/blocks/team.html +15 -0
  69. package/starter/blocks/text.html +4 -0
  70. package/starter/content/404/page.json +21 -0
  71. package/starter/content/about/page.json +65 -0
  72. package/starter/content/journal/designing-for-the-morning-shift/body.html +22 -0
  73. package/starter/content/journal/designing-for-the-morning-shift/checklist.jpg +0 -0
  74. package/starter/content/journal/designing-for-the-morning-shift/cover.jpg +0 -0
  75. package/starter/content/journal/designing-for-the-morning-shift/page.json +17 -0
  76. package/starter/content/journal/page.json +19 -0
  77. package/starter/content/journal/the-first-week/body.html +17 -0
  78. package/starter/content/journal/the-first-week/cover.jpg +0 -0
  79. package/starter/content/journal/the-first-week/page.json +17 -0
  80. package/starter/content/journal/the-first-week/wall-of-cards.jpg +0 -0
  81. package/starter/content/page.json +94 -0
  82. package/starter/content/site.json +88 -0
  83. package/starter/content/studio-table.jpg +0 -0
  84. package/starter/content/topics/page.json +27 -0
  85. package/starter/dockerignore +5 -0
  86. package/starter/elevate/config/design.ts +30 -0
  87. package/starter/elevate/config/elevate.ts +16 -0
  88. package/starter/elevate/config/syntax.ts +6 -0
  89. package/starter/elevate/design/site.ts +9 -0
  90. package/starter/elevate/design/tokens.json +20 -0
  91. package/starter/elevate/extend/fonts.css +1 -0
  92. package/starter/gitignore +6 -0
  93. package/starter/netlify.toml +5 -0
  94. package/starter/parts/.gitkeep +0 -0
  95. package/starter/public/favicon.svg +1 -0
  96. package/starter/templates/page.html +20 -0
  97. package/starter/templates/page.layout.json +23 -0
  98. package/starter/templates/post.html +65 -0
  99. package/starter/verso.defaults.json +33 -0
  100. package/starter-blank/blocks/site-footer.html +3 -0
  101. package/starter-blank/blocks/site-nav.html +8 -0
  102. package/starter-blank/blocks/text.html +4 -0
  103. package/starter-blank/content/404/page.json +18 -0
  104. package/starter-blank/content/page.json +18 -0
  105. package/starter-blank/content/site.json +36 -0
  106. package/starter-blank/elevate/design/tokens.json +10 -0
  107. package/starter-blank/templates/page.html +17 -0
  108. package/starter-blank/verso.defaults.json +26 -0
@@ -0,0 +1,819 @@
1
+ // The block builder. Build a block by choosing from the design system,
2
+ // never by typing CSS: every option is a swatch, a specimen or a ruler from
3
+ // Elevate's own tokens. What it writes is the same file a developer would
4
+ // write, and hand edits to that file survive every visual change.
5
+
6
+ const SVG = {
7
+ up: '<path d="M12 18V6m-5 5 5-5 5 5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',
8
+ down: '<path d="M12 6v12m-5-5 5 5 5-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',
9
+ trash: '<path d="M5 7h14M10 7V5h4v2M7 7l1 12h8l1-12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',
10
+ wrap: '<rect x="4" y="5" width="16" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><rect x="8" y="9" width="8" height="6" rx="1" fill="currentColor"/>',
11
+ unwrap: '<rect x="8" y="9" width="8" height="6" rx="1" fill="currentColor"/><path d="M4 9V7a2 2 0 0 1 2-2h2M16 5h2a2 2 0 0 1 2 2v2M20 15v2a2 2 0 0 1-2 2h-2M8 19H6a2 2 0 0 1-2-2v-2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',
12
+ code: '<path d="m9 8-4 4 4 4m6-8 4 4-4 4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',
13
+ cube: '<path d="M12 3 4 7.5v9L12 21l8-4.5v-9L12 3Zm0 0v9m0 0 8-4.5M12 12l-8-4.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/>',
14
+ plus: '<path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',
15
+ list: '<path d="M9 6h11M9 12h11M9 18h11" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><circle cx="4.5" cy="6" r="1.5" fill="currentColor"/><circle cx="4.5" cy="12" r="1.5" fill="currentColor"/><circle cx="4.5" cy="18" r="1.5" fill="currentColor"/>',
16
+ when: '<path d="M4 7h7l3 5-3 5H4M14 12h6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',
17
+ items: '<rect x="4" y="4" width="16" height="6" rx="1.5" fill="none" stroke="currentColor" stroke-width="2"/><rect x="4" y="14" width="16" height="6" rx="1.5" fill="none" stroke="currentColor" stroke-width="2"/>',
18
+ copy: '<rect x="8" y="8" width="12" height="12" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2" fill="none" stroke="currentColor" stroke-width="2"/>',
19
+ };
20
+ const CONSTRUCT_ICON = { each: 'list', if: 'when', list: 'items' };
21
+ const svg = (name, size = 18) => `<svg width="${size}" height="${size}" viewBox="0 0 24 24" aria-hidden="true">${SVG[name]}</svg>`;
22
+
23
+ export function init(verso) {
24
+ const { root, ui, toast, icon, esc, show, hide } = verso;
25
+ verso.menuItems.push({ label: 'Build a block', icon: svg('cube'), run: () => open() });
26
+ verso.addBarButton({ id: 'open-builder', title: 'Build a block', svg: svg('cube'), onClick: () => open() });
27
+ // Other parts of the editor open the builder on one block: verso.builder.open('hero').
28
+ verso.builder = { open: (name) => open(name) };
29
+
30
+ const state = { blocks: [], used: {}, usedOn: [], name: null, system: null, tree: [], constructs: [], targets: { own: [], page: [], each: {}, items: {} }, source: '', selected: '0', bp: '', code: false, busy: false, pending: null, conditionOpen: false, changed: false, otherwiseWords: false };
31
+ let wrap = null;
32
+
33
+ const api = async (url, body) => {
34
+ const res = await fetch(url, body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } : undefined);
35
+ const out = await res.json().catch(() => ({ ok: false, message: 'Verso didn\'t answer. Is it still running?' }));
36
+ if (!out.ok) throw new Error(out.message || 'That didn\'t work.');
37
+ return out;
38
+ };
39
+
40
+ // Opened on a block from the page, the builder shows that block. Opened
41
+ // on its own, it starts on a choice: a new block, or a copy of one, so no
42
+ // block that's on pages changes by surprise.
43
+ async function open(name) {
44
+ if (!wrap) build();
45
+ show(wrap, 'flex');
46
+ // The editor's messages sit under the builder; lift them while it's open.
47
+ const t = root.querySelector('#toast');
48
+ if (t) t.style.zIndex = '2147483000';
49
+ try {
50
+ await verso.flush?.();
51
+ const [blocks, system] = await Promise.all([api('/__verso/builder/blocks'), api('/__verso/builder/system')]);
52
+ state.blocks = blocks.blocks;
53
+ state.used = blocks.used || {};
54
+ state.system = system;
55
+ if (typeof name === 'string' && state.blocks.includes(name)) await load(name);
56
+ else renderChoice();
57
+ } catch (err) {
58
+ toast(err.message, 'error');
59
+ }
60
+ }
61
+
62
+ // Pages show the changes once the builder closes.
63
+ function close() {
64
+ hide(wrap);
65
+ root.querySelector('#toast')?.style.removeProperty('z-index');
66
+ if (state.changed) { state.changed = false; verso.reload?.(); }
67
+ }
68
+
69
+ function build() {
70
+ wrap = document.createElement('div');
71
+ wrap.className = ui("fixed top:0 left:0 w:full h:full col bg-color:paper-2 text:ink font:ui:small z:6");
72
+ wrap.style.display = 'none';
73
+ wrap.setAttribute('role', 'dialog');
74
+ wrap.setAttribute('aria-label', 'Block builder');
75
+ wrap.innerHTML = `
76
+ <header class="${ui("row:y-center:x-between:wrap gap:d2 pd:d3 bg-color:ink text:paper child:no-shrink")}">
77
+ <div class="${ui("row:y-center gap:d2 min-w:0")}">
78
+ <span class="${ui("row:x-center:y-center w:d9 h:d9 bd:round-full bg-color:proof text:paper")}">${svg('cube')}</span>
79
+ <select data-block class="${ui("h:d9 pd-x:d3 bd:round-pill bd:width-0 bg-color:ink-2 text:paper font:ui:small:medium cursor:pointer max-w:c11")}" aria-label="Block to change"></select>
80
+ <button data-new class="${ui("row:y-center gap:d1 h:d9 pd-x:d3 bd:round-pill bd:width-0 bg-color:transparent text:paper cursor:pointer @hover:[bg-color:ink-2] transition:fast")}">${svg('plus', 16)}<span class="${ui("hidden /sm/ inline")}">New block</span></button>
81
+ <button data-delete title="Delete this block" aria-label="Delete this block" class="${ui("row:x-center:y-center w:d9 h:d9 bd:round-full bd:width-0 bg-color:transparent text:paper cursor:pointer @hover:[bg-color:ink-2] transition:fast")}" style="display:none">${svg('trash', 16)}</button>
82
+ </div>
83
+ <div class="${ui("row:y-center gap:d2 min-w:0 max-w:full")}">
84
+ <div data-bps class="${ui("row:y-center gap:d0 pd:d0 bd:round-pill bg-color:ink-2 max-w:full overflow-x:auto")}" role="radiogroup" aria-label="Screen size"></div>
85
+ <button data-code class="${ui("row:y-center gap:d1 h:d9 pd-x:d3 bd:round-pill bd:width-0 bg-color:transparent text:paper cursor:pointer @hover:[bg-color:ink-2] transition:fast")}" aria-pressed="false">${svg('code', 16)}<span class="${ui("hidden /md/ inline")}">View code</span></button>
86
+ <button data-close class="${ui("row:x-center:y-center w:d9 h:d9 bd:round-full bd:width-0 bg-color:transparent text:paper cursor:pointer @hover:[bg-color:ink-2] transition:fast")}" aria-label="Close the builder">${icon('close')}</button>
87
+ </div>
88
+ </header>
89
+ <div data-choice class="${ui("child:grow min-h:0 overflow-y:auto bg-color:paper-2")}" style="display:none"></div>
90
+ <div data-work class="${ui("col child:grow min-h:0 /lg/ row")}">
91
+ <div class="${ui("relative child:grow min-h:0 min-w:0 col gap:d2 bg-color:paper-2 pd:d3")}">
92
+ <div data-banner style="display:none"></div>
93
+ <div data-frame-box class="${ui("relative child:grow min-h:0 w:full overflow:hidden")}">
94
+ <iframe data-preview title="Block preview" class="${ui("absolute top:0 left:0 w:full h:full bg-color:paper bd:round-d4 bd:width-px:solid:line")}"></iframe>
95
+ </div>
96
+ <p data-frame-width class="${ui("font:ui:tiny text:mist text:center")}" aria-live="polite"></p>
97
+ <pre data-source class="${ui("absolute top:0 left:0 w:full h:full mg:0 pd:d5 overflow:auto bg-color:ink text:paper font:mono:tiny")}" style="display:none"></pre>
98
+ </div>
99
+ <aside data-inspector class="${ui("w:full max-h:half-screen overflow-y:auto bg-color:paper bd-t:width-px:solid:line child:no-shrink /lg/ w:sheet max-h:full bd-t:width-0")}"></aside>
100
+ </div>`;
101
+ root.appendChild(wrap);
102
+ const q = (s) => wrap.querySelector(s);
103
+ q('[data-close]').addEventListener('click', close);
104
+ q('[data-block]').addEventListener('change', (e) => { if (e.target.value) load(e.target.value); });
105
+ q('[data-new]').addEventListener('click', () => renderChoice());
106
+ q('[data-delete]').addEventListener('click', () => removeBlock(false));
107
+ q('[data-code]').addEventListener('click', () => {
108
+ state.code = !state.code;
109
+ q('[data-code]').setAttribute('aria-pressed', String(state.code));
110
+ renderSource();
111
+ });
112
+ q('[data-preview]').addEventListener('load', () => { wirePreview(); sizePreview(); });
113
+ window.addEventListener('resize', () => { if (wrap.style.display !== 'none') sizePreview(); });
114
+ wrap.addEventListener('keydown', (e) => { if (e.key === 'Escape') close(); });
115
+ }
116
+
117
+ const q = (s) => wrap.querySelector(s);
118
+ // A block's file name in words: "team-members" → "Team members".
119
+ const pretty = (name) => String(name || '').replace(/[-_]+/g, ' ').trim().replace(/^./, (c) => c.toUpperCase());
120
+ // The site's screen sizes, narrowest first, with their words ("Tablets").
121
+ const screens = () => state.system?.breakpoints || [];
122
+ const screenOf = (bp) => screens().find((b) => b.name === bp);
123
+ const screenWords = (bp) => (bp ? screenOf(bp)?.label || bp : 'All sizes');
124
+ // Whether the selected element has its own styles at a screen size.
125
+ const setAt = (node, bp) => !!node && Object.values(node.picks[bp] || {}).some((v) => v != null && v !== '');
126
+
127
+ function renderHeader() {
128
+ q('[data-block]').innerHTML = (state.name ? '' : '<option value="" selected>Change a block</option>') + (state.blocks.map((b) => `<option value="${esc(b)}"${b === state.name ? ' selected' : ''}>${esc(pretty(b))}</option>`).join('') || '<option value="">No blocks yet</option>');
129
+ q('[data-delete]').style.display = state.name ? '' : 'none';
130
+ if (state.bp && !screenOf(state.bp)) state.bp = '';
131
+ const node = find(state.selected);
132
+ const bps = [{ name: '', label: 'All sizes' }, ...screens()];
133
+ q('[data-bps]').innerHTML = bps.map((b) => {
134
+ const dot = b.name && setAt(node, b.name) ? `<span class="${ui("block w:d1 h:d1 bd:round-full bg-color:proof")}" aria-hidden="true"></span>` : '';
135
+ const title = b.name ? `${b.label}: from ${b.px}px wide and up${dot ? '. The selected element has its own styles here.' : ''}` : 'Every screen size, unless a wider size changes it';
136
+ return `<button role="radio" aria-checked="${b.name === state.bp}" data-bp="${b.name}" title="${esc(title)}" class="${b.name === state.bp ? ui("row:y-center gap:d1 h:d8 pd-x:d3 bd:round-pill bd:width-0 bg-color:paper text:ink font:ui:tiny:semibold cursor:pointer format:no-wrap child:no-shrink") : ui("row:y-center gap:d1 h:d8 pd-x:d3 bd:round-pill bd:width-0 bg-color:transparent text:mist font:ui:tiny:semibold cursor:pointer format:no-wrap child:no-shrink @hover:[text:paper]")}">${esc(b.label)}${dot}</button>`;
137
+ }).join('');
138
+ q('[data-bps]').querySelectorAll('[data-bp]').forEach((b) => b.addEventListener('click', () => { state.bp = b.dataset.bp; renderHeader(); renderInspector(); sizePreview(); }));
139
+ q('[data-bps] [aria-checked="true"]')?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
140
+ }
141
+
142
+ // The preview shows a screen size at its narrowest, where its styles start,
143
+ // scaled down when the window is smaller than that.
144
+ function sizePreview() {
145
+ const box = q('[data-frame-box]');
146
+ const frame = q('[data-preview]');
147
+ const note = q('[data-frame-width]');
148
+ if (!box || !frame) return;
149
+ const s = screenOf(state.bp);
150
+ if (!s?.px) {
151
+ Object.assign(frame.style, { width: '', height: '', left: '', transform: '' });
152
+ note.textContent = '';
153
+ return;
154
+ }
155
+ const w = box.clientWidth;
156
+ const h = box.clientHeight;
157
+ const scale = Math.min(1, w / s.px);
158
+ Object.assign(frame.style, {
159
+ width: `${s.px}px`,
160
+ height: `${h / scale}px`,
161
+ left: `${Math.max(0, (w - s.px * scale) / 2)}px`,
162
+ transform: scale < 1 ? `scale(${scale})` : '',
163
+ transformOrigin: 'top left',
164
+ });
165
+ note.textContent = `${s.label} start at ${s.px}px wide${scale < 1 ? `, shown at ${Math.round(scale * 100)}%` : ''}. Choices apply from here up.`;
166
+ }
167
+
168
+ const card = ui("col gap:d2 pd:d5 bd:round-d4 bd:width-px:solid:line bg-color:paper text:ink text:left cursor:pointer @hover:[bd:proof] transition:fast");
169
+
170
+ // The "New block" screen: start from scratch, or from a copy of a block.
171
+ // Changing a block that's already on pages is there too, said plainly.
172
+ function renderChoice(from = false) {
173
+ state.name = null;
174
+ renderHeader();
175
+ hide(q('[data-work]'));
176
+ const box = q('[data-choice]');
177
+ show(box, 'block');
178
+ const usedText = (b) => (state.used[b] ? `On ${state.used[b]} ${state.used[b] === 1 ? 'page' : 'pages'}` : 'Not on any page yet');
179
+ const blockButtons = (attr) => state.blocks.map((b) => `<button ${attr}="${esc(b)}" class="${ui("col gap:d0 pd:d3 bd:round-d3 bd:width-px:solid:line bg-color:paper text:left cursor:pointer @hover:[bd:proof] transition:fast")}"><span class="${ui("font:ui:small:semibold")}">${esc(pretty(b))}</span><span class="${ui("font:ui:tiny text:ink-3")}">${usedText(b)}</span></button>`).join('');
180
+ box.innerHTML = `<div class="${ui("col gap:d6 pd:d6 max-w:s10 mg-x:auto w:full")}">
181
+ <div class="${ui("col gap:d1")}"><h2 class="${ui("font:ui:h5:semibold")}">New block</h2><p class="${ui("text:ink-3")}">A block is a piece you put on pages, like a hero or a list of plans.</p></div>
182
+ ${from ? `<div class="${ui("col gap:d3")}"><div class="${ui("row:y-center:x-between")}"><h3 class="${ui("font:ui:small:semibold")}">Start from which block?</h3>${button('data-choice-back', 'Back')}</div>${note('You get a copy with a new name. Pages using the original stay as they are.')}<div class="${ui("grid:cols-1-fr:gap-d2 /md/ grid:cols-2-fr:gap-d2")}">${blockButtons('data-copy')}</div></div>`
183
+ : `<div class="${ui("grid:cols-1-fr:gap-d3 /md/ grid:cols-2-fr:gap-d3")}">
184
+ <button data-scratch class="${card}"><span class="${ui("font:ui:base:semibold")}">Start from scratch</span><span class="${ui("text:ink-3")}">An empty block at page width.</span></button>
185
+ ${state.blocks.length ? `<button data-from class="${card}"><span class="${ui("font:ui:base:semibold")}">Start from an existing block</span><span class="${ui("text:ink-3")}">A copy to change, so pages using the original don't.</span></button>` : ''}
186
+ </div>
187
+ ${state.blocks.length ? `<div class="${ui("col gap:d3")}"><h3 class="${ui("font:ui:small:semibold")}">Or change a block you have</h3>${note('Changes show right away on every page that uses it.')}<div class="${ui("grid:cols-1-fr:gap-d2 /md/ grid:cols-2-fr:gap-d2")}">${blockButtons('data-change')}</div></div>` : ''}`}
188
+ </div>`;
189
+ box.querySelector('[data-scratch]')?.addEventListener('click', () => newBlock());
190
+ box.querySelector('[data-from]')?.addEventListener('click', () => renderChoice(true));
191
+ box.querySelector('[data-choice-back]')?.addEventListener('click', () => renderChoice());
192
+ box.querySelectorAll('[data-copy]').forEach((b) => b.addEventListener('click', () => newBlock(b.dataset.copy)));
193
+ box.querySelectorAll('[data-change]').forEach((b) => b.addEventListener('click', () => load(b.dataset.change)));
194
+ }
195
+
196
+ async function newBlock(from = null) {
197
+ const name = await ask(from ? `Name the copy of ${pretty(from)}` : 'Name the block, like Project facts', from ? `${pretty(from)} copy` : '', 'Create');
198
+ if (!name) return;
199
+ try {
200
+ const out = await api('/__verso/builder/new', { name, ...(from ? { from } : {}) });
201
+ state.blocks = (await api('/__verso/builder/blocks')).blocks;
202
+ await load(out.name);
203
+ } catch (err) {
204
+ toast(err.message, 'error');
205
+ }
206
+ }
207
+
208
+ // A small inline question, since alert() and prompt() aren't available everywhere.
209
+ function ask(question, value = '', action = 'Create') {
210
+ return new Promise((resolve) => {
211
+ const box = document.createElement('form');
212
+ box.className = ui("absolute top:c2 left:half translate:(-50%_0) row:y-center gap:d2 pd:d2 bg-color:paper text:ink bd:round-d4 shadow:float z:7");
213
+ box.innerHTML = `<input class="${ui("h:d9 w:c13 pd-x:d3 bd:round-d3 bd:width-px:solid:line font:ui:small @focus:[bd:proof_shadow:proof-focus_outline:none]")}" value="${esc(value)}" placeholder="${esc(question)}" aria-label="${esc(question)}"><button class="${ui("h:d9 pd-x:d4 bd:round-pill bd:width-0 bg-color:proof text:paper font:ui:small:semibold cursor:pointer")}">${esc(action)}</button>`;
214
+ wrap.appendChild(box);
215
+ const input = box.querySelector('input');
216
+ input.focus();
217
+ input.select();
218
+ const done = (v) => { box.remove(); resolve(v); };
219
+ box.addEventListener('submit', (e) => { e.preventDefault(); done(input.value.trim()); });
220
+ input.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.stopPropagation(); done(null); } });
221
+ });
222
+ }
223
+
224
+ async function load(name) {
225
+ try {
226
+ const out = await api(`/__verso/builder/block?name=${encodeURIComponent(name)}`);
227
+ state.name = name;
228
+ state.selected = '0';
229
+ state.usedOn = out.usedOn || [];
230
+ take(out);
231
+ hide(q('[data-choice]'));
232
+ show(q('[data-work]'), 'flex');
233
+ renderHeader();
234
+ renderBanner();
235
+ reloadPreview();
236
+ renderInspector();
237
+ renderSource();
238
+ } catch (err) {
239
+ toast(err.message, 'error');
240
+ }
241
+ }
242
+
243
+ function take(out) {
244
+ state.tree = out.tree;
245
+ state.source = out.source;
246
+ state.constructs = out.constructs || [];
247
+ state.targets = { items: {}, ...(out.targets || { own: [], page: [], each: {} }) };
248
+ if (isConstruct(state.selected) ? !construct() : !find(state.selected)) state.selected = state.tree[0] ? state.tree[0].path : '';
249
+ }
250
+
251
+ // Deleting a block: straight away when nothing uses it; otherwise the
252
+ // banner says where it's used and asks once more.
253
+ async function removeBlock(everywhere) {
254
+ if (!state.name) return;
255
+ const name = state.name;
256
+ const res = await fetch('/__verso/builder/delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, everywhere }) });
257
+ const out = await res.json().catch(() => ({ ok: false, message: 'Verso didn\'t answer. Is it still running?' }));
258
+ if (res.status === 409 && out.used) {
259
+ const el = q('[data-banner]');
260
+ el.className = ui("row:y-center:wrap gap:d3 pd:d3:d4 bd:round-d3 bg-color:proof-soft text:ink font:ui:small");
261
+ el.innerHTML = `<span class="${ui("child:grow")}">${esc(out.message)}</span>
262
+ <button data-yes class="${ui("h:d9 pd-x:d4 bd:round-pill bd:width-0 bg-color:proof text:paper font:ui:small:semibold cursor:pointer @hover:[bg-color:proof-2]")}">Delete it everywhere</button>
263
+ <button data-no class="${ui("h:d9 pd-x:d4 bd:round-pill bd:width-px:solid:line bg-color:paper text:ink font:ui:small:semibold cursor:pointer")}">Keep it</button>`;
264
+ el.querySelector('[data-yes]').addEventListener('click', () => removeBlock(true));
265
+ el.querySelector('[data-no]').addEventListener('click', renderBanner);
266
+ show(el, 'flex');
267
+ return;
268
+ }
269
+ if (!out.ok) { toast(out.message, 'error'); return; }
270
+ toast(out.removedFrom ? `Deleted ${pretty(name)}, and took it off the pages that used it.` : `Deleted ${pretty(name)}.`, 'ok');
271
+ state.changed = true;
272
+ state.name = null;
273
+ const list = await api('/__verso/builder/blocks');
274
+ state.blocks = list.blocks;
275
+ state.used = list.used || {};
276
+ renderChoice();
277
+ }
278
+
279
+ // "Used on Journal and Work. Changes show there right away."
280
+ function renderBanner() {
281
+ const el = q('[data-banner]');
282
+ const list = state.usedOn || [];
283
+ if (!list.length) { hide(el); return; }
284
+ const shown = list.slice(0, 4).map((u) => (u.url ? `<a href="${esc(u.url)}" class="${ui("text:proof-2:underline font:ui:small:semibold")}">${esc(u.label)}</a>` : `<span class="${ui("font:ui:small:semibold")}">${esc(u.label)}</span>`));
285
+ if (list.length > 4) shown.push(`${list.length - 4} more`);
286
+ const words = shown.length > 1 ? `${shown.slice(0, -1).join(', ')} and ${shown[shown.length - 1]}` : shown[0];
287
+ el.className = ui("row:y-center gap:d2 pd:d2:d4 bd:round-d3 bg-color:proof-soft text:ink font:ui:small");
288
+ el.innerHTML = `<span>Used on ${words}. Changes show there right away.</span>`;
289
+ el.querySelectorAll('a').forEach((a) => a.addEventListener('click', () => { hide(wrap); if (state.changed) state.changed = false; }));
290
+ show(el, 'flex');
291
+ }
292
+
293
+ const isConstruct = (sel) => String(sel).startsWith('c:');
294
+ const construct = (sel = state.selected) => (isConstruct(sel) ? state.constructs.find((c) => `c:${c.id}` === sel) : null);
295
+
296
+ function reloadPreview() {
297
+ q('[data-preview]').src = `/__verso/builder/preview?name=${encodeURIComponent(state.name)}&t=${Date.now()}`;
298
+ }
299
+
300
+ // After an edit, the preview changes in place: the new stylesheet loads
301
+ // beside the old one, then the block is swapped in. The frame never reloads,
302
+ // so nothing blinks and the fonts stay put. Only the newest edit is shown.
303
+ let previewSeq = 0;
304
+ function refreshPreview(html) {
305
+ const doc = q('[data-preview]').contentDocument;
306
+ if (!html || !doc?.body || !doc.querySelector('link[href*="/__verso/builder/css"]')) { reloadPreview(); return; }
307
+ const mine = ++previewSeq;
308
+ const next = new DOMParser().parseFromString(html, 'text/html');
309
+ const href = next.querySelector('link[href*="/__verso/builder/css"]')?.getAttribute('href');
310
+ const link = doc.createElement('link');
311
+ let done = false;
312
+ const finish = () => {
313
+ if (done) return;
314
+ done = true;
315
+ if (mine !== previewSeq) { link.remove(); return; }
316
+ [...doc.body.attributes].forEach((a) => doc.body.removeAttribute(a.name));
317
+ [...next.body.attributes].forEach((a) => doc.body.setAttribute(a.name, a.value));
318
+ doc.body.innerHTML = next.body.innerHTML;
319
+ doc.querySelectorAll('link[href*="/__verso/builder/css"]').forEach((l) => { if (l !== link) l.remove(); });
320
+ state.markPreview?.();
321
+ };
322
+ link.rel = 'stylesheet';
323
+ link.href = href;
324
+ link.addEventListener('load', finish);
325
+ link.addEventListener('error', finish);
326
+ setTimeout(finish, 2000);
327
+ doc.head.appendChild(link);
328
+ }
329
+
330
+ // A colour shows on the preview the moment it's picked; the saved version
331
+ // replaces it a moment later.
332
+ const instant = { background: 'backgroundColor', 'text-color': 'color' };
333
+ function showNow(picker, colour) {
334
+ const prop = instant[picker];
335
+ const el = q('[data-preview]').contentDocument?.querySelector(`[data-path="${state.selected}"]`);
336
+ if (prop && el) el.style[prop] = colour || '';
337
+ }
338
+
339
+ function wirePreview() {
340
+ const doc = q('[data-preview]').contentDocument;
341
+ if (!doc) return;
342
+ const mark = () => {
343
+ doc.querySelectorAll('[data-verso-selected]').forEach((n) => n.removeAttribute('data-verso-selected'));
344
+ doc.querySelector(`[data-path="${state.selected}"]`)?.setAttribute('data-verso-selected', '');
345
+ };
346
+ mark();
347
+ doc.addEventListener('click', (e) => {
348
+ const el = e.target.closest('[data-path]');
349
+ e.preventDefault();
350
+ if (!el) return;
351
+ state.selected = el.getAttribute('data-path');
352
+ mark();
353
+ renderInspector();
354
+ }, true);
355
+ doc.addEventListener('mouseover', (e) => {
356
+ doc.querySelectorAll('[data-verso-hover]').forEach((n) => n.removeAttribute('data-verso-hover'));
357
+ e.target.closest('[data-path]')?.setAttribute('data-verso-hover', '');
358
+ });
359
+ state.markPreview = mark;
360
+ }
361
+
362
+ function renderSource() {
363
+ const pre = q('[data-source]');
364
+ pre.textContent = state.source;
365
+ if (state.code) show(pre); else hide(pre);
366
+ }
367
+
368
+ function find(path, list = state.tree) {
369
+ for (const n of list) {
370
+ if (n.path === path) return n;
371
+ const inner = find(path, n.children);
372
+ if (inner) return inner;
373
+ }
374
+ return null;
375
+ }
376
+
377
+ // One edit at a time, in order. Clicks while one is saving aren't lost: the
378
+ // latest waits its turn, and replaces any other that was waiting.
379
+ let queued = null;
380
+ async function edit(body) {
381
+ if (state.busy) { queued = body; return; }
382
+ state.busy = true;
383
+ try {
384
+ const out = await api('/__verso/builder/edit', { name: state.name, ...body, preview: true });
385
+ if (out.source !== state.source) state.changed = true;
386
+ // A new piece, a moved element or a new condition: selected where it is now.
387
+ if (out.selected) state.selected = out.selected;
388
+ take(out);
389
+ state.pending = null;
390
+ state.conditionOpen = false;
391
+ state.otherwiseWords = false;
392
+ refreshPreview(out.preview);
393
+ renderInspector();
394
+ renderSource();
395
+ if (out.selected) q('[data-inspector]').querySelector(`[data-select="${out.selected}"]`)?.scrollIntoView({ block: 'nearest' });
396
+ if (out.moved?.length) toast(`Renamed. The words on ${out.moved.length === 1 ? out.moved[0].label : `${out.moved.length} pages`} moved with it.`);
397
+ if (out.removed?.from?.length) {
398
+ const names = out.removed.from.map((u) => u.label);
399
+ const before = out.removed.source;
400
+ toast(`This removes words on ${names.length} ${names.length === 1 ? 'page' : 'pages'} (${names.slice(0, 3).join(', ')}${names.length > 3 ? ' and more' : ''}).`, 'ok', { label: 'Undo', run: () => edit({ op: 'restore', source: before }) });
401
+ }
402
+ state.busy = false;
403
+ // A new piece's field gets a name writers will see.
404
+ if (out.added?.length === 1) {
405
+ const field = out.added[0];
406
+ const shown = pretty(field);
407
+ const said = await ask('Name it, like Price', shown, 'Name it');
408
+ if (said && said !== shown) await edit({ op: 'rename-field', from: field, to: said });
409
+ }
410
+ } catch (err) {
411
+ toast(err.message, 'error');
412
+ if (!queued) refreshPreview(null);
413
+ } finally {
414
+ state.busy = false;
415
+ if (queued) {
416
+ const nextEdit = queued;
417
+ queued = null;
418
+ await edit(nextEdit);
419
+ }
420
+ }
421
+ }
422
+
423
+ // ════ Inspector ════
424
+
425
+ const section = (title, content) => `<section class="${ui("col gap:d3 pd:d4 bd-t:width-px:solid:line")}"><h3 class="${ui("font:ui:small:medium text:mist")}">${title}</h3>${content}</section>`;
426
+ const label = (text) => `<span class="${ui("font:ui:tiny:medium text:ink-3")}">${text}</span>`;
427
+ const rem = (v) => {
428
+ const m = /^(-?[\d.]+)(rem|px)$/.exec(String(v).trim());
429
+ return m ? Number(m[1]) * (m[2] === 'rem' ? 16 : 1) : null;
430
+ };
431
+
432
+ const inherited = (picker, value, current) => current == null && value !== '' && state.inherit?.[picker] === value;
433
+ function chip(picker, value, current, inner, title) {
434
+ const on = value === current;
435
+ if (!on && inherited(picker, value, current)) {
436
+ return `<button data-pick="${picker}" data-value="${esc(value)}" title="${esc(`${title || value}, from a smaller size`)}" aria-pressed="false" class="${ui("row:x-center:y-center gap:d1 min-w:d8 h:d8 pd-x:d2 bd:round-d2 bd:width-px:dashed:proof bg-color:paper text:proof-2 font:ui:tiny cursor:pointer")}">${inner}</button>`;
437
+ }
438
+ return `<button data-pick="${picker}" data-value="${esc(value)}" title="${esc(title || value)}" aria-pressed="${on}" class="${on ? ui("row:x-center:y-center gap:d1 min-w:d8 h:d8 pd-x:d2 bd:round-d2 bd:width-px:solid:proof bg-color:proof-soft text:proof-2 font:ui:tiny:semibold cursor:pointer") : ui("row:x-center:y-center gap:d1 min-w:d8 h:d8 pd-x:d2 bd:round-d2 bd:width-px:solid:line bg-color:paper text:ink-3 font:ui:tiny cursor:pointer @hover:[bd:ink-3] transition:fast")}">${inner}</button>`;
439
+ }
440
+ const chips = (items) => `<div class="${ui("row:wrap gap:d1")}">${items.join('')}</div>`;
441
+
442
+ function ruler(picker, current, tokens) {
443
+ return `<div class="${ui("col gap:d1")}">${tokens.map((t) => {
444
+ const px = rem(t.value);
445
+ const on = t.name === current;
446
+ const from = !on && inherited(picker, t.name, current);
447
+ return `<button data-pick="${picker}" data-value="${esc(t.name)}" aria-pressed="${on}" title="${esc(t.name)} (${esc(t.value)})${from ? ', from a smaller size' : ''}" class="${on ? ui("row:y-center gap:d2 h:d6 pd-x:d1 bd:round-d1 bd:width-0 bg-color:proof-soft text:proof-2 cursor:pointer") : from ? ui("row:y-center gap:d2 h:d6 pd-x:d1 bd:round-d1 bd:width-px:dashed:proof bg-color:transparent text:proof-2 cursor:pointer") : ui("row:y-center gap:d2 h:d6 pd-x:d1 bd:round-d1 bd:width-0 bg-color:transparent text:ink-3 cursor:pointer @hover:[bg-color:paper-2]")}"><span class="${ui("w:d8 font:mono:tiny")}">${esc(t.name)}</span><span style="height:6px;border-radius:3px;background:${on ? '#FF4F2B' : '#C9C9C2'};width:${Math.min(200, Math.max(2, (px ?? 0) * 1.5))}px"></span><span class="${ui("font:ui:tiny text:mist")}">${esc(t.value)}</span></button>`;
448
+ }).join('')}</div>`;
449
+ }
450
+
451
+ // The site's own colours, then Elevate's built-in ones under "More colours"
452
+ // (open when one of them is picked, so the choice stays visible).
453
+ function swatches(picker, current) {
454
+ const one = (c) => {
455
+ const on = c.name === current;
456
+ const from = !on && inherited(picker, c.name, current);
457
+ return `<button data-pick="${picker}" data-value="${esc(c.name)}" title="${esc(c.name)} (${esc(c.value)})${from ? ', from a smaller size' : ''}" aria-label="${esc(c.name)}" aria-pressed="${on}" class="${on ? ui("w:d7 h:d7 bd:round-d1 bd:width-d0:solid:proof cursor:pointer shadow:proof-ring") : from ? ui("w:d7 h:d7 bd:round-d1 bd:width-d0:dashed:proof cursor:pointer") : ui("w:d7 h:d7 bd:round-d1 bd:width-px:solid:line cursor:pointer @hover:[bd:ink-3]")}" style="background:${esc(c.value)}"></button>`;
458
+ };
459
+ const own = state.system.colors.filter((c) => !c.elevate);
460
+ const more = state.system.colors.filter((c) => c.elevate);
461
+ const row = (list) => `<div class="${ui("row:wrap gap:d1")}">${list.map(one).join('')}</div>`;
462
+ if (!more.length) return row(own);
463
+ const open = more.some((c) => c.name === current) || !own.length;
464
+ return `${own.length ? row(own) : ''}<details${open ? ' open' : ''}><summary class="${ui("pd-y:d1 font:ui:tiny:medium text:ink-3 cursor:pointer @hover:[text:ink]")}">More colours</summary>${row(more)}</details>`;
465
+ }
466
+
467
+ // ════ Small form pieces, in the editor's own look ════
468
+ const select = (attr, options, current, labelText) => `<select ${attr} aria-label="${esc(labelText)}" class="${ui("h:d9 w:full pd-x:d2 bd:round-d2 bd:width-px:solid:line bg-color:paper text:ink font:ui:small cursor:pointer @focus:[bd:proof_outline:none]")}">${options.map((o) => `<option value="${esc(o.value)}"${o.value === current ? ' selected' : ''}>${esc(o.label)}</option>`).join('')}</select>`;
469
+ const input = (attr, value, placeholder) => `<input ${attr} value="${esc(value ?? '')}" placeholder="${esc(placeholder)}" aria-label="${esc(placeholder)}" class="${ui("h:d9 w:full pd-x:d3 bd:round-d2 bd:width-px:solid:line bg-color:paper text:ink font:ui:small @focus:[bd:proof_outline:none]")}">`;
470
+ const button = (attr, text, primary = false) => `<button ${attr} class="${primary ? ui("h:d9 pd-x:d4 bd:round-pill bd:width-0 bg-color:proof text:paper font:ui:small:semibold cursor:pointer @hover:[bg-color:proof-2] transition:fast") : ui("h:d9 pd-x:d3 bd:round-pill bd:width-px:solid:line bg-color:paper text:ink font:ui:small:medium cursor:pointer @hover:[bd:ink-3] transition:fast")}">${text}</button>`;
471
+ const option = (attr, text, on) => `<button ${attr} aria-pressed="${on}" class="${on ? ui("h:d8 pd-x:d3 bd:round-pill bd:width-px:solid:proof bg-color:proof-soft text:proof-2 font:ui:tiny:semibold cursor:pointer") : ui("h:d8 pd-x:d3 bd:round-pill bd:width-px:solid:line bg-color:paper text:ink-3 font:ui:tiny:medium cursor:pointer @hover:[bd:ink-3] transition:fast")}">${text}</button>`;
472
+ const note = (text) => `<p class="${ui("font:ui:tiny text:ink-3")}">${text}</p>`;
473
+
474
+ const folderOptions = () => [
475
+ ...state.system.folders.map((f) => ({ value: f.name, label: `${f.label} (${f.count} ${f.count === 1 ? 'page' : 'pages'})` })),
476
+ { value: 'children', label: 'The pages inside the page it\'s on' },
477
+ { value: 'siblings', label: 'The pages beside the page it\'s on' },
478
+ ];
479
+ const folderFields = (each) => {
480
+ const c = state.constructs.find((x) => x.id === each);
481
+ const folder = c && state.system.folders.find((f) => f.name === c.info.section);
482
+ return folder ? folder.fields : [];
483
+ };
484
+
485
+ // The tree: lists and conditions show as rows of their own, just above
486
+ // the element they start with.
487
+ function treeRows() {
488
+ const rows = [];
489
+ // A list and the box that holds only it are one row.
490
+ const startsAt = (path) => state.constructs.filter((c) => c.first === path && !c.box);
491
+ const constructRow = (c, depth, on) => `<button data-select="c:${c.id}" class="${on ? ui("row:y-center gap:d2 w:full pd:d1:d2 bd:round-d2 bd:width-0 bg-color:proof text:paper font:ui:tiny:semibold cursor:pointer text:left") : ui("row:y-center gap:d2 w:full pd:d1:d2 bd:round-d2 bd:width-0 bg-color:transparent text:proof-2 font:ui:tiny:semibold cursor:pointer text:left @hover:[bg-color:paper-2]")}" style="padding-left:${8 + depth * 14}px">${svg(CONSTRUCT_ICON[c.kind], 14)}<span>${esc(c.label)}</span></button>`;
492
+ const walk = (n, depth, parent = null) => {
493
+ const merged = state.constructs.find((c) => c.box === n.path);
494
+ if (merged) {
495
+ rows.push(constructRow(merged, depth, state.selected === `c:${merged.id}` || state.selected === n.path));
496
+ n.children.forEach((c) => walk(c, depth + 1, { ...n, name: merged.kind === 'list' ? 'List of items' : n.name }));
497
+ return;
498
+ }
499
+ startsAt(n.path).forEach((c) => rows.push(constructRow(c, depth, state.selected === `c:${c.id}`)));
500
+ state.constructs.filter((c) => c.altFirst === n.path).forEach((c) => rows.push(`<button data-select="c:${c.id}" class="${ui("row:y-center gap:d2 w:full pd:d0:d2 bd:width-0 bg-color:transparent text:ink-3 font:ui:tiny:medium cursor:pointer text:left @hover:[text:proof-2]")}" style="padding-left:${8 + depth * 14}px">${c.kind === 'each' ? 'When there are none' : 'Otherwise'}</button>`));
501
+ const on = n.path === state.selected;
502
+ const fields = [...n.fields, ...n.attrFields].map((f) => `<span class="${ui("pd:d0:d1 bd:round-d1 bg-color:paper-2 text:ink-3 font:ui:tiny")}">${esc(f.name)}</span>`).join(' ');
503
+ // In words: "Heading", "Image", "Item"… The tag is in View code.
504
+ const name = parent && parent.name === 'List of items' ? 'Item' : n.name || n.tag;
505
+ const words = n.text ? `<span class="${ui("font:ui:tiny text:ink-3")}">${esc(n.text.slice(0, 28))}</span>` : '';
506
+ rows.push(`<button data-select="${n.path}" class="${on ? ui("row:y-center gap:d2 w:full pd:d1:d2 bd:round-d2 bd:width-0 bg-color:proof-soft text:ink cursor:pointer") : ui("row:y-center gap:d2 w:full pd:d1:d2 bd:round-d2 bd:width-0 bg-color:transparent text:ink cursor:pointer @hover:[bg-color:paper-2]")}" style="padding-left:${8 + depth * 14}px"><span class="${ui("font:ui:tiny:semibold text:proof-2")}" title="${esc(`<${n.tag}>`)}">${esc(name)}</span>${fields}${words}</button>`);
507
+ n.children.forEach((c) => walk(c, depth + 1, n));
508
+ };
509
+ state.tree.forEach((n) => walk(n, 0));
510
+ return rows.join('');
511
+ }
512
+
513
+ // What can go inside the selected element, grouped, in words.
514
+ function paletteHtml(node) {
515
+ const paged = state.constructs.some((c) => c.kind === 'each' && c.info.paged);
516
+ const fits = (p) => {
517
+ if (p.where === 'always') return true;
518
+ if (p.where === 'item') return node.inEach;
519
+ if (p.where === 'paged') return paged && !node.inEach;
520
+ if (node.inRepeater && ['repeater', 'slot', 'page-list', 'pager'].includes(p.name)) return false;
521
+ return !node.inEach;
522
+ };
523
+ const groups = new Map();
524
+ state.system.palette.filter(fits).forEach((p) => groups.set(p.group, [...(groups.get(p.group) || []), p]));
525
+ const pending = state.pending ? (() => {
526
+ const item = state.pending;
527
+ if (item === 'page-list' || item === 'count') {
528
+ return `<div class="${ui("col gap:d2 pd:d3 bd:round-d3 bg-color:paper-2")}">${note(item === 'count' ? 'Count the pages in' : 'Show the pages in')}${select('data-pending-folder', folderOptions(), folderOptions()[0]?.value, 'Folder')}<div class="${ui("row gap:d2")}">${button('data-pending-add', 'Add', true)}${button('data-pending-cancel', 'Cancel')}</div></div>`;
529
+ }
530
+ const fields = folderFields(node.each).filter((f) => (item === 'item-image' ? f.type === 'image' : f.type !== 'image'));
531
+ if (!fields.length) return `<div class="${ui("col gap:d2 pd:d3 bd:round-d3 bg-color:paper-2")}">${note(item === 'item-image' ? 'The pages in this list have no image fields.' : 'The pages in this list have no other fields.')}${button('data-pending-cancel', 'Cancel')}</div>`;
532
+ return `<div class="${ui("col gap:d2 pd:d3 bd:round-d3 bg-color:paper-2")}">${note('Which one?')}${select('data-pending-field', fields.map((f) => ({ value: f.name, label: f.label })), fields[0].name, 'Field')}<div class="${ui("row gap:d2")}">${button('data-pending-add', 'Add', true)}${button('data-pending-cancel', 'Cancel')}</div></div>`;
533
+ })() : '';
534
+ const beside = node.void || (!node.children.length && (/^(h[1-6]|p|a|span|time|blockquote|button|strong|em|small|label|figcaption|video|iframe)$/.test(node.tag) || node.fields.length > 0 || node.refs.length > 0));
535
+ const where = beside && node.path !== '0' ? `Add after this ${esc((node.name || 'element').toLowerCase())}` : `Add inside this ${esc((node.name || 'box').toLowerCase())}`;
536
+ return `<div class="${ui("col gap:d3 pd-t:d2")}">${label(node.inEach ? `${where}: it repeats for each page in the list` : node.inRepeater ? `${where}: every item gets it` : where)}
537
+ ${[...groups].map(([group, items]) => `<div class="${ui("col gap:d1")}"><span class="${ui("font:ui:tiny text:mist")}">${esc(group)}</span><div class="${ui("row:wrap gap:d1")}">${items.map((p) => `<button data-add="${p.name}" class="${ui("h:d8 pd-x:d2 bd:round-pill bd:width-px:solid:line bg-color:paper text:ink font:ui:tiny:medium cursor:pointer @hover:[bd:proof_text:proof-2] transition:fast")}">+ ${esc(p.label)}</button>`).join('')}</div></div>`).join('')}
538
+ ${pending}</div>`;
539
+ }
540
+
541
+ // The words, references and fields of the selected element.
542
+ function contentHtml(node) {
543
+ const parts = [];
544
+ // The fields in this element, by the name writers see ("Client", not "text-2").
545
+ [...node.fields, ...node.attrFields].filter((f) => !f.name.startsWith('site.')).forEach((f) => {
546
+ const shown = f.name.replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase());
547
+ parts.push(`${label(f.type === 'image' ? 'Picture writers choose' : node.attrFields.includes(f) ? 'Set by writers' : 'Writers fill in')}<form data-rename="${esc(f.name)}" class="${ui("row gap:d2")}">${input('data-rename-input', shown, 'Name it, like Client')}${button('', 'Rename')}</form>`);
548
+ });
549
+ if (node.text != null) {
550
+ parts.push(`${label('Words')}<form data-words class="${ui("row gap:d2")}">${input('data-words-input', node.text, 'Words')}${button('', 'Save')}</form>${note('The same wherever this block is used. For words that change from page to page, add Text instead.')}`);
551
+ }
552
+ node.refs.forEach((r) => {
553
+ if (r.key === 'date') {
554
+ const fmts = [['long', 'November 16, 2026'], ['short', 'Nov 16, 2026'], ['numeric', '11/16/2026'], ['month', 'November 2026'], ['year', '2026']];
555
+ parts.push(`${label('Date looks like')}<div class="${ui("row:wrap gap:d1")}">${fmts.map(([f, ex]) => option(`data-format="${f}" data-ref="${esc(r.ref)}"`, ex, (r.format || 'long') === f)).join('')}</div>`);
556
+ } else if (!['url', 'date-iso'].includes(r.key)) {
557
+ const lengths = [['', 'All of it'], ['words-12', '12 words'], ['words-25', '25 words'], ['words-50', '50 words']];
558
+ parts.push(`${label(`${esc(r.key === 'title' ? 'Title' : r.key[0].toUpperCase() + r.key.slice(1).replace(/-/g, ' '))} length`)}<div class="${ui("row:wrap gap:d1")}">${lengths.map(([f, t]) => option(`data-format="${f}" data-ref="${esc(r.ref)}"`, t, (r.format || '') === f)).join('')}</div>`);
559
+ }
560
+ });
561
+ if (node.rich) {
562
+ const tools = [['headings', 'Headings'], ['lists', 'Lists'], ['links', 'Links'], ['images', 'Images'], ['quotes', 'Quotes'], ['tables', 'Tables'], ['callouts', 'Callouts'], ['embeds', 'Videos'], ['code', 'Code']];
563
+ parts.push(`${label('Writers can add')}<div class="${ui("row:wrap gap:d1")}">${tools.map(([t, l]) => option(`data-tool="${t}"`, l, node.rich.includes(t))).join('')}</div>${note('Paragraphs, bold and italic are always there.')}`);
564
+ }
565
+ if (!node.inEach && !node.void) {
566
+ parts.push(`${label('Colour chosen on the page')}<div class="${ui("row:wrap gap:d1")}">${option('data-colour="background"', 'Background', node.colors.background)}${option('data-colour="text"', 'Text', node.colors.text)}</div>${note('Writers pick from the site\'s colours.')}`);
567
+ }
568
+ if (node.path !== '0' && node.path.includes('.')) {
569
+ if (!state.conditionOpen) parts.push(button('data-condition-open', `${svg('when', 14)} Show only when…`));
570
+ else {
571
+ const targets = conditionTargets(node);
572
+ parts.push(`<form data-condition class="${ui("col gap:d2 pd:d3 bd:round-d3 bg-color:paper-2")}">${note('Show this only when')}
573
+ ${select('data-c-target', targets, (targets.find((t) => node.fields.some((f) => f.name === t.value)) || targets[0])?.value, 'What to check')}
574
+ ${select('data-c-op', [{ value: 'filled', label: 'is filled in' }, { value: 'empty', label: 'is empty' }, { value: 'is', label: 'is' }, { value: 'not', label: 'isn\'t' }], 'filled', 'How')}
575
+ ${input('data-c-value', '', 'Value, for is and isn\'t')}
576
+ <div class="${ui("row gap:d2")}">${button('', 'Add the condition', true)}${button('data-condition-cancel type="button"', 'Cancel')}</div></form>`);
577
+ }
578
+ }
579
+ return parts.length ? section('Content', parts.join('')) : '';
580
+ }
581
+
582
+ // What a condition can check: inside a list of items, the item's own
583
+ // fields first; inside a list of pages, each page's; then the block's
584
+ // own fields and the page's settings.
585
+ function conditionTargets(node) {
586
+ const seen = new Set();
587
+ const items = node && node.repeater != null ? state.targets.items[node.repeater] || [] : [];
588
+ const each = node && node.each != null ? state.targets.each[node.each] || [] : [];
589
+ const own = node && node.repeater != null ? [] : state.targets.own;
590
+ return [...items, ...each, ...own, ...state.targets.page].filter((t) => !seen.has(t.value) && seen.add(t.value));
591
+ }
592
+
593
+ // A list of pages, a condition or a list of items, selected in the tree.
594
+ function constructHtml(c) {
595
+ const head = `<div class="${ui("col gap:d2 pd:d4")}"><div class="${ui("row:y-center gap:d2 text:proof-2")}">${svg(CONSTRUCT_ICON[c.kind], 18)}<h2 class="${ui("font:ui:small:semibold text:ink")}">${esc(c.label)}</h2></div></div>`;
596
+ const otherwise = (what) => `${label(what)}<form data-otherwise class="${ui("row gap:d2")}">${input('data-otherwise-input', c.otherwise ?? '', 'Leave empty to show nothing')}${button('', 'Save')}</form>`;
597
+ if (c.kind === 'each') {
598
+ const i = c.info;
599
+ const tagLists = ['tags', 'item.tags', 'all-tags', 'tagged'].includes(i.section);
600
+ const folder = state.system.folders.find((f) => f.name === i.section);
601
+ const fields = folder ? folder.fields : [];
602
+ const filters = i.filters.map((f, n) => {
603
+ const text = f.type === 'tagged' ? `Tagged ${f.value}` : f.type === 'has' ? `${f.field} is filled in` : f.type === 'no' ? `${f.field} is empty` : `${f.field} ${f.type === 'is' ? 'is' : 'isn\'t'} ${f.value}`;
604
+ return `<span class="${ui("row:y-center gap:d1 h:d8 pd-l:d3 pd-r:d1 bd:round-pill bg-color:paper-2 font:ui:tiny:medium")}">${esc(text)}<button data-filter-remove="${n}" aria-label="Remove this filter" class="${ui("row:x-center:y-center w:d6 h:d6 bd:round-full bd:width-0 bg-color:transparent text:ink-3 cursor:pointer @hover:[text:proof-2]")}">×</button></span>`;
605
+ }).join('');
606
+ const tagOptions = (folder?.tags || []).map((t) => ({ value: `tagged:${t}`, label: `Tagged ${t}` }));
607
+ const filterOptions = [...tagOptions, ...fields.flatMap((f) => [{ value: `has:${f.name}`, label: `${f.label} is filled in` }, { value: `no:${f.name}`, label: `${f.label} is empty` }, ...(f.type === 'text' ? [{ value: `is:${f.name}`, label: `${f.label} is…` }, { value: `not:${f.name}`, label: `${f.label} isn't…` }] : [])])];
608
+ return [head, section('Which pages', `
609
+ ${tagLists ? note('This list shows tags.') : select('data-list-section', folderOptions().some((o) => o.value === i.section) ? folderOptions() : [{ value: i.section, label: i.section }, ...folderOptions()], i.section, 'Folder')}
610
+ ${label('In what order')}<div class="${ui("row:wrap gap:d1")}">${[['newest', 'Newest first'], ['oldest', 'Oldest first'], ['a-z', 'A to Z'], ['z-a', 'Z to A'], ['order', 'Site order']].map(([v, t]) => option(`data-list-sort="${v}"`, t, (i.sort || (tagLists ? 'a-z' : 'newest')) === v)).join('')}</div>
611
+ ${label('How many')}<div class="${ui("row:wrap gap:d1")}">${[null, 1, 2, 3, 4, 6, 8, 10, 12, 20].map((n) => option(`data-list-limit="${n ?? ''}"`, n ?? 'All', (i.limit ?? null) === n)).join('')}</div>
612
+ ${label('Leave out the first')}<div class="${ui("row:wrap gap:d1")}">${[0, 1, 2, 3].map((n) => option(`data-list-skip="${n}"`, n || 'None', (i.skip || 0) === n)).join('')}</div>
613
+ ${tagLists ? '' : `${label('This page')}<div class="${ui("row:wrap gap:d1")}">${option('data-list-others="0"', 'Include it', !i.others)}${option('data-list-others="1"', 'Leave out this page', !!i.others)}</div>${note('Leave it out for lists like "More projects", so a page doesn\'t list itself.')}`}
614
+ ${tagLists ? '' : `${label('Pages of the list')}<div class="${ui("row:wrap gap:d1")}">${option('data-list-paged="0"', 'All on one page', !i.paged)}${option('data-list-paged="1"', 'Split into pages', i.paged)}</div>${i.paged ? note('Add "Previous and next pages" so readers can move between them.') : note('Pick how many first, then split, to show that many per page.')}`}`),
615
+ tagLists ? '' : section('Only some of them', `${filters ? `<div class="${ui("row:wrap gap:d1")}">${filters}</div>` : note('Every page in the folder shows.')}
616
+ ${filterOptions.length ? `<form data-filter class="${ui("col gap:d2")}">${select('data-filter-kind', filterOptions, filterOptions[0].value, 'Filter')}${input('data-filter-value', '', 'Value, for is and isn\'t')}${button('', 'Add the filter')}</form>` : ''}`),
617
+ c.box ? section('Its box', `${button(`data-select="${esc(c.box)}"`, 'Style the box around the list')}`) : '',
618
+ section('When there are none', otherwise('Show these words')),
619
+ section('Remove', `${button('data-unwrap-construct', 'Stop repeating: keep one card, without the list')}`),
620
+ ].join('');
621
+ }
622
+ if (c.kind === 'if') {
623
+ const i = c.info;
624
+ const node = find(c.first);
625
+ const targets = [...conditionTargets(node), ...(i.target.startsWith('paging.') ? [{ value: i.target, label: i.target === 'paging.next' ? 'There\'s a next page' : 'There\'s a previous page' }] : [])];
626
+ if (!targets.some((t) => t.value === i.target)) targets.unshift({ value: i.target, label: i.target });
627
+ return [head, section('Show it only when', `
628
+ ${select('data-cond-target', targets, i.target, 'What to check')}
629
+ <div class="${ui("row:wrap gap:d1")}">${[['filled', 'is filled in'], ['empty', 'is empty'], ['is', 'is…'], ['not', 'isn\'t…']].map(([v, t]) => option(`data-cond-op="${v}"`, t, i.op === v)).join('')}</div>
630
+ ${i.op === 'is' || i.op === 'not' ? `<form data-cond-value class="${ui("row gap:d2")}">${input('data-cond-value-input', i.value, 'Value')}${button('', 'Save')}</form>` : ''}`),
631
+ section('Otherwise show', `<div class="${ui("row:wrap gap:d1")}">${option('data-ow="nothing"', 'Nothing', c.otherwiseKind === 'nothing' && !state.otherwiseWords)}${option('data-ow="words"', 'Words', c.otherwiseKind === 'words' || state.otherwiseWords)}${option('data-ow="next"', c.otherwiseKind === 'element' ? 'Another element' : 'The element after it', c.otherwiseKind === 'element')}</div>
632
+ ${c.otherwiseKind === 'words' || state.otherwiseWords ? `<form data-otherwise class="${ui("row gap:d2")}">${input('data-otherwise-input', c.otherwise ?? '', 'Words to show instead')}${button('', 'Save')}</form>` : ''}
633
+ ${c.otherwiseKind === 'element' ? note('The element under Otherwise in the tree shows when this one doesn\'t. Select it there to change it.') : c.otherwiseKind === 'nothing' && !state.otherwiseWords ? note('To show a plain version instead, put it right after this element in the tree, then choose The element after it.') : ''}`),
634
+ section('Remove', button('data-unwrap-construct', 'Always show it')),
635
+ ].join('');
636
+ }
637
+ // A list of items: name it ("People" makes the button "Add to People").
638
+ const shown = String(c.info.name || '').replace(/-/g, ' ').replace(/^./, (ch) => ch.toUpperCase());
639
+ return [head, section('Items', `${label('Name of the list')}<form data-rename="${esc(c.info.name)}" class="${ui("row gap:d2")}">${input('data-rename-input', shown, 'Name it, like People')}${button('', 'Rename')}</form>
640
+ ${note(`Writers add, move and remove items right on the page with "Add to ${esc(shown)}". What goes in each item is the element inside, so build one item here and every item looks the same.`)}`),
641
+ c.box ? section('Its box', `${button(`data-select="${esc(c.box)}"`, 'Style the box around the list')}`) : ''].join('');
642
+ }
643
+
644
+ // How many columns a grid has, for phones, tablets and desktops at once.
645
+ // Each width only changes from that width up (mobile first).
646
+ function columnsHtml(node) {
647
+ // The smallest size, then every size where it's set, then the current
648
+ // size; with few sizes, all of them.
649
+ const list = screens();
650
+ const show = list.length <= 3 ? list : list.filter((b) => b.name === state.bp || (node.picks[b.name] || {}).columns || ['md', 'lg'].includes(b.name));
651
+ const widths = [['', 'Smallest screens'], ...show.map((b) => [b.name, `${b.label} and up`])];
652
+ const row = ([bp, text]) => {
653
+ const current = (node.picks[bp] || {}).columns || null;
654
+ const opts = [1, 2, 3, 4, 5, 6].map((n) => {
655
+ const on = String(n) === current;
656
+ return `<button data-cols="${n}" data-cols-bp="${bp}" aria-pressed="${on}" title="${n} across ${text.toLowerCase()}" class="${on ? ui("row:x-center:y-center w:d8 h:d8 bd:round-d2 bd:width-px:solid:proof bg-color:proof-soft text:proof-2 font:ui:tiny:semibold cursor:pointer") : ui("row:x-center:y-center w:d8 h:d8 bd:round-d2 bd:width-px:solid:line bg-color:paper text:ink-3 font:ui:tiny cursor:pointer @hover:[bd:ink-3] transition:fast")}">${n}</button>`;
657
+ }).join('');
658
+ const same = bp && !current ? `<span class="${ui("font:ui:tiny text:mist")}">Same as smaller</span>` : '';
659
+ return `<div class="${ui("col gap:d1")}">${label(text)}<div class="${ui("row:wrap:y-center gap:d1")}">${opts}${same}</div></div>`;
660
+ };
661
+ return `${label('Columns')}<div class="${ui("col gap:d3")}">${widths.map(row).join('')}</div>`;
662
+ }
663
+
664
+ function renderInspector() {
665
+ const panel = q('[data-inspector]');
666
+ const c = construct();
667
+ const node = c ? null : find(state.selected);
668
+ if (!state.system || (!node && !c)) {
669
+ panel.innerHTML = '';
670
+ return;
671
+ }
672
+ const s = state.system;
673
+ const tool = (op, name, title, extra = '') => `<button data-op="${op}" ${extra} title="${title}" aria-label="${title}" class="${ui("row:x-center:y-center w:d8 h:d8 bd:round-d2 bd:width-px:solid:line bg-color:paper text:ink cursor:pointer @hover:[bd:ink-3] transition:fast")}">${svg(name, 16)}</button>`;
674
+ const elements = `<div class="${ui("col gap:d2 pd:d4")}">
675
+ <div class="${ui("row:y-center:x-between")}"><h2 class="${ui("font:ui:small:semibold")}">Elements</h2>
676
+ ${node ? `<div class="${ui("row gap:d1")}">${tool('move', 'up', 'Move up', 'data-dir="-1"')}${tool('move', 'down', 'Move down', 'data-dir="1"')}${tool('duplicate', 'copy', 'Make a copy')}${tool('wrap', 'wrap', 'Wrap in a box')}${tool('unwrap', 'unwrap', 'Unwrap')}${tool('remove', 'trash', 'Remove')}</div>` : ''}</div>
677
+ <div class="${ui("col gap:d0")}">${treeRows()}</div>
678
+ ${node ? paletteHtml(node) : ''}
679
+ </div>`;
680
+
681
+ if (c) {
682
+ panel.innerHTML = elements + constructHtml(c);
683
+ } else {
684
+ const picks = node.picks[state.bp] || {};
685
+ const others = screens().filter((b) => b.name !== state.bp && setAt(node, b.name)).map((b) => b.label);
686
+ const bpNote = state.bp
687
+ ? `<p class="${ui("pd:d2:d4 bg-color:proof-soft text:proof-2 font:ui:tiny")}">Choices apply to ${esc(screenWords(state.bp).toLowerCase())} and wider, from ${esc(String(screenOf(state.bp)?.px ?? ''))}px. A dashed choice comes from a smaller size.</p>`
688
+ : others.length ? `<p class="${ui("pd:d2:d4 bg-color:paper-2 text:ink-3 font:ui:tiny")}">This element also changes on ${esc(others.join(', ').toLowerCase())}. Pick a size above to see those.</p>` : '';
689
+ // What each choice is when this size sets nothing: the nearest smaller
690
+ // size that does (mobile first).
691
+ const order = ['', ...screens().map((b) => b.name)];
692
+ const below = order.slice(0, Math.max(0, order.indexOf(state.bp)));
693
+ state.inherit = {};
694
+ Object.keys(picks).concat(Object.keys(node.picks[''] || {})).forEach((k) => {
695
+ if (picks[k] != null) return;
696
+ for (let i = below.length - 1; i >= 0; i -= 1) {
697
+ const v = (node.picks[below[i]] || {})[k];
698
+ if (v != null) { state.inherit[k] = v; break; }
699
+ }
700
+ });
701
+ const fonts = s.families;
702
+ panel.innerHTML = [
703
+ elements,
704
+ contentHtml(node),
705
+ node.tag === 'img' ? section('Shape', `<div class="${ui("row:wrap gap:d1")}">${[['', 'As it is'], ['landscape', 'Landscape'], ['square', 'Square'], ['portrait', 'Portrait'], ['video', 'Wide']].map(([v, t]) => option(`data-ratio="${v}"`, t, (node.ratio || '') === v)).join('')}</div>${note('One shape for every picture keeps the tops of a grid in line. Pictures are cropped to fit.')}`) : '',
706
+ bpNote,
707
+ node.path === '0' || /\bcontain\b/.test(node.classes) ? section('Width', `<div class="${ui("row:wrap gap:d1")}">${option('data-page-width="0"', 'Full width', !/\bcontain\b/.test(node.classes))}${option('data-page-width="1"', 'Page width', /\bcontain\b/.test(node.classes))}</div>${note('Page width lines this up with the rest of the site.')}`) : '',
708
+ section('Layout', `
709
+ ${chips([chip('layout', '', picks.layout || (state.bp ? null : ''), 'None', 'No layout'), ...['row', 'col', 'stack', 'grid'].map((l) => chip('layout', l, picks.layout, { row: 'Row', col: 'Column', stack: 'Stack', grid: 'Grid' }[l]))])}
710
+ ${(node.picks[''] || {}).layout === 'grid' || picks.layout === 'grid' ? columnsHtml(node) : ''}
711
+ ${['row', 'col'].includes(picks.layout || state.inherit.layout) ? `${label('Across')}${chips(s.xAxis.map((a) => chip('align-x', a, picks['align-x'], esc(a.replace('x-', '')))))}${label('Down')}${chips(s.yAxis.map((a) => chip('align-y', a, picks['align-y'], esc(a.replace('y-', '')))))}` : ''}`),
712
+ section('Spacing', `${label('Inside (padding)')}${ruler('padding', picks.padding, s.spacing.slice(0, 16))}${label('Between children (gap)')}${ruler('gap', picks.gap, s.spacing.slice(0, 12))}${label('Outside (margin)')}${ruler('margin', picks.margin, s.spacing.slice(0, 12))}`),
713
+ section('Colour', `${label('Background')}${swatches('background', picks.background)}${label('Text')}${swatches('text-color', picks['text-color'])}`),
714
+ section('Type', `${label('Typeface')}${chips(fonts.map((f) => chip('family', f.name, picks.family, `<span style="font-family:${esc(f.value)};font-size:16px">Aa</span><span>${esc(f.name)}</span>`, f.value)))}
715
+ ${label('Size')}${chips(s.sizes.map((f) => chip('size', f.name, picks.size, esc(f.name), f.value)))}
716
+ ${label('Weight')}${chips(s.weights.map((f) => chip('weight', f.name, picks.weight, `<span style="font-weight:${esc(f.value)}">${esc(f.name)}</span>`)))}
717
+ ${label('Line height')}${chips(s.leading.map((f) => chip('leading', f.name, picks.leading, esc(f.name), f.value)))}`),
718
+ section('Corners and shadow', `${label('Rounding')}${chips(s.spacing.slice(0, 10).map((t) => chip('radius', t.name, picks.radius, `<span style="width:16px;height:16px;border:2px solid currentColor;border-radius:${Math.min(8, (rem(t.value) ?? 0) / 2)}px"></span>`, `${t.name} (${t.value})`)))}
719
+ ${label('Shadow')}${chips(s.shadows.map((t) => chip('shadow', t.name, picks.shadow, `<span style="width:22px;height:14px;background:#fff;border-radius:3px;box-shadow:${esc(t.value)}"></span>`, t.name)))}`),
720
+ section('Classes', `<p class="${ui("font:mono:tiny text:ink-3")}" style="word-break:break-word">${esc(node.classes) || '—'}</p><p class="${ui("font:ui:tiny text:mist")}">Choices above change only their own part of this list. Anything else in it was written by hand and is kept.</p>`),
721
+ ].join('');
722
+ }
723
+ wireInspector(panel, c, node);
724
+ // The size buttons mark where the selected element has its own styles.
725
+ if (state.system) renderHeader();
726
+ }
727
+
728
+ function wireInspector(panel, c, node) {
729
+ const on = (sel, ev, fn) => panel.querySelectorAll(sel).forEach((b) => b.addEventListener(ev, fn));
730
+ on('[data-select]', 'click', (e) => { state.selected = e.currentTarget.dataset.select; state.pending = null; state.conditionOpen = false; state.markPreview?.(); renderInspector(); });
731
+ on('[data-add]', 'click', (e) => {
732
+ const item = e.currentTarget.dataset.add;
733
+ if (['page-list', 'count', 'item-image', 'item-text'].includes(item)) { state.pending = item; renderInspector(); return; }
734
+ edit({ op: 'insert', path: state.selected, item });
735
+ });
736
+ on('[data-pending-cancel]', 'click', () => { state.pending = null; renderInspector(); });
737
+ on('[data-pending-add]', 'click', () => {
738
+ const folder = panel.querySelector('[data-pending-folder]')?.value;
739
+ const field = panel.querySelector('[data-pending-field]')?.value;
740
+ edit({ op: 'insert', path: state.selected, item: state.pending, options: folder ? { folder } : { field } });
741
+ });
742
+ on('[data-op]', 'click', (e) => edit({ op: e.currentTarget.dataset.op, path: state.selected, dir: Number(e.currentTarget.dataset.dir || 0) }));
743
+ on('[data-cols]', 'click', (e) => {
744
+ const b = e.currentTarget;
745
+ const bp = b.dataset.colsBp || null;
746
+ const current = (find(state.selected).picks[bp || ''] || {}).columns;
747
+ edit({ op: 'pick', path: state.selected, picker: 'columns', value: b.dataset.cols === current ? null : b.dataset.cols, bp });
748
+ });
749
+ on('[data-pick]', 'click', (e) => {
750
+ const b = e.currentTarget;
751
+ const current = (find(state.selected).picks[state.bp] || {})[b.dataset.pick];
752
+ const value = b.dataset.value === current ? null : b.dataset.value || null;
753
+ // Pressed at once, and a colour on the preview at once.
754
+ panel.querySelectorAll(`[data-pick="${b.dataset.pick}"]`).forEach((x) => { const on = x === b && !!value; x.setAttribute('aria-pressed', String(on)); x.style.boxShadow = on ? '0 0 0 2px #FF4F2B' : ''; });
755
+ if (instant[b.dataset.pick]) showNow(b.dataset.pick, value ? b.style.background : '');
756
+ edit({ op: 'pick', path: state.selected, picker: b.dataset.pick, value, bp: state.bp || null });
757
+ });
758
+ // Content
759
+ on('[data-words]', 'submit', (e) => { e.preventDefault(); edit({ op: 'text', path: state.selected, text: panel.querySelector('[data-words-input]').value }); });
760
+ on('[data-page-width]', 'click', (e) => edit({ op: 'page-width', path: state.selected, on: e.currentTarget.dataset.pageWidth === '1' }));
761
+ on('[data-rename]', 'submit', (e) => { e.preventDefault(); edit({ op: 'rename-field', from: e.currentTarget.dataset.rename, to: e.currentTarget.querySelector('[data-rename-input]').value }); });
762
+ on('[data-format]', 'click', (e) => edit({ op: 'format', path: state.selected, ref: e.currentTarget.dataset.ref, format: e.currentTarget.dataset.format || null }));
763
+ on('[data-tool]', 'click', (e) => {
764
+ const t = e.currentTarget.dataset.tool;
765
+ const tools = node.rich.includes(t) ? node.rich.filter((x) => x !== t) : [...node.rich, t];
766
+ edit({ op: 'tools', path: state.selected, tools });
767
+ });
768
+ on('[data-colour]', 'click', (e) => edit({ op: 'color', path: state.selected, prop: e.currentTarget.dataset.colour, on: !node.colors[e.currentTarget.dataset.colour] }));
769
+ on('[data-ratio]', 'click', (e) => edit({ op: 'ratio', path: state.selected, value: e.currentTarget.dataset.ratio || null }));
770
+ on('[data-condition-open]', 'click', () => { state.conditionOpen = true; renderInspector(); });
771
+ on('[data-condition-cancel]', 'click', () => { state.conditionOpen = false; renderInspector(); });
772
+ on('[data-condition]', 'submit', (e) => {
773
+ e.preventDefault();
774
+ edit({ op: 'condition', path: state.selected, info: { target: panel.querySelector('[data-c-target]').value, op: panel.querySelector('[data-c-op]').value, value: panel.querySelector('[data-c-value]').value } });
775
+ });
776
+ if (!c) return;
777
+ // Lists and conditions
778
+ const setList = (info) => edit({ op: 'list', id: c.id, info });
779
+ on('[data-list-section]', 'change', (e) => setList({ section: e.currentTarget.value }));
780
+ on('[data-list-sort]', 'click', (e) => setList({ sort: e.currentTarget.dataset.listSort }));
781
+ on('[data-list-limit]', 'click', (e) => {
782
+ const limit = e.currentTarget.dataset.listLimit ? Number(e.currentTarget.dataset.listLimit) : null;
783
+ setList({ limit, paged: limit ? c.info.paged : false });
784
+ });
785
+ on('[data-list-skip]', 'click', (e) => setList({ skip: Number(e.currentTarget.dataset.listSkip) }));
786
+ on('[data-list-others]', 'click', (e) => setList({ others: e.currentTarget.dataset.listOthers === '1' }));
787
+ on('[data-list-paged]', 'click', (e) => setList({ paged: e.currentTarget.dataset.listPaged === '1', limit: c.info.limit || (e.currentTarget.dataset.listPaged === '1' ? 10 : null) }));
788
+ on('[data-filter-remove]', 'click', (e) => setList({ filters: c.info.filters.filter((_, n) => n !== Number(e.currentTarget.dataset.filterRemove)) }));
789
+ on('[data-filter]', 'submit', (e) => {
790
+ e.preventDefault();
791
+ const [type, ...rest] = panel.querySelector('[data-filter-kind]').value.split(':');
792
+ const what = rest.join(':');
793
+ const value = panel.querySelector('[data-filter-value]').value.trim();
794
+ const f = type === 'tagged' ? { type, value: what } : type === 'has' || type === 'no' ? { type, field: what } : { type, field: what, value };
795
+ setList({ filters: [...c.info.filters, f] });
796
+ });
797
+ on('[data-ow]', 'click', async (e) => {
798
+ const want = e.currentTarget.dataset.ow;
799
+ if (want === 'next') { if (c.otherwiseKind !== 'element') edit({ op: 'otherwise-next', id: c.id }); return; }
800
+ if (c.otherwiseKind === 'element') await edit({ op: 'otherwise-out', id: c.id });
801
+ if (want === 'nothing') { state.otherwiseWords = false; if (c.otherwiseKind === 'words') edit({ op: 'otherwise', id: c.id, text: null }); else renderInspector(); return; }
802
+ state.otherwiseWords = true;
803
+ renderInspector();
804
+ });
805
+ on('[data-otherwise]', 'submit', (e) => {
806
+ e.preventDefault();
807
+ const text = panel.querySelector('[data-otherwise-input]').value.trim();
808
+ edit({ op: 'otherwise', id: c.id, text: text || null });
809
+ });
810
+ on('[data-unwrap-construct]', 'click', () => { state.selected = c.first || '0'; edit({ op: 'unwrap-construct', id: c.id }); });
811
+ on('[data-cond-target]', 'change', (e) => edit({ op: 'condition-set', id: c.id, info: { target: e.currentTarget.value } }));
812
+ on('[data-cond-op]', 'click', (e) => {
813
+ const op = e.currentTarget.dataset.condOp;
814
+ if ((op === 'is' || op === 'not') && !c.info.value) { c.info.op = op; renderInspector(); return; }
815
+ edit({ op: 'condition-set', id: c.id, info: { op } });
816
+ });
817
+ on('[data-cond-value]', 'submit', (e) => { e.preventDefault(); edit({ op: 'condition-set', id: c.id, info: { op: c.info.op, value: panel.querySelector('[data-cond-value-input]').value } }); });
818
+ }
819
+ }