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,1195 @@
1
+ // The Design panel: the site's colours, type, spacing, shadows and gradients,
2
+ // shown as themselves. Adding one writes elevate/design/tokens.json, Elevate
3
+ // recompiles, and the page's stylesheet is swapped without a reload.
4
+
5
+ const TABS = [
6
+ { id: 'colours', label: 'Colours' },
7
+ { id: 'type', label: 'Type' },
8
+ { id: 'spacing', label: 'Spacing' },
9
+ { id: 'effects', label: 'Effects' },
10
+ { id: 'text', label: 'Text' },
11
+ { id: 'screens', label: 'Screens' },
12
+ ];
13
+
14
+ // Text styles: one sample of everything rich text can hold, styled with the
15
+ // site's real classes.
16
+ const SAMPLE = `<h2>A large heading</h2>
17
+ <p>A paragraph of body text, with <a href="#">a link</a>, <strong>bold words</strong>, <em>italic words</em> and <code>inline code</code>. It runs long enough to show how lines sit together.</p>
18
+ <h3>A medium heading</h3>
19
+ <ul><li>A bulleted list</li><li>With a second item</li></ul>
20
+ <ol><li>A numbered list</li><li>With a second item</li></ol>
21
+ <h4>A small heading</h4>
22
+ <blockquote><p>A quote, set apart from the text around it.</p></blockquote>
23
+ <aside><p><strong>Note:</strong> a callout, for things readers shouldn't miss.</p></aside>
24
+ <pre><code>a code block {
25
+ keeps its spacing
26
+ }</code></pre>
27
+ <figure><img alt="" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='640' height='300'%3E%3Crect width='640' height='300' fill='%23d9d9d4'/%3E%3Cpath d='M0 300 L220 140 L360 240 L470 170 L640 300Z' fill='%23bdbdb6'/%3E%3C/svg%3E"><figcaption>A caption under a picture.</figcaption></figure>
28
+ <table><tbody><tr><th>Table heading</th><th>Another</th></tr><tr><td>A cell</td><td>Another cell</td></tr></tbody></table>`;
29
+
30
+ // What each picker is called, and which ones choose colours.
31
+ const STYLE_PICKERS = [
32
+ ['family', 'Font'], ['size', 'Size'], ['weight', 'Weight'], ['leading', 'Line height'],
33
+ ['text-color', 'Colour'], ['background', 'Background'],
34
+ ['margin-top', 'Space above'], ['margin-bottom', 'Space below'], ['padding', 'Padding'], ['radius', 'Corners'],
35
+ ];
36
+ const COLOUR_PICKERS = ['text-color', 'background'];
37
+
38
+ const PALETTE = '<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3a9 9 0 1 0 0 18c1.1 0 1.6-.8 1.6-1.6 0-.5-.2-.9-.5-1.2-.3-.3-.5-.7-.5-1.2 0-.9.7-1.6 1.6-1.6H16a5 5 0 0 0 5-5C21 6.5 17 3 12 3Z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><circle cx="7.5" cy="11" r="1.4" fill="currentColor"/><circle cx="10.5" cy="7" r="1.4" fill="currentColor"/><circle cx="15" cy="7.5" r="1.4" fill="currentColor"/></svg>';
39
+
40
+ const SIDEBAR = '<svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M15 4v16" fill="none" stroke="currentColor" stroke-width="2"/></svg>';
41
+ const EXPAND = '<svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
42
+
43
+ // The brand book's chapters, in reading order. Beside the page, the same
44
+ // chapters are tabs.
45
+ const CHAPTERS = [
46
+ { id: 'colours', label: 'Colour', tab: 'colours' },
47
+ { id: 'typefaces', label: 'Typefaces', tab: 'type' },
48
+ { id: 'sizes', label: 'Type sizes', tab: 'type' },
49
+ { id: 'text', label: 'Text styles', tab: 'text' },
50
+ { id: 'spacing', label: 'Spacing', tab: 'spacing' },
51
+ { id: 'effects', label: 'Effects', tab: 'effects' },
52
+ { id: 'screens', label: 'Screens', tab: 'screens' },
53
+ ];
54
+
55
+ const family = (name) => name.replace(/[-+]\d$/, '');
56
+
57
+ // Names people read instead of the scale's own (d4, h3, c1): a heading's
58
+ // size is "Heading 3", a step of space is how far it is, like "16px".
59
+ const NICE = {
60
+ h1: 'Heading 1', h2: 'Heading 2', h3: 'Heading 3', h4: 'Heading 4', h5: 'Heading 5', h6: 'Heading 6',
61
+ base: 'Body',
62
+ };
63
+ const pixels = (v) => {
64
+ const m = /^(-?[\d.]+)(rem|px|em)$/.exec(String(v || '').trim());
65
+ if (!m) return '';
66
+ return `${+(+m[1] * (m[2] === 'px' ? 1 : 16)).toFixed(1)}px`;
67
+ };
68
+ // "clamp(1rem, 0.8rem + 1vw, 1.5rem)" → ["1rem", "1.5rem"]; "1.25rem" → both.
69
+ const sizeEnds = (value) => {
70
+ const v = String(value || '').trim();
71
+ const m = /^clamp\(\s*([\d.]+(?:rem|px|em))\s*,.*,\s*([\d.]+(?:rem|px|em))\s*\)$/.exec(v);
72
+ if (m) return [m[1], m[2]];
73
+ return /^[\d.]+(?:rem|px|em)$/.test(v) ? [v, v] : ['', ''];
74
+ };
75
+ const sizeWords = (value) => {
76
+ const [a, b] = sizeEnds(value);
77
+ if (!a) return '';
78
+ const pa = pixels(a);
79
+ const pb = pixels(b);
80
+ return pa === pb ? pa : `${parseFloat(pa)} to ${pb}`;
81
+ };
82
+ const scaleStep = (name) => /^([dcs]\d+|px|0)$/.test(name);
83
+ const niceName = (name) => {
84
+ if (name == null || name === '') return '';
85
+ if (NICE[name]) return NICE[name];
86
+ if (scaleStep(name)) return '';
87
+ const words = String(name).replace(/[-_]+/g, ' ').trim();
88
+ return words.charAt(0).toUpperCase() + words.slice(1);
89
+ };
90
+ // A token as words: "Heading 3, 32 to 44px", "16px", "Semibold, 600".
91
+ const readable = (name, value) => {
92
+ const n = niceName(name);
93
+ const size = sizeWords(value);
94
+ const plain = /^[\d.]+$/.test(String(value || '')) ? String(value) : '';
95
+ const extra = size || plain;
96
+ if (n && extra && n !== extra) return `${n}, ${extra}`;
97
+ return n || extra || name;
98
+ };
99
+ const escapeRe = (t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
100
+
101
+ export function init(verso) {
102
+ const { root, ui, toast, icon, esc } = verso;
103
+ let state = { tab: 'colours', data: null, detail: null };
104
+
105
+ const panel = document.createElement('aside');
106
+ panel.id = 'design';
107
+ // Two ways to see it: the brand book, full screen; or tucked beside the
108
+ // page, to watch the site change while you work.
109
+ const DOCKED = ui("fixed top:d3 right:d3 bottom:c3 w:sheet col bg-color:paper bd:round-d5 shadow:float bd:width-px:solid:line z:4 overflow-y:auto font:ui:small text:ink");
110
+ const FULL = ui("fixed top:0 left:0 w:full h:full col bg-color:paper text:ink font:ui:small z:6");
111
+ try { state.docked = sessionStorage.getItem('verso-design-docked') === '1'; } catch {}
112
+ panel.className = state.docked ? DOCKED : FULL;
113
+ panel.setAttribute('role', 'dialog');
114
+ panel.setAttribute('aria-label', 'Design');
115
+ panel.style.display = 'none';
116
+ root.querySelector('.-verso')?.appendChild(panel) || root.appendChild(panel);
117
+
118
+ verso.addBarButton({ id: 'open-design', title: 'Design', svg: PALETTE, onClick: () => toggle() });
119
+ setTimeout(() => {
120
+ try {
121
+ const again = JSON.parse(sessionStorage.getItem('verso-reopen-design') || 'null');
122
+ if (!again) return;
123
+ sessionStorage.removeItem('verso-reopen-design');
124
+ state.tab = again.tab || 'colours';
125
+ open();
126
+ if (again.said) toast(again.said, 'ok');
127
+ state.bookScroll = again.scroll || 0;
128
+ setTimeout(() => { (q('[data-book]') || panel).scrollTop = again.scroll || 0; }, 400);
129
+ } catch {}
130
+ }, 0);
131
+ verso.menuItems.push({ label: 'Design', icon: PALETTE, run: () => open() });
132
+
133
+ // Swap the page's stylesheet when Elevate has recompiled.
134
+ try {
135
+ const events = new EventSource('/__verso/events');
136
+ events.onmessage = (e) => {
137
+ const event = JSON.parse(e.data);
138
+ if (event.type !== 'css') return;
139
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((link) => {
140
+ if (!/\/elevate\.css/.test(link.getAttribute('href') || '')) return;
141
+ // A colour being tried stays on screen until the new stylesheet is in.
142
+ if (live && live.link === link) {
143
+ link.addEventListener('load', endPreview, { once: true });
144
+ link.disabled = false;
145
+ }
146
+ link.href = `/elevate.css?v=${Date.now()}`;
147
+ });
148
+ if (panel.style.display !== 'none') { if (state.docked && state.tab === 'text') setTimeout(drawSample, 50); else load(); }
149
+ };
150
+ } catch {
151
+ // Live updates are a convenience; a reload shows the same thing.
152
+ }
153
+
154
+ // Trying a colour: a copy of the page's stylesheet with the old colour
155
+ // swapped for the new one stands in for it until the change is saved.
156
+ let live = null;
157
+ let frame = 0;
158
+ async function previewColour(from, to) {
159
+ const link = [...document.querySelectorAll('link[rel="stylesheet"]')].find((l) => /\/elevate\.css/.test(l.getAttribute('href') || ''));
160
+ if (!link || !from) return;
161
+ if (!live) {
162
+ const style = document.createElement('style');
163
+ style.dataset.versoPreview = '';
164
+ live = { link, style, css: null };
165
+ link.after(style);
166
+ live.css = await fetch(link.href).then((r) => r.text()).catch(() => null);
167
+ if (!live?.css) { endPreview(); return; }
168
+ }
169
+ if (!live.css) return;
170
+ cancelAnimationFrame(frame);
171
+ frame = requestAnimationFrame(() => {
172
+ if (!live) return;
173
+ live.style.textContent = live.css.replace(new RegExp(escapeRe(from), 'gi'), to);
174
+ live.link.disabled = true;
175
+ });
176
+ }
177
+ function endPreview() {
178
+ cancelAnimationFrame(frame);
179
+ if (!live) return;
180
+ live.link.disabled = false;
181
+ live.style.remove();
182
+ live = null;
183
+ }
184
+
185
+ const request = async (url, body) => {
186
+ const res = await fetch(url, body === undefined ? undefined : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
187
+ const out = await res.json().catch(() => ({ ok: false, message: 'Verso didn\'t answer. Is it still running?' }));
188
+ if (out.cssProblem) toast(`Saved, but Elevate reports a problem: ${out.cssProblem.message}`, 'error');
189
+ return out;
190
+ };
191
+
192
+ async function load() {
193
+ const out = await request('/__verso/tokens');
194
+ if (!out.ok) { toast(out.message, 'error'); return; }
195
+ state.data = out;
196
+ render();
197
+ }
198
+
199
+ // The panel survives a page reload it caused itself.
200
+ const comeBack = (said) => { try { sessionStorage.setItem('verso-reopen-design', JSON.stringify({ tab: state.tab, scroll: (q('[data-book]') || panel).scrollTop, said })); } catch {} };
201
+ const forget = () => { try { sessionStorage.removeItem('verso-reopen-design'); } catch {} };
202
+
203
+ function open() {
204
+ root.getElementById('settings')?.style && (root.getElementById('settings').style.display = 'none');
205
+ panel.style.display = 'flex';
206
+ lockPage();
207
+ if (state.data) render();
208
+ load();
209
+ }
210
+ function close() { panel.style.display = 'none'; state.detail = null; endPreview(); lockPage(false); }
211
+ // Full screen, the page behind doesn't scroll.
212
+ function lockPage(on = !state.docked) { document.documentElement.style.overflow = on && panel.style.display !== 'none' ? 'hidden' : ''; }
213
+ function setDocked(docked) {
214
+ state.docked = docked;
215
+ try { sessionStorage.setItem('verso-design-docked', docked ? '1' : '0'); } catch {}
216
+ panel.className = docked ? DOCKED : FULL;
217
+ lockPage();
218
+ render();
219
+ }
220
+ panel.addEventListener('keydown', (e) => {
221
+ if (e.key !== 'Escape' || e.target.closest('input, select, textarea')) return;
222
+ if (state.detail && !state.docked) { state.detail = null; render(); return; }
223
+ close();
224
+ });
225
+ function toggle() { if (panel.style.display === 'none') open(); else close(); }
226
+
227
+ // ════ Rendering ════
228
+
229
+ const isOwn = (type, name) => !!state.data?.own?.[type] && name in state.data.own[type];
230
+
231
+ function render() {
232
+ const d = state.data;
233
+ if (!d) return;
234
+ if (!state.docked) { renderBook(); return; }
235
+ panel.innerHTML = `
236
+ <header class="${ui("col gap:d3 pd-x:d5 pd-t:d5 pd-b:d3 sticky top:0 bg-color:paper z:1")}">
237
+ <div class="${ui("row:y-center:x-between")}">
238
+ <div class="${ui("col gap:d0")}">
239
+ <h2 class="${ui("font:h6:semibold text:ink")}">Design</h2>
240
+ <p class="${ui("font:tiny text:mist")}">The site's colours, fonts and spacing. Change one and everything that uses it follows.</p>
241
+ </div>
242
+ <span class="${ui("row:y-center gap:d1 child:no-shrink")}">
243
+ <button data-expand title="Open the full brand book" class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d9 h:d9 bd:round-full text:ink @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}" aria-label="Full screen">${EXPAND}</button>
244
+ <button data-close class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d9 h:d9 bd:round-full text:ink @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}" aria-label="Close">${icon('close')}</button>
245
+ </span>
246
+ </div>
247
+ <nav class="${ui("grid:cols-3-fr:gap-d1 pd:d1 bg-color:paper-2 bd:round-d5")}" role="tablist">
248
+ ${TABS.map((t) => `<button role="tab" data-tab="${t.id}" aria-selected="${state.tab === t.id}" class="${state.tab === t.id ? ui("bd:width-0 cursor:pointer child:grow h:d8 pd-x:d2 bd:round-pill bg-color:paper text:ink font:small:semibold shadow:float") : ui("bg-color:transparent bd:width-0 cursor:pointer child:grow h:d8 pd-x:d2 bd:round-pill text:ink-3 font:small:medium @hover:[text:ink] transition:fast")}">${t.label}</button>`).join('')}
249
+ </nav>
250
+ </header>
251
+ ${d.ready ? '' : `<p class="${ui("mg-x:d5 pd:d4 bd:round-d4 bg-color:proof-soft text:ink font:small:normal")}">New colours and sizes can't be saved on this site yet. Its style settings need to load <strong>elevate/design/tokens.json</strong>, in elevate/config/design.ts.</p>`}
252
+ <div class="${ui("col gap:d6 pd-x:d5 pd-t:d3 pd-b:c3")}">${({ colours, type, spacing, effects, text, screens })[state.tab]()}</div>`;
253
+ wire();
254
+ if (state.tab === 'text') wireText();
255
+ if (state.tab === 'screens') wireScreens();
256
+ }
257
+
258
+ const section = (title, body, note = '') => `
259
+ <section class="${ui("col gap:d3")}">
260
+ <div class="${ui("col gap:d0")}">
261
+ <h3 class="${ui("font:small:medium text:mist")}">${title}</h3>
262
+ ${note ? `<p class="${ui("font:tiny text:mist")}">${note}</p>` : ''}
263
+ </div>
264
+ ${body}
265
+ </section>`;
266
+
267
+ const input = (attrs, placeholder = '') => `<input ${attrs} placeholder="${esc(placeholder)}" class="${ui("w:full h:d10 pd-x:d3 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink @focus:[bd:proof_shadow:proof-focus_outline:none] transition:fast")}">`;
268
+ const button = (attrs, label, primary = false) => `<button ${attrs} class="${primary ? ui("bd:width-0 cursor:pointer h:d10 pd-x:d4 bd:round-pill bg-color:proof text:paper font:small:semibold format:no-wrap @hover:[bg-color:proof-2] @focus-visible:[outline:d0:solid:ink] transition:fast") : ui("bd:width-px:solid:line cursor:pointer h:d10 pd-x:d4 bd:round-pill bg-color:paper text:ink font:small:semibold format:no-wrap @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">${label}</button>`;
269
+
270
+ // Where a token is used, in plain words: "3 blocks: Hero, Quote, Call to
271
+ // action; 2 page types: Page, Post". File names and lines are one click away.
272
+ const plural = (n, word) => (n === 1 ? word : word === 'article text' ? word : `${word}s`);
273
+ const usageWords = (used) => {
274
+ const groups = new Map();
275
+ used.forEach((u) => {
276
+ const g = u.group || 'file';
277
+ if (!groups.has(g)) groups.set(g, new Set());
278
+ groups.get(g).add(u.label || u.file);
279
+ });
280
+ return [...groups.entries()].map(([g, labels]) => `${labels.size} ${plural(labels.size, g)}: ${[...labels].join(', ')}`).join('; ');
281
+ };
282
+
283
+ // One of the site's own: click it to change it, rename it or remove it.
284
+ const usedIn = (name) => {
285
+ const n = state.data?.usage?.[name];
286
+ if (n == null) return '';
287
+ return n ? `Used in ${n} place${n === 1 ? '' : 's'}` : 'Not used yet';
288
+ };
289
+
290
+ // A colour can be a CSS variable, like var(--paper), so a site's own CSS can
291
+ // change it (one value per theme, say). The panel shows what it is right now
292
+ // and leaves the variable alone unless someone chooses a fixed colour.
293
+ const variableOf = (value) => (/^var\(\s*(--[\w-]+)/.exec(String(value || '')) || [])[1] || null;
294
+ const hexNow = (value) => {
295
+ const probe = document.createElement('i');
296
+ probe.style.color = value;
297
+ document.body.append(probe);
298
+ const rgb = getComputedStyle(probe).color.match(/\d+(\.\d+)?/g) || [];
299
+ probe.remove();
300
+ return rgb.length >= 3 ? '#' + rgb.slice(0, 3).map((n) => Math.round(Number(n)).toString(16).padStart(2, '0')).join('').toUpperCase() : null;
301
+ };
302
+ const tidyColour = (value) => (/^#[0-9a-f]{3,8}$/i.test(value) ? value.toUpperCase() : value);
303
+
304
+ const detail = (type, name, force = false) => {
305
+ if (!force && !state.docked) return '';
306
+ if (!state.detail || state.detail.type !== type || state.detail.name !== name) return '';
307
+ const used = state.detail.usage;
308
+ const value = state.data.own[type][name];
309
+ const isColour = type === 'ColorToken';
310
+ const variable = isColour ? variableOf(value) : null;
311
+ const hex = /^#[0-9a-f]{6}$/i.test(value) ? value : (variable || isColour ? hexNow(value) : null);
312
+ const valueEditor = isColour
313
+ ? `${variable ? `<div data-variable class="${ui("col gap:d2")}">
314
+ <p class="${ui("font:tiny text:ink-3")}">This colour comes from the CSS variable <code class="${ui("font:mono:tiny text:ink")}">${esc(variable)}</code>, so the site's own CSS can change it, for example once per theme. Here it's ${esc(hex || 'not set')}.</p>
315
+ ${button('data-fix-colour', 'Use a fixed colour instead')}
316
+ </div>` : ''}
317
+ <div data-colour-picker class="${ui("row:y-center gap:d3")}"${variable ? ' hidden' : ''}>
318
+ <input type="color" data-edit-colour value="${esc(hex || '#000000')}" aria-label="Colour" class="${ui("w:c1 h:d11 pd:d0 bd:round-d3 bd:width-px:solid:line bg-color:paper cursor:pointer child:no-shrink")}">
319
+ <p class="${ui("font:tiny text:ink-3")}">Drag to try colours. The page shows each one as you go, and nothing changes until you save.${variable ? ` Saving replaces ${esc(variable)} with this colour.` : ''}</p>
320
+ </div>
321
+ <details class="${ui("col gap:d1")}"><summary class="${ui("font:tiny text:mist cursor:pointer")}">The CSS</summary>
322
+ <div class="${ui("row:y-center gap:d2 pd-t:d1")}">${input(`data-edit-value value="${esc(value)}" aria-label="CSS value" spellcheck="false"`)}</div>
323
+ </details>`
324
+ : type === 'FontSizeToken'
325
+ ? (() => {
326
+ // A size reads as two plain sizes, for phones and wide screens;
327
+ // Verso writes the clamp() between them. The CSS is there too.
328
+ const [phone, wide] = sizeEnds(value);
329
+ return `<div class="${ui("grid:cols-2-fr:gap-d2")}">
330
+ <label class="${ui("col gap:d1 font:tiny text:ink-3")}">On phones${input(`data-size-phone value="${esc(phone)}" aria-label="Size on phones" spellcheck="false" placeholder="1rem"`)}</label>
331
+ <label class="${ui("col gap:d1 font:tiny text:ink-3")}">On wide screens${input(`data-size-wide value="${esc(wide)}" aria-label="Size on wide screens" spellcheck="false" placeholder="1.5rem"`)}</label>
332
+ </div>
333
+ <details class="${ui("col gap:d1")}"><summary class="${ui("font:tiny text:mist cursor:pointer")}">The CSS</summary>
334
+ <div class="${ui("row:y-center gap:d2 pd-t:d1")}">${input(`data-edit-value value="${esc(value)}" aria-label="CSS value" spellcheck="false"`)}</div>
335
+ </details>`;
336
+ })()
337
+ : `<div class="${ui("row:y-center gap:d2")}">${input(`data-edit-value value="${esc(value)}" aria-label="Value" spellcheck="false"`)}</div>`;
338
+ return `
339
+ <div class="${ui("col gap:d3 pd:d4 bd:round-d4 bg-color:paper-2")}" data-detail>
340
+ ${isColour ? '' : `<p class="${ui("font:small:semibold text:ink")}">${esc(readable(name, value))}</p>`}
341
+ ${used ? (used.length
342
+ ? `<p class="${ui("font:tiny text:ink-3")}">Used in ${esc(usageWords(used))}.</p>
343
+ <details class="${ui("font:tiny text:mist")}"><summary class="${ui("cursor:pointer")}">Where exactly</summary>${used.slice(0, 12).map((u) => `<p class="${ui("font:mono:tiny text:ink-3 overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(u.where || `${u.file}${u.line ? `, line ${u.line}` : ''}`)}</p>`).join('')}</details>`
344
+ : `<p class="${ui("font:tiny text:ink-3")}">Not used anywhere yet.</p>`) : `<p class="${ui("font:tiny text:mist")}">Checking where it's used…</p>`}
345
+ <div class="${ui("col gap:d2")}">
346
+ <span class="${ui("font:tiny:medium text:ink")}">${isColour ? 'Colour' : 'Value'}</span>
347
+ ${valueEditor}
348
+ <div class="${ui("row:y-center gap:d2")}">${button('data-do-value', isColour ? 'Save the colour' : 'Save', true)}${isColour ? button('data-undo-value', 'Put it back') : ''}</div>
349
+ <p class="${ui("font:tiny text:mist")}">Everything that uses ${esc(name)} changes with it.</p>
350
+ </div>
351
+ <div class="${ui("col gap:d2")}">
352
+ <span class="${ui("font:tiny:medium text:ink")}">Name</span>
353
+ <div class="${ui("row:y-center gap:d2")}">${input(`data-rename value="${esc(name)}" aria-label="New name"`)}${button('data-do-rename', 'Rename')}</div>
354
+ <p class="${ui("font:tiny text:mist")}">Pages and blocks that use it follow the new name.</p>
355
+ </div>
356
+ ${button('data-do-remove', used && used.length ? 'Remove anyway' : 'Remove')}
357
+ </div>`;
358
+ };
359
+
360
+ // ════ The brand book ════
361
+ // Full screen: a cover set in the site's own type and colours, then one
362
+ // chapter after another. Picking anything opens it in a drawer, so the page
363
+ // never shifts under you.
364
+
365
+ // The site's look, read from the page itself: its heading and body fonts,
366
+ // the colour behind its headline, and the headline's colour.
367
+ function brandLook() {
368
+ const h = document.querySelector('main h1, h1, main h2, h2');
369
+ const p = document.querySelector('main p, p');
370
+ const behind = (el) => {
371
+ for (let n = el; n && n.nodeType === 1; n = n.parentElement) {
372
+ const bg = getComputedStyle(n).backgroundColor;
373
+ if (bg && !/rgba\(0, 0, 0, 0\)|transparent/.test(bg)) return bg;
374
+ }
375
+ return '#FFFFFF';
376
+ };
377
+ const words = (h?.textContent || '').replace(/\s+/g, ' ').trim();
378
+ return {
379
+ heading: h ? getComputedStyle(h).fontFamily : 'inherit',
380
+ body: p ? getComputedStyle(p).fontFamily : 'inherit',
381
+ bg: behind(h || document.body),
382
+ fg: h ? getComputedStyle(h).color : '#151518',
383
+ line: words.length > 44 ? `${words.slice(0, 42).replace(/\s+\S*$/, '')}…` : words,
384
+ };
385
+ }
386
+
387
+ const chapter = (id, title, intro, body) => `
388
+ <section id="design-${id}" data-chapter="${id}" class="${ui("col gap:d8 pd-t:c2 bd-t:width-px:solid:line")}">
389
+ <div class="${ui("col gap:d2")}">
390
+ <h3 class="${ui("font:h4:semibold text:ink")}">${title}</h3>
391
+ <p class="${ui("font:base text:ink-3")}" style="max-width:62ch">${intro}</p>
392
+ </div>
393
+ ${body}
394
+ </section>`;
395
+
396
+ const sub = (title, body, note = '') => `
397
+ <div class="${ui("col gap:d4")}">
398
+ <div class="${ui("col gap:d0")}">
399
+ <h4 class="${ui("font:small:semibold text:ink")}">${title}</h4>
400
+ ${note ? `<p class="${ui("font:small text:mist")}" style="max-width:62ch">${note}</p>` : ''}
401
+ </div>
402
+ ${body}
403
+ </div>`;
404
+
405
+ function cover(look) {
406
+ const own = state.data.own.ColorToken || {};
407
+ const band = Object.values(own).map((v) => `<span style="flex:1;background:${esc(v)}"></span>`).join('');
408
+ const name = verso.data.siteName || document.title || 'This site';
409
+ return `
410
+ <div class="${ui("col")}" style="background:${esc(look.bg)};color:${esc(look.fg)}">
411
+ <div class="${ui("col gap:d5 pd-x:d6 pd-t:c4 pd-b:c3 /lg/ pd-x:c2")}">
412
+ <h1 style="font-family:${esc(look.heading)};font-size:clamp(3rem,7vw,6.5rem);line-height:1;letter-spacing:-0.02em;max-width:14ch">${esc(name)}</h1>
413
+ <p class="${ui("font:base")}" style="max-width:52ch;opacity:.78">The colours, typefaces and spacing this site is made from. Change one here and every page that uses it follows.</p>
414
+ </div>
415
+ ${band ? `<div style="display:flex;height:20px;box-shadow:0 -1px 0 rgba(0,0,0,.08)">${band}</div>` : ''}
416
+ </div>`;
417
+ }
418
+
419
+ // ── Colour, as joined strips, the way paint chips sit in a swatch book ──
420
+ function bookColours() {
421
+ const own = state.data.own.ColorToken || {};
422
+ const all = state.data.tokens.ColorToken || {};
423
+ const families = {};
424
+ Object.keys(own).forEach((n) => { (families[family(n)] ||= []).push(n); });
425
+ const ramps = Object.values(families).filter((names) => names.length > 1);
426
+ const singles = Object.values(families).filter((names) => names.length === 1).flat();
427
+ const rows = [...ramps];
428
+ for (let i = 0; i < singles.length; i += 6) rows.push(singles.slice(i, i + 6));
429
+ const chip = (n) => {
430
+ const on = state.detail?.type === 'ColorToken' && state.detail.name === n;
431
+ return `<button data-token="ColorToken" data-name="${esc(n)}" aria-pressed="${on}" title="${esc(n)} ${esc(own[n])}" style="flex:1 1 0" class="${ui("col bd:width-0 pd:d0 bg-color:paper text:ink text:left cursor:pointer min-w:0 @focus-visible:[outline:d0:solid:proof]")}">
432
+ <span data-swatch="${esc(n)}" class="${ui("block w:full h:c7")}" style="background:${esc(own[n])};${on ? 'box-shadow:inset 0 0 0 3px #FF4F2B' : ''}"></span>
433
+ <span class="${ui("col gap:d0 pd:d3 min-w:0")}">
434
+ <span class="${ui("font:small:semibold text:ink overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(n)}</span>
435
+ <span class="${ui("font:tiny text:ink-3")}">${esc(own[n])}</span>
436
+ <span class="${ui("font:tiny text:mist")}">${usedIn(n)}</span>
437
+ </span>
438
+ </button>`;
439
+ };
440
+ const strips = rows.map((names) => `<div class="${ui("row gap:px bg-color:line bd:round-d4 bd:width-px:solid:line overflow:hidden")}">${names.map(chip).join('')}</div>`).join('');
441
+ const groups = {};
442
+ Object.keys(all).filter((n) => !(n in own)).forEach((n) => { (groups[family(n)] ||= []).push(n); });
443
+ const builtIn = Object.entries(groups).map(([g, names]) => `
444
+ <div class="${ui("row:y-center gap:d4")}">
445
+ <span class="${ui("w:c4 child:no-shrink font:tiny text:ink-3")}">${esc(g)}</span>
446
+ <div class="${ui("row child:grow bd:round-d2 overflow:hidden")}">${names.map((n) => `<button data-token="ColorToken" data-name="${esc(n)}" title="${esc(n)} ${esc(all[n])}" class="${ui("bd:width-0 cursor:pointer pd:d0 bg-color:transparent child:grow h:d8")}" style="background:${esc(all[n])}"></button>`).join('')}</div>
447
+ </div>`).join('');
448
+ return chapter('colours', 'Colour', 'Every colour the site uses, with where each one appears. Pick one to change it; everything that uses it follows.', `
449
+ ${strips || `<p class="${ui("font:small text:ink-3")}">This site doesn't have colours of its own yet. Add the first one below.</p>`}
450
+ ${sub('Add a colour', `
451
+ <div class="${ui("row:y-center:wrap gap:d3")}">
452
+ <input type="color" data-new-colour value="#B8471F" aria-label="Colour" class="${ui("w:c3 h:c3 pd:d0 bd:round-d3 bd:width-px:solid:line bg-color:paper cursor:pointer child:no-shrink")}">
453
+ <span class="${ui("child:grow")}" style="max-width:22rem">${input('data-new-colour-name', 'Name, like brand')}</span>
454
+ ${button('data-add-colour', 'Add colour', true)}${button('data-preview-ramp', 'Make nine shades')}
455
+ </div>
456
+ <div data-ramp></div>`, 'One colour, or nine shades from dark to light around it.')}
457
+ <details class="${ui("col gap:d3")}">
458
+ <summary class="${ui("font:small:semibold text:ink cursor:pointer")}">Elevate's built-in colours</summary>
459
+ <div class="${ui("col gap:d2 pd-t:d4")}">${builtIn}</div>
460
+ </details>`);
461
+ }
462
+
463
+ // ── Typefaces, as specimens ──
464
+ function bookTypefaces(look) {
465
+ const fam = state.data.tokens.FontFamilyToken || {};
466
+ const own = state.data.own.FontFamilyToken || {};
467
+ const order = [...Object.keys(fam).filter((n) => n in own), ...Object.keys(fam).filter((n) => !(n in own))];
468
+ const card = (n) => {
469
+ const v = fam[n];
470
+ const on = state.detail?.type === 'FontFamilyToken' && state.detail.name === n;
471
+ return `<button data-token="FontFamilyToken" data-name="${esc(n)}" aria-pressed="${on}" class="${on ? ui("col gap:d5 pd:d6 bd:round-d4 bd:width-d0:solid:proof bg-color:paper text:ink text:left cursor:pointer") : ui("col gap:d5 pd:d6 bd:round-d4 bd:width-px:solid:line bg-color:paper text:ink text:left cursor:pointer @hover:[bd:ink-3] @focus-visible:[outline:d0:solid:proof] transition:fast")}">
472
+ <span style="font-family:${esc(v)};font-size:5.5rem;line-height:1">Aa</span>
473
+ <span style="font-family:${esc(v)};font-size:1.125rem;line-height:1.5;overflow-wrap:anywhere">ABCDEFGHIJKLMNOPQRSTUVWXYZ<br>abcdefghijklmnopqrstuvwxyz<br>0123456789 &amp; ? ! ( ) “ ”</span>
474
+ <span class="${ui("row:y-center:x-between gap:d3")}">
475
+ <span class="${ui("font:small:semibold text:ink")}">${esc(niceName(n) || n)}</span>
476
+ <span class="${ui("font:tiny text:mist")}">${n in own ? 'Added for this site' : 'Built in'}${look.heading.includes(String(v).split(',')[0].replace(/["']/g, '').trim()) && String(v).split(',')[0].trim() ? ', used for headings' : ''}</span>
477
+ </span>
478
+ </button>`;
479
+ };
480
+ return chapter('typefaces', 'Typefaces', 'The fonts the site can use. Drop in a font file to add one; Verso reads its name, weight and style.', `
481
+ <div class="${ui("grid:cols-1-fr:gap-d4 /lg/ grid:cols-2-fr:gap-d4")}">
482
+ ${order.map(card).join('')}
483
+ <div class="${ui("col gap:d3")}">
484
+ <label data-font-drop class="${ui("col:x-center:y-center gap:d2 child:grow pd:d8 bd:round-d4 bd:width-px:dashed:line text:ink-3 cursor:pointer @hover:[bg-color:paper-2] transition:fast")}" style="min-height:14rem">
485
+ <span class="${ui("font:base:semibold text:ink")}">Add a font</span>
486
+ <span class="${ui("font:small")}">Drop a font file here, or click to choose one. WOFF2 is best; WOFF, TTF and OTF work too.</span>
487
+ <input type="file" data-font-file accept=".woff2,.woff,.ttf,.otf" class="${ui("hidden")}">
488
+ </label>
489
+ <details class="${ui("col gap:d2")}">
490
+ <summary class="${ui("font:tiny:medium text:ink-3 cursor:pointer")}">Name it or set its weight yourself</summary>
491
+ <div class="${ui("col gap:d2 pd-t:d2")}">
492
+ ${input('data-font-family', 'Family name, from the file')}
493
+ <div class="${ui("grid:cols-3-fr:gap-d2")}">
494
+ <select data-font-weight aria-label="Weight" class="${ui("w:full min-w:0 h:d10 pd-x:d2 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink")}"><option value="auto" selected>Weight: from the file</option>${[100, 200, 300, 400, 500, 600, 700, 800, 900].map((w) => `<option value="${w}">Weight ${w}</option>`).join('')}</select>
495
+ <select data-font-style aria-label="Style" class="${ui("w:full min-w:0 h:d10 pd-x:d2 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink")}"><option value="auto" selected>Style: from the file</option><option value="normal">Upright</option><option value="italic">Italic</option></select>
496
+ <select data-font-fallback aria-label="Fallback" class="${ui("w:full min-w:0 h:d10 pd-x:d2 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink")}"><option value="auto" selected>Fallback: from the file</option><option value="sans">Sans fallback</option><option value="serif">Serif fallback</option><option value="mono">Monospace fallback</option></select>
497
+ </div>
498
+ </div>
499
+ </details>
500
+ </div>
501
+ </div>`);
502
+ }
503
+
504
+ // ── Type sizes, as a typeset scale ──
505
+ function bookSizes(look) {
506
+ const sizes = state.data.tokens.FontSizeToken || {};
507
+ const own = state.data.own.FontSizeToken || {};
508
+ const headingSize = (n) => /^(h\d|display)$/.test(n);
509
+ const row = (n, v) => {
510
+ const on = state.detail?.type === 'FontSizeToken' && state.detail.name === n;
511
+ return `<button data-token="FontSizeToken" data-name="${esc(n)}" aria-pressed="${on}" class="${on ? ui("row:y-center gap:d6 w:full pd:d4 bd:round-d3 bd:width-0 bg-color:proof-soft text:ink text:left cursor:pointer") : ui("row:y-center gap:d6 w:full pd:d4 bd:round-d3 bd:width-0 bg-color:transparent text:ink text:left cursor:pointer @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">
512
+ <span class="${ui("col gap:d0 w:c10 child:no-shrink")}">
513
+ <span class="${ui("font:small:semibold text:ink")}">${esc(niceName(n) || n)}</span>
514
+ <span class="${ui("font:tiny text:mist format:no-wrap")}">${esc(sizeWords(v) || v)}</span>
515
+ </span>
516
+ <span class="${ui("child:grow min-w:0 overflow:hidden text-overflow:ellipsis format:no-wrap")}" style="font-family:${esc(headingSize(n) ? look.heading : look.body)};font-size:${esc(v)};line-height:1.15">${esc(look.line || verso.data.siteName || 'The quick brown fox')}</span>
517
+ </button>`;
518
+ };
519
+ return chapter('sizes', 'Type sizes', 'From the largest heading to the smallest note, set in the site\'s own fonts. Sizes with two numbers grow with the screen between them.', `
520
+ <div class="${ui("col gap:d0")}">${Object.entries(sizes).reverse().map(([n, v]) => row(n, v)).join('')}</div>
521
+ ${sub('Add a size', `
522
+ <div class="${ui("grid:cols-1-fr:gap-d2 /md/ grid:cols-3-fr:gap-d2")}" style="max-width:48rem">${input('data-fluid-name', 'Name, like lede')}${input('data-fluid-min', 'On phones, like 1.125rem')}${input('data-fluid-max', 'On wide screens, like 1.5rem')}</div>
523
+ <p data-fluid-preview class="${ui("text:ink:snug overflow:hidden")}" style="font-family:${esc(look.body)}">Grows smoothly with the screen.</p>
524
+ <div>${button('data-add-fluid', 'Add size', true)}</div>`, 'Give a size for phones and one for wide screens.')}`);
525
+ }
526
+
527
+ // The drawer: everything about one token, beside the book.
528
+ function drawer() {
529
+ if (!state.detail) return '';
530
+ const { type, name } = state.detail;
531
+ const value = state.data.own?.[type]?.[name];
532
+ if (value == null) return '';
533
+ const look = type === 'ColorToken'
534
+ ? `<span data-swatch="${esc(name)}" class="${ui("block w:full h:c6 bd:round-d4 bd:width-px:solid:line")}" style="background:${esc(value)}"></span>`
535
+ : type === 'FontFamilyToken' ? `<p style="font-family:${esc(value)};font-size:3.5rem;line-height:1">Aa</p>`
536
+ : type === 'FontSizeToken' ? `<p class="${ui("overflow:hidden format:no-wrap text-overflow:ellipsis")}" style="font-size:${esc(value)};line-height:1.1">${esc(niceName(name) || name)}</p>`
537
+ : type === 'ShadowToken' ? `<span class="${ui("block w:full h:c5 bd:round-d4 bg-color:paper")}" style="box-shadow:${esc(value)}"></span>`
538
+ : type === 'GradientToken' ? `<span class="${ui("block w:full h:c5 bd:round-d4")}" style="background:${esc(value)}"></span>` : '';
539
+ return `
540
+ <aside data-drawer aria-label="${esc(name)}" class="${ui("absolute top:0 right:0 h:full w:sheet col gap:d4 pd:d5 bg-color:paper bd-l:width-px:solid:line shadow:float overflow-y:auto z:2")}">
541
+ <div class="${ui("row:y-center:x-between gap:d3")}">
542
+ <h4 class="${ui("font:h6:semibold text:ink overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(name)}</h4>
543
+ <button data-drawer-close class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d9 h:d9 bd:round-full text:ink child:no-shrink @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}" aria-label="Done">${icon('close')}</button>
544
+ </div>
545
+ ${look}
546
+ ${type === 'ColorToken' ? `<button data-try-beside class="${ui("row:y-center:x-center gap:d2 h:d10 pd-x:d4 bd:round-pill bd:width-px:solid:line bg-color:paper text:ink font:small:semibold cursor:pointer @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">${SIDEBAR}Try it beside the page</button>` : ''}
547
+ ${detail(type, name, true)}
548
+ </aside>`;
549
+ }
550
+
551
+ function renderBook() {
552
+ const was = q('[data-book]');
553
+ const scroll = was ? was.scrollTop : (state.bookScroll || 0);
554
+ state.bookScroll = 0;
555
+ const look = brandLook();
556
+ const d = state.data;
557
+ const navBtn = (c) => `<button data-goto="${c.id}" class="${ui("row:y-center h:d10 pd-x:d3 bd:round-d3 bd:width-0 bg-color:transparent text:ink-3 font:small:medium text:left cursor:pointer @hover:[bg-color:paper-2_text:ink] @focus-visible:[outline:d0:solid:proof] transition:fast")}">${c.label}</button>`;
558
+ panel.innerHTML = `
559
+ <header class="${ui("row:y-center gap:d3 pd-x:d5 pd-y:d3 bd-b:width-px:solid:line bg-color:paper child:no-shrink")}">
560
+ <h2 class="${ui("font:small:semibold text:ink")}">Design</h2>
561
+ <span class="${ui("child:grow")}"></span>
562
+ <button data-dock title="Tuck the book beside the page, to see the site change as you work" class="${ui("row:y-center gap:d2 h:d10 pd-x:d4 bd:round-pill bd:width-px:solid:line bg-color:paper text:ink font:small:semibold cursor:pointer @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">${SIDEBAR}Beside the page</button>
563
+ <button data-close class="${ui("bg-color:transparent bd:width-0 cursor:pointer row:x-center:y-center w:d10 h:d10 bd:round-full text:ink @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}" aria-label="Close">${icon('close')}</button>
564
+ </header>
565
+ <div class="${ui("relative row child:grow overflow:hidden")}">
566
+ <nav aria-label="Chapters" class="${ui("hidden w:c10 pd:d4 bd-r:width-px:solid:line child:no-shrink /lg/ col gap:d0")}">${CHAPTERS.map(navBtn).join('')}</nav>
567
+ <main data-book class="${ui("child:grow overflow-y:auto")}">
568
+ ${cover(look)}
569
+ ${d.ready ? '' : `<p class="${ui("mg:d6 pd:d4 bd:round-d4 bg-color:proof-soft text:ink font:small:normal")}">New colours and sizes can't be saved on this site yet. Its style settings need to load <strong>elevate/design/tokens.json</strong>, in elevate/config/design.ts.</p>`}
570
+ <div class="${ui("col gap:c2 pd-x:d6 pd-b:c6 /lg/ pd-x:c2")}" style="max-width:84rem">
571
+ ${bookColours()}
572
+ ${bookTypefaces(look)}
573
+ ${bookSizes(look)}
574
+ ${chapter('text', 'Text styles', 'How articles and posts look: headings, paragraphs, links, lists and quotes. Pick a kind of text to change its font, size, colour and spacing.', text())}
575
+ ${chapter('spacing', 'Spacing', 'The steps of space between things, from the smallest gap to the largest.', spacing())}
576
+ ${chapter('effects', 'Effects', 'Shadows and gradients the site can use.', effects())}
577
+ ${chapter('screens', 'Screens', 'Where layouts change as the screen gets wider. Every layout starts on the smallest screens.', screens())}
578
+ </div>
579
+ </main>
580
+ ${drawer()}
581
+ </div>`;
582
+ const main = q('[data-book]');
583
+ main.scrollTop = scroll;
584
+ wire();
585
+ wireText();
586
+ wireScreens();
587
+ wireBook(main);
588
+ }
589
+
590
+ function wireBook(main) {
591
+ q('[data-dock]')?.addEventListener('click', () => setDocked(true));
592
+ q('[data-drawer-close]')?.addEventListener('click', () => { endPreview(); state.detail = null; render(); });
593
+ q('[data-try-beside]')?.addEventListener('click', () => { state.tab = 'colours'; setDocked(true); });
594
+ panel.querySelectorAll('[data-goto]').forEach((b) => b.addEventListener('click', () => {
595
+ main.querySelector(`#design-${b.dataset.goto}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
596
+ }));
597
+ // The chapter on screen is marked in the list.
598
+ const mark = () => {
599
+ const top = main.getBoundingClientRect().top + 120;
600
+ let current = CHAPTERS[0].id;
601
+ main.querySelectorAll('[data-chapter]').forEach((c) => { if (c.getBoundingClientRect().top <= top) current = c.dataset.chapter; });
602
+ panel.querySelectorAll('[data-goto]').forEach((b) => {
603
+ const on = b.dataset.goto === current;
604
+ b.setAttribute('aria-current', on ? 'true' : 'false');
605
+ b.style.color = on ? '#151518' : '';
606
+ b.style.boxShadow = on ? 'inset 2px 0 0 #FF4F2B' : '';
607
+ });
608
+ };
609
+ main.addEventListener('scroll', () => requestAnimationFrame(mark), { passive: true });
610
+ mark();
611
+ q('[data-drawer]')?.querySelector('input, button:not([data-drawer-close])')?.focus({ preventScroll: true });
612
+ }
613
+
614
+ // ── Colours ──
615
+ function colours() {
616
+ const own = state.data.own.ColorToken || {};
617
+ const all = state.data.tokens.ColorToken || {};
618
+ const swatch = (name, value, big = false) => `
619
+ <button data-token="ColorToken" data-name="${esc(name)}" title="${esc(name)} ${esc(value)}" class="${big ? ui("bd:width-0 cursor:pointer col gap:d1 pd:d0 bg-color:transparent text:ink text:left") : ui("bd:width-0 cursor:pointer pd:d0 bg-color:transparent child:grow")}">
620
+ <span class="${big ? ui("block w:full h:d11 bd:round-d3 bd:width-px:solid:line") : ui("block w:full h:d6")}" style="background:${esc(value)}"></span>
621
+ ${big ? `<span class="${ui("font:tiny:medium text:ink overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(name)}</span>` : ''}
622
+ </button>`;
623
+ const ownNames = Object.keys(own);
624
+ const ownRow = (n) => {
625
+ const openNow = state.detail?.type === 'ColorToken' && state.detail.name === n;
626
+ return `
627
+ <button data-token="ColorToken" data-name="${esc(n)}" aria-expanded="${openNow}" class="${ui("bd:width-0 cursor:pointer row:y-center gap:d3 w:full pd:d2 bd:round-d3 bg-color:transparent text:ink text:left @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">
628
+ <span data-swatch="${esc(n)}" class="${ui("block w:d10 h:d10 bd:round-d3 bd:width-px:solid:line child:no-shrink")}" style="background:${esc(own[n])}"></span>
629
+ <span class="${ui("col gap:d0 child:grow min-w:0")}">
630
+ <span class="${ui("font:small:medium text:ink overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(n)}</span>
631
+ <span class="${ui("font:tiny text:mist")}">${usedIn(n)}</span>
632
+ </span>
633
+ </button>${detail('ColorToken', n)}`;
634
+ };
635
+ const groups = {};
636
+ Object.keys(all).filter((n) => !(n in own)).forEach((n) => { (groups[family(n)] ||= []).push(n); });
637
+ return `
638
+ ${ownNames.length ? section('This site\'s colours', `<div class="${ui("col gap:d1")}">${ownNames.map(ownRow).join('')}</div>`, 'Click one to change it.') : ''}
639
+ ${section('Add a colour', `
640
+ <div class="${ui("row:y-center gap:d2")}">
641
+ <input type="color" data-new-colour value="#B8471F" aria-label="Colour" class="${ui("w:d11 h:d10 pd:d0 bd:round-d3 bd:width-px:solid:line bg-color:paper cursor:pointer child:no-shrink")}">
642
+ ${input('data-new-colour-name', 'Name, like brand')}
643
+ </div>
644
+ <div class="${ui("row gap:d2")}">${button('data-add-colour', 'Add colour', true)}${button('data-preview-ramp', 'Make shades')}</div>
645
+ <div data-ramp></div>`, 'Shades are nine steps from dark to light around your colour.')}
646
+ ${section('Built-in colours', `<div class="${ui("col gap:d2")}">${Object.entries(groups).map(([g, names]) => `
647
+ <div class="${ui("col gap:d1")}">
648
+ <span class="${ui("font:tiny text:mist")}">${esc(g)}</span>
649
+ <div class="${ui("row bd:round-d2 overflow:hidden bd:width-px:solid:line")}">${names.map((n) => swatch(n, all[n])).join('')}</div>
650
+ </div>`).join('')}</div>`, 'Built in, and ready to use in any block. Add your own to change one.')}`;
651
+ }
652
+
653
+ function rampPreview(steps, name) {
654
+ return `
655
+ <div class="${ui("col gap:d3 pd:d4 bd:round-d4 bg-color:paper-2")}">
656
+ <div class="${ui("row bd:round-d3 overflow:hidden")}">
657
+ ${steps.map((s) => `<div class="${ui("col:x-center:y-center child:grow h:c3 gap:d0")}" style="background:${esc(s.value)};color:${s.onWhite >= 4.5 ? '#FFFFFF' : esc(steps[0].value)}">
658
+ <span class="${ui("font:small:semibold")}">Aa</span>
659
+ <span class="${ui("font:tiny")}">${(s.onWhite >= 4.5 ? s.onWhite : s.onDarkest).toFixed(1)}</span>
660
+ </div>`).join('')}
661
+ </div>
662
+ <p class="${ui("font:tiny text:ink-3")}">Each step shows the text colour it reads best with, and its contrast. 4.5 or more passes for body text.</p>
663
+ <div class="${ui("row gap:d2")}">${button(`data-save-ramp="${esc(name)}"`, 'Save the shades', true)}${button('data-cancel-ramp', 'Cancel')}</div>
664
+ </div>`;
665
+ }
666
+
667
+ // ── Type ──
668
+ function type() {
669
+ const fam = state.data.tokens.FontFamilyToken || {};
670
+ const sizes = state.data.tokens.FontSizeToken || {};
671
+ const ownSizes = state.data.own.FontSizeToken || {};
672
+ const ownFam = state.data.own.FontFamilyToken || {};
673
+ return `
674
+ ${section('Families', `<div class="${ui("col gap:d2")}">${Object.entries(fam).map(([n, v]) => `
675
+ <button data-token="FontFamilyToken" data-name="${esc(n)}" class="${ui("bd:width-0 cursor:pointer col gap:d0 pd:d3 bd:round-d3 bg-color:paper-2 text:ink text:left @hover:[bg-color:line] transition:fast")}">
676
+ <span class="${ui("font:h5 text:ink overflow:hidden text-overflow:ellipsis format:no-wrap")}" style="font-family:${esc(v)}">The quick brown fox</span>
677
+ <span class="${ui("font:tiny text:mist")}">${esc(niceName(n))}${n in ownFam ? ', added for this site' : ''}</span>
678
+ </button>${detail('FontFamilyToken', n)}`).join('')}</div>`)}
679
+ ${section('Add a font', `
680
+ <label data-font-drop class="${ui("col:x-center:y-center gap:d1 pd:d6 bd:round-d4 bd:width-px:dashed:line text:ink-3 cursor:pointer @hover:[bg-color:paper-2] transition:fast")}">
681
+ <span class="${ui("font:small:medium text:ink")}">Drop a font file, or click to choose</span>
682
+ <span class="${ui("font:tiny")}">WOFF2 is best. WOFF, TTF and OTF work too.</span>
683
+ <input type="file" data-font-file accept=".woff2,.woff,.ttf,.otf" class="${ui("hidden")}">
684
+ </label>
685
+ <details class="${ui("col gap:d2")}">
686
+ <summary class="${ui("font:tiny:medium text:ink-3 cursor:pointer")}">Name it or set its weight yourself</summary>
687
+ <div class="${ui("col gap:d2 pd-t:d2")}">
688
+ ${input('data-font-family', 'Family name, from the file')}
689
+ <div class="${ui("grid:cols-3-fr:gap-d2")}">
690
+ <select data-font-weight aria-label="Weight" class="${ui("w:full min-w:0 h:d10 pd-x:d2 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink")}"><option value="auto" selected>Weight: from the file</option>${[100, 200, 300, 400, 500, 600, 700, 800, 900].map((w) => `<option value="${w}">Weight ${w}</option>`).join('')}</select>
691
+ <select data-font-style aria-label="Style" class="${ui("w:full min-w:0 h:d10 pd-x:d2 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink")}"><option value="auto" selected>Style: from the file</option><option value="normal">Upright</option><option value="italic">Italic</option></select>
692
+ <select data-font-fallback aria-label="Fallback" class="${ui("w:full min-w:0 h:d10 pd-x:d2 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink")}"><option value="auto" selected>Fallback: from the file</option><option value="sans">Sans fallback</option><option value="serif">Serif fallback</option><option value="mono">Monospace fallback</option></select>
693
+ </div>
694
+ <p class="${ui("font:tiny text:mist")}">Set these before dropping the file. Left alone, Verso reads them from it.</p>
695
+ </div>
696
+ </details>`, 'Verso reads the font\'s name, weight and style from the file, keeps it in public/fonts/, and writes the @font-face rule. Drop each weight and the italic of a family; a variable font is one file for every weight.')}
697
+ ${section('Sizes', `<div class="${ui("col gap:d1")}">${Object.entries(sizes).map(([n, v]) => `
698
+ <button data-token="FontSizeToken" data-name="${esc(n)}" class="${ui("bd:width-0 cursor:pointer col gap:d0 w:full pd:d2 bd:round-d3 bg-color:transparent text:ink text:left overflow:hidden @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">
699
+ <span class="${ui("format:no-wrap text:ink:none overflow:hidden text-overflow:ellipsis")}" style="font-size:${esc(v)}">${esc(niceName(n) || n)}</span>
700
+ <span class="${ui("font:tiny text:mist")}">${esc(sizeWords(v) || v)}${n in ownSizes ? `, added for this site. ${usedIn(n)}` : ''}</span>
701
+ </button>${detail('FontSizeToken', n)}`).join('')}</div>`, 'Sizes that run from one number to another grow with the screen.')}
702
+ ${section('Add a size', `
703
+ ${input('data-fluid-name', 'Name, like lede')}
704
+ <div class="${ui("row gap:d2")}">${input('data-fluid-min', 'On phones, like 1.125rem')}${input('data-fluid-max', 'On wide screens, like 1.5rem')}</div>
705
+ <p data-fluid-preview class="${ui("text:ink:snug overflow:hidden")}">Grows smoothly with the screen.</p>
706
+ ${button('data-add-fluid', 'Add size', true)}`, 'Give a size for phones and one for wide screens. It grows smoothly in between.')}`;
707
+ }
708
+
709
+ // ── Spacing ──
710
+ function spacing() {
711
+ const all = state.data.tokens.SpacingToken || {};
712
+ const own = state.data.own.SpacingToken || {};
713
+ const measurable = Object.entries(all).filter(([, v]) => /^\d*\.?\d+(rem|px|em)$/.test(v) && parseFloat(pixels(v)) > 0);
714
+ // Bars grow with the log of the distance, so 4px and 8px differ, and so
715
+ // do 512px and 1024px, in the same panel.
716
+ const most = Math.max(1, ...measurable.map(([, v]) => parseFloat(pixels(v))));
717
+ const width = (v) => Math.max(2, Math.round((Math.log2(parseFloat(pixels(v)) + 1) / Math.log2(most + 1)) * 100));
718
+ return `
719
+ ${section('Steps', `<div class="${ui("col gap:d0")}">${measurable.map(([n, v]) => `
720
+ <button data-token="SpacingToken" data-name="${esc(n)}" title="${esc(pixels(v))}" class="${ui("bd:width-0 cursor:pointer row:y-center gap:d3 w:full pd:d1 bd:round-d2 bg-color:transparent text:ink text:left @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">
721
+ <span class="${ui("w:d12 child:no-shrink font:tiny:medium text:ink-3 format:no-wrap")}">${esc(niceName(n) || pixels(v))}</span>
722
+ <span class="${ui("child:grow min-w:0")}"><span class="${ui("block h:d3 bg-color:proof bd:round-d0")}" style="width:${width(v)}%"></span></span>
723
+ ${niceName(n) ? `<span class="${ui("font:tiny text:mist format:no-wrap")}">${esc(pixels(v))}</span>` : ''}
724
+ </button>${detail('SpacingToken', n)}`).join('')}</div>`, 'From the smallest gap to the largest. Bars grow more slowly than the distance, so big steps still look different.')}
725
+ ${section('Add a step', `<div class="${ui("row gap:d2")}">${input('data-space-name', 'Name, like gutter')}${input('data-space-value', 'Size, like 28px')}</div>${button('data-add-space', 'Add step', true)}`)}`;
726
+ }
727
+
728
+ // ── Shadows and gradients ──
729
+ function effects() {
730
+ const sh = state.data.tokens.ShadowToken || {};
731
+ const gr = state.data.tokens.GradientToken || {};
732
+ return `
733
+ ${section('Shadows', `<div class="${ui("grid:cols-3-fr:gap-d4 pd:d3 bd:round-d4 bg-color:paper-2")}">${Object.entries(sh).map(([n, v]) => `
734
+ <button data-token="ShadowToken" data-name="${esc(n)}" class="${ui("bd:width-0 cursor:pointer col gap:d2 pd:d0 bg-color:transparent text:ink text:left")}">
735
+ <span class="${ui("block w:full h:d12 bd:round-d3 bg-color:paper")}" style="box-shadow:${esc(v)}"></span>
736
+ <span class="${ui("font:tiny text:ink-3 overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(niceName(n) || n)}</span>
737
+ </button>`).join('')}</div>${Object.keys(sh).map((n) => detail('ShadowToken', n)).join('')}`)}
738
+ ${section('Gradients', `<div class="${ui("grid:cols-2-fr:gap-d3")}">${Object.entries(gr).map(([n, v]) => `
739
+ <button data-token="GradientToken" data-name="${esc(n)}" class="${ui("bd:width-0 cursor:pointer col gap:d1 pd:d0 bg-color:transparent text:ink text:left")}">
740
+ <span class="${ui("block w:full h:d12 bd:round-d3")}" style="background:${esc(v)}"></span>
741
+ <span class="${ui("font:tiny text:ink-3 overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(niceName(n) || n)}</span>
742
+ </button>`).join('')}</div>${Object.keys(gr).map((n) => detail('GradientToken', n)).join('')}`)}
743
+ ${section('Add a shadow or gradient', `
744
+ <div class="${ui("row gap:d2")}">
745
+ <select data-effect-type class="${ui("h:d10 pd-x:d3 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink")}"><option value="ShadowToken">Shadow</option><option value="GradientToken">Gradient</option></select>
746
+ ${input('data-effect-name', 'Name')}
747
+ </div>
748
+ <label class="${ui("col gap:d1 font:tiny text:ink-3")}">The CSS${input('data-effect-value', '0 8px 24px rgba(0,0,0,.18)')}</label>
749
+ <span data-effect-preview class="${ui("block w:full h:d12 bd:round-d3 bg-color:paper")}"></span>
750
+ ${button('data-add-effect', 'Add', true)}`)}`;
751
+ }
752
+
753
+ // ── Text styles ──
754
+ // How article text looks: classes in verso.json "rich", picked from tokens.
755
+ function text() {
756
+ const t = state.text;
757
+ if (!t) { loadText(); return `<p class="${ui("font:small text:ink-3")}">Loading text styles…</p>`; }
758
+ const groups = [];
759
+ t.styles.forEach((st) => { let g = groups.find((x) => x.name === st.group); if (!g) groups.push(g = { name: st.group, items: [] }); g.items.push(st); });
760
+ const sel = t.styles.find((x) => x.tag === state.textTag);
761
+ const list = groups.map((g) => section(esc(g.name), `<div class="${ui("col gap:d1")}">${g.items.map((st) => `
762
+ <button data-text-tag="${esc(st.tag)}" aria-expanded="${st.tag === state.textTag}" class="${st.tag === state.textTag ? ui("bd:width-0 cursor:pointer row:y-center:x-between gap:d3 pd:d3 bd:round-d3 bg-color:paper-2 text:ink text:left font:small:semibold") : ui("bd:width-0 cursor:pointer row:y-center:x-between gap:d3 pd:d3 bd:round-d3 bg-color:transparent text:ink text:left font:small:medium @hover:[bg-color:paper-2] transition:fast")}">
763
+ <span>${esc(st.label)}</span>
764
+ <span class="${ui("font:tiny text:mist overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(summary(st))}</span>
765
+ </button>
766
+ ${st.tag === state.textTag ? stylePickers(sel) : ''}`).join('')}</div>`)).join('');
767
+ // In the book: the sample stays in view on the left while you work down
768
+ // the list on the right.
769
+ if (!state.docked) {
770
+ return `<div class="${ui("grid:cols-1-fr:gap-d6 /lg/ grid:cols-2-fr:gap-c1")}">
771
+ <div><iframe data-text-sample title="Sample of the site's article text" class="${ui("block w:full bd:round-d4 bd:width-px:solid:line bg-color:paper sticky top:d4")}" style="height:min(72vh,46rem)"></iframe></div>
772
+ <div class="${ui("col gap:d6")}">${list}</div>
773
+ </div>`;
774
+ }
775
+ return `
776
+ ${section('Text styles', `<iframe data-text-sample title="Sample of the site's article text" class="${ui("block w:full h:c11 bd:round-d4 bd:width-px:solid:line bg-color:paper")}"></iframe>`, 'How article text looks everywhere on the site. Pick a kind of text, then change its font, size, colour and spacing.')}
777
+ ${groups.map((g) => section(esc(g.name), `<div class="${ui("col gap:d1")}">${g.items.map((st) => `
778
+ <button data-text-tag="${esc(st.tag)}" aria-expanded="${st.tag === state.textTag}" class="${st.tag === state.textTag ? ui("bd:width-0 cursor:pointer row:y-center:x-between gap:d3 pd:d3 bd:round-d3 bg-color:paper-2 text:ink text:left font:small:semibold") : ui("bd:width-0 cursor:pointer row:y-center:x-between gap:d3 pd:d3 bd:round-d3 bg-color:transparent text:ink text:left font:small:medium @hover:[bg-color:paper-2] transition:fast")}">
779
+ <span>${esc(st.label)}</span>
780
+ <span class="${ui("font:tiny text:mist overflow:hidden text-overflow:ellipsis format:no-wrap")}">${esc(summary(st))}</span>
781
+ </button>
782
+ ${st.tag === state.textTag ? stylePickers(sel) : ''}`).join('')}</div>`)).join('')}`;
783
+ }
784
+
785
+ const optionLabel = (o) => readable(o.name, o.value);
786
+ const summary = (st) => {
787
+ const p = st.picks;
788
+ const bits = [niceName(p.size), niceName(p.weight), p['text-color']].filter(Boolean);
789
+ return bits.length ? bits.join(', ') : st.classes ? 'Custom' : 'Site default';
790
+ };
791
+
792
+ const swatch = (pk, st) => (o) => `<button data-text-colour="${pk}" data-value="${esc(o.name)}" title="${esc(o.name)}" aria-label="${esc(o.name)}" aria-pressed="${st.picks[pk] === o.name}" class="${st.picks[pk] === o.name ? ui("bd:width-px:solid:ink cursor:pointer w:d7 h:d7 bd:round-full shadow:proof-focus") : ui("bd:width-px:solid:line cursor:pointer w:d7 h:d7 bd:round-full @hover:[bd:ink] @focus-visible:[outline:d0:solid:proof] transition:fast")}" style="background:${esc(o.value)}"></button>`;
793
+
794
+ function stylePickers(st) {
795
+ const opts = state.text.options;
796
+ const select = (pk, label) => `
797
+ <label class="${ui("col gap:d1 min-w:0")}">
798
+ <span class="${ui("font:tiny:medium text:ink-3")}">${label}</span>
799
+ <select data-text-pick="${pk}" class="${ui("w:full min-w:0 h:d10 pd-x:d2 bd:round-d3 bd:width-px:solid:line bg-color:paper font:ui:small text:ink")}">
800
+ <option value="">${st.picks[pk] ? 'None' : 'Not set'}</option>
801
+ ${(opts[pk] || []).map((o) => `<option value="${esc(o.name)}"${st.picks[pk] === o.name ? ' selected' : ''}>${esc(optionLabel(o))}</option>`).join('')}
802
+ </select>
803
+ </label>`;
804
+ const swatches = (pk, label) => `
805
+ <div class="${ui("col gap:d1")}" role="group" aria-label="${label}">
806
+ <span class="${ui("font:tiny:medium text:ink-3")}">${label}${st.picks[pk] ? `: ${esc(st.picks[pk])}` : ''}</span>
807
+ <div class="${ui("row:wrap gap:d1")}">
808
+ <button data-text-colour="${pk}" data-value="" title="None" aria-pressed="${!st.picks[pk]}" class="${ui("bd:width-px:solid:line cursor:pointer w:d7 h:d7 bd:round-full bg-color:paper font:tiny text:mist @focus-visible:[outline:d0:solid:proof]")}">×</button>
809
+ ${(opts[pk] || []).filter((o) => !o.elevate || o.name === st.picks[pk]).map(swatch(pk, st)).join('')}
810
+ </div>
811
+ ${(opts[pk] || []).some((o) => o.elevate) ? `<details class="${ui("col gap:d1")}">
812
+ <summary class="${ui("font:tiny text:mist cursor:pointer")}">More colours</summary>
813
+ <div class="${ui("row:wrap gap:d1 pd-t:d1")}">${(opts[pk] || []).filter((o) => o.elevate).map(swatch(pk, st)).join('')}</div>
814
+ </details>` : ''}
815
+ </div>`;
816
+ const row = (items) => `<div class="${ui("grid:cols-2-fr:gap-d2")}">${items.map(([pk, label]) => select(pk, label)).join('')}</div>`;
817
+ const by = Object.fromEntries(STYLE_PICKERS);
818
+ return `
819
+ <div data-text-detail class="${ui("col gap:d4 pd:d4 bd:round-d4 bd:width-px:solid:line bg-color:paper")}">
820
+ ${select('family', by.family)}
821
+ ${row([['size', by.size], ['weight', by.weight]])}
822
+ ${row([['leading', by.leading], ['radius', by.radius]])}
823
+ ${swatches('text-color', by['text-color'])}
824
+ ${swatches('background', by.background)}
825
+ ${row([['margin-top', by['margin-top']], ['margin-bottom', by['margin-bottom']]])}
826
+ ${select('padding', by.padding)}
827
+ <details class="${ui("col gap:d2")}">
828
+ <summary class="${ui("font:tiny:medium text:ink-3 cursor:pointer")}">Advanced</summary>
829
+ <div class="${ui("row:y-center gap:d2 pd-t:d2")}">${input(`data-text-classes value="${esc(st.classes)}" aria-label="Classes for ${esc(st.label)}"`)}${button('data-text-apply', 'Apply')}</div>
830
+ <p class="${ui("font:tiny text:mist")}">The style as Elevate classes. Verso checks them before saving.</p>
831
+ </details>
832
+ </div>`;
833
+ }
834
+
835
+ async function loadText() {
836
+ if (state.textLoading) return;
837
+ state.textLoading = true;
838
+ const out = await request('/__verso/tokens/text-styles');
839
+ state.textLoading = false;
840
+ if (!out.ok) { toast(out.message, 'error'); return; }
841
+ state.text = out;
842
+ if (state.tab === 'text' || !state.docked) render();
843
+ }
844
+
845
+ // The sample, in a frame with the page's own stylesheets and the class of
846
+ // the element rich text sits in, so it looks the way articles do.
847
+ function drawSample() {
848
+ const frame = q('[data-text-sample]');
849
+ if (!frame || !state.text) return;
850
+ const classes = Object.fromEntries(state.text.styles.map((st) => [st.tag, st.classes]));
851
+ const doc = new DOMParser().parseFromString(`<div>${SAMPLE}</div>`, 'text/html');
852
+ doc.body.querySelectorAll('*').forEach((el) => {
853
+ const tag = el.tagName.toLowerCase();
854
+ const inPre = tag === 'code' && el.parentElement?.tagName === 'PRE';
855
+ const key = inPre && 'pre code' in classes ? 'pre code' : tag;
856
+ if (classes[key]) el.setAttribute('class', classes[key]);
857
+ if (key === state.textTag) el.setAttribute('style', 'outline:2px solid #FF4F2B;outline-offset:3px');
858
+ });
859
+ const host = document.querySelector('[data-verso-rich]');
860
+ const links = [...document.querySelectorAll('link[rel="stylesheet"]')].map((l) => `<link rel="stylesheet" href="${esc(l.href)}">`).join('');
861
+ // The colours the text really sits on: the nearest background behind
862
+ // article text on the page, not the page's outermost one (a dark frame
863
+ // around a light card made the sample dark text on dark).
864
+ // Without article text on this page, the paragraph with the most words
865
+ // stands in: that's the body copy, not a coloured note above a headline.
866
+ const longest = [...document.querySelectorAll('p')].sort((a, b) => b.textContent.length - a.textContent.length)[0];
867
+ const from = host || longest || document.body;
868
+ let bg = '#FFFFFF';
869
+ for (let n = from; n && n.nodeType === 1; n = n.parentElement) {
870
+ const c = getComputedStyle(n).backgroundColor;
871
+ if (c && !/rgba\(0, 0, 0, 0\)|transparent/.test(c)) { bg = c; break; }
872
+ }
873
+ const fg = getComputedStyle(from).color;
874
+ frame.srcdoc = `<!DOCTYPE html><html><head><meta charset="utf-8">${links}<style>html,body{background:${bg}!important;color:${fg}!important}body{margin:0!important;padding:24px!important;min-height:0!important}</style></head><body class="${esc(document.body.className)}"><div class="${esc(host?.className || '')}">${doc.body.firstElementChild.innerHTML}</div></body></html>`;
875
+ frame.addEventListener('load', () => {
876
+ const el = frame.contentDocument?.querySelector('[style*="outline"]');
877
+ if (el) el.scrollIntoView({ block: 'center' });
878
+ }, { once: true });
879
+ }
880
+
881
+ // Shows a change on the page at once: rich text on the page takes the new
882
+ // classes, and the rich text editor uses them from now on.
883
+ function applyOnPage(tag, classes) {
884
+ verso.data.rich = verso.data.rich || {};
885
+ if (classes) verso.data.rich[tag] = classes; else delete verso.data.rich[tag];
886
+ const all = verso.data.rich;
887
+ document.querySelectorAll('[data-verso-rich]').forEach((box) => {
888
+ box.querySelectorAll(tag === 'pre code' ? 'pre > code' : tag).forEach((el) => {
889
+ if (tag === 'code' && el.parentElement?.tagName === 'PRE' && 'pre code' in all) return;
890
+ if (classes) el.setAttribute('class', classes); else el.removeAttribute('class');
891
+ });
892
+ });
893
+ }
894
+
895
+ async function saveText(body) {
896
+ const out = await request('/__verso/tokens/text-styles', { tag: state.textTag, ...body });
897
+ if (!out.ok) { toast(out.message, 'error'); return; }
898
+ const i = state.text.styles.findIndex((st) => st.tag === out.style.tag);
899
+ state.text.styles[i] = { ...state.text.styles[i], classes: out.style.classes, picks: out.style.picks };
900
+ applyOnPage(out.style.tag, out.style.classes);
901
+ render();
902
+ }
903
+
904
+ function wireText() {
905
+ drawSample();
906
+ panel.querySelectorAll('[data-text-tag]').forEach((b) => b.addEventListener('click', () => {
907
+ state.textTag = state.textTag === b.dataset.textTag ? null : b.dataset.textTag;
908
+ render();
909
+ panel.querySelector(`[data-text-tag="${CSS.escape(b.dataset.textTag)}"]`)?.focus();
910
+ }));
911
+ panel.querySelectorAll('[data-text-pick]').forEach((sel) => sel.addEventListener('change', () => saveText({ picker: sel.dataset.textPick, value: sel.value || null })));
912
+ panel.querySelectorAll('[data-text-colour]').forEach((b) => b.addEventListener('click', () => saveText({ picker: b.dataset.textColour, value: b.dataset.value || null })));
913
+ q('[data-text-apply]')?.addEventListener('click', () => saveText({ classes: q('[data-text-classes]').value }));
914
+ q('[data-text-classes]')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); saveText({ classes: e.target.value }); } });
915
+ }
916
+
917
+ // ── Screens ──
918
+ // The site's screen sizes: where layouts change. Mobile first, so the
919
+ // smallest screens are the starting point and each size changes things
920
+ // from its width up.
921
+ function screens() {
922
+ const sc = state.screens;
923
+ if (!sc) { loadScreens(); return `<p class="${ui("font:small text:mist")}">Loading the screen sizes…</p>`; }
924
+ const max = Math.max(1600, ...sc.screens.map((x) => x.px || 0)) * 1.08;
925
+ const ruler = `<div class="${ui("relative h:d10 bd:round-d3 bg-color:paper-2")}" aria-hidden="true">
926
+ ${sc.screens.map((x) => `<span title="${esc(x.label)}, ${x.px}px" class="${ui("absolute top:0 h:full w:px bg-color:proof")}" style="left:${(x.px / max) * 100}%"></span>`).join('')}
927
+ </div>
928
+ <div class="${ui("row:x-between font:tiny text:mist")}" aria-hidden="true"><span>0</span><span>${Math.round(max / 100) * 100}px</span></div>`;
929
+ const open = state.screenOpen;
930
+ const row = (x) => {
931
+ const on = open === x.name;
932
+ return `<button data-screen="${esc(x.name)}" aria-expanded="${on}" class="${ui("bd:width-0 cursor:pointer row:y-center gap:d3 w:full pd:d2 bd:round-d3 bg-color:transparent text:ink text:left @hover:[bg-color:paper-2] @focus-visible:[outline:d0:solid:proof] transition:fast")}">
933
+ <span class="${ui("w:c3 font:mono:tiny text:ink-3 text:right child:no-shrink")}">${x.px}px</span>
934
+ <span class="${ui("col gap:d0 child:grow min-w:0")}">
935
+ <span class="${ui("font:small:medium text:ink")}">${esc(x.label)}</span>
936
+ <span class="${ui("font:tiny text:mist")}">${x.used ? `Used in ${x.used} place${x.used === 1 ? '' : 's'}` : 'Not used yet'}</span>
937
+ </span>
938
+ </button>${on ? screenDetail(x) : ''}`;
939
+ };
940
+ return `
941
+ ${section('Screen sizes', `${ruler}
942
+ <div class="${ui("col gap:d0")}">
943
+ <div class="${ui("row:y-center gap:d3 pd:d2")}"><span class="${ui("w:c3 font:mono:tiny text:ink-3 text:right child:no-shrink")}">0px</span><span class="${ui("col gap:d0")}"><span class="${ui("font:small:medium text:ink")}">Smallest screens</span><span class="${ui("font:tiny text:mist")}">Where every layout starts</span></span></div>
944
+ ${sc.screens.map(row).join('')}
945
+ </div>`, 'Layouts are made for the smallest screens first. Each size below changes things from its width up: pick one in Build a block to style for it.')}
946
+ ${section('Add a screen size', `
947
+ <div class="${ui("grid:cols-2-fr:gap-d2")}">
948
+ <label class="${ui("col gap:d1 font:tiny text:ink-3")}">Name${input('data-screen-new-label aria-label="Name of the new screen size"', 'Wide screens')}</label>
949
+ <label class="${ui("col gap:d1 font:tiny text:ink-3")}">Starts at (px)${input('data-screen-new-width inputmode="numeric" aria-label="Width it starts at, in pixels"', '1440')}</label>
950
+ </div>
951
+ <div>${button('data-screen-add', 'Add', true)}</div>`)}`;
952
+ }
953
+
954
+ function screenDetail(x) {
955
+ const used = state.screenUsage;
956
+ return `<div class="${ui("col gap:d3 pd:d4 bd:round-d4 bg-color:paper-2")}">
957
+ <div class="${ui("grid:cols-2-fr:gap-d2")}">
958
+ <label class="${ui("col gap:d1 font:tiny text:ink-3")}">Name${input(`data-screen-label value="${esc(x.label)}" aria-label="Name"`)}</label>
959
+ <label class="${ui("col gap:d1 font:tiny text:ink-3")}">Starts at (px)${input(`data-screen-width value="${x.px}" inputmode="numeric" aria-label="Width it starts at, in pixels"`)}</label>
960
+ </div>
961
+ <div>${button('data-screen-save', 'Save', true)}</div>
962
+ <p class="${ui("font:tiny text:mist")}">In class lists it's written <code>/${esc(x.name)}/</code>. Moving it changes where every layout set for ${esc(x.label.toLowerCase())} starts.</p>
963
+ ${used ? (used.length
964
+ ? `<p class="${ui("font:tiny text:ink-3")}">Styled for in ${esc(usageWords(used))}. Removing it removes those styles too.</p>`
965
+ : `<p class="${ui("font:tiny text:ink-3")}">Nothing is styled for it yet.</p>`) : ''}
966
+ <div>${button('data-screen-remove', used && used.length ? 'Remove it and its styles' : 'Remove')}</div>
967
+ </div>`;
968
+ }
969
+
970
+ async function loadScreens() {
971
+ if (state.screensLoading) return;
972
+ state.screensLoading = true;
973
+ const out = await request('/__verso/tokens/screens');
974
+ state.screensLoading = false;
975
+ if (!out.ok) { toast(out.message, 'error'); return; }
976
+ state.screens = out;
977
+ if (state.tab === 'screens' || !state.docked) render();
978
+ }
979
+
980
+ async function changeScreens(body, done) {
981
+ const out = await request('/__verso/tokens/screens', body);
982
+ if (!out.ok) { toast(out.message, 'error'); return null; }
983
+ if (done) toast(done, 'ok');
984
+ state.screens = null;
985
+ await loadScreens();
986
+ return out;
987
+ }
988
+
989
+ function wireScreens() {
990
+ panel.querySelectorAll('[data-screen]').forEach((b) => b.addEventListener('click', async () => {
991
+ const name = b.dataset.screen;
992
+ state.screenOpen = state.screenOpen === name ? null : name;
993
+ state.screenUsage = null;
994
+ render();
995
+ if (!state.screenOpen) return;
996
+ const out = await request(`/__verso/tokens/screens/usage?name=${encodeURIComponent(name)}`);
997
+ if (state.screenOpen === name) { state.screenUsage = out.usage || []; render(); }
998
+ }));
999
+ q('[data-screen-save]')?.addEventListener('click', () => {
1000
+ const label = q('[data-screen-label]').value;
1001
+ const width = q('[data-screen-width]').value;
1002
+ changeScreens({ action: 'save', name: state.screenOpen, label, width }, `${label.trim()} now start at ${String(width).replace(/px$/, '')}px.`);
1003
+ });
1004
+ q('[data-screen-remove]')?.addEventListener('click', async () => {
1005
+ const x = state.screens.screens.find((s) => s.name === state.screenOpen);
1006
+ if (state.screenUsage?.length) comeBack(`${x.label} removed, with the styles set for it.`);
1007
+ const out = await changeScreens({ action: 'remove', name: x.name, force: !!state.screenUsage?.length }, `${x.label} removed.`);
1008
+ if (!out || !out.changed?.length) forget();
1009
+ if (out) state.screenOpen = null;
1010
+ if (out?.changed?.length) render();
1011
+ });
1012
+ const add = () => {
1013
+ const label = q('[data-screen-new-label]').value;
1014
+ const width = q('[data-screen-new-width]').value;
1015
+ changeScreens({ action: 'save', label, width }, `${label.trim()} added. Pick it in Build a block to style for it.`);
1016
+ };
1017
+ q('[data-screen-add]')?.addEventListener('click', add);
1018
+ q('[data-screen-new-width]')?.addEventListener('keydown', (e) => { if (e.key === 'Enter') add(); });
1019
+ }
1020
+
1021
+ // A token's name from what was typed: "Desk 2" → "desk-2".
1022
+ const tokenName = (text) => String(text || '').trim().toLowerCase().replace(/[^a-z0-9+]+/g, '-').replace(/^[-\d]+|-+$/g, '');
1023
+
1024
+ // ════ Wiring ════
1025
+
1026
+ const q = (sel) => panel.querySelector(sel);
1027
+
1028
+ async function save(url, body, done) {
1029
+ const out = await request(url, body);
1030
+ if (!out.ok) { toast(out.message, 'error'); return null; }
1031
+ done && toast(done, 'ok');
1032
+ await load();
1033
+ return out;
1034
+ }
1035
+
1036
+ function wire() {
1037
+ q('[data-close]').addEventListener('click', close);
1038
+ q('[data-expand]')?.addEventListener('click', () => setDocked(false));
1039
+ panel.querySelectorAll('[data-tab]').forEach((b) => b.addEventListener('click', () => { endPreview(); state.tab = b.dataset.tab; state.detail = null; if (state.tab === 'text') state.text = null; if (state.tab === 'screens') { state.screens = null; state.screenOpen = null; } render(); }));
1040
+
1041
+ panel.querySelectorAll('[data-token]').forEach((b) => b.addEventListener('click', async () => {
1042
+ const { token: type, name } = b.dataset;
1043
+ if (!isOwn(type, name)) { toast('This one is built in, so it can\'t be changed here. Add your own next to it.', 'ok'); return; }
1044
+ endPreview();
1045
+ if (state.detail?.name === name && state.detail.type === type) { state.detail = null; render(); return; }
1046
+ state.detail = { type, name, usage: null };
1047
+ render();
1048
+ const out = await request(`/__verso/tokens/usage?name=${encodeURIComponent(name)}`);
1049
+ if (state.detail?.name === name) { state.detail.usage = out.usage || []; render(); }
1050
+ }));
1051
+
1052
+ // Changing a value: the colour picker and the text box stay in step.
1053
+ const pickColour = q('[data-edit-colour]');
1054
+ const editValue = q('[data-edit-value]');
1055
+ const tryColour = (to) => {
1056
+ const { name } = state.detail || {};
1057
+ const from = state.data.own.ColorToken?.[name];
1058
+ panel.querySelectorAll(`[data-swatch="${CSS.escape(name || '')}"]`).forEach((chip) => { chip.style.background = to; });
1059
+ if (from && to.toUpperCase() !== from.toUpperCase()) previewColour(from, to); else endPreview();
1060
+ };
1061
+ pickColour?.addEventListener('input', () => { editValue.value = pickColour.value.toUpperCase(); tryColour(pickColour.value); });
1062
+ q('[data-fix-colour]')?.addEventListener('click', () => {
1063
+ q('[data-variable]')?.setAttribute('hidden', '');
1064
+ q('[data-colour-picker]')?.removeAttribute('hidden');
1065
+ pickColour?.focus();
1066
+ });
1067
+ q('[data-undo-value]')?.addEventListener('click', () => {
1068
+ const from = state.data.own.ColorToken?.[state.detail?.name];
1069
+ if (!from) return;
1070
+ editValue.value = from;
1071
+ if (/^#[0-9a-f]{6}$/i.test(from)) pickColour.value = from;
1072
+ if (variableOf(from)) {
1073
+ q('[data-variable]')?.removeAttribute('hidden');
1074
+ q('[data-colour-picker]')?.setAttribute('hidden', '');
1075
+ }
1076
+ tryColour(from);
1077
+ });
1078
+ editValue?.addEventListener('input', () => { if (pickColour && /^#[0-9a-f]{6}$/i.test(editValue.value.trim())) pickColour.value = editValue.value.trim(); });
1079
+ const saveValue = async () => {
1080
+ const { type, name } = state.detail;
1081
+ const phone = q('[data-size-phone]');
1082
+ const wide = q('[data-size-wide]');
1083
+ if (type === 'FontSizeToken' && phone && wide) {
1084
+ const [p0, w0] = sizeEnds(state.data.own[type][name]);
1085
+ const p1 = phone.value.trim();
1086
+ const w1 = wide.value.trim();
1087
+ if (p1 && w1 && (p1 !== p0 || w1 !== w0) && editValue.value.trim() === state.data.own[type][name]) {
1088
+ const keep = { ...state.detail };
1089
+ const out = p1 === w1
1090
+ ? await save('/__verso/tokens', { type, name, value: p1 }, `${name} is now ${p1}.`)
1091
+ : await save('/__verso/tokens/fluid', { name, min: p1, max: w1, override: true }, `${name} now runs from ${p1} on phones to ${w1} on wide screens.`);
1092
+ if (out) { state.detail = keep; render(); }
1093
+ return;
1094
+ }
1095
+ }
1096
+ const value = editValue.value.trim();
1097
+ if (!value || value === state.data.own[type][name]) return;
1098
+ const keep = { ...state.detail };
1099
+ const stored = type === 'ColorToken' ? tidyColour(value) : value;
1100
+ const out = await save('/__verso/tokens', { type, name, value: stored }, `${name} is now ${stored}.`);
1101
+ if (out) { state.detail = keep; render(); } else endPreview();
1102
+ };
1103
+ q('[data-do-value]')?.addEventListener('click', saveValue);
1104
+ [editValue, q('[data-size-phone]'), q('[data-size-wide]')].forEach((el) => el?.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); saveValue(); } }));
1105
+
1106
+ q('[data-do-rename]')?.addEventListener('click', async () => {
1107
+ const to = tokenName(q('[data-rename]').value);
1108
+ const { type, name } = state.detail;
1109
+ if (!to || to === name) return;
1110
+ // Renaming rewrites pages and blocks, so the page is drawn again;
1111
+ // the panel comes back where it was, and says what happened.
1112
+ const said = `Renamed to ${to}. Pages and blocks that use it follow the new name.`;
1113
+ comeBack(said);
1114
+ const out = await save('/__verso/tokens/rename', { type, from: name, to }, null);
1115
+ if (out) { state.detail = null; toast(said, 'ok'); render(); if (!out.changed?.length) forget(); } else forget();
1116
+ });
1117
+ q('[data-do-remove]')?.addEventListener('click', async () => {
1118
+ const { type, name, usage } = state.detail;
1119
+ const out = await save('/__verso/tokens/remove', { type, name, force: !!(usage && usage.length) }, `Removed ${name}.`);
1120
+ if (out) { state.detail = null; render(); }
1121
+ });
1122
+
1123
+ // Colours
1124
+ q('[data-add-colour]')?.addEventListener('click', () => {
1125
+ const name = tokenName(q('[data-new-colour-name]').value);
1126
+ if (!name) { toast('Give the colour a name first, like brand.', 'error'); return; }
1127
+ save('/__verso/tokens', { type: 'ColorToken', name, value: q('[data-new-colour]').value.toUpperCase() }, `Added ${name}. It's in the colour pickers now.`);
1128
+ });
1129
+ q('[data-preview-ramp]')?.addEventListener('click', async () => {
1130
+ const name = tokenName(q('[data-new-colour-name]').value);
1131
+ if (!name) { toast('Give the ramp a name first, like brand.', 'error'); return; }
1132
+ const res = await fetch('/__verso/tokens/ramp?preview=1', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, hex: q('[data-new-colour]').value }) });
1133
+ const out = await res.json();
1134
+ if (!out.ok) { toast(out.message, 'error'); return; }
1135
+ q('[data-ramp]').innerHTML = rampPreview(out.steps, name);
1136
+ q('[data-save-ramp]').addEventListener('click', () => save('/__verso/tokens/ramp', { name, hex: q('[data-new-colour]').value }, `Added nine shades of ${name}.`));
1137
+ q('[data-cancel-ramp]').addEventListener('click', () => { q('[data-ramp]').innerHTML = ''; });
1138
+ });
1139
+
1140
+ // Type
1141
+ const fluidPreview = () => {
1142
+ const el = q('[data-fluid-preview]');
1143
+ if (!el) return;
1144
+ const min = q('[data-fluid-min]').value.trim();
1145
+ const max = q('[data-fluid-max]').value.trim();
1146
+ el.style.fontSize = min && max ? `clamp(${min}, calc((${min} + ${max}) / 2), ${max})` : '';
1147
+ };
1148
+ q('[data-fluid-min]')?.addEventListener('input', fluidPreview);
1149
+ q('[data-fluid-max]')?.addEventListener('input', fluidPreview);
1150
+ q('[data-add-fluid]')?.addEventListener('click', () => {
1151
+ const name = tokenName(q('[data-fluid-name]').value);
1152
+ save('/__verso/tokens/fluid', { name, min: q('[data-fluid-min]').value, max: q('[data-fluid-max]').value }, `Added the ${name} size.`);
1153
+ });
1154
+ const uploadFont = async (file) => {
1155
+ const typed = q('[data-font-family]').value.trim();
1156
+ const params = new URLSearchParams({ family: typed, weight: q('[data-font-weight]').value, style: q('[data-font-style]').value, fallback: q('[data-font-fallback]').value });
1157
+ const res = await fetch(`/__verso/fonts?${params}`, { method: 'POST', body: file });
1158
+ const out = await res.json().catch(() => ({ ok: false, message: 'The upload didn\'t finish.' }));
1159
+ if (!out.ok) { toast(out.message, 'error'); return; }
1160
+ const what = `${out.family}${out.style === 'italic' ? ' italic' : ''}`;
1161
+ toast(out.weights ? `Added ${what}, with every weight from ${out.weights[0]} to ${out.weights[1]}. It's in the font pickers now.` : `Added ${what} at weight ${out.weight}. It's in the font pickers now.`, 'ok');
1162
+ load();
1163
+ };
1164
+ q('[data-font-file]')?.addEventListener('change', (e) => { const f = e.target.files[0]; if (f) uploadFont(f); });
1165
+ const drop = q('[data-font-drop]');
1166
+ if (drop) {
1167
+ drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.style.borderColor = '#FF4F2B'; });
1168
+ drop.addEventListener('dragleave', () => { drop.style.borderColor = ''; });
1169
+ drop.addEventListener('drop', (e) => { e.preventDefault(); e.stopPropagation(); drop.style.borderColor = ''; const f = e.dataTransfer.files[0]; if (f) uploadFont(f); });
1170
+ }
1171
+
1172
+ // Spacing
1173
+ q('[data-add-space]')?.addEventListener('click', () => {
1174
+ const name = tokenName(q('[data-space-name]').value);
1175
+ save('/__verso/tokens', { type: 'SpacingToken', name, value: q('[data-space-value]').value }, `Added ${name}. It's in the spacing pickers now.`);
1176
+ });
1177
+
1178
+ // Effects
1179
+ const effectPreview = () => {
1180
+ const el = q('[data-effect-preview]');
1181
+ if (!el) return;
1182
+ const v = q('[data-effect-value]').value;
1183
+ const isShadow = q('[data-effect-type]').value === 'ShadowToken';
1184
+ el.style.boxShadow = isShadow ? v : '';
1185
+ el.style.background = isShadow ? '' : v;
1186
+ };
1187
+ q('[data-effect-value]')?.addEventListener('input', effectPreview);
1188
+ q('[data-effect-type]')?.addEventListener('change', effectPreview);
1189
+ q('[data-add-effect]')?.addEventListener('click', () => {
1190
+ const type = q('[data-effect-type]').value;
1191
+ const name = tokenName(q('[data-effect-name]').value);
1192
+ save('/__verso/tokens', { type, name, value: q('[data-effect-value]').value }, `Added ${name}.`);
1193
+ });
1194
+ }
1195
+ }