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,734 @@
1
+ // The block builder: build a block by choosing tokens, and keep the file a
2
+ // developer can open and edit by hand. Every change is a surgical edit to
3
+ // blocks/<name>.html (see src/html-edit.js), checked by Elevate first.
4
+
5
+ import { screensFor, readScreenLabels } from '../screens.js';
6
+ import fs from 'fs';
7
+ import path from 'path';
8
+ import { loadElevate } from '../elevate.js';
9
+ import { humanize, escapeHtml, PLACEHOLDER_IMAGE, parseBlock, renderPage } from '../template.js';
10
+ import { loadSite, withParts } from '../site.js';
11
+ import { blockSurround } from '../blocks.js';
12
+ import {
13
+ parseFragment, findElement, allElements, setClass, insertPalette, removeElement, moveElement,
14
+ wrapElement, unwrapElement, decodeTokens, applyPick, currentPick, PICKERS, PALETTE, elementName,
15
+ constructs, setConstructTag, setOtherwise, otherwiseText, wrapCondition, unwrapConstruct,
16
+ plainText, setText, refsIn, setFormat, setRichTools, setColorField, colorFields,
17
+ insertAfter, duplicateElement, otherwiseKind, otherwiseNext, otherwiseOut, withStyles, tokenize,
18
+ } from '../html-edit.js';
19
+
20
+ const NAME = /^[a-z0-9][a-z0-9-]{0,60}$/;
21
+
22
+ // "Client name" → "client-name": the way a field is named in the file.
23
+ export const fieldSlug = (said) => String(said).trim().toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').replace(/^[0-9-]+/, '').slice(0, 40);
24
+
25
+ // Every file that holds blocks people put on pages: pages, the blocks that
26
+ // are the same on every page (content/site.json), components and starting
27
+ // layouts.
28
+ export function contentFiles(root) {
29
+ const out = [];
30
+ const walk = (dir) => {
31
+ if (!fs.existsSync(dir)) return;
32
+ fs.readdirSync(dir, { withFileTypes: true }).forEach((e) => {
33
+ if (e.name.startsWith('.')) return;
34
+ const file = path.join(dir, e.name);
35
+ if (e.isDirectory()) walk(file);
36
+ else if (e.name === 'page.json') out.push({ file, kind: 'page' });
37
+ });
38
+ };
39
+ walk(path.join(root, 'content'));
40
+ const site = path.join(root, 'content', 'site.json');
41
+ if (fs.existsSync(site)) out.push({ file: site, kind: 'site' });
42
+ const list = (dir, end, kind) => {
43
+ const d = path.join(root, dir);
44
+ if (fs.existsSync(d)) fs.readdirSync(d).filter((f) => f.endsWith(end)).sort().forEach((f) => out.push({ file: path.join(d, f), kind }));
45
+ };
46
+ list('components', '.json', 'component');
47
+ list('templates', '.layout.json', 'layout');
48
+ return out.map((f) => {
49
+ try { return { ...f, data: JSON.parse(fs.readFileSync(f.file, 'utf8')) }; } catch { return null; }
50
+ }).filter(Boolean);
51
+ }
52
+
53
+ // Is this a block of `name`, or an item of one of its lists of items?
54
+ const ofBlock = (node, name) => node && typeof node === 'object' && typeof node.block === 'string' && (node.block === name || node.block.startsWith(`${name}--`));
55
+ const walkJSON = (node, fn) => {
56
+ if (Array.isArray(node)) node.forEach((n) => walkJSON(n, fn));
57
+ else if (node && typeof node === 'object') {
58
+ fn(node);
59
+ Object.values(node).forEach((v) => { if (v && typeof v === 'object') walkJSON(v, fn); });
60
+ }
61
+ };
62
+ const renameKey = (obj, from, to) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [k === from ? to : k, v]));
63
+ const filled = (v) => (typeof v === 'string' ? v.replace(/<[^>]*>/g, '').trim() !== '' : Array.isArray(v) ? v.length > 0 : v && typeof v === 'object' ? Object.values(v).some(filled) : v != null && v !== false);
64
+
65
+ // The keys, in each component, of the blocks of `name` in its tree.
66
+ const componentKeys = (files, name) => new Map(files.filter((f) => f.kind === 'component').map((f) => {
67
+ const keys = new Set();
68
+ walkJSON(f.data.tree, (n) => { if (ofBlock(n, name) && n.key) keys.add(n.key); });
69
+ return [path.basename(f.file, '.json'), keys];
70
+ }));
71
+
72
+ // Where people see a file, in words.
73
+ const whereLabel = (root, f) => {
74
+ if (f.kind === 'site') return { label: 'Same on every page', url: null };
75
+ if (f.kind === 'component') return { label: `${f.data.label || humanize(path.basename(f.file, '.json'))} (component)`, url: null };
76
+ if (f.kind === 'layout') return { label: `Starting layout of ${humanize(path.basename(f.file, '.layout.json'))} pages`, url: null };
77
+ const dir = path.relative(path.join(root, 'content'), path.dirname(f.file)).split(path.sep).filter(Boolean);
78
+ const title = typeof f.data.title === 'string' ? f.data.title.split(/\s+[—–|]\s+/)[0].trim() : '';
79
+ return { label: dir.length ? title || humanize(dir[dir.length - 1]) : 'Home', url: dir.length ? `/${dir.join('/')}/` : '/' };
80
+ };
81
+
82
+ // The pages (and shared places) a block is on. With `fields`, only those
83
+ // where one of these fields (or lists of items) has something in it.
84
+ export function blockUses(root, name, fields = null) {
85
+ const files = contentFiles(root);
86
+ const keys = componentKeys(files, name);
87
+ const has = (bag, names, prefix = '') => names.some((n) => filled(bag?.[`${prefix}${n}`]));
88
+ const found = [];
89
+ files.forEach((f) => {
90
+ let hit = false;
91
+ walkJSON(f.data, (n) => {
92
+ if (hit) return;
93
+ if (ofBlock(n, name)) hit = !fields || has(n.fields, fields) || (n.block === name && has(n.blocks, fields));
94
+ else if (typeof n.component === 'string' && keys.get(n.component)?.size) {
95
+ hit = !fields || [...keys.get(n.component)].some((k) => has(n.fields, fields, `${k}.`));
96
+ }
97
+ });
98
+ if (!hit && f.kind === 'component' && fields) {
99
+ const k = keys.get(path.basename(f.file, '.json'));
100
+ hit = [...(k || [])].some((key) => has(f.data.shared, fields, `${key}.`) || has(f.data.defaults, fields, `${key}.`));
101
+ }
102
+ if (hit) found.push(whereLabel(root, f));
103
+ });
104
+ return found;
105
+ }
106
+
107
+ // Renames a field (or a list of items) of block `name` in everything people
108
+ // wrote with it, so no words are lost. All files are written, or none.
109
+ export function migrateField(root, name, from, to, onWrite = () => {}) {
110
+ const files = contentFiles(root);
111
+ const keys = componentKeys(files, name);
112
+ const changed = [];
113
+ files.forEach((f) => {
114
+ let touched = false;
115
+ walkJSON(f.data, (n) => {
116
+ if (ofBlock(n, name)) {
117
+ if (n.fields && typeof n.fields === 'object' && from in n.fields) { n.fields = renameKey(n.fields, from, to); touched = true; }
118
+ if (n.block === name && n.blocks && typeof n.blocks === 'object' && from in n.blocks) { n.blocks = renameKey(n.blocks, from, to); touched = true; }
119
+ if (n.block === `${name}--${from}`) { n.block = `${name}--${to}`; touched = true; }
120
+ } else if (typeof n.component === 'string' && keys.get(n.component)?.size && n.fields && typeof n.fields === 'object') {
121
+ keys.get(n.component).forEach((k) => { if (`${k}.${from}` in n.fields) { n.fields = renameKey(n.fields, `${k}.${from}`, `${k}.${to}`); touched = true; } });
122
+ }
123
+ });
124
+ if (f.kind === 'component') {
125
+ (keys.get(path.basename(f.file, '.json')) || new Set()).forEach((k) => {
126
+ ['shared', 'defaults'].forEach((bag) => {
127
+ if (f.data[bag] && typeof f.data[bag] === 'object' && `${k}.${from}` in f.data[bag]) { f.data[bag] = renameKey(f.data[bag], `${k}.${from}`, `${k}.${to}`); touched = true; }
128
+ });
129
+ });
130
+ }
131
+ if (touched) changed.push(f);
132
+ });
133
+ // Every file goes to a temporary file first; only when they all wrote do
134
+ // they take the place of the old ones.
135
+ const temps = [];
136
+ try {
137
+ changed.forEach((f) => {
138
+ const tmp = `${f.file}.${process.pid}.tmp`;
139
+ const text = JSON.stringify(f.data, null, 2) + '\n';
140
+ fs.writeFileSync(tmp, text, 'utf8');
141
+ temps.push({ tmp, file: f.file, text });
142
+ });
143
+ } catch (err) {
144
+ temps.forEach((t) => fs.rmSync(t.tmp, { force: true }));
145
+ throw err;
146
+ }
147
+ temps.forEach((t) => { onWrite(t.file, t.text); fs.renameSync(t.tmp, t.file); });
148
+ return changed.map((f) => whereLabel(root, f));
149
+ }
150
+
151
+ // Renames one of a block's fields everywhere it appears in the block:
152
+ // {{ text:text }} → {{ client:text }}, and {{ if:text }} with it. Writers see
153
+ // the field by this name ("Client") on the page.
154
+ export function renameField(source, from, said) {
155
+ const plain = (message) => Object.assign(new Error(message), { plain: true });
156
+ const to = fieldSlug(said);
157
+ if (!to) throw plain('Give it a name with at least one letter, like Client.');
158
+ if (to === from) return source;
159
+ if (['each', 'if', 'item', 'page', 'parent', 'part', 'end', 'list', 'count', 'site', 'paging'].includes(to)) throw plain(`"${said}" is a word Verso uses itself. Try another name.`);
160
+ const used = new RegExp(`\\{\\{\\s*(?:if:!?|list:)?${to.replace(/-/g, '\\-')}(?=[\\s:}=!])`);
161
+ if (used.test(source)) throw plain(`This block already has something called "${said}".`);
162
+ const esc = from.replace(/[.*+?^${}()|[\]\\-]/g, '\\$&');
163
+ return source
164
+ .replace(new RegExp(`(\\{\\{\\s*)${esc}(?=[\\s:}])`, 'g'), `$1${to}`)
165
+ .replace(new RegExp(`(\\{\\{\\s*if:!?)${esc}(?=[\\s}=!])`, 'g'), `$1${to}`)
166
+ .replace(new RegExp(`(\\{\\{\\s*list:)${esc}(?=[\\s}])`, 'g'), `$1${to}`);
167
+ }
168
+
169
+ export async function setup(ctx) {
170
+ const { root } = ctx;
171
+ // The site's own article styles (verso.json "rich"), so a heading or a
172
+ // paragraph the builder adds looks like the rest of the site from the start.
173
+ const articleStyles = () => {
174
+ try {
175
+ const rich = JSON.parse(fs.readFileSync(path.join(root, 'verso.json'), 'utf8')).rich;
176
+ return rich && typeof rich === 'object' && !Array.isArray(rich) ? rich : {};
177
+ } catch { return {}; }
178
+ };
179
+ // Inside a card of a list, words look like a card's: the article styles
180
+ // without their margins, plain links and lists, pictures at one shape so
181
+ // the tops of a grid line up. Anything Elevate can't read is left out.
182
+ const cardStyles = (a) => {
183
+ const rich = articleStyles();
184
+ const out = {};
185
+ ['h1', 'h2', 'h3', 'h4', 'p', 'time'].forEach((t) => {
186
+ if (typeof rich[t] === 'string') out[t] = rich[t].split(/\s+/).filter((x) => x && !/^mg[-:]/.test(x)).join(' ');
187
+ });
188
+ out.img = `${typeof rich.img === 'string' && rich.img.trim() ? rich.img.trim() : 'block w:full h:auto'} aspect:landscape fit:cover`;
189
+ // A class on a link or a list item would take away the reset's plain look.
190
+ ['a', 'ul', 'ol', 'li', 'blockquote'].forEach((t) => { out[t] = ''; });
191
+ Object.keys(out).forEach((t) => { if (out[t] && a.validate(out[t]).problems.length) delete out[t]; });
192
+ return out;
193
+ };
194
+ const blocksDir = path.join(root, 'blocks');
195
+ let api = null;
196
+ let loadedAt = 0;
197
+ // Elevate's API, reloaded at most every few seconds so new tokens show up.
198
+ const elevate = async () => {
199
+ if (!api || Date.now() - loadedAt > 3000) {
200
+ api = await loadElevate(root);
201
+ loadedAt = Date.now();
202
+ }
203
+ return api;
204
+ };
205
+
206
+ const plain = (message) => Object.assign(new Error(message), { plain: true });
207
+ const fileFor = (name) => {
208
+ if (!NAME.test(String(name || ''))) throw plain('Block names use lowercase letters, numbers and dashes, like feature-card.');
209
+ return path.join(blocksDir, `${name}.html`);
210
+ };
211
+ const read = (name) => {
212
+ const file = fileFor(name);
213
+ if (!fs.existsSync(file)) throw plain(`There's no block called "${name}".`);
214
+ return fs.readFileSync(file, 'utf8');
215
+ };
216
+ const write = (name, source) => {
217
+ const file = fileFor(name);
218
+ fs.mkdirSync(blocksDir, { recursive: true });
219
+ ctx.written.set(ctx.relPath(file), ctx.hash(Buffer.from(source, 'utf8')));
220
+ fs.writeFileSync(file, source, 'utf8');
221
+ };
222
+
223
+ // Fields named in a piece of source, leaving out if/each and item./page.
224
+ const fieldsIn = (text) => [...text.matchAll(/\{\{\s*([a-zA-Z][\w-]*)(?::([a-z]+))?[^}]*\}\}/g)]
225
+ // Verso's own words (lists, conditions, references) aren't fields writers fill in.
226
+ .filter((m) => !['if', 'each', 'item', 'page', 'list', 'else', 'count', 'paging', 'parent', 'site'].includes(m[1]))
227
+ .map((m) => ({ name: m[1], type: m[2] || 'text' }));
228
+
229
+ // Lists, conditions and repeaters, with the element each one starts at.
230
+ const constructInfo = (source, folderList = []) => {
231
+ const all = constructs(source);
232
+ const els = allElements(parseFragment(source));
233
+ // The element whose inside holds a position.
234
+ const container = (pos) => els.filter((el) => !el.void && el.openEnd < pos && pos < el.closeStart).sort((a, b) => b.start - a.start)[0] || null;
235
+ return all.map((c) => {
236
+ const box = container(c.open.start);
237
+ const mainEnd = c.alt ? c.alt.start : c.close.start;
238
+ const siblings = box ? box.children : parseFragment(source).children;
239
+ const first = siblings.find((el) => el.start >= c.open.end && el.end <= mainEnd);
240
+ const sec = c.info.section;
241
+ const label = c.kind === 'each' ? ({ 'item.tags': 'Its tags', tags: "This page's tags", 'all-tags': 'All the tags', tagged: 'Pages with this tag' }[sec]
242
+ || `List of pages from ${sec === 'children' ? 'the pages inside this one' : sec === 'siblings' ? 'the pages beside this one' : folderList.find((f) => f.name === sec)?.label || humanize(sec)}`)
243
+ : c.kind === 'if' ? `Shown only when ${humanize(c.info.target.replace(/^(item|page|parent|paging|site)\./, ''))} ${{ filled: 'is filled in', empty: 'is empty', is: `is ${c.info.value}`, not: `isn't ${c.info.value}` }[c.info.op]}`
244
+ : `List of items: ${humanize(c.info.name)}`;
245
+ // The element around the list, when the list is all it holds: the
246
+ // builder shows the two as one row.
247
+ const only = box && box.children.every((el) => el.start >= c.open.end && el.end <= c.close.start)
248
+ && !source.slice(box.openEnd + 1, c.open.start).trim() && !source.slice(c.close.end, box.closeStart).trim();
249
+ const altFirst = c.alt ? siblings.find((el) => el.start >= c.alt.end && el.end <= c.close.start) : null;
250
+ return { id: c.id, kind: c.kind, parent: c.parent, info: c.info, label, first: first ? first.path : null, altFirst: altFirst ? altFirst.path : null, box: c.kind !== 'if' && only && box.path !== '0' ? box.path : null, otherwise: c.kind === 'list' ? null : otherwiseText(source, c), otherwiseKind: c.kind === 'list' ? null : otherwiseKind(source, c) };
251
+ });
252
+ };
253
+
254
+ const tree = (source, system) => {
255
+ const all = constructs(source);
256
+ const node = (el) => {
257
+ const inner = el.void || el.raw ? '' : source.slice(el.openEnd + 1, el.children[0] ? el.children[0].start : el.closeStart);
258
+ const value = el.attr ? el.attr.value : '';
259
+ return {
260
+ path: el.path,
261
+ tag: el.tag,
262
+ name: elementName(el.tag, value, inner),
263
+ classes: value,
264
+ tokens: decodeTokens(value, system),
265
+ // What each picker shows, at each breakpoint ('' is the base).
266
+ picks: Object.fromEntries(['', ...system.breakpoints.map((b) => b.name)].map((bp) => [bp, Object.fromEntries(Object.keys(PICKERS).map((p) => [p, currentPick(value, p, bp || null, system)]))])),
267
+ fields: fieldsIn(inner),
268
+ attrFields: fieldsIn(source.slice(el.start, el.openEnd)),
269
+ void: !!el.void,
270
+ text: plainText(source, el),
271
+ refs: refsIn(source, el).map(({ ref, key, format }) => ({ ref, key, format })),
272
+ rich: (/\{\{\s*[\w.-]+:rich((?::[\w-]+)*)\s*\}\}/.exec(inner)?.[1] || null)?.split(':').filter((t) => t && t !== 'required') ?? null,
273
+ colors: colorFields(source, el),
274
+ // Inside a list of pages (not its "otherwise"): it shows each page.
275
+ inEach: all.some((c) => c.kind === 'each' && c.open.end <= el.start && el.end <= (c.alt ? c.alt.start : c.close.start)),
276
+ each: all.filter((c) => c.kind === 'each' && c.open.end <= el.start && el.end <= (c.alt ? c.alt.start : c.close.start)).map((c) => c.id).pop() ?? null,
277
+ inRepeater: all.some((c) => c.kind === 'list' && c.open.end <= el.start && el.end <= c.close.start),
278
+ repeater: all.filter((c) => c.kind === 'list' && c.open.end <= el.start && el.end <= c.close.start).map((c) => c.id).pop() ?? null,
279
+ ratio: el.tag === 'img' ? (/(?:^|\s)aspect:([\w-]+)/.exec(value.split(/\s\/[\w-]+\/(\s|$)/)[0])?.[1] || '') : null,
280
+ children: el.children.map(node),
281
+ };
282
+ };
283
+ return parseFragment(source).children.map(node);
284
+ };
285
+
286
+ // What a condition can check: the block's own fields, this page's
287
+ // settings, and inside a list, each page's fields.
288
+ const targets = (source, folderList) => {
289
+ const own = [];
290
+ const items = {};
291
+ try {
292
+ const parsed = parseBlock(withParts(root, source), 'block.html');
293
+ parsed.fields.forEach((f, name) => {
294
+ if (f.type !== 'blocks') own.push({ value: name, label: f.site ? `${humanize(name.slice(5))} (same on every page)` : humanize(name) });
295
+ });
296
+ // Inside a list of items, a condition checks the item's own fields.
297
+ constructs(source).filter((c) => c.kind === 'list').forEach((c) => {
298
+ const r = (parsed.repeaters || []).find((x) => x.name === c.info.name);
299
+ items[c.id] = r ? [...r.item.fields].filter(([, f]) => f.type !== 'blocks').map(([name]) => ({ value: name, label: `Its ${humanize(name).toLowerCase()}` })) : [];
300
+ });
301
+ } catch { /* the block doesn't read right now; offer page settings only */ }
302
+ const page = [['page.title', 'Page title'], ['page.description', 'Page description'], ['page.date', 'Page date'], ['page.tags', 'Page tags']].map(([value, label]) => ({ value, label }));
303
+ const each = {};
304
+ constructs(source).filter((c) => c.kind === 'each').forEach((c) => {
305
+ const folder = folderList.find((f) => f.name === c.info.section);
306
+ const fields = folder ? folder.fields.map((f) => ({ value: `item.${f.name}`, label: `Its ${f.label.toLowerCase()}` })) : [];
307
+ each[c.id] = [{ value: 'item.title', label: 'Its title' }, { value: 'item.description', label: 'Its description' }, { value: 'item.date', label: 'Its date' }, { value: 'item.tags', label: 'Its tags' }, ...fields];
308
+ });
309
+ return { own, page, each, items };
310
+ };
311
+
312
+ // Content folders with pages in them, what fields those pages have, and
313
+ // their tags, for list and condition pickers.
314
+ const folders = () => {
315
+ let site;
316
+ try { site = loadSite(root); } catch { return []; }
317
+ const map = new Map();
318
+ site.pages.forEach((p) => {
319
+ const parts = p.url.split('/').filter(Boolean);
320
+ if (!parts.length) return;
321
+ const folder = parts.slice(0, -1).join('/');
322
+ if (!folder) return;
323
+ const f = map.get(folder) || { name: folder, label: site.pages.find((x) => x.url === `/${folder}/`)?.label || humanize(folder.split('/').pop()), count: 0, fields: new Map(), tags: new Set() };
324
+ f.count += 1;
325
+ (p.tags || []).forEach((t) => f.tags.add(t));
326
+ site.templates.get(p.template)?.fields.forEach((field, name) => {
327
+ if (!field.site && field.type !== 'blocks') f.fields.set(name, field.type);
328
+ });
329
+ map.set(folder, f);
330
+ });
331
+ // A channel with nothing in it yet is still a folder to list.
332
+ Object.entries(site.config.channels || {}).forEach(([folder, c]) => {
333
+ if (map.has(folder)) return;
334
+ const fields = new Map();
335
+ site.templates.get(c?.template)?.fields.forEach((field, name) => { if (!field.site && field.type !== 'blocks') fields.set(name, field.type); });
336
+ map.set(folder, { name: folder, label: c?.label || humanize(folder.split('/').pop()), count: 0, fields, tags: new Set() });
337
+ });
338
+ return [...map.values()].sort((a, b) => a.name.localeCompare(b.name))
339
+ .map((f) => ({ name: f.name, label: f.label, count: f.count, tags: [...f.tags].sort(), fields: [...f.fields].map(([name, type]) => ({ name, type, label: humanize(name) })) }));
340
+ };
341
+
342
+ // Elevate's own colour ramps (name → value), read from its design file. A
343
+ // colour counts as the site's own when the site added it or changed it.
344
+ const elevateColors = () => {
345
+ const file = path.join(root, 'elevate/core/system/design/colors.ts');
346
+ if (!fs.existsSync(file)) return new Map();
347
+ return new Map([...fs.readFileSync(file, 'utf8').matchAll(/^\s*'?([a-z][\w+-]*)'?\s*:\s*'([^']*)'/gm)].map((m) => [m[1], m[2].toLowerCase()]));
348
+ };
349
+ const siteColorsFirst = (colors) => {
350
+ const defaults = elevateColors();
351
+ return colors
352
+ .map((c) => ({ ...c, elevate: defaults.get(c.name) === String(c.value).toLowerCase() }))
353
+ .sort((a, b) => Number(a.elevate) - Number(b.elevate));
354
+ };
355
+
356
+ // Only what the builder offers, from describe(): no free-form values.
357
+ const systemFor = (d) => {
358
+ const list = (type) => Object.entries(d.tokens[type] || {}).map(([name, value]) => ({ name, value }));
359
+ const rules = (type) => Object.entries(d.rules[type] || {}).map(([name, value]) => ({ name, value }));
360
+ return {
361
+ // With what people call them ("Tablets"), narrowest first.
362
+ breakpoints: screensFor(d.breakpoints, readScreenLabels(root)),
363
+ spacing: list('SpacingToken').filter((t) => /^(d\d+|c\d+|0|px)$/.test(t.name)),
364
+ widths: list('SpacingToken').filter((t) => /^(s\d+|full|fit-content|auto)$/.test(t.name)),
365
+ // The site's own colours first; Elevate's built-in ramps after, marked,
366
+ // so the builder can tuck them under "More colours".
367
+ colors: siteColorsFirst(list('ColorToken')),
368
+ families: list('FontFamilyToken'),
369
+ sizes: list('FontSizeToken'),
370
+ weights: list('FontWeightToken'),
371
+ leading: list('LineHeightToken'),
372
+ shadows: list('ShadowToken'),
373
+ xAxis: rules('xAxis').map((r) => r.name),
374
+ yAxis: rules('yAxis').map((r) => r.name),
375
+ palette: Object.entries(PALETTE).map(([name, p]) => ({ name, label: p.label, group: p.group, where: p.where })),
376
+ folders: folders(),
377
+ };
378
+ };
379
+
380
+ // A pick may not make a class string worse than it was.
381
+ const checkClass = (a, before, after) => {
382
+ const old = new Set(a.validate(before).problems.map((p) => p.token));
383
+ const bad = a.validate(after).problems.find((p) => !old.has(p.token));
384
+ if (bad) throw plain(`That would make "${bad.token}", which Elevate can't use: ${bad.message}`);
385
+ };
386
+
387
+ const walkBlocks = (blocks, fn) => Object.values(blocks || {}).forEach((list) => (Array.isArray(list) ? list : []).forEach((b) => { fn(b); walkBlocks(b.blocks, fn); }));
388
+ let siteCompile = null;
389
+ const filledValue = (v) => (typeof v === 'string' ? v.trim() !== '' : v != null);
390
+ const preview = async (name) => {
391
+ const source = read(name);
392
+ const templates = fs.existsSync(path.join(root, 'templates')) ? fs.readdirSync(path.join(root, 'templates')).filter((f) => f.endsWith('.html')).sort() : [];
393
+ const shell = templates.length ? fs.readFileSync(path.join(root, 'templates', templates.includes('page.html') ? 'page.html' : templates[0]), 'utf8') : '';
394
+ const head = (/<head[^>]*>([\s\S]*?)<\/head>/i.exec(shell)?.[1] || '<meta charset="utf-8">')
395
+ .replace(/<title[\s\S]*?<\/title>/i, '')
396
+ .replace(/<link[^>]*elevate\.css[^>]*>/gi, '')
397
+ .replace(/\{\{[^}]*\}\}/g, '');
398
+ const body = (/<body([^>]*)>/i.exec(shell)?.[1] || '').replace(/\{\{[^}]*\}\}/g, '');
399
+ // Mark each element with its path, then show the block with real pages,
400
+ // and the block's own fields filled with their names.
401
+ const els = allElements(parseFragment(source)).sort((a, b) => b.openEnd - a.openEnd);
402
+ let html = source;
403
+ els.forEach((el) => {
404
+ const at = el.selfClosing ? el.openEnd - 1 : el.openEnd;
405
+ html = `${html.slice(0, at)} data-path="${el.path}"${html.slice(at)}`;
406
+ });
407
+ let problem = '';
408
+ let around = { open: '', close: '' };
409
+ const real = (() => {
410
+ try {
411
+ const site = loadSite(root);
412
+ around = blockSurround(site, name);
413
+ const tpl = parseBlock(withParts(root, html, `blocks/${name}.html`), `blocks/${name}.html`);
414
+ const sampleFields = (t) => {
415
+ const fields = {};
416
+ t.fields.forEach((f, k) => {
417
+ if (f.site) return;
418
+ if (f.type === 'text') fields[k] = humanize(k);
419
+ else if (f.type === 'rich') fields[k] = `<p>${escapeHtml(humanize(k))}</p>`;
420
+ });
421
+ return fields;
422
+ };
423
+ const blocks = {};
424
+ (tpl.repeaters || []).forEach((r) => {
425
+ blocks[r.name] = [1, 2].map((n) => ({ id: `preview-${r.name}-${n}`, block: `${name}--${r.name}`, fields: sampleFields(r.item) }));
426
+ });
427
+ const inst = { id: 'preview', block: name, fields: sampleFields(tpl), blocks };
428
+ const uses = (p) => JSON.stringify(p.blocks || {}).includes(`"block":"${name}"`);
429
+ const page = site.pages.find(uses) || site.pages.find((p) => p.url === '/') || site.pages[0] || { url: '/', fields: {}, rich: {} };
430
+ // The words of the first page that uses the block, where it has them.
431
+ let real = null;
432
+ if (uses(page)) walkBlocks(page.blocks, (b) => { if (!real && b.block === name) real = b; });
433
+ if (real) {
434
+ Object.entries(real.fields || {}).forEach(([k, v]) => { if (tpl.fields.has(k) && filledValue(v)) inst.fields[k] = v; });
435
+ (tpl.repeaters || []).forEach((r) => {
436
+ const items = real.blocks?.[r.name];
437
+ // Real items as they are: a Badge left empty stays empty, so
438
+ // the preview shows which items a condition picks out.
439
+ if (Array.isArray(items) && items.length) inst.blocks[r.name] = items.map((it, n) => ({ ...it, fields: { ...(it.fields || {}) }, id: it.id || `preview-${r.name}-${n}` }));
440
+ });
441
+ }
442
+ const own = { ...page, fields: {}, rich: {} };
443
+ Object.entries(inst.fields).forEach(([k, v]) => { if (tpl.fields.get(k)?.type === 'rich') own.rich[k] = v; else own.fields[k] = v; });
444
+ return renderPage(tpl, own, { mode: 'editor', pages: site.pages, blocks: site.blocks, rich: site.config.rich, locale: site.config.locale, prefix: '@preview.', instance: inst });
445
+ } catch (err) {
446
+ problem = err.message;
447
+ return null;
448
+ }
449
+ })();
450
+ if (real != null) html = real;
451
+ else html = html
452
+ .replace(/\{\{\s*\/?(if|each)\b[^}]*\}\}/g, '') // conditions and lists: show what's inside
453
+ .replace(/\{\{\s*(item|page)\.([\w-]+)\s*\}\}/g, (m, scope, key) => escapeHtml(humanize(key)))
454
+ .replace(/\{\{\s*([a-zA-Z][\w-]*)(?::([a-z]+))?([^}]*)\}\}/g, (m, field, type = 'text') => {
455
+ if (type === 'image') return PLACEHOLDER_IMAGE;
456
+ if (type === 'blocks') return `<div style="border:1.5px dashed #FF4F2B;border-radius:8px;padding:20px;font:500 13px/1.4 ui-sans-serif,system-ui,sans-serif;color:#D93A1A;text-align:center">Blocks go here: ${escapeHtml(humanize(field))}</div>`;
457
+ if (type === 'rich') return `<p>${escapeHtml(humanize(field))}</p>`;
458
+ return escapeHtml(humanize(field));
459
+ }).replace(/\{\{[^}]*\}\}/g, '');
460
+ return `<!DOCTYPE html><html><head>${head}
461
+ <link rel="stylesheet" href="/__verso/builder/css?name=${encodeURIComponent(name)}&t=${Date.now()}">
462
+ <style>a{pointer-events:auto}[data-verso-field]:empty::before{content:attr(data-verso-field);opacity:.45}[data-path]{cursor:pointer}[data-verso-selected]{outline:2px solid #FF4F2B!important;outline-offset:2px}[data-verso-hover]:not([data-verso-selected]){outline:1px solid rgba(255,79,43,.6);outline-offset:2px}</style>
463
+ </head><body${body}>${problem ? `<p style="margin:0;padding:10px 16px;background:#FFEEE8;color:#B42D12;font:500 13px/1.4 ui-sans-serif,system-ui,sans-serif">${escapeHtml(problem)}</p>` : ''}<div style="padding:clamp(16px,4vw,48px)">${around.open}${html}${around.close}</div></body></html>`;
464
+ };
465
+
466
+ return {
467
+ async handle(req, res, url) {
468
+ const p = url.pathname;
469
+ if (!p.startsWith('/__verso/builder/')) return false;
470
+ try {
471
+ if (p === '/__verso/builder/blocks' && req.method === 'GET') {
472
+ const names = fs.existsSync(blocksDir) ? fs.readdirSync(blocksDir).filter((f) => f.endsWith('.html')).map((f) => f.slice(0, -5)).sort() : [];
473
+ // How many places use each block, for the "New block" screen.
474
+ const files = contentFiles(root);
475
+ const used = Object.fromEntries(names.map((n) => [n, files.filter((f) => { let hit = false; walkJSON(f.data, (x) => { if (!hit && ofBlock(x, n)) hit = true; }); return hit; }).length]));
476
+ ctx.sendJSON(res, 200, { ok: true, blocks: names, used });
477
+ return true;
478
+ }
479
+ if (p === '/__verso/builder/system' && req.method === 'GET') {
480
+ ctx.sendJSON(res, 200, { ok: true, ...systemFor((await elevate()).describe()) });
481
+ return true;
482
+ }
483
+ if (p === '/__verso/builder/block' && req.method === 'GET') {
484
+ const name = url.searchParams.get('name');
485
+ const source = read(name);
486
+ const folderList = folders();
487
+ ctx.sendJSON(res, 200, { ok: true, name, source, tree: tree(source, (await elevate()).describe()), constructs: constructInfo(source, folderList), targets: targets(source, folderList), usedOn: blockUses(root, name) });
488
+ return true;
489
+ }
490
+ if (p === '/__verso/builder/preview' && req.method === 'GET') {
491
+ ctx.send(res, 200, await preview(url.searchParams.get('name')));
492
+ return true;
493
+ }
494
+ if (p === '/__verso/builder/css' && req.method === 'GET') {
495
+ const a = await elevate();
496
+ const source = read(url.searchParams.get('name'));
497
+ const extra = allElements(parseFragment(source)).map((el) => el.attr?.value).filter(Boolean);
498
+ const result = await a.build({ write: false, files: false, extra });
499
+ ctx.send(res, 200, result.ok ? result.css : ctx.css, 'text/css; charset=utf-8');
500
+ return true;
501
+ }
502
+ if (p === '/__verso/builder/delete' && req.method === 'POST') {
503
+ // Deleting a block deletes its file. If pages use it, that's said
504
+ // first; with { everywhere: true } it's taken off them too.
505
+ const asked = await ctx.readBody(req);
506
+ const name = String(asked.name || '');
507
+ read(name);
508
+ const files = contentFiles(root);
509
+ const uses = files.filter((f) => { let hit = false; walkJSON(f.data, (x) => { if (!hit && ofBlock(x, name)) hit = true; }); return hit; });
510
+ const inComponent = uses.filter((f) => f.kind === 'component').map((f) => humanize(path.basename(f.file, '.json')));
511
+ if (inComponent.length) throw plain(`${humanize(name)} is part of the ${inComponent.join(' and ')} component. Take it out of the component first.`);
512
+ if (uses.length && asked.everywhere !== true) {
513
+ const where = blockUses(root, name).map((u) => u.label);
514
+ ctx.sendJSON(res, 409, { ok: false, used: where, message: `${humanize(name)} is used on ${where.length === 1 ? where[0] : `${where.length} pages`}. Deleting it takes it off ${where.length === 1 ? 'that page' : 'them'} too.` });
515
+ return true;
516
+ }
517
+ const strip = (node) => {
518
+ if (Array.isArray(node)) {
519
+ for (let i = node.length - 1; i >= 0; i -= 1) { if (node[i] && typeof node[i] === 'object' && node[i].block === name) node.splice(i, 1); else strip(node[i]); }
520
+ } else if (node && typeof node === 'object') Object.values(node).forEach(strip);
521
+ };
522
+ uses.forEach((f) => {
523
+ strip(f.data);
524
+ const text = JSON.stringify(f.data, null, 2) + '\n';
525
+ fs.writeFileSync(f.file, text, 'utf8');
526
+ ctx.written.set(ctx.relPath(f.file), ctx.hash(Buffer.from(text, 'utf8')));
527
+ });
528
+ fs.rmSync(fileFor(name));
529
+ ctx.written.set(ctx.relPath(fileFor(name)), 'deleted');
530
+ await ctx.compile({});
531
+ ctx.sendJSON(res, 200, { ok: true, name, removedFrom: uses.length });
532
+ return true;
533
+ }
534
+ if (p === '/__verso/builder/new' && req.method === 'POST') {
535
+ // People name blocks the way they'd say them ("Project facts");
536
+ // the file gets a tidy name ("project-facts").
537
+ const asked = await ctx.readBody(req);
538
+ const said = String(asked.name || '').trim();
539
+ const name = said.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60);
540
+ if (!name) throw plain('Give the block a name with at least one letter, like Project facts.');
541
+ const file = fileFor(name);
542
+ if (fs.existsSync(file)) throw plain(`There's already a block called "${said}".`);
543
+ // A new block lines up with the rest of the site from the start.
544
+ // "Start from an existing block": a copy, so the pages using the
545
+ // original don't change.
546
+ write(name, asked.from ? read(String(asked.from)) : '<section class="contain max-w:s11 w:full col gap:d4 pd-y:d10">\n</section>\n');
547
+ ctx.sendJSON(res, 200, { ok: true, name });
548
+ return true;
549
+ }
550
+ if (p === '/__verso/builder/edit' && req.method === 'POST') {
551
+ const body = await ctx.readBody(req);
552
+ const a = await elevate();
553
+ const system = a.describe();
554
+ const before = read(body.name);
555
+ let after = before;
556
+ let selected = null;
557
+ const extra = {};
558
+ const el = body.path ? findElement(parseFragment(before), body.path) : null;
559
+ const lists = constructs(before).filter((c) => c.kind === 'each' || c.kind === 'list');
560
+ const inCard = (x) => !!x && x.tag && lists.some((c) => c.open.end <= x.start && x.end <= c.close.start);
561
+ // Fields a new piece brought, so the builder can ask what to call it.
562
+ const added = (source, at) => {
563
+ const e = at && findElement(parseFragment(source), at);
564
+ return e ? [...new Set(fieldsIn(source.slice(e.start, e.end)).map((f) => f.name))] : [];
565
+ };
566
+ switch (body.op) {
567
+ case 'pick': {
568
+ if (!el) throw plain('Pick an element first.');
569
+ const value = el.attr ? el.attr.value : '';
570
+ if (body.value != null && typeof body.value !== 'string') throw plain('That choice isn\'t one the builder offers.');
571
+ const next = applyPick(value, body.picker, body.value || null, body.bp || null, system);
572
+ checkClass(a, value, next);
573
+ after = setClass(before, body.path, next);
574
+ break;
575
+ }
576
+ case 'page-width': {
577
+ // "Page width" lines the element up with the rest of the site:
578
+ // Elevate's contain, at the starter's reading width.
579
+ if (!el) throw plain('Pick an element first.');
580
+ const value = el.attr ? el.attr.value : '';
581
+ const parts = value.split(/\s+/).filter(Boolean);
582
+ const has = parts.includes('contain');
583
+ let next;
584
+ // w:full keeps the width when the block sits in a flex column
585
+ // (contain centres with auto margins, which would shrink it).
586
+ if (body.on && !has) next = ['contain', 'max-w:s11', 'w:full', ...parts.filter((t) => !/^max-w:/.test(t) && t !== 'w:full')].join(' ');
587
+ else if (!body.on && has) next = parts.filter((t) => t !== 'contain' && t !== 'max-w:s11' && t !== 'w:full').join(' ');
588
+ else next = value;
589
+ checkClass(a, value, next);
590
+ after = setClass(before, body.path, next);
591
+ break;
592
+ }
593
+ case 'insert': {
594
+ // A piece goes after the selected element; into it when it's a
595
+ // box (or the block's outer element), at the end.
596
+ const target = el || findElement(parseFragment(before), '0');
597
+ const leaf = target && (target.void || target.raw || (!target.children.length
598
+ && (/^(h[1-6]|p|a|span|time|blockquote|button|strong|em|small|label|figcaption|video|iframe)$/.test(target.tag) || /\{\{/.test(before.slice(target.openEnd + 1, target.closeStart)))));
599
+ const beside = leaf && target.path !== '0';
600
+ const styles = inCard(beside ? target.parent : target) ? cardStyles(a) : articleStyles();
601
+ if (beside) {
602
+ insertPalette(before, '0', body.item, null, body.options || {}); // checks the piece and its choices
603
+ const html = withStyles(PALETTE[body.item].html(before, body.options || {}), styles);
604
+ const r = insertAfter(before, target.path, html);
605
+ after = r.source;
606
+ selected = r.path;
607
+ } else {
608
+ after = insertPalette(before, target ? target.path : '0', body.item, null, { ...(body.options || {}), styles });
609
+ selected = target ? `${target.path}.${target.children.length}` : null;
610
+ }
611
+ if (selected && !findElement(parseFragment(after), selected)) selected = null;
612
+ extra.added = added(after, selected);
613
+ break;
614
+ }
615
+ case 'duplicate': {
616
+ if (!el) throw plain('Pick an element first.');
617
+ const r = duplicateElement(before, body.path);
618
+ after = r.source;
619
+ selected = r.path;
620
+ break;
621
+ }
622
+ case 'ratio': {
623
+ // A picture's shape: the base classes only (before any screen size).
624
+ if (!el || el.tag !== 'img') throw plain('Pick a picture first.');
625
+ const value = el.attr ? el.attr.value : '';
626
+ const parts = value.split(/\s+/).filter(Boolean);
627
+ const cut = parts.findIndex((t) => /^\/[\w-]+\/$/.test(t));
628
+ const base = (cut < 0 ? parts : parts.slice(0, cut)).filter((t) => !/^aspect:/.test(t) && t !== 'fit:cover');
629
+ if (body.value) {
630
+ if (!['landscape', 'square', 'portrait', 'video', 'widescreen'].includes(body.value)) throw plain('That shape isn\'t one the builder offers.');
631
+ base.push(`aspect:${body.value}`, 'fit:cover');
632
+ }
633
+ const next = [...base, ...(cut < 0 ? [] : parts.slice(cut))].join(' ');
634
+ checkClass(a, value, next);
635
+ after = setClass(before, body.path, next);
636
+ break;
637
+ }
638
+ case 'list': after = setConstructTag(before, body.id, body.info || {}); break;
639
+ case 'condition': {
640
+ if (!el) throw plain('Pick an element first.');
641
+ after = wrapCondition(before, body.path, body.info || {});
642
+ // Select the new condition, so it shows in the tree and its
643
+ // "Otherwise" is right there.
644
+ const made = constructs(after).find((c) => c.kind === 'if' && c.open.start === el.start);
645
+ if (made) selected = `c:${made.id}`;
646
+ break;
647
+ }
648
+ case 'otherwise-next': after = otherwiseNext(before, body.id); selected = `c:${body.id}`; break;
649
+ case 'otherwise-out': after = otherwiseOut(before, body.id); selected = `c:${body.id}`; break;
650
+ case 'condition-set': after = setConstructTag(before, body.id, body.info || {}); break;
651
+ case 'otherwise': after = setOtherwise(before, body.id, body.text == null ? null : String(body.text)); break;
652
+ case 'unwrap-construct': after = unwrapConstruct(before, body.id); break;
653
+ case 'text': after = setText(before, body.path, body.text); break;
654
+ case 'rename-field': {
655
+ const from = String(body.from || '');
656
+ after = renameField(before, from, String(body.to || ''));
657
+ if (after !== before) {
658
+ try { parseBlock(withParts(root, after), `blocks/${body.name}.html`); } catch (err) { throw plain(`That would break the block: ${err.message}`); }
659
+ // The words people wrote follow the new name on every page.
660
+ extra.moved = migrateField(root, body.name, from, fieldSlug(String(body.to || '')), (file, text) => ctx.written.set(ctx.relPath(file), ctx.hash(Buffer.from(text, 'utf8'))));
661
+ }
662
+ break;
663
+ }
664
+ case 'restore': {
665
+ // Undo: the block as it was. Words stay in the pages, so they're back too.
666
+ if (typeof body.source !== 'string' || !body.source.trim()) throw plain('There\'s nothing to put back.');
667
+ after = body.source;
668
+ break;
669
+ }
670
+ case 'format': after = setFormat(before, body.path, body.ref, body.format || null); break;
671
+ case 'tools': after = setRichTools(before, body.path, Array.isArray(body.tools) ? body.tools : []); break;
672
+ case 'color': after = setColorField(before, body.path, body.prop, !!body.on); break;
673
+ case 'remove':
674
+ if (body.path === '0' && parseFragment(before).children.length === 1) throw plain('A block needs its outer element. Delete the block file to remove the whole block.');
675
+ after = removeElement(before, body.path);
676
+ if (el) {
677
+ // Words that pages hold for what's going away: say where, so
678
+ // it can be undone.
679
+ const gone = new Set(fieldsIn(before.slice(el.start, el.end)).map((f) => f.name));
680
+ [...before.slice(el.start, el.end).matchAll(/\{\{\s*list:([\w-]+)/g)].forEach((m) => gone.add(m[1]));
681
+ fieldsIn(after).forEach((f) => gone.delete(f.name));
682
+ [...after.matchAll(/\{\{\s*list:([\w-]+)/g)].forEach((m) => gone.delete(m[1]));
683
+ extra.removed = { from: gone.size ? blockUses(root, body.name, [...gone]) : [], source: before };
684
+ }
685
+ break;
686
+ case 'move': {
687
+ const dir = body.dir < 0 ? -1 : 1;
688
+ after = moveElement(before, body.path, dir);
689
+ if (after === before) {
690
+ const sibs = el?.parent?.children || [];
691
+ const edge = sibs.indexOf(el) + dir < 0 || sibs.indexOf(el) + dir >= sibs.length;
692
+ throw plain(edge ? (dir < 0 ? 'That\'s already first in its box.' : 'That\'s already last in its box.') : 'That shares a condition or list with its neighbour, so it can\'t move past it. Move the condition or list instead.');
693
+ }
694
+ const parts = String(body.path).split('.');
695
+ parts[parts.length - 1] = String(Number(parts[parts.length - 1]) + dir);
696
+ selected = parts.join('.');
697
+ break;
698
+ }
699
+ case 'wrap': after = wrapElement(before, body.path, 'div'); break;
700
+ case 'unwrap': after = unwrapElement(before, body.path); break;
701
+ default: throw plain(`"${body.op}" isn't something the builder can do.`);
702
+ }
703
+ // Never write a block that no longer reads: say why instead.
704
+ if (after !== before) {
705
+ let wasFine = true;
706
+ try { parseBlock(withParts(root, before), `blocks/${body.name}.html`); } catch { wasFine = false; }
707
+ if (wasFine) {
708
+ try { parseBlock(withParts(root, after), `blocks/${body.name}.html`); } catch (err) { throw plain(`That would break the block: ${err.message}`); }
709
+ }
710
+ }
711
+ if (after !== before) {
712
+ write(body.name, after);
713
+ // The page under the builder needs the new CSS too, but not this
714
+ // instant: wait for a pause in the clicks, so the site's build
715
+ // doesn't hold up the builder's own preview.
716
+ clearTimeout(siteCompile);
717
+ siteCompile = setTimeout(() => ctx.compile().catch(() => {}), 400);
718
+ }
719
+ const folderList = folders();
720
+ // The builder asks for the new preview with the edit: one round trip.
721
+ const shown = body.preview ? { preview: await preview(body.name) } : {};
722
+ ctx.sendJSON(res, 200, { ok: true, name: body.name, source: after, tree: tree(after, system), constructs: constructInfo(after, folderList), targets: targets(after, folderList), ...extra, ...shown, ...(selected ? { selected } : {}) });
723
+ return true;
724
+ }
725
+ ctx.send(res, 404, 'Not found', 'text/plain');
726
+ return true;
727
+ } catch (err) {
728
+ if (!err.plain) throw err;
729
+ ctx.sendJSON(res, 400, { ok: false, message: err.message });
730
+ return true;
731
+ }
732
+ },
733
+ };
734
+ }