@bright-logic-digital/site-editor 0.0.0-stage → 1.0.0-rc.0

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 (86) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +4 -0
  3. package/README.md +318 -2
  4. package/bin/cli.js +92 -0
  5. package/bin/copy-editor.js +211 -0
  6. package/bin/node-version.js +20 -0
  7. package/bin/site-config.js +46 -0
  8. package/bin/site-editor.js +16 -0
  9. package/editor/admin.css +438 -0
  10. package/editor/api.js +138 -0
  11. package/editor/app.js +1178 -0
  12. package/editor/asset-map.js +38 -0
  13. package/editor/boot.js +72 -0
  14. package/editor/copy.js +239 -0
  15. package/editor/drafts.js +67 -0
  16. package/editor/format.js +80 -0
  17. package/editor/forms.js +918 -0
  18. package/editor/images.js +212 -0
  19. package/editor/index.html +27 -0
  20. package/editor/model.js +152 -0
  21. package/editor/pages.js +297 -0
  22. package/editor/photos.js +232 -0
  23. package/editor/publish.js +45 -0
  24. package/editor/shared/rules.js +118 -0
  25. package/editor/shared/site.js +128 -0
  26. package/editor/shared/validate.js +303 -0
  27. package/editor/signin.js +154 -0
  28. package/editor/status.js +90 -0
  29. package/editor/uploads.js +91 -0
  30. package/guide/check.js +233 -0
  31. package/hosts/next.js +19 -0
  32. package/hosts/pages.js +20 -0
  33. package/hosts/shared.js +42 -0
  34. package/package.json +91 -4
  35. package/server/blob-sha.js +10 -0
  36. package/server/changes.js +24 -0
  37. package/server/check-content.js +197 -0
  38. package/server/config.js +97 -0
  39. package/server/dispatch.js +207 -0
  40. package/server/github.js +149 -0
  41. package/server/handlers.js +364 -0
  42. package/server/index.js +153 -0
  43. package/server/local-repo.js +171 -0
  44. package/server/mapped-repo.js +48 -0
  45. package/server/memory-repo.js +104 -0
  46. package/server/path-map.js +26 -0
  47. package/server/signin/access.js +329 -0
  48. package/server/signin/code-store.sql +60 -0
  49. package/server/signin/code.js +192 -0
  50. package/server/signin/codes.js +171 -0
  51. package/server/signin/refusal.js +76 -0
  52. package/server/signin/session.js +90 -0
  53. package/tests/fixtures/image-files.json +14 -0
  54. package/tests/fixtures/slugs.json +202 -0
  55. package/tests/fixtures/validation.json +12734 -0
  56. package/types/bin/cli.d.ts +1 -0
  57. package/types/bin/copy-editor.d.ts +32 -0
  58. package/types/bin/node-version.d.ts +8 -0
  59. package/types/bin/site-config.d.ts +17 -0
  60. package/types/bin/site-editor.d.ts +2 -0
  61. package/types/editor/api.d.ts +37 -0
  62. package/types/editor/copy.d.ts +153 -0
  63. package/types/editor/shared/rules.d.ts +33 -0
  64. package/types/editor/shared/site.d.ts +35 -0
  65. package/types/editor/shared/validate.d.ts +19 -0
  66. package/types/guide/check.d.ts +31 -0
  67. package/types/hosts/next.d.ts +12 -0
  68. package/types/hosts/pages.d.ts +9 -0
  69. package/types/hosts/shared.d.ts +21 -0
  70. package/types/server/blob-sha.d.ts +1 -0
  71. package/types/server/changes.d.ts +2 -0
  72. package/types/server/check-content.d.ts +16 -0
  73. package/types/server/config.d.ts +46 -0
  74. package/types/server/dispatch.d.ts +51 -0
  75. package/types/server/github.d.ts +27 -0
  76. package/types/server/handlers.d.ts +116 -0
  77. package/types/server/index.d.ts +75 -0
  78. package/types/server/local-repo.d.ts +16 -0
  79. package/types/server/mapped-repo.d.ts +10 -0
  80. package/types/server/memory-repo.d.ts +28 -0
  81. package/types/server/path-map.d.ts +3 -0
  82. package/types/server/signin/access.d.ts +68 -0
  83. package/types/server/signin/code.d.ts +44 -0
  84. package/types/server/signin/codes.d.ts +98 -0
  85. package/types/server/signin/refusal.d.ts +122 -0
  86. package/types/server/signin/session.d.ts +29 -0
@@ -0,0 +1,212 @@
1
+ // A picked photo turned into the files the site serves: decoded once, drawn
2
+ // upright onto a white canvas at each width the site uses, and encoded as
3
+ // WebP (or JPEG where the browser cannot make WebP). Nothing here touches
4
+ // the form or the API. Every browser part comes in through `env`, so the
5
+ // tests can drive it with fakes.
6
+ import { PHOTO_ERRORS } from "./copy.js";
7
+
8
+ export const PHOTO_WIDTHS = [700, 1100, 1800];
9
+ /** The largest source file read at all (25 MB). */
10
+ export const MAX_SOURCE_BYTES = 25 * 1024 * 1024;
11
+ /** The largest file the upload route takes. */
12
+ export const MAX_FILE_BYTES = 2_000_000;
13
+ /** A file over this is encoded once more, smaller: the upload route's CPU
14
+ * cost grows with the file (about 6 ms per MB of text, 10 ms allowed). */
15
+ export const REENCODE_ABOVE_BYTES = 1_000_000;
16
+ export const DECODE_TIMEOUT_MS = 20 * 1000;
17
+ export const UPLOAD_BASE = "/assets/img/uploads/";
18
+
19
+ // uploadStem's output plus "-1800.webp" stays a short file name.
20
+ const STEM_MAX = 40;
21
+ const ID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
22
+ const WEBP = Object.freeze({ type: "image/webp", ext: "webp", quality: 0.8 });
23
+ const JPEG = Object.freeze({ type: "image/jpeg", ext: "jpg", quality: 0.82 });
24
+ const HEAVY_QUALITY = 0.65;
25
+
26
+ export class ImageError extends Error {
27
+ /** code: cannot_read, too_big, too_small or too_heavy. */
28
+ constructor(code) {
29
+ super(PHOTO_ERRORS[code]);
30
+ this.name = "ImageError";
31
+ this.code = code;
32
+ }
33
+ }
34
+
35
+ /** The site's widths a source this wide can fill, ascending. */
36
+ export function targetWidths(sourceWidth) {
37
+ return PHOTO_WIDTHS.filter((w) => w <= sourceWidth);
38
+ }
39
+
40
+ /** A file name stem from the picked file's name and a short id: plain
41
+ * a-z0-9 words joined by "-", at most 47 characters. */
42
+ export function uploadStem(fileName, id) {
43
+ const words = String(fileName)
44
+ .replace(/\.[^.]*$/, "")
45
+ .normalize("NFKD")
46
+ .replace(/[\u0300-\u036f]/g, "")
47
+ .toLowerCase()
48
+ .replace(/[^a-z0-9]+/g, "-")
49
+ .replace(/^-+/, "")
50
+ .slice(0, STEM_MAX)
51
+ .replace(/-+$/, "");
52
+ return `${words || "photo"}-${id}`;
53
+ }
54
+
55
+ /** Six characters of a-z0-9 from crypto.getRandomValues. */
56
+ export function shortId(crypto) {
57
+ const bytes = new Uint8Array(6);
58
+ crypto.getRandomValues(bytes);
59
+ return Array.from(bytes, (b) => ID_CHARS[b % ID_CHARS.length]).join("");
60
+ }
61
+
62
+ function browserEnv() {
63
+ const g = globalThis;
64
+ return {
65
+ createImageBitmap: typeof g.createImageBitmap === "function"
66
+ ? (...args) => g.createImageBitmap(...args) : undefined,
67
+ document: g.document,
68
+ URL: g.URL,
69
+ crypto: g.crypto,
70
+ setTimeout: (fn, ms) => g.setTimeout(fn, ms),
71
+ clearTimeout: (id) => g.clearTimeout(id),
72
+ };
73
+ }
74
+
75
+ /** fn, run at most once however often it is called. */
76
+ function once(fn) {
77
+ let done = false;
78
+ return () => {
79
+ if (done) return;
80
+ done = true;
81
+ fn();
82
+ };
83
+ }
84
+
85
+ /** {source, width, height, release} by createImageBitmap, or failing that
86
+ * by an <img> (which also honours the photo's orientation). held.revoke
87
+ * releases the <img>'s object URL, if one was made. */
88
+ async function decodeWith(file, env, held) {
89
+ if (typeof env.createImageBitmap === "function") {
90
+ try {
91
+ const bitmap = await env.createImageBitmap(file, { imageOrientation: "from-image" });
92
+ return {
93
+ source: bitmap, width: bitmap.width, height: bitmap.height,
94
+ release: once(() => { if (typeof bitmap.close === "function") bitmap.close(); }),
95
+ };
96
+ } catch {
97
+ // Try the <img> below.
98
+ }
99
+ }
100
+ const url = env.URL.createObjectURL(file);
101
+ held.revoke = once(() => env.URL.revokeObjectURL(url));
102
+ try {
103
+ const img = env.document.createElement("img");
104
+ await new Promise((resolve, reject) => {
105
+ img.addEventListener("load", resolve);
106
+ img.addEventListener("error", reject);
107
+ img.src = url;
108
+ });
109
+ return { source: img, width: img.naturalWidth, height: img.naturalHeight, release: held.revoke };
110
+ } catch (err) {
111
+ held.revoke();
112
+ throw err;
113
+ }
114
+ }
115
+
116
+ /** The decoded photo, or ImageError("cannot_read") when it cannot be read
117
+ * within DECODE_TIMEOUT_MS. Whatever arrives late is released. */
118
+ async function decode(file, env) {
119
+ const held = { revoke: null };
120
+ const attempt = decodeWith(file, env, held);
121
+ let timer;
122
+ const deadline = new Promise((resolve, reject) => {
123
+ timer = env.setTimeout(() => reject(new ImageError("cannot_read")), DECODE_TIMEOUT_MS);
124
+ });
125
+ try {
126
+ const decoded = await Promise.race([attempt, deadline]);
127
+ if (!(decoded.width > 0 && decoded.height > 0)) {
128
+ decoded.release();
129
+ throw new ImageError("cannot_read");
130
+ }
131
+ return decoded;
132
+ } catch {
133
+ attempt.then((late) => late.release(), () => {});
134
+ if (held.revoke) held.revoke();
135
+ throw new ImageError("cannot_read");
136
+ } finally {
137
+ env.clearTimeout(timer);
138
+ }
139
+ }
140
+
141
+ function draw(document, source, width, height) {
142
+ const canvas = document.createElement("canvas");
143
+ canvas.width = width;
144
+ canvas.height = height;
145
+ const ctx = canvas.getContext("2d");
146
+ if (!ctx) throw new ImageError("cannot_read");
147
+ // A transparent photo saved as JPEG gets white behind it, not black.
148
+ ctx.fillStyle = "#ffffff";
149
+ ctx.fillRect(0, 0, width, height);
150
+ ctx.imageSmoothingQuality = "high";
151
+ ctx.drawImage(source, 0, 0, width, height);
152
+ return canvas;
153
+ }
154
+
155
+ /** The canvas encoded; a browser that cannot (a canvas too large for it)
156
+ * gives null, which is cannot_read. */
157
+ async function encode(canvas, type, quality) {
158
+ const blob = await new Promise((resolve) => canvas.toBlob(resolve, type, quality));
159
+ if (!blob) throw new ImageError("cannot_read");
160
+ return blob;
161
+ }
162
+
163
+ /**
164
+ * Prepare a picked photo for upload.
165
+ * Returns {field, files: [{name, blob, width}], previewUrl}: field is the
166
+ * image value for the document (alt ""), files are ascending by width, and
167
+ * previewUrl is an object URL of the smallest file that the caller revokes.
168
+ * Rejects with ImageError.
169
+ */
170
+ export async function prepareImage(file, env = {}) {
171
+ const e = { ...browserEnv(), ...env };
172
+ if (file.size > MAX_SOURCE_BYTES) throw new ImageError("too_big");
173
+ const decoded = await decode(file, e);
174
+ try {
175
+ const widths = targetWidths(decoded.width);
176
+ if (widths.length === 0) throw new ImageError("too_small");
177
+ const largest = widths[widths.length - 1];
178
+ const height = Math.max(1, Math.round((decoded.height * largest) / decoded.width));
179
+ const stem = uploadStem(file.name, shortId(e.crypto));
180
+ let format = WEBP;
181
+ const files = [];
182
+ for (const width of widths) {
183
+ // The build's rule for the height at another width.
184
+ const h = width === largest ? height : Math.max(1, Math.floor((height * width) / largest + 0.5));
185
+ const canvas = draw(e.document, decoded.source, width, h);
186
+ try {
187
+ let blob = await encode(canvas, format.type, format.quality);
188
+ if (files.length === 0 && format === WEBP && blob.type !== WEBP.type) {
189
+ format = JPEG;
190
+ blob = await encode(canvas, format.type, format.quality);
191
+ }
192
+ if (blob.type !== format.type) throw new ImageError("cannot_read");
193
+ if (blob.size > REENCODE_ABOVE_BYTES) blob = await encode(canvas, format.type, HEAVY_QUALITY);
194
+ if (blob.size > MAX_FILE_BYTES) throw new ImageError("too_heavy");
195
+ files.push({ name: `${stem}-${width}.${format.ext}`, blob, width });
196
+ } finally {
197
+ // Phones keep little canvas memory: give it back straight away.
198
+ canvas.width = 0;
199
+ canvas.height = 0;
200
+ }
201
+ }
202
+ return {
203
+ field: {
204
+ base: `${UPLOAD_BASE}${stem}`, ext: format.ext, widths, width: largest, height, alt: "",
205
+ },
206
+ files,
207
+ previewUrl: e.URL.createObjectURL(files[0].blob),
208
+ };
209
+ } finally {
210
+ decoded.release();
211
+ }
212
+ }
@@ -0,0 +1,27 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <meta name="robots" content="noindex">
7
+ <title>Website editor</title>
8
+ <link rel="stylesheet" href="/admin/admin.css">
9
+ <script type="module" src="/admin/boot.js"></script>
10
+ </head>
11
+ <body>
12
+ <header class="top">
13
+ <p class="brand" id="brand"></p>
14
+ <div class="top-actions">
15
+ <a class="help-link" href="/admin/guide.html" target="_blank" rel="noopener">Help</a>
16
+ <button type="button" class="help-link sign-out" id="sign-out" hidden></button>
17
+ </div>
18
+ </header>
19
+ <main class="main" id="main" tabindex="-1"></main>
20
+ <div class="bar is-empty" id="bar">
21
+ <div class="bar-inner">
22
+ <p class="status" id="status" role="status" aria-live="polite"></p>
23
+ <div class="bar-actions" id="bar-actions"></div>
24
+ </div>
25
+ </div>
26
+ </body>
27
+ </html>
@@ -0,0 +1,152 @@
1
+ // Pure document helpers for the editor. Nothing here mutates its input;
2
+ // every function returns new objects along the changed path.
3
+ import { BAD_CHAR, applies, emptyValue as sharedEmptyValue } from "./shared/validate.js";
4
+
5
+ const BAD_CHARS = new RegExp(BAD_CHAR.source, "gu");
6
+
7
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
8
+
9
+ /** The value at path, or undefined when any step is missing. */
10
+ export function getAt(doc, path) {
11
+ let cur = doc;
12
+ for (const key of path) {
13
+ if (cur === null || typeof cur !== "object" || !Object.hasOwn(cur, key)) return undefined;
14
+ cur = cur[key];
15
+ }
16
+ return cur;
17
+ }
18
+
19
+ /** A copy of doc with value at path. Missing steps are created. */
20
+ export function setAt(doc, path, value) {
21
+ if (path.length === 0) return value;
22
+ const [key, ...rest] = path;
23
+ const base = doc !== null && typeof doc === "object"
24
+ ? doc : (typeof key === "number" ? [] : {});
25
+ const child = Object.hasOwn(base, key) ? base[key] : undefined;
26
+ const next = setAt(child, rest, value);
27
+ if (Array.isArray(base)) {
28
+ const copy = base.slice();
29
+ copy[key] = next;
30
+ return copy;
31
+ }
32
+ return { ...base, [key]: next };
33
+ }
34
+
35
+ /** The empty value of a field, by the same rules as emptyDoc. */
36
+ export function emptyValue(field) {
37
+ return sharedEmptyValue(field);
38
+ }
39
+
40
+ /** doc with item appended to the list at path; doc itself at maxItems. */
41
+ export function listAdd(doc, path, item, maxItems) {
42
+ const list = getAt(doc, path);
43
+ if (!Array.isArray(list)) return doc;
44
+ if (maxItems !== undefined && list.length >= maxItems) return doc;
45
+ return setAt(doc, path, [...list, item]);
46
+ }
47
+
48
+ /** doc without list[index]; doc itself when that would go below min. */
49
+ export function listRemove(doc, path, index, min = 0) {
50
+ const list = getAt(doc, path);
51
+ if (!Array.isArray(list)) return doc;
52
+ if (list.length <= min || !Number.isInteger(index) || index < 0 || index >= list.length) {
53
+ return doc;
54
+ }
55
+ return setAt(doc, path, list.filter((_, i) => i !== index));
56
+ }
57
+
58
+ /** doc with list[index] moved by delta places; doc itself off either end. */
59
+ export function listMove(doc, path, index, delta) {
60
+ const list = getAt(doc, path);
61
+ if (!Array.isArray(list)) return doc;
62
+ const to = index + delta;
63
+ if (!Number.isInteger(index) || index < 0 || index >= list.length ||
64
+ !Number.isInteger(to) || to < 0 || to >= list.length || to === index) {
65
+ return doc;
66
+ }
67
+ const copy = list.slice();
68
+ const [moved] = copy.splice(index, 1);
69
+ copy.splice(to, 0, moved);
70
+ return setAt(doc, path, copy);
71
+ }
72
+
73
+ function same(a, b) {
74
+ if (a === b) return true;
75
+ if (Array.isArray(a)) {
76
+ return Array.isArray(b) && a.length === b.length && a.every((v, i) => same(v, b[i]));
77
+ }
78
+ if (isObject(a) && isObject(b)) {
79
+ const keys = Object.keys(a);
80
+ return keys.length === Object.keys(b).length &&
81
+ keys.every((k) => Object.hasOwn(b, k) && same(a[k], b[k]));
82
+ }
83
+ return false;
84
+ }
85
+
86
+ /** True when a and b differ structurally; key order does not matter. */
87
+ export function isDirty(a, b) {
88
+ return !same(a, b);
89
+ }
90
+
91
+ /** Text as the validator wants it: LF line breaks, plain spaces, none of the
92
+ * characters it rejects, one line unless multiline, trimmed. */
93
+ export function cleanText(str, multiline) {
94
+ let s = String(str)
95
+ .replace(/\r\n?/g, "\n")
96
+ .replace(/[\t\u00a0]/g, " ")
97
+ .replace(BAD_CHARS, "");
98
+ if (!multiline) s = s.replace(/\n/g, " ");
99
+ return s.trim();
100
+ }
101
+
102
+ /** obj with its `when` fields settled: a field whose condition now holds is
103
+ * added empty, one whose condition no longer holds is dropped, until nothing
104
+ * more changes. Keys follow field order; unknown keys are kept at the end.
105
+ * Returns obj itself when nothing changes. */
106
+ export function settleWhen(fields, obj) {
107
+ let cur = obj;
108
+ for (let changed = true; changed;) {
109
+ changed = false;
110
+ for (const field of fields) {
111
+ if (!field.when) continue;
112
+ const present = Object.hasOwn(cur, field.key);
113
+ if (present !== applies(field, cur)) {
114
+ cur = present
115
+ ? Object.fromEntries(Object.entries(cur).filter(([k]) => k !== field.key))
116
+ : { ...cur, [field.key]: emptyValue(field) };
117
+ changed = true;
118
+ }
119
+ }
120
+ }
121
+ if (cur === obj) return obj;
122
+ const known = new Set(fields.map((f) => f.key));
123
+ const ordered = {};
124
+ for (const field of fields) if (Object.hasOwn(cur, field.key)) ordered[field.key] = cur[field.key];
125
+ for (const [k, v] of Object.entries(cur)) if (!known.has(k)) ordered[k] = v;
126
+ return ordered;
127
+ }
128
+
129
+ function cleanValue(field, value) {
130
+ if (typeof value === "string" && (field.type === "text" || field.type === "textarea")) {
131
+ return cleanText(value, field.type === "textarea");
132
+ }
133
+ if (field.type === "image" && isObject(value) && typeof value.alt === "string") {
134
+ return { ...value, alt: cleanText(value.alt, false) };
135
+ }
136
+ if (field.type === "object" && isObject(value)) return cleanDoc(field.fields, value);
137
+ if (field.type === "list" && Array.isArray(value)) {
138
+ return value.map((item) => (isObject(item) ? cleanDoc(field.fields, item) : item));
139
+ }
140
+ return value;
141
+ }
142
+
143
+ /** A copy of doc with cleanText applied to every text value (multiline for
144
+ * a textarea) and to every photo description. Anything else is left as it is,
145
+ * for the validator to report. */
146
+ export function cleanDoc(fields, doc) {
147
+ const out = { ...doc };
148
+ for (const field of fields) {
149
+ if (Object.hasOwn(out, field.key)) out[field.key] = cleanValue(field, out[field.key]);
150
+ }
151
+ return out;
152
+ }
@@ -0,0 +1,297 @@
1
+ // Simple pages ("Extra pages"): content/custom/<slug>.json, each served at
2
+ // /<slug>/. Home's list of them, the "Add a page" form with its address
3
+ // preview, and the "Delete this page" question. The helpers above the DOM
4
+ // parts are pure; app.js wires the rest (publishing, drafts, routes).
5
+ import { MAX_CUSTOM_PAGES, uniqueSlug } from "./shared/rules.js";
6
+ import { emptyDoc } from "./shared/validate.js";
7
+ import { cleanText } from "./model.js";
8
+ import { draftPaths, loadDraft, saveDraft } from "./drafts.js";
9
+ import { el } from "./forms.js";
10
+ import { TEXT, deleteAsk, newPageAddress } from "./copy.js";
11
+
12
+ const CUSTOM_RE = /^content\/custom\/([a-z0-9-]+)\.json$/;
13
+ const PAGE_RE = /^content\/pages\/([a-z0-9-]+)\.json$/;
14
+
15
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
16
+
17
+ /** The address of a simple page's document, or null for any other path. */
18
+ export function customSlug(path) {
19
+ const m = typeof path === "string" ? CUSTOM_RE.exec(path) : null;
20
+ return m ? m[1] : null;
21
+ }
22
+
23
+ export const customPath = (slug) => `content/custom/${slug}.json`;
24
+
25
+ /** The page's title as typed, or its address when it has none. */
26
+ export function pageTitle(doc, slug) {
27
+ const title = isObject(doc) && typeof doc.title === "string" ? doc.title.trim() : "";
28
+ return title || slug;
29
+ }
30
+
31
+ /** The simple pages made in this browser and never published: drafts
32
+ * (path -> {base, doc}) begun from nothing, for a path the site lacks. */
33
+ export function newPagePaths(docs, drafts) {
34
+ return [...drafts].filter(([path, d]) => d.base === null && !Object.hasOwn(docs, path) &&
35
+ customSlug(path) !== null).map(([path]) => path);
36
+ }
37
+
38
+ /** The stored drafts of simple pages: Map path -> {base, doc, ...}. */
39
+ export function customDrafts(storage) {
40
+ return new Map(draftPaths(storage).filter((path) => customSlug(path) !== null)
41
+ .map((path) => [path, loadDraft(storage, path)]));
42
+ }
43
+
44
+ /** True when path is a simple page made in this browser: its draft began
45
+ * from nothing. */
46
+ export function isNewPageDraft(storage, path) {
47
+ return customSlug(path) !== null && loadDraft(storage, path)?.base === null;
48
+ }
49
+
50
+ /** How many simple pages there are: on the site, plus new ones here. */
51
+ export function pageCount(docs, drafts) {
52
+ return Object.keys(docs).filter((p) => customSlug(p) !== null).length +
53
+ newPagePaths(docs, drafts).length;
54
+ }
55
+
56
+ /** Every address a new page may not take: the other pages', every simple
57
+ * page on the site and every one with a draft in this browser (a new page
58
+ * made in another tab included). */
59
+ export function takenSlugs(docs, drafts) {
60
+ const taken = new Set();
61
+ for (const path of [...Object.keys(docs), ...drafts.keys()]) {
62
+ const slug = customSlug(path) ?? PAGE_RE.exec(path)?.[1];
63
+ if (slug) taken.add(slug);
64
+ }
65
+ return taken;
66
+ }
67
+
68
+ /** Home's rows, alphabetical by title (then address): [{path, slug, title,
69
+ * state}], state "new" for a page never published, "draft" for one with
70
+ * unpublished changes, null otherwise. A title comes from the draft, then
71
+ * from titles (path -> the published title), then the address. */
72
+ export function extraPageRows(docs, drafts, titles) {
73
+ const paths = [...Object.keys(docs).filter((p) => customSlug(p) !== null), ...newPagePaths(docs, drafts)];
74
+ return paths.map((path) => {
75
+ const slug = customSlug(path);
76
+ const draft = drafts.get(path);
77
+ const title = draft ? pageTitle(draft.doc, "") : "";
78
+ return {
79
+ path, slug,
80
+ title: title || titles.get(path) || slug,
81
+ state: !Object.hasOwn(docs, path) ? "new" : draft ? "draft" : null,
82
+ };
83
+ }).sort((a, b) => a.title.localeCompare(b.title, "en", { sensitivity: "base" }) ||
84
+ (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
85
+ }
86
+
87
+ /** A new page's first version: every field empty but its title, and the
88
+ * estimate band on. */
89
+ export function newPageDoc(schema, title) {
90
+ return { ...emptyDoc(schema, "custom"), title: cleanText(title, false), show_cta: true };
91
+ }
92
+
93
+ /** Published titles, read once per version of each page. readDoc(path)
94
+ * resolves to {sha, doc}. */
95
+ export function createTitles(readDoc) {
96
+ const known = new Map(); // path -> {sha, title}; a blank title is known too
97
+ /** The entries ([[path, sha]]) whose title is not known yet. */
98
+ const missing = (entries) => entries.filter(([path, sha]) => known.get(path)?.sha !== sha);
99
+ const set = (path, sha, doc) => known.set(path, { sha, title: pageTitle(doc, "") });
100
+ return {
101
+ missing,
102
+ set,
103
+ /** path -> title for the versions given whose title is known and not blank. */
104
+ titlesFor(entries) {
105
+ const out = new Map();
106
+ for (const [path, sha] of entries) {
107
+ const k = known.get(path);
108
+ if (k && k.sha === sha && k.title) out.set(path, k.title);
109
+ }
110
+ return out;
111
+ },
112
+ /** Read the titles not known yet; one that cannot be read stays unknown. */
113
+ async load(entries) {
114
+ await Promise.all(missing(entries).map(async ([path]) => {
115
+ try {
116
+ const { sha, doc } = await readDoc(path);
117
+ set(path, sha, doc);
118
+ } catch {
119
+ // The address stands in for it.
120
+ }
121
+ }));
122
+ },
123
+ };
124
+ }
125
+
126
+ // ---- On the page ----
127
+
128
+ /**
129
+ * Home's "Extra pages": each simple page, then "Add a page".
130
+ * docs: the site's documents (path -> sha); storage: where drafts are kept
131
+ * (a new page is its draft until it is published); titles: from
132
+ * createTitles; schema: the site's; host: shown in the address preview;
133
+ * links: Map filled with path -> link, so Home can update badges in place;
134
+ * open(path): show the new page's form.
135
+ */
136
+ export function extraPagesSection({ docs, storage, titles, schema, host, links, open }) {
137
+ const drafts = customDrafts(storage);
138
+ const list = el("div", { class: "extra-list" });
139
+ const published = Object.keys(docs).filter((p) => customSlug(p) !== null && !drafts.has(p))
140
+ .map((p) => [p, docs[p]]);
141
+
142
+ function drawList() {
143
+ const rows = extraPageRows(docs, drafts, titles.titlesFor(published));
144
+ list.replaceChildren(rows.length === 0 ? "" : el("ul", { class: "pages" }, rows.map((row) => {
145
+ const badge = { new: TEXT.notPublishedYet, draft: TEXT.unpublished }[row.state];
146
+ const link = el("a", { class: "page-link", href: `#/edit/${row.path}` }, [
147
+ el("span", { class: "page-name", text: row.title }),
148
+ badge ? el("span", { class: "badge", text: badge }) : null,
149
+ ]);
150
+ links.set(row.path, link);
151
+ return el("li", {}, [link]);
152
+ })));
153
+ }
154
+
155
+ if (titles.missing(published).length === 0) {
156
+ drawList();
157
+ } else {
158
+ list.append(el("p", { class: "loading", text: TEXT.loading }));
159
+ titles.load(published).then(() => {
160
+ if (list.isConnected) drawList();
161
+ });
162
+ }
163
+
164
+ const full = pageCount(docs, drafts) >= MAX_CUSTOM_PAGES;
165
+ const add = el("div", { class: "add-area" });
166
+ const addButton = el("button", {
167
+ type: "button", class: "button add-page", text: TEXT.addPage, disabled: full,
168
+ "aria-describedby": full ? "page-cap" : null,
169
+ on: { click: () => openForm() },
170
+ });
171
+ const drawButton = () => add.replaceChildren(addButton,
172
+ full ? el("p", { class: "help cap", id: "page-cap", text: TEXT.pageCap }) : "");
173
+
174
+ function openForm() {
175
+ const input = el("input", {
176
+ id: "new-page-title", class: "input", type: "text", autocomplete: "off",
177
+ "aria-describedby": "new-page-address new-page-fixed new-page-note",
178
+ });
179
+ const address = el("p", { class: "address", id: "new-page-address" });
180
+ const fixed = el("p", { class: "help", id: "new-page-fixed", text: TEXT.addressFixed });
181
+ const preview = el("div", { class: "address-preview", "aria-live": "polite" }, [address, fixed]);
182
+ const note = el("p", { class: "note", id: "new-page-note", role: "status" });
183
+ const create = el("button", {
184
+ type: "button", class: "button primary create-page", text: TEXT.createPage, on: { click: submit },
185
+ });
186
+ const cancel = el("button", {
187
+ type: "button", class: "button", text: TEXT.cancel,
188
+ on: {
189
+ click: () => {
190
+ drawButton();
191
+ addButton.focus();
192
+ },
193
+ },
194
+ });
195
+ // Read from storage each time: another tab may have made a page since.
196
+ const slugNow = () => uniqueSlug(input.value, takenSlugs(docs, customDrafts(storage)));
197
+ let shown = null; // the address the preview shows
198
+ function update() {
199
+ const blank = cleanText(input.value, false) === "";
200
+ shown = blank ? null : slugNow();
201
+ preview.hidden = blank;
202
+ address.textContent = blank ? "" : newPageAddress(host, shown);
203
+ create.disabled = blank;
204
+ note.textContent = "";
205
+ }
206
+ function submit() {
207
+ if (cleanText(input.value, false) === "") return;
208
+ const slug = slugNow();
209
+ // Never over another page's draft, and never at an address he has
210
+ // not seen: if it changed, show the new one first.
211
+ if (slug !== shown || loadDraft(storage, customPath(slug)) !== null) {
212
+ update();
213
+ return;
214
+ }
215
+ const path = customPath(slug);
216
+ if (saveDraft(storage, path, null, newPageDoc(schema, input.value))) open(path);
217
+ else note.textContent = TEXT.cannotKeepNewPage;
218
+ }
219
+ input.addEventListener("input", update);
220
+ input.addEventListener("keydown", (e) => {
221
+ if (e.key === "Enter" && !e.isComposing) {
222
+ e.preventDefault();
223
+ submit();
224
+ }
225
+ });
226
+ update();
227
+ add.replaceChildren(el("div", { class: "add-page-form", role: "group", "aria-labelledby": "new-page-label" }, [
228
+ el("label", { class: "label", for: "new-page-title", id: "new-page-label", text: TEXT.newPageTitle }),
229
+ input, preview, note,
230
+ el("div", { class: "actions" }, [create, cancel]),
231
+ ]));
232
+ input.focus();
233
+ }
234
+
235
+ drawButton();
236
+ return el("section", { class: "extra", "aria-labelledby": "extra-heading" }, [
237
+ el("h2", { id: "extra-heading", text: TEXT.extraPages }),
238
+ list, add,
239
+ ]);
240
+ }
241
+
242
+ /**
243
+ * "Delete this page", asking first in place. title() gives the page's
244
+ * title when asked; onDelete() is called on "Yes, delete it". reset() puts
245
+ * the button back (after a delete that failed); ask(reason) asks again,
246
+ * with a line saying why.
247
+ */
248
+ export function deleteControl({ title, onDelete }) {
249
+ const node = el("div", { class: "delete-area" });
250
+ const button = el("button", {
251
+ type: "button", class: "button delete-page", text: TEXT.deletePage, on: { click: () => ask() },
252
+ });
253
+
254
+ function reset() {
255
+ node.replaceChildren(button);
256
+ }
257
+
258
+ function ask(reason = null) {
259
+ const question = el("p", {
260
+ class: "confirm-text", id: "delete-ask", tabindex: "-1", text: deleteAsk(title()),
261
+ });
262
+ const why = reason ? el("p", { class: "notice", id: "delete-why", text: reason }) : null;
263
+ const row = el("div", {
264
+ class: "confirm", role: "group", "aria-labelledby": "delete-ask", "aria-describedby": why && "delete-why",
265
+ }, [
266
+ why, question,
267
+ el("div", { class: "actions" }, [
268
+ el("button", {
269
+ type: "button", class: "button danger", text: TEXT.deleteYes,
270
+ on: {
271
+ click: () => {
272
+ for (const b of row.querySelectorAll("button")) {
273
+ b.disabled = true;
274
+ b.setAttribute("data-spent", "");
275
+ }
276
+ onDelete();
277
+ },
278
+ },
279
+ }),
280
+ el("button", {
281
+ type: "button", class: "button", text: TEXT.deleteNo,
282
+ on: {
283
+ click: () => {
284
+ reset();
285
+ button.focus();
286
+ },
287
+ },
288
+ }),
289
+ ]),
290
+ ]);
291
+ node.replaceChildren(row);
292
+ question.focus();
293
+ }
294
+
295
+ reset();
296
+ return { node, reset, ask };
297
+ }