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,915 @@
1
+ // Templates are plain HTML files with a few kinds of tag in them:
2
+ //
3
+ // Fields {{ headline:text:required }} {{ body:rich:headings:links }} {{ cover:image }}
4
+ // Site fields {{ site.tagline:text }}, the same on every page
5
+ // Slots {{ sections:blocks }}
6
+ // Repeaters {{ list:team }} … {{ /list }}, a list of items edited on the page
7
+ // Lists {{ each:journal:newest:10 }} … {{ else }} … {{ /each }}, with {{ item.title }} inside
8
+ // Conditions {{ if:cover }} … {{ else }} … {{ /if }}, {{ if:kind=essay }}, {{ if:!cover }}
9
+ // Counts {{ count:journal }}
10
+ // References {{ page.title }}, {{ parent.title }}, {{ item.date:short }}, {{ paging.next }}
11
+ //
12
+ // This file reads a template once into a tree, checks it, and renders pages
13
+ // from it.
14
+
15
+ import { VersoError, lineAt } from './errors.js';
16
+ import { applyRichClasses, richIsEmpty } from './rich.js';
17
+ import { expandList } from './components.js';
18
+
19
+ // ════ Field types ════
20
+ export const RICH_TOOLS = ['headings', 'lists', 'links', 'images', 'tables', 'quotes', 'callouts', 'embeds', 'code'];
21
+ export const fieldTypes = {
22
+ text: { modifiers: ['required'] },
23
+ rich: { modifiers: ['required', ...RICH_TOOLS] },
24
+ image: { modifiers: ['required'] },
25
+ // One of the site's design colours, chosen visually. Renders its CSS value,
26
+ // for use in a style attribute: style="--ink: {{ ink:color }}".
27
+ color: { modifiers: ['required'] },
28
+ // A slot: {{ sections:blocks }} takes any block, {{ items:blocks:card:quote }}
29
+ // only those. The names are checked against blocks/ when the site loads.
30
+ blocks: { modifiers: null },
31
+ };
32
+ const SORTS = ['newest', 'oldest', 'a-z', 'z-a', 'order', 'most'];
33
+ const BUILT_INS = ['url', 'title', 'description', 'date', 'date-iso', 'label', 'tags', 'tag', 'count'];
34
+ const PAGING = ['next', 'previous', 'number', 'total'];
35
+ const PAGE_SETTINGS = BUILT_INS.filter((k) => k !== 'count');
36
+ // Lists that aren't folders in content/.
37
+ const SPECIAL_LISTS = ['children', 'siblings', 'item', 'tags', 'item.tags', 'tagged', 'all-tags'];
38
+ export const DATE_FORMATS = ['long', 'short', 'numeric', 'month', 'year', 'iso'];
39
+ const FORMAT = /^(long|short|numeric|month|year|iso|words-\d+|chars-\d+)$/;
40
+ const RESERVED = new Set(['each', 'if', 'item', 'page', 'parent', 'part', 'end']);
41
+
42
+ const TAG = /\{\{([^{}<>]*)\}\}/g;
43
+ const NAME = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
44
+ const FIELD_NAME = /^(site\.)?[a-zA-Z][a-zA-Z0-9_-]*$/;
45
+ const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
46
+ const RAW = new Set(['script', 'style', 'textarea', 'title']);
47
+
48
+ export const humanize = (name) => {
49
+ const words = String(name).replace(/[-_]+/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2').trim().toLowerCase();
50
+ return words.charAt(0).toUpperCase() + words.slice(1);
51
+ };
52
+ export const escapeHtml = (value) => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
53
+ export const escapeAttr = (value) => escapeHtml(value).replace(/"/g, '&quot;').replace(/'/g, '&#39;');
54
+
55
+ // ════ Reading one {{ … }} ════
56
+ function readTag(inner, file, line) {
57
+ const raw = inner.trim();
58
+ const token = `{{ ${raw} }}`;
59
+ const fail = (message, hint) => { throw new VersoError(message, { file, line, hint: hint || `In ${token}` }); };
60
+
61
+ if (raw === '/each' || raw === '/if' || raw === '/list') return { kind: 'close', block: raw.slice(1), token };
62
+ if (raw === 'else') return { kind: 'else', token };
63
+ if (raw.startsWith('/') || raw === 'end' || raw === 'endif' || raw === 'endeach') {
64
+ const guess = nearest(raw.replace(/^\/|^end/, ''), ['each', 'if', 'list']);
65
+ fail(`There's no ${token}. Close with {{ /each }}, {{ /if }} or {{ /list }}.`, guess ? `Did you mean {{ /${guess} }}?` : undefined);
66
+ }
67
+ if (raw.startsWith('{') || raw.endsWith('}')) fail(`${token} has an extra brace. Tags use two on each side, like {{ title:text }}.`);
68
+
69
+ if (raw === 'list' || raw.startsWith('list:')) {
70
+ const name = raw.slice(5).trim();
71
+ if (!name) fail('Name the list, like {{ list:team }}. Its items are edited right on the page.');
72
+ if (!NAME.test(name)) fail(`"${name}" can't be a list name. Use letters, numbers, - and _, starting with a letter.`);
73
+ if (RESERVED.has(name)) fail(`"${name}" is a word templates use for themselves. Give the list another name.`);
74
+ return { kind: 'list', name, token };
75
+ }
76
+
77
+ const readList = (rest, what) => {
78
+ const [rawSection = '', ...mods] = rest.split(':').map((p) => p.trim());
79
+ const section = rawSection.replace(/^\/+|\/+$/g, '');
80
+ if (!section) fail(`Say which pages to ${what}. {{ ${what === 'count' ? 'count' : 'each'}:journal }} uses the pages in content/journal/, {{ each:children }} the pages inside this one.`);
81
+ if (!SPECIAL_LISTS.includes(section) && (!/^[a-zA-Z0-9][a-zA-Z0-9_/-]*$/.test(section) || section.split('/').some((s) => !s || s === '..'))) {
82
+ fail(`"${section}" isn't a folder in content/. Use its path, like journal or work/clients, or children, siblings, tags or tagged.`);
83
+ }
84
+ let sort = ['tags', 'item.tags', 'all-tags'].includes(section) ? 'a-z' : 'newest';
85
+ let limit = null;
86
+ let skip = 0;
87
+ let paged = false;
88
+ const filters = [];
89
+ mods.forEach((m) => {
90
+ let f;
91
+ if (SORTS.includes(m)) sort = m;
92
+ else if (/^\d+$/.test(m) && Number(m) > 0) limit = Number(m);
93
+ else if (/^skip-\d+$/.test(m)) skip = Number(m.slice(5));
94
+ else if (m === 'paged') paged = true;
95
+ else if (m === 'others') filters.push({ type: 'others' });
96
+ else if ((f = /^tagged-(.+)$/.exec(m))) filters.push({ type: 'tagged', value: slugifyTag(f[1]) });
97
+ else if ((f = /^(has|no)-([a-zA-Z][a-zA-Z0-9_-]*)$/.exec(m))) filters.push({ type: f[1], field: f[2] });
98
+ else if ((f = /^([a-zA-Z][a-zA-Z0-9_-]*)(!?=)(.*)$/.exec(m))) filters.push({ type: f[2] === '=' ? 'is' : 'not', field: f[1], value: unquote(f[3]) });
99
+ else fail(`"${m}" isn't something a list understands.${nearest(m, [...SORTS, 'paged', 'others']) ? ` Did you mean ${nearest(m, [...SORTS, 'paged', 'others'])}?` : ''}`, `Use a sort (${SORTS.join(', ')}), a number, skip-1, paged, others (leave out this page), tagged-design, has-cover, no-cover, or kind=essay. In ${token}`);
100
+ });
101
+ if (paged && !limit) fail('Say how many go on each page, like {{ each:journal:10:paged }}.');
102
+ return { section: section.replace(/\/+$/, ''), sort, limit, skip, paged, filters };
103
+ };
104
+
105
+ if (raw === 'each' || raw.startsWith('each:')) {
106
+ return { kind: 'each', ...readList(raw.slice(5), 'list'), token };
107
+ }
108
+
109
+ if (raw === 'count' || raw.startsWith('count:')) {
110
+ const list = readList(raw.slice(6), 'count');
111
+ if (list.paged) fail('A count has no pages. Remove :paged.');
112
+ return { kind: 'count', ...list, token };
113
+ }
114
+
115
+ if (raw === 'if' || raw.startsWith('if:')) {
116
+ const target = raw.slice(3).trim();
117
+ if (!target) fail('Say what to check. {{ if:cover }} shows what follows only when cover has something in it.');
118
+ const m = /^(!)?((?:item|page|parent|paging|site)\.)?([a-zA-Z][a-zA-Z0-9_-]*)(?:\s*(!?==?)\s*(.*))?$/.exec(target);
119
+ if (m && m[4]) m[4] = m[4].replace('==', '=');
120
+ if (!m) fail(`"${target}" isn't something {{ if }} can check.`, 'Use a field name, item.name inside a list, !name for "empty", or name=value.');
121
+ if (m[1] && m[4]) fail(`Use either ! or ${m[4]}, not both, in ${token}.`);
122
+ const scope = m[2] ? m[2].slice(0, -1) : 'own';
123
+ if (scope === 'paging' && !PAGING.includes(m[3])) fail(`paging.${m[3]} isn't something pages know. Use paging.${PAGING.join(', paging.')}.`);
124
+ return { kind: 'if', target: scope === 'own' ? m[3] : `${scope}.${m[3]}`, scope, key: m[3], negate: !!m[1], compare: m[4] ? { not: m[4] === '!=', value: unquote(m[5] || '') } : null, token };
125
+ }
126
+
127
+ if (raw.startsWith('part.')) {
128
+ fail(`${token} only works inside a file in parts/, where {{ part:… }} fills it in.`);
129
+ }
130
+
131
+ if (raw === 'part' || raw.startsWith('part:')) {
132
+ fail('A part can\'t use another part.', 'Copy what you need into this file instead.');
133
+ }
134
+
135
+ const ref = /^(item|page|parent|paging)\.([a-zA-Z][a-zA-Z0-9_-]*)(?::([a-z0-9-]+))?$/.exec(raw);
136
+ if (ref && ref[2] === 'parent') {
137
+ fail(`Verso only looks one level up. {{ parent.title }} shows the page this one is inside; there's no ${token}.`);
138
+ }
139
+ if (ref && ref[1] === 'paging' && !PAGING.includes(ref[2])) fail(`paging.${ref[2]} isn't something pages know. Use paging.${PAGING.join(', paging.')}.`);
140
+ if (ref && ref[3] && !FORMAT.test(ref[3])) fail(`"${ref[3]}" isn't a format.`, `Dates take ${DATE_FORMATS.join(', ')}; text takes words-20 or chars-120. In ${token}`);
141
+ if (ref) return { kind: 'ref', scope: ref[1], key: ref[2], format: ref[3] || null, token };
142
+
143
+ const [name, type = 'text', ...modifiers] = raw.split(':').map((p) => p.trim());
144
+ if (!name) fail('This has no field name. Write it like {{ headline:text }}.');
145
+ if (!FIELD_NAME.test(name)) fail(`"${name}" can't be a field name. Use letters, numbers, - and _, starting with a letter.`);
146
+ if (RESERVED.has(name)) fail(`"${name}" is a word templates use for themselves. Give the field another name.`);
147
+ if (!fieldTypes[type]) {
148
+ const guess = nearest(type, Object.keys(fieldTypes));
149
+ fail(`"${type}" isn't a field type. Use ${Object.keys(fieldTypes).join(', ')}.`, guess ? `Did you mean {{ ${name}:${guess} }}?` : undefined);
150
+ }
151
+ if (name.startsWith('site.') && !['text', 'rich', 'blocks'].includes(type)) fail(`A field that's the same on every page can be text, rich text or blocks, not ${type}.`, 'For a shared image, use a shared block area: {{ site.header:blocks }}.');
152
+ modifiers.forEach((m) => {
153
+ if (type === 'blocks') {
154
+ if (!NAME.test(m)) fail(`"${m}" can't be a block name. Use the name of a file in blocks/, without .html.`);
155
+ return;
156
+ }
157
+ if (!fieldTypes[type].modifiers.includes(m)) {
158
+ fail(`"${m}" isn't something a ${type} field can be. It accepts: ${fieldTypes[type].modifiers.join(', ')}.`);
159
+ }
160
+ });
161
+ return { kind: 'field', name, type, modifiers, site: name.startsWith('site.'), token };
162
+ }
163
+
164
+ // The closest word to a typo, for "Did you mean…?": one or two letters off,
165
+ // or the start of the word.
166
+ export function nearest(word, options) {
167
+ const w = String(word).toLowerCase();
168
+ if (!w) return null;
169
+ const distance = (a, b) => {
170
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
171
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
172
+ for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
173
+ return d[a.length][b.length];
174
+ };
175
+ const synonyms = { latest: 'newest', recent: 'newest', new: 'newest', old: 'oldest', alpha: 'a-z', alphabetical: 'a-z', txt: 'text', string: 'text', html: 'rich', img: 'image', picture: 'image', colour: 'color', block: 'blocks', slot: 'blocks', page: 'paged', pages: 'paged' };
176
+ if (synonyms[w] && options.includes(synonyms[w])) return synonyms[w];
177
+ let best = null;
178
+ let score = Infinity;
179
+ options.forEach((o) => {
180
+ const d = o.startsWith(w) && w.length >= 3 ? 1 : distance(w, o);
181
+ if (d < score) { score = d; best = o; }
182
+ });
183
+ return score <= Math.max(1, Math.floor(w.length / 3)) ? best : null;
184
+ }
185
+
186
+ const unquote = (v) => String(v).trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1');
187
+
188
+ // Tags without repeats: "Design" and "design" are one tag, spelled the way
189
+ // it was first written.
190
+ export const uniqueTags = (tags) => {
191
+ const seen = new Map();
192
+ tags.map((t) => String(t).trim()).filter(Boolean).forEach((t) => { if (!seen.has(slugifyTag(t))) seen.set(slugifyTag(t), t); });
193
+ return [...seen.values()];
194
+ };
195
+
196
+ // "Design Systems" → "design-systems", for tag addresses and tagged- filters.
197
+ export const slugifyTag = (tag) => String(tag).toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
198
+
199
+ // ════ Parse ════
200
+ // One pass over the HTML with a stack of open elements gives each {{ … }} its
201
+ // context: page text (clickable), an attribute, or the <head>. A second
202
+ // stack pairs up each/if blocks.
203
+ export function parseTemplate(source, file = 'template.html', { fragment = false, itemOf = null } = {}) {
204
+ const matches = [...source.matchAll(TAG)];
205
+ // {{{ title }}} reads as {{ title }} with a brace on each side; say so.
206
+ matches.forEach((m) => {
207
+ if (source[m.index - 1] === '{' || source[m.index + m[0].length] === '}') {
208
+ throw new VersoError(`{{${m[1]}}} has an extra brace around it. Tags use two on each side, like {{ title:text }}.`, { file, line: lineAt(source, m.index) });
209
+ }
210
+ });
211
+ const tags = [];
212
+ const elements = [];
213
+ let mi = 0;
214
+ let pos = 0;
215
+ let headEnd = -1;
216
+ let bodyEnd = -1;
217
+ let titleRange = null;
218
+ let titleHasTag = false;
219
+ let descriptionRange = null;
220
+ let linksElevate = false;
221
+ const topLevel = [];
222
+
223
+ const inHead = () => elements.some((el) => el.name === 'head');
224
+ const add = (m, context, extra = {}) => {
225
+ const line = lineAt(source, m.index);
226
+ tags.push({ ...readTag(m[1], file, line), start: m.index, end: m.index + m[0].length, line, context, ...extra });
227
+ };
228
+
229
+ const textTagsBefore = (limit) => {
230
+ while (mi < matches.length && matches[mi].index < limit) {
231
+ const m = matches[mi++];
232
+ if (m.index + m[0].length > limit) continue;
233
+ if (inHead()) { add(m, 'head'); continue; }
234
+ const parent = elements[elements.length - 1] || null;
235
+ let sole = false;
236
+ if (parent) {
237
+ const before = source.slice(parent.openEnd + 1, m.index);
238
+ const rest = source.slice(m.index + m[0].length);
239
+ const next = rest.indexOf('<');
240
+ sole = before.trim() === '' && next !== -1 && rest.slice(0, next).trim() === '' &&
241
+ rest.slice(next, next + 2 + parent.name.length).toLowerCase() === `</${parent.name}`;
242
+ }
243
+ add(m, 'text', { parent: parent && { name: parent.name, openEnd: parent.openEnd }, sole });
244
+ }
245
+ };
246
+
247
+ while (pos < source.length) {
248
+ const lt = source.indexOf('<', pos);
249
+ if (lt === -1) { textTagsBefore(source.length); break; }
250
+ textTagsBefore(lt);
251
+ if (source.startsWith('<!--', lt)) {
252
+ const close = source.indexOf('-->', lt + 4);
253
+ const end = close === -1 ? source.length : close + 3;
254
+ while (mi < matches.length && matches[mi].index < end) mi++; // comments are left alone
255
+ pos = end;
256
+ continue;
257
+ }
258
+ const head = /^<(\/?)([a-zA-Z][\w:-]*)/.exec(source.slice(lt, lt + 80));
259
+ if (!head) { pos = lt + 1; continue; }
260
+ let j = lt + head[0].length;
261
+ let quote = null;
262
+ for (; j < source.length; j++) {
263
+ const c = source[j];
264
+ if (quote) { if (c === quote) quote = null; } else if (c === '"' || c === "'") quote = c; else if (c === '>') break;
265
+ }
266
+ const tagEnd = j;
267
+ const name = head[2].toLowerCase();
268
+ const closing = head[1] === '/';
269
+ const tagText = source.slice(lt, tagEnd + 1);
270
+ const selfClosing = source[tagEnd - 1] === '/';
271
+
272
+ while (mi < matches.length && matches[mi].index < tagEnd) {
273
+ const m = matches[mi++];
274
+ const attr = /([^\s=<>"'/]+)\s*=\s*["']?[^"']*$/.exec(source.slice(lt, m.index));
275
+ add(m, inHead() || name === 'head' ? 'head' : 'attr', {
276
+ tag: name, attr: attr ? attr[1].toLowerCase() : null,
277
+ element: { start: lt, openEnd: selfClosing ? tagEnd - 1 : tagEnd, hasAlt: /\salt\s*=/i.test(tagText) },
278
+ });
279
+ }
280
+
281
+ if (closing) {
282
+ const at = elements.map((el) => el.name).lastIndexOf(name);
283
+ if (at !== -1) elements.length = at;
284
+ if (name === 'head' && headEnd === -1) headEnd = lt;
285
+ if (name === 'body') bodyEnd = lt;
286
+ pos = tagEnd + 1;
287
+ continue;
288
+ }
289
+ if (name === 'meta' && /\bname\s*=\s*["']?description\b/i.test(tagText)) descriptionRange = [lt, tagEnd + 1];
290
+ if (name === 'link' && /elevate\.css/.test(tagText)) linksElevate = true;
291
+
292
+ if (RAW.has(name)) {
293
+ const close = source.toLowerCase().indexOf(`</${name}`, tagEnd);
294
+ const end = close === -1 ? source.length : close;
295
+ while (mi < matches.length && matches[mi].index < end) {
296
+ const m = matches[mi++];
297
+ if (name === 'script' || name === 'style') {
298
+ throw new VersoError(`Template tags can't go inside <${name}>.`, { file, line: lineAt(source, m.index), hint: 'Put the value in an attribute or the page text instead.' });
299
+ }
300
+ if (name === 'title') titleHasTag = true;
301
+ add(m, name === 'textarea' ? 'attr' : 'head', { tag: name });
302
+ }
303
+ if (name === 'title') {
304
+ const closeEnd = source.indexOf('>', end);
305
+ titleRange = [lt, closeEnd === -1 ? source.length : closeEnd + 1];
306
+ }
307
+ pos = end;
308
+ continue;
309
+ }
310
+ if (!elements.length) topLevel.push({ name, start: lt, openEnd: selfClosing ? tagEnd - 1 : tagEnd, line: lineAt(source, lt) });
311
+ if (!VOID.has(name) && !selfClosing) elements.push({ name, openEnd: tagEnd });
312
+ pos = tagEnd + 1;
313
+ }
314
+
315
+ if (fragment) {
316
+ if (topLevel.length !== 1 && itemOf) {
317
+ throw new VersoError(`Each item in ${itemOf} needs exactly one outer element, like <li>…</li>, but this one has ${topLevel.length || 'none'}.`, { file, line: topLevel[1]?.line || lineAt(source, source.length), hint: 'Wrap the item in one element, so Verso can add, move and remove it as a whole.' });
318
+ }
319
+ if (topLevel.length !== 1) {
320
+ throw new VersoError(`A block needs exactly one outer element, like <section>…</section>, but this one has ${topLevel.length || 'none'}.`, { file, line: topLevel[1]?.line || 1, hint: 'Wrap the block in one element, so Verso can move it as a whole.' });
321
+ }
322
+ } else if (headEnd === -1) {
323
+ throw new VersoError('This template needs a <head>, so Verso can add the page title and stylesheet.', { file, hint: 'Start it with <!DOCTYPE html><html><head>…</head><body>…</body></html>.' });
324
+ }
325
+
326
+ // ════ Blocks ════
327
+ const root = { kind: 'root', bodyStart: 0, bodyEnd: source.length, children: [], parent: null };
328
+ let node = root;
329
+ const err = (t, message, hint) => new VersoError(message, { file, line: t.line, hint });
330
+ const lineAtPos = (pos) => lineAt(source, pos);
331
+ tags.forEach((t) => {
332
+ if (['each', 'if', 'close', 'else', 'list'].includes(t.kind)) {
333
+ if (t.context === 'attr') throw err(t, `${t.token} can't go inside a tag. Put it between elements.`);
334
+ if (t.context === 'head' && t.tag === 'title') throw err(t, `${t.token} can't go inside <title>.`);
335
+ }
336
+ if (t.kind === 'each') {
337
+ if ((t.section === 'item' || t.section === 'item.tags') && !insideEach(node)) throw err(t, `{{ each:${t.section} }} only works inside another {{ each }}.`);
338
+ let depth = 0;
339
+ for (let n = node; n; n = n.parent) if (n.kind === 'each') depth += 1;
340
+ if (depth >= 3) throw err(t, 'Lists go three deep at most.');
341
+ if (t.paged && insideEach(node)) throw err(t, 'Only the outermost list on a page can be split into pages.');
342
+ const block = { ...t, children: [], parent: node, bodyStart: t.end };
343
+ node.children.push(block);
344
+ node = block;
345
+ } else if (t.kind === 'if') {
346
+ const block = { ...t, children: [], parent: node, bodyStart: t.end };
347
+ node.children.push(block);
348
+ node = block;
349
+ } else if (t.kind === 'list') {
350
+ if (itemOf) throw err(t, `An item of ${itemOf} can't hold another {{ list }}.`);
351
+ for (let n = node; n; n = n.parent) if (n.kind === 'each' || n.kind === 'list') throw err(t, `${t.token} can't go inside ${n.token}.`);
352
+ const block = { ...t, element: t.parent, children: [], parent: node, bodyStart: t.end };
353
+ node.children.push(block);
354
+ node = block;
355
+ } else if (t.kind === 'else') {
356
+ if (node.kind !== 'if' && node.kind !== 'each') {
357
+ throw err(t, node.kind === 'else' ? `There's already an {{ else }} for the ${node.parent.token} on line ${node.parent.line}.` : '{{ else }} goes inside {{ if }} or {{ each }}, before its closing tag.');
358
+ }
359
+ const alt = { kind: 'else', token: t.token, line: t.line, children: [], parent: node, bodyStart: t.end };
360
+ node.bodyEnd = t.start;
361
+ node.alt = alt;
362
+ node = alt;
363
+ } else if (t.kind === 'close') {
364
+ const open = node.kind === 'else' ? node.parent : node;
365
+ if (open.kind !== t.block) {
366
+ const what = open.kind === 'root' ? `there's no {{ ${t.block} }} open` : `the ${open.token} on line ${open.line} is still open`;
367
+ throw err(t, `${t.token} doesn't match: ${what}.`);
368
+ }
369
+ if (node.kind === 'else') node.bodyEnd = t.start;
370
+ else open.bodyEnd = t.start;
371
+ open.end = t.end;
372
+ node = open.parent;
373
+ if (open.kind === 'list') {
374
+ // A list of items needs an element to itself, like <ul>{{ list:team }}…{{ /list }}</ul>,
375
+ // so the editor has somewhere to put items as they're added.
376
+ const el = open.element || null;
377
+ const rest = source.slice(t.end);
378
+ const next = rest.indexOf('<');
379
+ const alone = el && source.slice(el.openEnd + 1, open.start).trim() === '' && next !== -1 && rest.slice(0, next).trim() === '' &&
380
+ rest.slice(next, next + 2 + el.name.length).toLowerCase() === `</${el.name}`;
381
+ if (!alone) throw err(open, `${open.token} needs an element to itself, like <ul>${open.token} … {{ /list }}</ul>.`);
382
+ }
383
+ } else {
384
+ node.children.push(t);
385
+ t.block = node;
386
+ }
387
+ });
388
+ if (node !== root) {
389
+ const open = node.kind === 'else' ? node.parent : node;
390
+ throw err(open, `${open.token} is never closed. Add {{ /${open.kind} }} after the part it covers.`);
391
+ }
392
+
393
+ // ════ Fields ════
394
+ const fields = new Map();
395
+ const repeaters = [];
396
+ const walk = (n, fn) => n.children.forEach((c) => {
397
+ fn(c);
398
+ if (c.kind === 'list') return; // a list's fields belong to its items
399
+ if (c.children) walk(c, fn);
400
+ if (c.alt) walk(c.alt, fn);
401
+ });
402
+ const paged = [];
403
+ walk(root, (t) => {
404
+ if (t.kind === 'each' && t.paged) paged.push(t);
405
+ if (t.kind === 'list') {
406
+ if (fields.has(t.name)) throw err(t, `"${t.name}" is already a field on line ${fields.get(t.name).line}. Give the list another name.`);
407
+ fields.set(t.name, { name: t.name, type: 'blocks', required: false, tools: [], line: t.line, label: humanize(t.name), contexts: new Set(['text']), repeater: true });
408
+ repeaters.push(t);
409
+ }
410
+ if (t.kind === 'field') {
411
+ if (insideEach(t.block)) throw err(t, `Fields can't go inside a list. To show ${t.name} from each page, write {{ item.${t.name} }}.`);
412
+ if (t.type === 'rich' && (t.context !== 'text' || !t.sole)) {
413
+ throw err(t, 'A rich text field needs an element to itself, like <div>{{ body:rich }}</div>.');
414
+ }
415
+ if (t.type === 'blocks' && (t.context !== 'text' || !t.sole)) {
416
+ throw err(t, 'A block area needs an element to itself, like <div>{{ sections:blocks }}</div>.');
417
+ }
418
+ if (t.type === 'image' && t.context === 'text') {
419
+ throw err(t, 'An image field goes in an attribute, like <img src="{{ photo:image }}">.');
420
+ }
421
+ const seen = fields.get(t.name);
422
+ if (seen && seen.type !== t.type) throw err(t, `"${t.name}" is a ${seen.type} field on line ${seen.line} but a ${t.type} field here. Give one of them another name.`);
423
+ if (!seen) fields.set(t.name, { name: t.name, type: t.type, required: false, tools: [], line: t.line, label: humanize(t.name.replace(/^site\./, '')), contexts: new Set(), site: t.site });
424
+ const f = fields.get(t.name);
425
+ t.modifiers.forEach((m) => {
426
+ if (m === 'required' && t.type === 'blocks') throw err(t, `A block area can't be required. Remove :required from ${t.token}.`);
427
+ if (m === 'required') f.required = true;
428
+ else if (!f.tools.includes(m)) f.tools.push(m);
429
+ });
430
+ f.contexts.add(t.context);
431
+ }
432
+ if (t.kind === 'ref' && t.scope === 'item' && !insideEach(t.block)) {
433
+ throw err(t, `${t.token} only works inside {{ each }}. For this page's own fields, use the field itself.`);
434
+ }
435
+ if (t.kind === 'ref' && t.scope === 'page' && !BUILT_INS.includes(t.key)) {
436
+ throw err(t, `${t.token} isn't a page setting. Use page.${PAGE_SETTINGS.join(', page.')}.`);
437
+ }
438
+ });
439
+ if (paged.length > 1) throw err(paged[1], `Only one list on a page can be split into pages, and the ${paged[0].token} on line ${paged[0].line} already is.`);
440
+ walk(root, (t) => {
441
+ const usesPaging = (t.kind === 'ref' && t.scope === 'paging') || (t.kind === 'if' && t.scope === 'paging');
442
+ if (usesPaging && !paged.length) throw err(t, `${t.token} needs a list split into pages, like {{ each:journal:10:paged }}.`);
443
+ if (t.kind !== 'if') return;
444
+ if (t.scope === 'own' && !fields.has(t.key)) throw err(t, `${t.token} checks "${t.key}", but this template has no field with that name.`);
445
+ if (t.scope === 'item' && !insideEach(t.parent)) throw err(t, `${t.token} only works inside {{ each }}.`);
446
+ if (t.scope === 'page' && !BUILT_INS.includes(t.key)) throw err(t, `${t.token} isn't a page setting. Use page.${PAGE_SETTINGS.join(', page.')}.`);
447
+ });
448
+
449
+ // Each repeater's item is a small template of its own, like a block.
450
+ repeaters.forEach((r) => {
451
+ const inner = '\n'.repeat(lineAt(source, r.bodyStart) - 1) + source.slice(r.bodyStart, r.bodyEnd);
452
+ r.item = parseTemplate(inner, file, { fragment: true, itemOf: r.token });
453
+ });
454
+
455
+ return {
456
+ file, source, root, fields, tags, fragment, rootElement: fragment ? topLevel[0] : null,
457
+ headEnd, bodyEnd, descriptionRange, linksElevate,
458
+ titleRange: titleHasTag ? null : titleRange,
459
+ repeaters,
460
+ paged: paged[0] || null,
461
+ lists: [...new Set(tags.filter((t) => (t.kind === 'each' || t.kind === 'count') && !SPECIAL_LISTS.includes(t.section)).map((t) => t.section))],
462
+ };
463
+ }
464
+
465
+ // True when a tag is repeated for each item of a list. The {{ else }} of a
466
+ // list shows once, when it's empty, so it isn't inside it.
467
+ function insideEach(node) {
468
+ let n = node;
469
+ while (n) {
470
+ if (n.kind === 'else') { n = n.parent.parent; continue; }
471
+ if (n.kind === 'each') return true;
472
+ n = n.parent;
473
+ }
474
+ return false;
475
+ }
476
+
477
+ // ════ Values ════
478
+
479
+ // An image beside its page ("photo.jpg"), or shared by the site and kept in
480
+ // content/ itself ("/logo.png").
481
+ export const imageUrl = (page, file) => (!file ? '' : file.startsWith('/') ? `/${encodeURIComponent(file.slice(1))}` : `${page.url}${encodeURIComponent(file)}`);
482
+
483
+ export function formatDate(iso, locale = 'en-US', style = 'long') {
484
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(iso || '')) return '';
485
+ if (style === 'iso') return iso;
486
+ const [y, m, d] = iso.split('-').map(Number);
487
+ const options = {
488
+ long: { year: 'numeric', month: 'long', day: 'numeric' },
489
+ short: { year: 'numeric', month: 'short', day: 'numeric' },
490
+ numeric: { year: 'numeric', month: 'numeric', day: 'numeric' },
491
+ month: { year: 'numeric', month: 'long' },
492
+ year: { year: 'numeric' },
493
+ }[style] || { year: 'numeric', month: 'long', day: 'numeric' };
494
+ try {
495
+ return new Intl.DateTimeFormat(locale, { ...options, timeZone: 'UTC' }).format(Date.UTC(y, m - 1, d));
496
+ } catch {
497
+ return iso;
498
+ }
499
+ }
500
+
501
+ // {{ item.summary:words-20 }} and {{ item.date:short }}.
502
+ function formatValue(value, format, iso, locale) {
503
+ if (!format) return value;
504
+ if (DATE_FORMATS.includes(format)) return iso ? formatDate(iso, locale, format) : value;
505
+ const n = Number(format.split('-')[1]);
506
+ const text = String(value).trim();
507
+ if (format.startsWith('words-')) {
508
+ const words = text.split(/\s+/);
509
+ return words.length > n ? `${words.slice(0, n).join(' ').replace(/[\s,.;:!?]+$/, '')}…` : text;
510
+ }
511
+ if (text.length <= n) return text;
512
+ const cut = text.slice(0, n + 1);
513
+ const space = cut.lastIndexOf(' ');
514
+ return `${(space > n * 0.6 ? cut.slice(0, space) : cut.slice(0, n)).replace(/[\s,.;:!?]+$/, '')}…`;
515
+ }
516
+
517
+ // What a page shows for a name: a built-in setting, or one of its fields.
518
+ // Returns { kind: 'text' | 'html' | 'image', value }.
519
+ function lookup(page, key, { locale, scope, colors = {} }) {
520
+ if (!page) return { kind: 'text', value: '' };
521
+ if (scope === 'page' || BUILT_INS.includes(key)) {
522
+ if (key === 'url') return { kind: 'text', value: page.url };
523
+ if (key === 'title') return { kind: 'text', value: page.title || page.label };
524
+ if (key === 'label') return { kind: 'text', value: page.label };
525
+ if (key === 'description') return { kind: 'text', value: page.description };
526
+ if (key === 'date') return { kind: 'text', value: formatDate(page.date, locale) };
527
+ if (key === 'date-iso') return { kind: 'text', value: page.date || '' };
528
+ if (key === 'tags') return { kind: 'text', value: (page.tags || []).join(', ') };
529
+ if (key === 'tag') return { kind: 'text', value: page.tag || '' };
530
+ if (key === 'count') return { kind: 'text', value: page.count == null ? '' : String(page.count) };
531
+ }
532
+ if (page.rich && key in page.rich) return { kind: 'html', value: page.rich[key] };
533
+ const v = page.fields?.[key];
534
+ if (v && typeof v === 'object' && 'color' in v) return { kind: 'text', value: colors[v.color] || '' };
535
+ if (v && typeof v === 'object') return { kind: 'image', value: v.file ? imageUrl(page, v.file) : '', alt: v.alt || '' };
536
+ return { kind: 'text', value: v == null ? '' : String(v) };
537
+ }
538
+
539
+ // An empty value inside a style attribute becomes "initial", so a custom
540
+ // property like --ink: {{ ink:color }} falls back to var(--ink, #000)'s
541
+ // default instead of an empty, valid value that blanks the colour.
542
+ const emptyInStyle = (t) => (t.context === 'attr' && t.attr === 'style' ? 'initial' : '');
543
+
544
+ // Site fields ({{ site.tagline:text }}) are shared by every page; they live in
545
+ // content/site.json. Set by loadSite, like the colours.
546
+ let siteData = { fields: {}, rich: {} };
547
+ export const setSiteData = (data) => { siteData = data || { fields: {}, rich: {} }; };
548
+ export const getSiteData = () => siteData;
549
+
550
+ // The pages (or tags) a list shows, before skip and limit. Lists of tags give
551
+ // each tag as an item with a title, a url (its tag page, when the site has
552
+ // one) and a count.
553
+ export function selectPages(block, page, outer, pages, { locale = 'en-US', colors = {}, drafts = false } = {}) {
554
+ // In the editor, drafts show in lists too, so a new post doesn't vanish
555
+ // while it's being written; the build leaves them out.
556
+ const live = pages.filter((p) => (drafts || !p.draft) && !p.virtual);
557
+ const homes = live.filter((p) => p.tagsOf);
558
+ // A tag links to its folder's tags page, if the folder has one; never to
559
+ // another folder's, which would list the wrong pages.
560
+ const tagUrl = (fromUrl, tag) => {
561
+ const home = homes.find((h) => fromUrl.startsWith(`/${h.tagsOf}/`));
562
+ return home ? `${home.url}${slugifyTag(tag)}/` : '';
563
+ };
564
+ const tagItem = (tag, fromUrl, count) => ({ url: tagUrl(fromUrl, tag), title: tag, label: tag, fields: {}, rich: {}, tags: [], count });
565
+ // The pages directly inside a folder. A folder's tags page and the 404
566
+ // page aren't among its posts.
567
+ const direct = (prefix) => {
568
+ const depth = prefix.split('/').filter(Boolean).length + 1;
569
+ return live.filter((p) => p.url.startsWith(prefix) && p.url.split('/').filter(Boolean).length === depth && !p.tagsOf && p.url !== '/404/');
570
+ };
571
+ const s = block.section;
572
+ let items;
573
+ if (s === 'tags' || s === 'item.tags') {
574
+ const from = s === 'tags' ? page : outer;
575
+ items = from ? (from.tags || []).map((t) => tagItem(t, from.url)) : [];
576
+ } else if (s === 'all-tags') {
577
+ const pool = page.tagsOf ? direct(`/${page.tagsOf}/`) : live;
578
+ const counts = new Map();
579
+ pool.forEach((p) => (p.tags || []).forEach((t) => {
580
+ const key = slugifyTag(t);
581
+ const seen = counts.get(key) || { tag: t, count: 0, from: p.url };
582
+ seen.count += 1;
583
+ counts.set(key, seen);
584
+ }));
585
+ items = [...counts.values()].map((c) => tagItem(c.tag, c.from, c.count));
586
+ } else {
587
+ const prefix = s === 'children' ? page.url
588
+ : s === 'siblings' ? (page.url && page.url !== '/' ? page.url.replace(/[^/]+\/$/, '') : '\u0000')
589
+ : s === 'item' ? outer?.url || '\u0000'
590
+ : s === 'tagged' ? (page.tagsOf ? `/${page.tagsOf}/` : '\u0000')
591
+ : `/${s}/`;
592
+ items = direct(prefix).filter((p) => !(s === 'siblings' && p.url === page.url));
593
+ if (s === 'tagged' && page.tag) items = items.filter((p) => (p.tags || []).some((t) => slugifyTag(t) === slugifyTag(page.tag)));
594
+ }
595
+ const text = (p, field) => String(lookup(p, field, { locale, colors }).value ?? '').trim().toLowerCase();
596
+ (block.filters || []).forEach((f) => {
597
+ if (f.type === 'others') items = items.filter((p) => p.url !== page.url && p.url !== page.tagHome);
598
+ else if (f.type === 'tagged') items = items.filter((p) => (p.tags || []).some((t) => slugifyTag(t) === f.value));
599
+ else if (f.type === 'has') items = items.filter((p) => hasValue(lookup(p, f.field, { locale, colors })));
600
+ else if (f.type === 'no') items = items.filter((p) => !hasValue(lookup(p, f.field, { locale, colors })));
601
+ else if (f.type === 'is') items = items.filter((p) => text(p, f.field) === f.value.toLowerCase());
602
+ else if (f.type === 'not') items = items.filter((p) => text(p, f.field) !== f.value.toLowerCase());
603
+ });
604
+ // Titles are compared the way people read them: "0.10" comes after "0.9".
605
+ const byTitle = (a, b) => (a.title || a.label).localeCompare(b.title || b.label, undefined, { numeric: true, sensitivity: 'base' });
606
+ const byDate = (a, b) => (a.date || '').localeCompare(b.date || '') || byTitle(a, b);
607
+ // order: the order set in the site view (page.json "order"), then title.
608
+ const byOrder = (a, b) => (a.order ?? 1e9) - (b.order ?? 1e9) || byTitle(a, b);
609
+ const byCount = (a, b) => (b.count || 0) - (a.count || 0) || byTitle(a, b);
610
+ const sorts = { order: byOrder, oldest: byDate, 'a-z': byTitle, 'z-a': (a, b) => byTitle(b, a), most: byCount, newest: (a, b) => byDate(b, a) };
611
+ return items.sort(sorts[block.sort] || sorts.newest);
612
+ }
613
+
614
+ // How many pages a template's split list makes for this page: 1 or more.
615
+ export function pageCount(template, page, pages, options = {}) {
616
+ const block = template.paged;
617
+ if (!block) return 1;
618
+ const total = Math.max(0, selectPages(block, page, null, pages, options).length - (block.skip || 0));
619
+ return Math.max(1, Math.ceil(total / block.limit));
620
+ }
621
+
622
+ // How many pages a page makes, counting split lists in its blocks too (and
623
+ // in the site's shared slots it shows).
624
+ export function splitPages(template, page, pages, blocks = new Map(), site = siteData, options = {}) {
625
+ let n = pageCount(template, page, pages, options);
626
+ const visit = (list) => (Array.isArray(list) ? list : []).forEach((inst) => {
627
+ const tpl = blocks.get(inst.block);
628
+ if (tpl?.paged) n = Math.max(n, pageCount(tpl, page, pages, options));
629
+ Object.values(inst.blocks || {}).forEach(visit);
630
+ });
631
+ Object.values(page.blocks || {}).forEach(visit);
632
+ [...template.fields.values()].filter((f) => f.site && f.type === 'blocks').forEach((f) => visit(site.blocks?.[f.name.slice(5)]));
633
+ return n;
634
+ }
635
+
636
+ // The address of page n of a split list: /journal/, /journal/page/2/, …
637
+ export const pagedUrl = (url, n) => (n <= 1 ? url : `${url}page/${n}/`);
638
+
639
+ const hasValue = (found) => (found.kind === 'html' ? !richIsEmpty(found.value) : String(found.value || '').trim() !== '');
640
+
641
+ // ════ Render ════
642
+ // mode 'build' writes the page as it ships. mode 'editor' marks each field so
643
+ // the editor can find it, shows placeholders for empty fields, keeps
644
+ // conditional parts visible so their fields can be filled, and adds the
645
+ // editor script.
646
+ // The site's colour tokens, name → CSS value, set whenever Elevate compiles,
647
+ // so color fields render the same everywhere a page is rendered.
648
+ let siteColors = {};
649
+ export const setColors = (colors) => { siteColors = colors || {}; };
650
+ export const getColors = () => siteColors;
651
+
652
+ export function renderPage(template, page, options = {}) {
653
+ const { mode = 'build', siteName = '', editor = null, pages = [], rich = {}, locale = 'en-US', imageSize = null, blocks = new Map(), prefix = '', instance = null, colors = siteColors, paging = null, site = siteData } = options;
654
+ const parentUrl = page.url && page.url !== '/' ? page.url.replace(/[^/]+\/$/, '') : null;
655
+ const parentPage = parentUrl ? pages.find((p) => p.url === parentUrl) || null : null;
656
+ const { source } = template;
657
+ const ctx = { mode, pages, rich, locale, imageSize };
658
+
659
+ const headTags = () => {
660
+ const number = paging?.number || 1;
661
+ // The site's name follows the page's title in the browser tab and in
662
+ // search results, unless the title already has it: "About — Northlight".
663
+ const own = (page.title || '').trim();
664
+ const named = !own ? siteName : !siteName || own.toLowerCase().includes(siteName.toLowerCase()) ? own : `${own} — ${siteName}`;
665
+ const title = named && number > 1 ? `${named}, page ${number}` : named;
666
+ const description = (page.description || '').trim();
667
+ return [
668
+ template.titleRange || !source.toLowerCase().includes('<title') ? `<title>${escapeHtml(title)}</title>` : '',
669
+ description ? `<meta name="description" content="${escapeAttr(description)}">` : '',
670
+ options.feed ? `<link rel="alternate" type="application/rss+xml" title="${escapeAttr(options.feed.title)}" href="${escapeAttr(options.feed.url)}">` : '',
671
+ template.linksElevate ? '' : '<link rel="stylesheet" href="/elevate.css">',
672
+ ].filter(Boolean).join('\n') + '\n';
673
+ };
674
+
675
+ // Edits at fixed places in the source that aren't {{ tags }}.
676
+ const fixed = [];
677
+ if (template.fragment) {
678
+ // A block: mark its outer element so the editor can move it as a whole.
679
+ if (mode === 'editor' && instance) {
680
+ const at = template.rootElement.openEnd;
681
+ const part = instance.part
682
+ ? ` data-verso-component="${escapeAttr(instance.part.instance)}" data-verso-component-name="${escapeAttr(instance.part.label)}" data-verso-part="${escapeAttr(instance.part.key)}"${instance.part.top ? ' data-verso-component-top' : ''}`
683
+ : '';
684
+ fixed.push({ start: at, end: at, text: () => ` data-verso-block="${escapeAttr(instance.id)}" data-verso-block-name="${escapeAttr(instance.block)}"${part}` });
685
+ }
686
+ } else {
687
+ if (template.titleRange) fixed.push({ start: template.titleRange[0], end: template.titleRange[1], text: () => '' });
688
+ if (template.descriptionRange) fixed.push({ start: template.descriptionRange[0], end: template.descriptionRange[1], text: () => '' });
689
+ fixed.push({ start: template.headEnd, end: template.headEnd, text: headTags });
690
+ if (mode === 'editor' && !prefix) {
691
+ // Page scripts can check document.documentElement.hasAttribute('data-verso-editing')
692
+ // and leave the page's fields alone while it's being edited.
693
+ const html = /<html\b/i.exec(source);
694
+ if (html) fixed.push({ start: html.index + 5, end: html.index + 5, text: () => ' data-verso-editing' });
695
+ }
696
+ if (mode === 'editor' && editor) {
697
+ const at = template.bodyEnd === -1 ? source.length : template.bodyEnd;
698
+ fixed.push({
699
+ start: at, end: at,
700
+ text: () => `<script type="application/json" id="verso-data">${JSON.stringify(editor).replace(/</g, '\\u003c')}</script>\n<script type="module" src="/__verso/editor.js"></script>\n`,
701
+ });
702
+ }
703
+ }
704
+
705
+ // A split list: which page this is, and how many there are.
706
+ const pageNumber = Math.max(1, paging?.number || 1);
707
+ const pageTotal = template.paged ? pageCount(template, page, pages, { locale, colors, drafts: mode === 'editor' }) : 1;
708
+ const pagingValue = (key) => {
709
+ if (key === 'number') return String(pageNumber);
710
+ if (key === 'total') return String(pageTotal);
711
+ if (key === 'next') return pageNumber < pageTotal ? pagedUrl(page.url, pageNumber + 1) : '';
712
+ if (key === 'previous') return pageNumber > 1 ? pagedUrl(page.url, pageNumber - 1) : '';
713
+ return '';
714
+ };
715
+ const siteValue = (name) => {
716
+ const key = name.replace(/^site\./, '');
717
+ if (site.rich && key in site.rich) return { kind: 'html', value: site.rich[key] };
718
+ const v = site.fields?.[key];
719
+ return { kind: 'text', value: v == null ? '' : String(v) };
720
+ };
721
+
722
+ const renderNode = (node, item) => {
723
+ const edits = [];
724
+ const inChild = (p) => node.children.some((c) => c.children && p >= c.start && p < c.end);
725
+ fixed.forEach((f) => {
726
+ if (f.start >= node.bodyStart && f.end <= node.bodyEnd && !inChild(f.start)) edits.push(f);
727
+ });
728
+ node.children.forEach((c) => {
729
+ if (c.kind === 'each') edits.push({ start: c.start, end: c.end, text: () => renderEach(c, item) });
730
+ else if (c.kind === 'if') edits.push({ start: c.start, end: c.end, text: () => renderIf(c, item) });
731
+ else if (c.kind === 'list') edits.push(...fieldEdits({ type: 'blocks', name: c.name, parent: c.element, start: c.start, end: c.end, repeater: c }));
732
+ else if (c.kind === 'count') edits.push({ start: c.start, end: c.end, text: () => String(Math.max(0, selectPages(c, page, item, pages, { locale, colors, drafts: mode === 'editor' }).length - (c.skip || 0))) });
733
+ else edits.push(...tagEdits(c, item));
734
+ });
735
+ edits.sort((a, b) => a.start - b.start || a.end - b.end);
736
+ let out = '';
737
+ let at = node.bodyStart;
738
+ edits.forEach((e) => {
739
+ out += source.slice(at, e.start) + e.text();
740
+ at = e.end;
741
+ });
742
+ return out + source.slice(at, node.bodyEnd);
743
+ };
744
+
745
+ const renderEach = (block, outer) => {
746
+ const items = selectPages(block, page, outer, pages, { locale, colors, drafts: mode === 'editor' });
747
+ const from = (block.skip || 0) + (block.paged ? (pageNumber - 1) * block.limit : 0);
748
+ const shown = items.slice(from, block.limit ? from + block.limit : undefined);
749
+ if (!shown.length) return block.alt ? renderNode(block.alt, outer) : '';
750
+ return shown.map((p) => renderNode(block, p)).join('');
751
+ };
752
+
753
+ // Whether a part of the template has fields of this page in it.
754
+ const hasOwnFields = (node) => node.children.some((c) => c.kind === 'field' || c.kind === 'list' || (c.children && c.kind !== 'each' && hasOwnFields(c)) || (c.alt && hasOwnFields(c.alt)));
755
+
756
+ const renderIf = (block, item) => {
757
+ const { scope, key } = block;
758
+ const found = scope === 'paging' ? { kind: 'text', value: pagingValue(key) }
759
+ : scope === 'site' ? siteValue(key)
760
+ : scope === 'item' ? lookup(item, key, { locale, colors })
761
+ : scope === 'parent' ? lookup(parentPage, key, { locale, colors })
762
+ : lookup(page, key, { locale, colors, scope: scope === 'page' ? 'page' : null });
763
+ let yes = block.compare
764
+ ? (String(found.value ?? '').trim().toLowerCase() === block.compare.value.toLowerCase()) !== block.compare.not
765
+ : hasValue(found) !== block.negate;
766
+ // In the editor, the part that holds this page's own fields stays
767
+ // visible, so an empty field can still be filled in.
768
+ if (mode === 'editor' && scope === 'own') {
769
+ const main = hasOwnFields(block);
770
+ const alt = block.alt ? hasOwnFields(block.alt) : false;
771
+ if (main && !alt) yes = true;
772
+ else if (alt && !main) yes = false;
773
+ }
774
+ if (yes) return renderNode(block, item);
775
+ return block.alt ? renderNode(block.alt, item) : '';
776
+ };
777
+
778
+ const tagEdits = (t, item) => {
779
+ if (t.kind === 'ref' && t.scope === 'paging') {
780
+ const value = pagingValue(t.key);
781
+ return [{ start: t.start, end: t.end, text: () => (t.context === 'text' ? escapeHtml(value) : escapeAttr(value)) }];
782
+ }
783
+ if (t.kind === 'ref') {
784
+ const target = t.scope === 'item' ? item : t.scope === 'parent' ? parentPage : page;
785
+ const found = lookup(target, t.key, { locale, colors, scope: t.scope === 'parent' ? null : t.scope });
786
+ if (!target) return [{ start: t.start, end: t.end, text: () => emptyInStyle(t) }];
787
+ const edits = [{ start: t.start, end: t.end, text: () => refText(found, t, target) || emptyInStyle(t) }];
788
+ // An image from another page brings its alt text, as an image field does.
789
+ if (found.kind === 'image' && t.tag === 'img' && t.attr === 'src' && !t.element.hasAlt) {
790
+ edits.push({ start: t.element.openEnd, end: t.element.openEnd, text: () => ` alt="${escapeAttr(found.alt || '')}"` });
791
+ }
792
+ return edits;
793
+ }
794
+ return fieldEdits(t);
795
+ };
796
+
797
+ const refText = (found, t, target) => {
798
+ if (found.kind === 'html') {
799
+ if (t.context !== 'text' || t.format) return (t.context === 'text' ? escapeHtml : escapeAttr)(formatValue(stripTags(found.value), t.format, null, locale));
800
+ return applyRichClasses(found.value, rich, { base: target.url, imageSize: imageSize && ((f) => imageSize(target, f)) });
801
+ }
802
+ const iso = t.key === 'date' || t.key === 'date-iso' ? target.date : /^\d{4}-\d{2}-\d{2}$/.test(String(found.value)) ? String(found.value) : null;
803
+ const value = formatValue(found.value, t.format, iso, locale);
804
+ return t.context === 'text' ? escapeHtml(value) : escapeAttr(value);
805
+ };
806
+
807
+ const fieldEdits = (t) => {
808
+ const field = template.fields.get(t.name);
809
+ const key = field?.site ? t.name : `${prefix}${t.name}`;
810
+ const locked = instance?.part?.locked?.includes(t.name) ? ' data-verso-locked' : '';
811
+ const marks = (extra = '') => ` data-verso-field="${key}"${extra}${field.required ? ' data-verso-required' : ''}${locked}`;
812
+
813
+ if (t.type === 'blocks') {
814
+ const stored = field.site ? site.blocks?.[t.name.slice(5)] : instance ? instance.blocks?.[t.name] : page.blocks?.[t.name];
815
+ const list = expandList(stored || [], blocks.components);
816
+ const html = list.map((inst) => renderBlock(inst, t.repeater?.item)).join('');
817
+ if (mode !== 'editor') return [{ start: t.start, end: t.end, text: () => html }];
818
+ const owner = instance && !field.site ? instance.id : '';
819
+ const allows = field.tools.length ? field.tools.join(' ') : '*';
820
+ const label = t.repeater ? `No ${escapeHtml(field.label.toLowerCase())} yet. Add the first one.` : 'Drag a block here from the Blocks library';
821
+ const empty = `<div data-verso-slot-empty style="display:grid;place-items:center;min-height:7rem;border:1.5px dashed rgba(127,127,127,.45);border-radius:10px;font:500 14px/1.4 ui-sans-serif,system-ui,sans-serif;color:rgba(127,127,127,.9)">${label}</div>`;
822
+ const repeat = t.repeater ? ` data-verso-repeater="${escapeAttr(field.label)}"` : '';
823
+ return [
824
+ { start: t.parent.openEnd, end: t.parent.openEnd, text: () => ` data-verso-slot="${escapeAttr(`${owner}:${t.name}`)}" data-verso-allows="${escapeAttr(allows)}"${repeat}` },
825
+ { start: t.start, end: t.end, text: () => html || empty },
826
+ ];
827
+ }
828
+
829
+ if (t.type === 'color') {
830
+ const v = (instance ? instance.fields : page.fields)?.[t.name];
831
+ const value = (v && typeof v === 'object' ? colors[v.color] || '' : '') || emptyInStyle(t);
832
+ return [{ start: t.start, end: t.end, text: () => (t.context === 'text' ? escapeHtml(value) : escapeAttr(value)) }];
833
+ }
834
+
835
+ if (t.type === 'image') {
836
+ const v = page.fields?.[t.name];
837
+ const file = v && typeof v === 'object' ? v.file : '';
838
+ const url = imageUrl(page, file);
839
+ const edits = [];
840
+ const shown = url || (mode === 'editor' ? PLACEHOLDER_IMAGE : '');
841
+ edits.push({ start: t.start, end: t.end, text: () => escapeAttr(shown) });
842
+ const extra = [];
843
+ if (t.tag === 'img' && t.attr === 'src') {
844
+ if (!t.element.hasAlt) extra.push(` alt="${escapeAttr(v?.alt || '')}"`);
845
+ const size = file && imageSize ? imageSize(page, file) : null;
846
+ if (size && !/\swidth\s*=/.test(source.slice(t.element.start, t.element.openEnd))) extra.push(` width="${size.width}" height="${size.height}"`);
847
+ }
848
+ if (mode === 'editor' && t.context === 'attr') extra.push(` data-verso-image="${key}"${file ? '' : ' data-verso-empty'}${field.required ? ' data-verso-required' : ''}`);
849
+ if (extra.length) edits.push({ start: t.element.openEnd, end: t.element.openEnd, text: () => extra.join('') });
850
+ return edits;
851
+ }
852
+
853
+ if (t.type === 'rich') {
854
+ const html = (field.site ? siteValue(t.name).value : page.rich?.[t.name]) || '';
855
+ const empty = richIsEmpty(html);
856
+ const rendered = applyRichClasses(html, rich, { base: page.url, imageSize: imageSize && ((f) => imageSize(page, f)) });
857
+ if (mode !== 'editor') return [{ start: t.start, end: t.end, text: () => rendered }];
858
+ const tools = ` data-verso-rich="${key}" data-verso-tools="${field.tools.join(' ')}"${empty ? ' data-verso-empty' : ''}${field.required ? ' data-verso-required' : ''}${locked}`;
859
+ // The main text of a page invites writing; other rich fields name themselves.
860
+ const prompt = ['body', 'content', 'text', 'story', 'article'].includes(t.name) ? 'Start writing…' : field.label;
861
+ const placeholder = applyRichClasses(`<p>${escapeHtml(prompt)}</p>`, rich, {});
862
+ return [
863
+ { start: t.parent.openEnd, end: t.parent.openEnd, text: () => tools },
864
+ { start: t.start, end: t.end, text: () => (empty ? placeholder : rendered) },
865
+ ];
866
+ }
867
+
868
+ // text
869
+ const value = field.site ? siteValue(t.name).value : page.fields?.[t.name] == null ? '' : String(page.fields[t.name]);
870
+ if (t.context !== 'text' || mode !== 'editor') {
871
+ const edits = [{ start: t.start, end: t.end, text: () => (t.context === 'text' ? escapeHtml(value) : escapeAttr(value)) }];
872
+ // In the editor, an element with a field in an attribute (a link's
873
+ // address, say) says which, so the editor can offer it beside the element.
874
+ if (mode === 'editor' && t.context === 'attr' && t.element && /^[a-z][a-z0-9-]*$/.test(t.attr || '') && t.attr !== 'style') {
875
+ edits.push({ start: t.element.openEnd, end: t.element.openEnd, text: () => ` data-verso-attr-${t.attr}="${escapeAttr(key)}"` });
876
+ }
877
+ return edits;
878
+ }
879
+ const empty = value.trim() === '';
880
+ const shown = empty ? escapeHtml(field.label) : escapeHtml(value);
881
+ if (t.sole && t.parent) {
882
+ return [
883
+ { start: t.parent.openEnd, end: t.parent.openEnd, text: () => marks(empty ? ' data-verso-empty' : '') },
884
+ { start: t.start, end: t.end, text: () => shown },
885
+ ];
886
+ }
887
+ return [{ start: t.start, end: t.end, text: () => `<span${marks(empty ? ' data-verso-empty' : '')}>${shown}</span>` }];
888
+ };
889
+
890
+ // A block instance, rendered with its own values. Its fields are named
891
+ // "@<id>.<field>" in the editor, and its images live in the page's folder.
892
+ const renderBlock = (inst, itemTemplate = null) => {
893
+ if (inst.missingComponent) {
894
+ return mode === 'editor' ? `<div data-verso-block="${escapeAttr(inst.id)}" data-verso-block-name="" style="padding:1rem;border:1.5px dashed #FF4F2B;color:#D93A1A;font:14px ui-sans-serif,system-ui">There's no component called "${escapeHtml(inst.missingComponent)}" in components/.</div>` : '';
895
+ }
896
+ const tpl = itemTemplate || blocks.get(inst.block);
897
+ if (!tpl) return mode === 'editor' ? `<div style="padding:1rem;border:1.5px dashed #FF4F2B;color:#D93A1A;font:14px ui-sans-serif,system-ui">There's no block called "${escapeHtml(inst.block)}" in blocks/.</div>` : '';
898
+ const own = { ...page, fields: {}, rich: {} };
899
+ Object.entries(inst.fields || {}).forEach(([k, v]) => {
900
+ if (tpl.fields.get(k)?.type === 'rich') own.rich[k] = String(v || '');
901
+ else own.fields[k] = v;
902
+ });
903
+ return renderPage(tpl, own, { ...options, prefix: `@${inst.id}.`, instance: inst });
904
+ };
905
+
906
+ return renderNode(template.root, null);
907
+ }
908
+
909
+ // Reads a block file: an HTML fragment with exactly one outer element.
910
+ export const parseBlock = (source, file) => parseTemplate(source, file, { fragment: true });
911
+
912
+ const stripTags = (html) => String(html).replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
913
+
914
+ // A soft grey frame with a picture icon, for image fields that are empty in the editor.
915
+ export const PLACEHOLDER_IMAGE = `data:image/svg+xml;utf8,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 600"><rect width="1200" height="600" fill="#EDEBE6"/><g fill="none" stroke="#A39E92" stroke-width="8" stroke-linejoin="round"><rect x="540" y="215" width="120" height="96" rx="12"/><path d="m548 298 34-38 28 28 20-17 34 27"/></g><circle cx="630" cy="244" r="10" fill="#A39E92"/><text x="600" y="372" text-anchor="middle" font-family="ui-sans-serif,system-ui,sans-serif" font-size="30" fill="#77736A">Add a picture</text></svg>')}`;