verso-cms 0.0.0-stage → 0.1.2

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 +288 -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 +1166 -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,341 @@
1
+ // Channels: folders of posts, declared in verso.json, with their own list in
2
+ // the editor. A writer picks a channel, sees its posts newest first, and
3
+ // starts a new one by typing a title. The channel decides the template.
4
+ //
5
+ // "channels": { "journal": { "label": "Journal", "template": "post", "item": "post" } }
6
+ //
7
+ // The key is the folder inside content/ ("docs/guides" works too). label
8
+ // defaults to the folder's name, item (what one post is called) to "entry".
9
+
10
+ import fs from 'fs';
11
+ import path from 'path';
12
+ import { readPage, writePage, urlForDir, dirForUrl, listTemplates, listPageDirs, listBlocks, loadTemplate, slugify, today, startingLayout, fillHeading, PAGE_FILE } from '../site.js';
13
+ import { newId } from '../blocks.js';
14
+ import { humanize } from '../template.js';
15
+ import { VersoError } from '../errors.js';
16
+
17
+ const isObject = (v) => v && typeof v === 'object' && !Array.isArray(v);
18
+
19
+ // Reads and checks the channels in verso.json. Never throws: a channel with a
20
+ // problem is left out and the problem is reported in plain words.
21
+ export function readChannels(root) {
22
+ let config = {};
23
+ try {
24
+ config = JSON.parse(fs.readFileSync(path.join(root, 'verso.json'), 'utf8'));
25
+ } catch {
26
+ return { channels: [], problems: [] }; // verso.json's own problems are reported elsewhere
27
+ }
28
+ const declared = config.channels;
29
+ if (declared == null) return { channels: [], problems: [] };
30
+ if (!isObject(declared)) {
31
+ return { channels: [], problems: ['"channels" in verso.json should list folders, like { "journal": { "template": "post" } }.'] };
32
+ }
33
+ const templates = listTemplates(root);
34
+ const channels = [];
35
+ const problems = [];
36
+ Object.entries(declared).forEach(([key, value]) => {
37
+ const folder = String(key).replace(/^\/+|\/+$/g, '');
38
+ const where = `The channel "${key}" in verso.json`;
39
+ if (!folder || folder.split('/').some((p) => !p || p === '.' || p === '..' || p.startsWith('.'))) {
40
+ problems.push(`${where} isn't a folder name Verso can use. Write the folder inside content/, like "journal" or "docs/guides".`);
41
+ return;
42
+ }
43
+ if (!isObject(value)) {
44
+ problems.push(`${where} should say which template its posts use, like { "template": "post" }.`);
45
+ return;
46
+ }
47
+ const dir = path.join(root, 'content', ...folder.split('/'));
48
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
49
+ problems.push(`${where} points to content/${folder}/, but there's no such folder. Make the folder, or fix the name in verso.json.`);
50
+ return;
51
+ }
52
+ const template = typeof value.template === 'string' ? value.template : '';
53
+ if (!template) {
54
+ problems.push(`${where} doesn't say which template its posts use. Add "template": "post", naming a file in templates/.`);
55
+ return;
56
+ }
57
+ if (!templates.includes(template)) {
58
+ problems.push(`${where} uses the template "${template}", but there's no templates/${template}.html.${templates.length ? ` The templates are: ${templates.join(', ')}.` : ''}`);
59
+ return;
60
+ }
61
+ const label = typeof value.label === 'string' && value.label.trim() ? value.label.trim() : humanize(folder.split('/').pop());
62
+ const item = typeof value.item === 'string' && value.item.trim() ? value.item.trim().toLowerCase() : 'entry';
63
+ channels.push({ key: folder, label, item, template, dir, url: urlForDir(root, dir) });
64
+ });
65
+ return { channels, problems };
66
+ }
67
+
68
+ // The posts directly inside a channel's folder, newest first.
69
+ function entries(root, channel) {
70
+ return fs.readdirSync(channel.dir, { withFileTypes: true })
71
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.') && fs.existsSync(path.join(channel.dir, e.name, PAGE_FILE)))
72
+ .map((e) => {
73
+ try {
74
+ const page = readPage(root, path.join(channel.dir, e.name));
75
+ if (page.tagsOf) return null; // a tags page lists the channel; it isn't one of its entries
76
+ return { url: page.url, label: page.label, title: page.title, date: page.date, draft: page.draft, template: page.template, description: page.description };
77
+ } catch {
78
+ return null; // a page that can't be read is reported by the rest of Verso
79
+ }
80
+ })
81
+ .filter(Boolean)
82
+ .sort((a, b) => (b.date || '').localeCompare(a.date || '') || b.label.localeCompare(a.label, undefined, { numeric: true, sensitivity: 'base' }));
83
+ }
84
+
85
+ // A folder name from a title that isn't taken yet: "spring-menu", "spring-menu-2"…
86
+ function freeSlug(dir, title, fallback) {
87
+ const base = slugify(title) || fallback;
88
+ let slug = base;
89
+ for (let n = 2; fs.existsSync(path.join(dir, slug)); n += 1) slug = `${base}-${n}`;
90
+ return slug;
91
+ }
92
+
93
+ export async function setup(ctx) {
94
+ const { root } = ctx;
95
+ const rel = (p) => path.relative(root, p).split(path.sep).join('/');
96
+ const note = (files) => Object.entries(files).forEach(([r, text]) => ctx.written.set(r, ctx.hash(Buffer.from(text, 'utf8'))));
97
+ // A folder Verso made or removed itself. The watcher can't read a folder as
98
+ // a file, so it treats it like a file Verso deleted and doesn't reload.
99
+ const ownFolder = (dir) => ctx.written.set(rel(dir), 'deleted');
100
+
101
+ const channelFor = (key) => {
102
+ const { channels, problems } = readChannels(root);
103
+ const channel = channels.find((c) => c.key === String(key || '').replace(/^\/+|\/+$/g, ''));
104
+ if (!channel) throw new VersoError(problems.find((p) => p.includes(`"${key}"`)) || `There's no channel called "${key}" in verso.json.`);
105
+ return channel;
106
+ };
107
+
108
+ // The channel a post belongs to, and the post's folder.
109
+ const postFor = (url) => {
110
+ const dir = dirForUrl(root, String(url || ''));
111
+ if (!dir || !fs.existsSync(path.join(dir, PAGE_FILE))) throw new VersoError('That post no longer exists. It may have been moved or deleted.');
112
+ const channel = readChannels(root).channels.find((c) => path.dirname(dir) === c.dir);
113
+ if (!channel) throw new VersoError('That page isn\'t in a channel, so it can\'t be changed from here.');
114
+ return { dir, channel };
115
+ };
116
+
117
+ const create = ({ channel: key, title }) => {
118
+ const channel = channelFor(key);
119
+ const name = String(title || '').trim().slice(0, 300);
120
+ if (!slugify(name)) throw new VersoError(`Give the ${channel.item} a title with at least one letter or number.`);
121
+ const dir = path.join(channel.dir, freeSlug(channel.dir, name, channel.item));
122
+ ownFolder(dir);
123
+ note(writePage(root, fillHeading(root, { dir, template: channel.template, title: name, description: '', date: today(), draft: true, fields: {}, rich: {}, ...startingLayout(root, channel.template) })));
124
+ return { url: urlForDir(root, dir) };
125
+ };
126
+
127
+ // A copy beside the original, with everything in its folder: rich text,
128
+ // images and any blocks. It starts as a draft dated today.
129
+ const duplicate = ({ url }) => {
130
+ const { dir, channel } = postFor(url);
131
+ const page = readPage(root, dir);
132
+ const title = `${page.title || page.label} (copy)`;
133
+ const target = path.join(channel.dir, freeSlug(channel.dir, `${path.basename(dir)}-copy`, channel.item));
134
+ fs.cpSync(dir, target, { recursive: true });
135
+ ownFolder(target);
136
+ const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).forEach((e) => {
137
+ const p = path.join(d, e.name);
138
+ if (e.isDirectory()) { ownFolder(p); walk(p); }
139
+ else ctx.written.set(rel(p), ctx.hash(fs.readFileSync(p)));
140
+ });
141
+ walk(target);
142
+ const copy = readPage(root, target);
143
+ note(writePage(root, { ...copy, title, date: today(), draft: true }));
144
+ return { url: copy.url, title };
145
+ };
146
+
147
+ const remove = ({ url }) => {
148
+ const { dir } = postFor(url);
149
+ const page = readPage(root, dir);
150
+ const inside = fs.readdirSync(dir, { withFileTypes: true }).some((e) => e.isDirectory() && fs.existsSync(path.join(dir, e.name, PAGE_FILE)));
151
+ if (inside) throw new VersoError(`${page.label} has pages inside it. Move or delete those first, in the site view.`);
152
+ const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).forEach((e) => {
153
+ const p = path.join(d, e.name);
154
+ if (e.isDirectory()) { ownFolder(p); walk(p); }
155
+ else ctx.written.set(rel(p), 'deleted');
156
+ });
157
+ walk(dir);
158
+ ownFolder(dir);
159
+ fs.rmSync(dir, { recursive: true, force: true });
160
+ return { url: page.url, label: page.label };
161
+ };
162
+
163
+ // ════ Setting channels up ════
164
+ // verso.json changes in place, so every other key keeps its spot.
165
+ const configFile = path.join(root, 'verso.json');
166
+ const readConfigRaw = () => {
167
+ try {
168
+ const config = JSON.parse(fs.readFileSync(configFile, 'utf8'));
169
+ if (!isObject(config)) throw new Error();
170
+ return config;
171
+ } catch {
172
+ throw new VersoError('verso.json can\'t be read right now, so channels can\'t change. Fix it by hand, or ask a developer.');
173
+ }
174
+ };
175
+ const writeConfig = (config) => {
176
+ const text = `${JSON.stringify(config, null, 2)}\n`;
177
+ ctx.written.set('verso.json', ctx.hash(Buffer.from(text, 'utf8')));
178
+ fs.writeFileSync(configFile, text, 'utf8');
179
+ };
180
+
181
+ // { folder, label, item, template, indexTemplate, edit }. folder is a folder
182
+ // in content/, or a new name (made, with a page using indexTemplate). With
183
+ // edit, the channel already exists and only its name, item and template change.
184
+ // A new channel's own page lists its items from the start: its type's
185
+ // starting layout, or else the site's block that lists the pages inside
186
+ // the page it's on ({{ each:children }}), placed in its first slot.
187
+ const indexLayout = (template, label) => {
188
+ const layout = startingLayout(root, template);
189
+ let tpl = null;
190
+ try { tpl = loadTemplate(root, template); } catch { return layout; }
191
+ const slot = tpl && [...tpl.fields.values()].find((f) => f.type === 'blocks' && !f.site && !f.repeater);
192
+ const lister = listBlocks(root).find((b) => /\{\{\s*each:children\b/.test(fs.readFileSync(path.join(root, 'blocks', `${b}.html`), 'utf8')));
193
+ if (!slot || !lister) return layout;
194
+ return { ...layout, blocks: { ...layout.blocks, [slot.name]: [{ id: newId(), block: lister, fields: { heading: label } }] } };
195
+ };
196
+
197
+ const setupChannel = (body) => {
198
+ const config = readConfigRaw();
199
+ const templates = listTemplates(root);
200
+ const label = String(body.label || '').trim().slice(0, 80);
201
+ const item = String(body.item || '').trim().toLowerCase().slice(0, 40) || 'entry';
202
+ const template = String(body.template || '');
203
+ if (!label) throw new VersoError('Give the channel a name, like Journal.');
204
+ if (!templates.includes(template)) throw new VersoError(`Choose the page type each new ${item} uses.`);
205
+ const channels = isObject(config.channels) ? config.channels : {};
206
+ let folder = String(body.folder || '').trim().replace(/^\/+|\/+$/g, '');
207
+ if (body.edit) {
208
+ if (!channels[folder]) throw new VersoError(`There's no channel for content/${folder}/ to change.`);
209
+ } else {
210
+ const exists = folder && folder.split('/').every((p) => p && !p.startsWith('.') && p !== '..') && fs.existsSync(path.join(root, 'content', ...folder.split('/'), PAGE_FILE));
211
+ if (!exists) {
212
+ // A new folder at the top level, named from what was typed.
213
+ const name = slugify(folder || label);
214
+ if (!name) throw new VersoError('Name the new folder with at least one letter or number, like journal.');
215
+ folder = name;
216
+ const dir = path.join(root, 'content', name);
217
+ if (fs.existsSync(dir)) throw new VersoError(`content/${name}/ already exists but has no page in it. Choose it from the list once it has a page, or use another name.`);
218
+ const indexTemplate = String(body.indexTemplate || '');
219
+ if (!templates.includes(indexTemplate)) throw new VersoError(`Choose the page type for the ${label} page itself, the one that lists every ${item}.`);
220
+ fs.mkdirSync(dir, { recursive: true });
221
+ ownFolder(dir);
222
+ note(writePage(root, { dir, template: indexTemplate, title: label, description: '', date: '', draft: false, fields: {}, rich: {}, ...indexLayout(indexTemplate, label) }));
223
+ }
224
+ if (channels[folder]) throw new VersoError(`${channels[folder].label || humanize(folder)} is already a channel.`);
225
+ }
226
+ channels[folder] = { ...(isObject(channels[folder]) ? channels[folder] : {}), label, template, item };
227
+ config.channels = channels;
228
+ writeConfig(config);
229
+ return { key: folder };
230
+ };
231
+
232
+ // Stops listing a channel. Its pages stay where they are.
233
+ const forget = ({ key }) => {
234
+ const config = readConfigRaw();
235
+ const folder = String(key || '').replace(/^\/+|\/+$/g, '');
236
+ if (!isObject(config.channels) || !config.channels[folder]) throw new VersoError('That channel is already gone.');
237
+ const label = config.channels[folder].label || humanize(folder);
238
+ delete config.channels[folder];
239
+ if (!Object.keys(config.channels).length) delete config.channels;
240
+ writeConfig(config);
241
+ return { label };
242
+ };
243
+
244
+ const list = () => {
245
+ const { channels, problems } = readChannels(root);
246
+ return {
247
+ problems,
248
+ channels: channels.map(({ dir, ...c }) => ({ ...c, entries: entries(root, { dir }) })),
249
+ // For "Make a channel": folders that hold pages, and the page types.
250
+ // Folders with the most pages in them first: those are most likely channels.
251
+ folders: listPageDirs(root).filter((d) => d !== path.join(root, 'content'))
252
+ .map((d) => ({ key: path.relative(path.join(root, 'content'), d).split(path.sep).join('/'), pages: fs.readdirSync(d, { withFileTypes: true }).filter((e) => e.isDirectory() && fs.existsSync(path.join(d, e.name, PAGE_FILE))).length }))
253
+ // A single post isn't a folder of posts: only folders with pages in them.
254
+ .filter((f) => f.pages > 0)
255
+ .sort((a, b) => b.pages - a.pages || a.key.localeCompare(b.key))
256
+ .map((f) => f.key),
257
+ templates: listTemplates(root).map((name) => ({ name, label: humanize(name) })),
258
+ hasAddress: (() => { try { return typeof readConfigRaw().url === 'string' && !!readConfigRaw().url; } catch { return false; } })(),
259
+ };
260
+ };
261
+
262
+ // A tags page: { url, folder, add } says whether the page sits inside the
263
+ // folder whose tags it lists (so it would show up as one of its items),
264
+ // which of the site's blocks would show the tags, and, with add: true,
265
+ // puts those blocks on the page. Page settings calls it when "Lists the
266
+ // tags of" changes.
267
+ const tagsPage = (body) => {
268
+ const dir = dirForUrl(root, String(body.url || '/'));
269
+ if (!dir) throw new VersoError('That page doesn\'t exist any more.');
270
+ const page = readPage(root, dir);
271
+ const folder = String(body.folder || '').replace(/^\/+|\/+$/g, '');
272
+ const { channels } = readChannels(root);
273
+ const channel = channels.find((c) => c.key === folder);
274
+ const inside = !!folder && page.url.startsWith(`/${folder}/`) && page.url !== `/${folder}/`;
275
+ const items = channel ? (/s$/.test(channel.item) ? channel.item : `${channel.item}s`) : 'pages';
276
+ const warning = inside ? `This page is inside ${channel?.label || humanize(folder)}, so it's listed with its ${items}. Move it out of the folder to keep it out of that list.` : '';
277
+ // Blocks that show every tag, and the pages with this page's tag.
278
+ const source = (b) => fs.readFileSync(path.join(root, 'blocks', `${b}.html`), 'utf8');
279
+ const blocks = listBlocks(root);
280
+ const wanted = [blocks.find((b) => /\{\{\s*each:all-tags\b/.test(source(b))), blocks.find((b) => /\{\{\s*each:tagged\b/.test(source(b)))].filter(Boolean);
281
+ let tpl = null;
282
+ try { tpl = loadTemplate(root, page.template); } catch { /* reported with the page */ }
283
+ const area = tpl && [...tpl.fields.values()].find((f) => f.type === 'blocks' && !f.site && !f.repeater);
284
+ const has = (b) => Object.values(page.blocks || {}).some((list) => (list || []).some((inst) => inst.block === b));
285
+ const missing = area ? wanted.filter((b) => !has(b)) : [];
286
+ let added = [];
287
+ if (body.add && missing.length) {
288
+ page.blocks = page.blocks || {};
289
+ page.blocks[area.name] = [...(page.blocks[area.name] || []), ...missing.map((b) => ({ id: newId(), block: b, fields: {} }))];
290
+ note(writePage(root, page));
291
+ added = missing;
292
+ }
293
+ return { inside, warning, canAdd: missing.map((b) => humanize(b)), added: added.map((b) => humanize(b)) };
294
+ };
295
+
296
+ const answer = async (res, fn) => {
297
+ try {
298
+ ctx.sendJSON(res, 200, { ok: true, ...(await fn()) });
299
+ } catch (err) {
300
+ if (!(err instanceof VersoError)) throw err;
301
+ ctx.sendJSON(res, 400, { ok: false, message: err.message });
302
+ }
303
+ return true;
304
+ };
305
+ const changed = () => {
306
+ ctx.broadcast({ type: 'pages' });
307
+ ctx.broadcast({ type: 'status' });
308
+ };
309
+
310
+ return {
311
+ async handle(req, res, url) {
312
+ const p = url.pathname;
313
+ if (p === '/__verso/channels' && req.method === 'GET') return answer(res, list);
314
+ if (req.method !== 'POST') return false;
315
+ const action = {
316
+ '/__verso/channels/new': create,
317
+ '/__verso/channels/duplicate': duplicate,
318
+ '/__verso/channels/delete': remove,
319
+ '/__verso/channels/setup': setupChannel,
320
+ '/__verso/channels/forget': forget,
321
+ '/__verso/tags-page': tagsPage,
322
+ }[p];
323
+ if (!action) return false;
324
+ return answer(res, async () => {
325
+ const out = action(await ctx.readBody(req));
326
+ changed();
327
+ return out;
328
+ });
329
+ },
330
+ // The channels, for the bar and the palette, and the one this page is in.
331
+ editorData(site, page) {
332
+ const { channels } = readChannels(root);
333
+ // The channel's own page counts too, so Channels opens on it there.
334
+ const here = page?.dir ? channels.find((c) => page.dir === c.dir || path.dirname(page.dir) === c.dir) : null;
335
+ return {
336
+ channels: channels.map(({ key, label, item, url: u }) => ({ key, label, item, url: u })),
337
+ channel: here ? here.key : null,
338
+ };
339
+ },
340
+ };
341
+ }
@@ -0,0 +1,141 @@
1
+ // Components in the editor: save a block (with what's inside it) as a
2
+ // component, detach an instance back into plain blocks, lock a field so it
3
+ // reads the same on every page, and live previews for the library.
4
+
5
+ import fs from 'fs';
6
+ import path from 'path';
7
+ import { loadSite, readPage, writePage, dirForUrl, slugify, PAGE_FILE } from '../site.js';
8
+ import { renderPage, humanize } from '../template.js';
9
+ import { imageSize } from '../images.js';
10
+ import { VersoError } from '../errors.js';
11
+ import { findBlock } from '../blocks.js';
12
+ import { componentFromBlock, detachInstance, expandList, findPart, topBlocks, usesOf, writeComponent, componentFile } from '../components.js';
13
+
14
+ export async function setup(ctx) {
15
+ const { root, written, hash, send, sendJSON, readBody, broadcast } = ctx;
16
+
17
+ const openPage = (url) => {
18
+ const dir = dirForUrl(root, String(url || ''));
19
+ if (!dir || !fs.existsSync(path.join(dir, PAGE_FILE))) throw new VersoError('That page no longer exists.');
20
+ const site = loadSite(root);
21
+ return { site, page: readPage(root, dir) };
22
+ };
23
+ const savePage = (page) => {
24
+ Object.entries(writePage(root, page)).forEach(([rel, text]) => written.set(rel, hash(Buffer.from(text, 'utf8'))));
25
+ };
26
+ const saveComponent = (comp) => {
27
+ const out = writeComponent(root, comp);
28
+ written.set(out.rel, hash(Buffer.from(out.text, 'utf8')));
29
+ };
30
+
31
+ const routes = {
32
+ // { url, id, label } → the block becomes components/<name>.json and an instance
33
+ save(body) {
34
+ const { site, page } = openPage(body.url);
35
+ const found = findBlock(page, String(body.id || ''));
36
+ if (!found) throw new VersoError('That block is no longer on the page.');
37
+ if (found.inst.component) throw new VersoError('That\'s already a component.');
38
+ const label = String(body.label || '').trim().slice(0, 80);
39
+ if (!label) throw new VersoError('Give the component a name.');
40
+ const name = slugify(label);
41
+ if (!name) throw new VersoError('Give the component a name with at least one letter or number.');
42
+ if (fs.existsSync(componentFile(root, name))) throw new VersoError(`There's already a component called "${label}". Pick another name.`);
43
+ const { comp, instance } = componentFromBlock(found.inst, { name, label, blockTemplates: site.blocks });
44
+ saveComponent(comp);
45
+ found.list.splice(found.index, 1, instance);
46
+ savePage(page);
47
+ return { name, label };
48
+ },
49
+ // { url, id } → plain blocks with the same content, no longer linked
50
+ detach(body) {
51
+ const { site, page } = openPage(body.url);
52
+ const found = findBlock(page, String(body.id || ''));
53
+ if (!found || !found.inst.component) throw new VersoError('That component is no longer on the page.');
54
+ const comp = site.blocks.components?.get(found.inst.component);
55
+ if (!comp) throw new VersoError(`The component file for "${found.inst.component}" is missing, so it can't be detached.`);
56
+ found.list.splice(found.index, 1, ...detachInstance(found.inst, comp));
57
+ savePage(page);
58
+ return { label: comp.label };
59
+ },
60
+ // { url, field: "@<instance>-<key>.<field>", locked }
61
+ lock(body) {
62
+ const { site, page } = openPage(body.url);
63
+ const m = /^@([a-z0-9-]+)\.([a-zA-Z][a-zA-Z0-9_-]*)$/.exec(String(body.field || ''));
64
+ const part = m && findPart(page, m[1], site.blocks.components);
65
+ if (!part) throw new VersoError('That field isn\'t in a component on this page.');
66
+ const field = site.blocks.get(part.node.block)?.fields.get(m[2]);
67
+ if (!field || field.type === 'blocks') throw new VersoError('That isn\'t a field in the component.');
68
+ const key = `${part.key}.${m[2]}`;
69
+ const { comp, inst } = part;
70
+ const current = key in comp.shared ? comp.shared[key] : key in (inst.fields || {}) ? inst.fields[key] : comp.defaults[key] ?? '';
71
+ if (body.locked) {
72
+ if (field.type === 'image') throw new VersoError('Images can\'t be locked, because each page keeps its own images.');
73
+ comp.shared[key] = current;
74
+ } else {
75
+ delete comp.shared[key];
76
+ // Every page keeps showing what it showed, and new ones start with it.
77
+ comp.defaults[key] = current;
78
+ inst.fields = inst.fields || {};
79
+ inst.fields[key] = current;
80
+ savePage(page);
81
+ }
82
+ saveComponent(comp);
83
+ return { label: comp.label, field: field.label, pages: usesOf(site.pages, comp.name).length };
84
+ },
85
+ };
86
+
87
+ // A component on its own, with its default content, in the site's own <head>.
88
+ const preview = (name) => {
89
+ const site = loadSite(root);
90
+ const comp = site.blocks.components?.get(name);
91
+ if (!comp) return null;
92
+ const host = [...site.templates.values()][0];
93
+ const head = host ? host.source.slice(0, host.headEnd) : '<!DOCTYPE html><html><head><meta charset="utf-8">';
94
+ const css = host && host.linksElevate ? '' : '<link rel="stylesheet" href="/elevate.css">';
95
+ const page = { url: '/', dir: root, label: 'Preview', title: '', description: '', date: '', fields: {}, rich: {}, blocks: {} };
96
+ const parts = expandList([{ id: 'preview', component: name, fields: {} }], site.blocks.components);
97
+ const body = parts.map((part) => {
98
+ const tpl = site.blocks.get(part.block);
99
+ if (!tpl) return '';
100
+ const own = { ...page, fields: {}, rich: {} };
101
+ Object.entries(part.fields).forEach(([k, v]) => {
102
+ if (tpl.fields.get(k)?.type === 'rich') own.rich[k] = String(v || '');
103
+ else own.fields[k] = v;
104
+ });
105
+ return renderPage(tpl, own, { mode: 'editor', instance: part, prefix: `@${part.id}.`, pages: site.pages, rich: site.config.rich, locale: site.config.locale, imageSize, blocks: site.blocks });
106
+ }).join('');
107
+ const bodyClass = host ? (/<body[^>]*class="([^"]*)"/.exec(host.source)?.[1] || '') : '';
108
+ return `${head}${css}<style>body{margin:0}</style></head><body class="${bodyClass}">${body}</body></html>`;
109
+ };
110
+
111
+ return {
112
+ async handle(req, res, url) {
113
+ const p = url.pathname;
114
+ if (p.startsWith('/__verso/component-preview/') && req.method === 'GET') {
115
+ const html = preview(decodeURIComponent(p.slice('/__verso/component-preview/'.length).replace(/\/$/, '')));
116
+ if (html) send(res, 200, html);
117
+ else send(res, 404, 'Not found', 'text/plain');
118
+ return true;
119
+ }
120
+ const m = /^\/__verso\/components\/(save|detach|lock)$/.exec(p);
121
+ if (!m || req.method !== 'POST') return false;
122
+ try {
123
+ const out = routes[m[1]](await readBody(req));
124
+ broadcast({ type: 'status' });
125
+ sendJSON(res, 200, { ok: true, ...out });
126
+ } catch (err) {
127
+ if (!(err instanceof VersoError)) throw err;
128
+ sendJSON(res, 400, { ok: false, message: err.message });
129
+ }
130
+ return true;
131
+ },
132
+ editorData(site) {
133
+ const comps = site.blocks.components || new Map();
134
+ return {
135
+ components: [...comps.values()].map((c) => ({ name: c.name, label: c.label, blocks: topBlocks(c), pages: usesOf(site.pages, c.name).length })),
136
+ };
137
+ },
138
+ };
139
+ }
140
+
141
+ void humanize;
@@ -0,0 +1,169 @@
1
+ // History and clashes. Every publish is a restore point: this lists them,
2
+ // shows a page as it was, and puts an old version back. When two people
3
+ // publish the same page, it shows both versions and publishes the one chosen.
4
+
5
+ import fs from 'fs';
6
+ import os from 'os';
7
+ import path from 'path';
8
+ import { history, pageAt, restorePage, writeFolder, pageFolder, getConflict, resolveConflict, conflictPending } from '../git.js';
9
+ import { loadSite, readPage, dirForUrl } from '../site.js';
10
+ import { renderPage, escapeHtml, humanize } from '../template.js';
11
+ import { imageSize } from '../images.js';
12
+ import { IMAGE_FILE } from '../rich.js';
13
+
14
+ const SHA = /^[0-9a-f]{7,40}$/i;
15
+
16
+ export async function setup(ctx) {
17
+ const { root, send, sendJSON, readBody, broadcast } = ctx;
18
+ let undoRestore = null;
19
+
20
+ const formatDate = (iso) => {
21
+ try {
22
+ return new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(iso));
23
+ } catch {
24
+ return iso;
25
+ }
26
+ };
27
+
28
+ const message = (title, text) => `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${escapeHtml(title)}</title></head>
29
+ <body style="margin:0;min-height:100vh;display:grid;place-items:center;background:#F6F6F4;color:#25262A;font:16px/1.5 ui-sans-serif,system-ui,sans-serif"><main style="max-width:30rem;padding:2rem"><h1 style="font-size:1.25rem;margin:0 0 .5rem">${escapeHtml(title)}</h1><p style="margin:0;color:#55565C">${escapeHtml(text)}</p></main></body></html>`;
30
+
31
+ // A page as it was at a commit, rendered with today's template and styles.
32
+ const renderAt = async (url, sha) => {
33
+ const files = await pageAt(root, sha, url);
34
+ if (!files) return message('Not there yet', 'This page didn\'t exist at that point.');
35
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'verso-past-'));
36
+ try {
37
+ files.forEach((f) => fs.writeFileSync(path.join(tmp, f.name), f.data));
38
+ const site = loadSite(root);
39
+ const page = { ...readPage(root, tmp), url, label: url === '/' ? 'Home' : humanize(url.split('/').filter(Boolean).pop()) };
40
+ const template = site.templates.get(page.template);
41
+ if (!template) return message('Can\'t show this version', `It uses the template "${page.template}", which can't be read now.`);
42
+ // The shared header and footer as they were then, too.
43
+ let siteThen = site.siteData;
44
+ if (url !== '/') {
45
+ const home = await pageAt(root, sha, '/').catch(() => null);
46
+ const file = home && home.find((f) => f.name === 'site.json');
47
+ if (file) { try { const d = JSON.parse(String(file.data)); siteThen = { fields: d.fields || {}, rich: d.rich || {}, blocks: d.blocks || {} }; } catch { /* keep today's */ } }
48
+ } else {
49
+ const file = files.find((f) => f.name === 'site.json');
50
+ if (file) { try { const d = JSON.parse(String(file.data)); siteThen = { fields: d.fields || {}, rich: d.rich || {}, blocks: d.blocks || {} }; } catch { /* keep today's */ } }
51
+ }
52
+ let html = renderPage(template, page, {
53
+ mode: 'build', siteName: site.config.name, pages: site.pages, rich: site.config.rich, locale: site.config.locale,
54
+ imageSize: (pg, f) => imageSize({ dir: tmp }, f), blocks: site.blocks, site: siteThen,
55
+ });
56
+ // Images come from that commit too, in case they've since been replaced.
57
+ files.filter((f) => IMAGE_FILE.test(f.name)).forEach((f) => {
58
+ const now = `${url}${encodeURIComponent(f.name)}`;
59
+ const then = `/__verso/history/file?sha=${sha}&amp;url=${encodeURIComponent(url)}&amp;name=${encodeURIComponent(f.name)}`;
60
+ html = html.split(`"${now}"`).join(`"${then}"`);
61
+ });
62
+ return html;
63
+ } finally {
64
+ fs.rmSync(tmp, { recursive: true, force: true });
65
+ }
66
+ };
67
+
68
+ const pageUrl = (raw) => {
69
+ const url = String(raw || '/');
70
+ const dir = dirForUrl(root, url);
71
+ return dir ? (url.endsWith('/') ? url : `${url}/`) : null;
72
+ };
73
+
74
+ return {
75
+ editorData() {
76
+ return { conflictPending: conflictPending(root) };
77
+ },
78
+
79
+ async handle(req, res, url) {
80
+ const p = url.pathname;
81
+ const q = url.searchParams;
82
+
83
+ if (p === '/__verso/history' && req.method === 'GET') {
84
+ const page = q.get('url') ? pageUrl(q.get('url')) : null;
85
+ const entries = await history(root, { url: page, limit: Number(q.get('limit')) || 50 });
86
+ sendJSON(res, 200, { entries: entries.map((e) => ({ ...e, when: formatDate(e.date) })) });
87
+ return true;
88
+ }
89
+
90
+ if (p === '/__verso/history/preview' && req.method === 'GET') {
91
+ const page = pageUrl(q.get('url'));
92
+ const sha = q.get('sha') || '';
93
+ if (!page || !SHA.test(sha)) send(res, 400, message('Can\'t show this version', 'That link is missing a page or a version.'));
94
+ else send(res, 200, await renderAt(page, sha));
95
+ return true;
96
+ }
97
+
98
+ if (p === '/__verso/history/file' && req.method === 'GET') {
99
+ const page = pageUrl(q.get('url'));
100
+ const sha = q.get('sha') || '';
101
+ const name = q.get('name') || '';
102
+ const files = page && SHA.test(sha) && IMAGE_FILE.test(name) ? await pageAt(root, sha, page) : null;
103
+ const file = files && files.find((f) => f.name === name);
104
+ if (!file) send(res, 404, 'Not found', 'text/plain');
105
+ else {
106
+ const ext = path.extname(name).toLowerCase().slice(1);
107
+ send(res, 200, file.data, `image/${ext === 'jpg' ? 'jpeg' : ext}`);
108
+ }
109
+ return true;
110
+ }
111
+
112
+ if (p === '/__verso/history/restore' && req.method === 'POST') {
113
+ const body = await readBody(req);
114
+ const page = pageUrl(body.url);
115
+ if (!page || !SHA.test(String(body.sha || ''))) {
116
+ sendJSON(res, 400, { ok: false, message: 'Choose a version to restore.' });
117
+ return true;
118
+ }
119
+ const result = await restorePage(root, page, body.sha);
120
+ if (!result.ok) { sendJSON(res, 400, result); return true; }
121
+ // The last restore can be undone, until the next one.
122
+ undoRestore = { url: page, files: result.before, token: Math.random().toString(36).slice(2) };
123
+ broadcast({ type: 'status' });
124
+ sendJSON(res, 200, { ok: true, undo: undoRestore.token });
125
+ return true;
126
+ }
127
+
128
+ if (p === '/__verso/history/undo-restore' && req.method === 'POST') {
129
+ const body = await readBody(req);
130
+ if (!undoRestore || body.token !== undoRestore.token) {
131
+ sendJSON(res, 400, { ok: false, message: 'That restore can\'t be undone any more.' });
132
+ return true;
133
+ }
134
+ writeFolder(pageFolder(root, undoRestore.url), undoRestore.files);
135
+ const url = undoRestore.url;
136
+ undoRestore = null;
137
+ broadcast({ type: 'status' });
138
+ sendJSON(res, 200, { ok: true, url });
139
+ return true;
140
+ }
141
+
142
+ if (p === '/__verso/conflict' && req.method === 'GET') {
143
+ const record = await getConflict(root);
144
+ if (!record) sendJSON(res, 200, { conflict: null });
145
+ else {
146
+ sendJSON(res, 200, {
147
+ conflict: {
148
+ pages: record.pages.map((pg) => ({ ...pg, choice: record.choices[pg.url] || null })),
149
+ mine: record.mine,
150
+ theirs: { ...record.theirs, when: formatDate(record.theirs.date) },
151
+ },
152
+ });
153
+ }
154
+ return true;
155
+ }
156
+
157
+ if (p === '/__verso/conflict/resolve' && req.method === 'POST') {
158
+ const body = await readBody(req);
159
+ const page = pageUrl(body.url);
160
+ const result = page ? await resolveConflict(root, page, body.keep) : { ok: false, message: 'Choose a page.' };
161
+ broadcast({ type: 'status' });
162
+ sendJSON(res, result.ok ? 200 : 409, result);
163
+ return true;
164
+ }
165
+
166
+ return false;
167
+ },
168
+ };
169
+ }