@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,918 @@
1
+ // The editing form for one page, built from its schema fields. Text a person
2
+ // typed is data: every element is made with createElement and filled through
3
+ // textContent, value and attributes; nothing is ever parsed as markup.
4
+ // The rules live in model.js, format.js and shared/validate.js; this file
5
+ // only turns them into controls. The helpers above renderForm need no DOM.
6
+ import { ALT_MAX, IMAGE_BASE, applies, textLimit } from "./shared/validate.js";
7
+ import {
8
+ cleanText, emptyValue, getAt, listAdd, listMove, listRemove, setAt, settleWhen,
9
+ } from "./model.js";
10
+ import { refusal, wrapSelection } from "./format.js";
11
+ import { ImageError, UPLOAD_BASE } from "./images.js";
12
+ import {
13
+ PHOTO_ERRORS, TEXT, addKindLabel, addLabel, characters, confirmRemove, itemKindName, itemName,
14
+ moveDownName, moveUpName, removeName,
15
+ } from "./copy.js";
16
+ import { SITE } from "./shared/site.js";
17
+
18
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19
+
20
+ /** The field of a list item that says which kind it is: a choice marked
21
+ * `fixed`, set when the item is added and never drawn as a control. */
22
+ const kindField = (fields) => fields.find((f) => f.type === "choice" && f.fixed === true) ?? null;
23
+
24
+ /** A new list item: every field empty, preset's values in place, and the
25
+ * fields their `when` allows. */
26
+ const newItem = (fields, preset) =>
27
+ settleWhen(fields, { ...emptyValue({ type: "object", fields }), ...preset });
28
+
29
+ /** The validator's name for a path: ["items", 2, "question"] -> "items[2].question". */
30
+ export function pathToField(path) {
31
+ let out = "";
32
+ for (const part of path) {
33
+ if (typeof part === "number") out += `[${part}]`;
34
+ else out += out === "" ? part : `.${part}`;
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /** A stable element id for a path. Keys start with a letter and hold no
40
+ * "-", so the joined form is unique and never holds "--", which the form
41
+ * keeps for the ids of a field's parts ("<id>--help"). */
42
+ export function fieldId(path) {
43
+ return ["f", ...path].join("-");
44
+ }
45
+
46
+ /** Problems as a Map from field name to its messages, in order. */
47
+ export function problemsByField(problems) {
48
+ const map = new Map();
49
+ for (const p of problems) {
50
+ if (!map.has(p.field)) map.set(p.field, []);
51
+ map.get(p.field).push(p.message);
52
+ }
53
+ return map;
54
+ }
55
+
56
+ /** The character count to show, or null while under 80% of max. Counts
57
+ * characters as the validator does (code points). */
58
+ export function countText(value, max) {
59
+ const n = [...String(value)].length;
60
+ return n * 5 < max * 4 ? null : characters(n, max);
61
+ }
62
+
63
+ /** The problems in shown that fresh still reports, with fresh's messages.
64
+ * A fixed field drops out; a field not already shown is never added. */
65
+ export function remainingProblems(shown, fresh) {
66
+ const kept = new Map();
67
+ for (const key of shown.keys()) if (fresh.has(key)) kept.set(key, fresh.get(key));
68
+ return kept;
69
+ }
70
+
71
+ /** Which control a text field gets: "textarea" for a textarea, "single"
72
+ * (a box on one logical line that grows to show all its text) for a text
73
+ * field that may hold more than 60 characters, "input" otherwise. */
74
+ export function controlKind(field, limit) {
75
+ if (field.type === "textarea") return "textarea";
76
+ return limit > 60 ? "single" : "input";
77
+ }
78
+
79
+ const LINE_BREAK = /\r\n?|\n/g;
80
+
81
+ /** value with every line break turned into a space, and where the caret at
82
+ * caret ends up. */
83
+ export function flattenLines(value, caret) {
84
+ return {
85
+ value: value.replace(LINE_BREAK, " "),
86
+ caret: value.slice(0, caret).replace(LINE_BREAK, " ").length,
87
+ };
88
+ }
89
+
90
+ /** Size a growing box to its text. Reads and sets the height through the
91
+ * style object, which the page's policy allows (a style attribute is not). */
92
+ function fit(area) {
93
+ if (!area.isConnected || area.scrollHeight === 0) return;
94
+ area.style.height = "auto";
95
+ area.style.height = `${area.scrollHeight + area.offsetHeight - area.clientHeight}px`;
96
+ }
97
+
98
+ const fitAll = (root) => root.querySelectorAll("textarea.single").forEach(fit);
99
+
100
+ // One width watcher per form container, so a redraw does not add another.
101
+ const watchers = new WeakMap();
102
+ // The latest form drawn into each container: an older one's late work
103
+ // (a photo finishing its preparation) is let go.
104
+ const generations = new WeakMap();
105
+
106
+ // Made once when the editor loads. With photos "key", the editor asks for a
107
+ // site photo with this query, so a miss (asked before the site serves the
108
+ // file) is never cached under the photo's public address.
109
+ const PREVIEW_KEY = Date.now().toString(36);
110
+ // With photos "asset-map": the hashed ending the site's build gives a file.
111
+ const HASH_AND_EXT = /^\.[0-9a-f]{10}\.(webp|jpg)$/;
112
+
113
+ /** The address of the photo's 700-wide file as the site serves it, or null.
114
+ * It is made of the stored base, checked against the validator's pattern,
115
+ * and the extension: with photos "key", with the editor's query; with
116
+ * photos "asset-map", with the hashed ending assetMap (the build's map of
117
+ * file names) gives it, checked against the build's pattern. */
118
+ export function photoSrc(image, assetMap) {
119
+ if (!isObject(image) || typeof image.base !== "string" || !IMAGE_BASE.test(image.base)) {
120
+ return null;
121
+ }
122
+ if (image.ext !== "webp" && image.ext !== "jpg") return null;
123
+ const stem = `${image.base}-700`;
124
+ if (SITE.photos === "key") return `${stem}.${image.ext}?v=${PREVIEW_KEY}`;
125
+ if (!isObject(assetMap)) return null;
126
+ const plain = `${stem}.${image.ext}`;
127
+ const hashed = Object.hasOwn(assetMap, plain) ? assetMap[plain] : undefined;
128
+ if (typeof hashed !== "string" || !hashed.startsWith(stem)) return null;
129
+ const ending = hashed.slice(stem.length);
130
+ const m = HASH_AND_EXT.exec(ending);
131
+ return m && m[1] === image.ext ? stem + ending : null;
132
+ }
133
+
134
+ /** Every description the published page gives a photo with this base,
135
+ * wherever it appears (one stock photo may be used more than once). */
136
+ export function publishedAlts(published, base) {
137
+ const out = new Set();
138
+ const walk = (value) => {
139
+ if (Array.isArray(value)) {
140
+ value.forEach(walk);
141
+ } else if (isObject(value)) {
142
+ if (value.base === base && typeof value.alt === "string") out.add(value.alt);
143
+ Object.values(value).forEach(walk);
144
+ }
145
+ };
146
+ walk(published);
147
+ return out;
148
+ }
149
+
150
+ /** True when the item holds typed words or a photo anywhere inside it. */
151
+ export function itemHasContent(fields, item) {
152
+ if (!isObject(item)) return false;
153
+ return fields.some((field) => {
154
+ const v = Object.hasOwn(item, field.key) ? item[field.key] : undefined;
155
+ switch (field.type) {
156
+ case "text":
157
+ case "textarea":
158
+ return typeof v === "string" && v.trim() !== "";
159
+ case "image":
160
+ return v !== null && v !== undefined;
161
+ case "object":
162
+ return itemHasContent(field.fields, v);
163
+ case "list":
164
+ return Array.isArray(v) && v.some((it) => itemHasContent(field.fields, it));
165
+ default:
166
+ return false;
167
+ }
168
+ });
169
+ }
170
+
171
+ /** An element with properties: "text" sets textContent, "on" adds
172
+ * listeners, anything else is an attribute (skipped when null, undefined or
173
+ * false). Children are nodes or strings (as text). Shared with app.js. */
174
+ export function el(tag, props = {}, children = []) {
175
+ const node = document.createElement(tag);
176
+ for (const [k, v] of Object.entries(props)) {
177
+ if (v === undefined || v === null || v === false) continue;
178
+ if (k === "text") node.textContent = v;
179
+ else if (k === "on") for (const [type, fn] of Object.entries(v)) node.addEventListener(type, fn);
180
+ else node.setAttribute(k, v === true ? "" : String(v));
181
+ }
182
+ node.append(...children.filter((c) => c !== null && c !== undefined));
183
+ return node;
184
+ }
185
+
186
+ const describe = (ids) => ids.filter(Boolean).join(" ") || null;
187
+
188
+ /**
189
+ * Fill container with the form for doc, in schema order.
190
+ * fields: the page's schema fields. onChange(doc) gets the whole new
191
+ * document after every change.
192
+ * ctx: {assetMap: the build's map of photo file names (photos "asset-map"),
193
+ * problems: [{field, message}], wide: open groups by default,
194
+ * photos: the page's new photos, which lets a photo be picked:
195
+ * {prepare(file) -> Promise<prepared>, chosen(name, prepared, old),
196
+ * drop(prepared), previewFor(image) -> url|null,
197
+ * needsRepick(name), keepCurrent(name),
198
+ * listChanged(listName, mapIndex)},
199
+ * published() -> the page as the site has it now (null for a page
200
+ * never published): a replaced photo's description is cleared
201
+ * while it is still the one published for the old photo,
202
+ * groupState: Map kept by the caller so open groups stay open,
203
+ * recheck(doc) -> problems: run after each change while problems show,
204
+ * onProblems(count): told the number of problems still showing}.
205
+ * While problems show, each change re-checks the page: a fixed field loses
206
+ * its message; a new problem waits for the next publish.
207
+ * Returns {focusFirstProblem(): boolean}.
208
+ */
209
+ export function renderForm(container, fields, doc, onChange, ctx = {}) {
210
+ let current = doc;
211
+ const generation = (generations.get(container) ?? 0) + 1;
212
+ generations.set(container, generation);
213
+ // Photos being prepared: {path}, kept pointing at the field they were
214
+ // picked for as list items move; path is null once that item is gone.
215
+ const picks = new Set();
216
+ let problems = problemsByField(ctx.problems ?? []);
217
+ const groupState = ctx.groupState ?? new Map();
218
+ // Each shown problem: field name -> {p: its message, controls: marked controls}.
219
+ let marks = new Map();
220
+ // Where focus goes for each problem, in page order: [{key, target}].
221
+ let targets = [];
222
+ let hinted = false;
223
+
224
+ const countOf = (map) => [...map.values()].reduce((n, messages) => n + messages.length, 0);
225
+
226
+ function unmark(key) {
227
+ const mark = marks.get(key);
228
+ marks.delete(key);
229
+ if (!mark) return;
230
+ for (const control of mark.controls) {
231
+ control.removeAttribute("aria-invalid");
232
+ const ids = (control.getAttribute("aria-describedby") ?? "").split(" ")
233
+ .filter((ref) => ref && ref !== mark.p.id);
234
+ if (ids.length > 0) control.setAttribute("aria-describedby", ids.join(" "));
235
+ else control.removeAttribute("aria-describedby");
236
+ }
237
+ const box = mark.p.closest(".problems-other");
238
+ mark.p.remove();
239
+ if (box && !box.querySelector(".problem")) box.remove();
240
+ }
241
+
242
+ function recheck() {
243
+ const kept = remainingProblems(problems, problemsByField(ctx.recheck(current)));
244
+ for (const key of problems.keys()) if (!kept.has(key)) unmark(key);
245
+ for (const [key, messages] of kept) {
246
+ const mark = marks.get(key);
247
+ if (mark) mark.p.textContent = messages.join(" ");
248
+ }
249
+ problems = kept;
250
+ if (ctx.onProblems) ctx.onProblems(countOf(problems));
251
+ }
252
+
253
+ function change(next) {
254
+ current = next;
255
+ onChange(current);
256
+ if (problems.size > 0 && ctx.recheck) recheck();
257
+ }
258
+
259
+ const hasProblemWithin = (key) => [...problems.keys()].some((f) =>
260
+ f === key || f.startsWith(`${key}.`) || f.startsWith(`${key}[`));
261
+
262
+ /** The problem message for key, tied to the control that should get focus
263
+ * (and is marked invalid); without one, the message itself takes focus. */
264
+ function problemFor(key, id, target) {
265
+ if (!problems.has(key)) return null;
266
+ const p = el("p", { class: "problem", id: `${id}--problem`, tabindex: "-1" },
267
+ [problems.get(key).join(" ")]);
268
+ marks.set(key, { p, controls: target ? [target] : [] });
269
+ targets.push({ key, target: target ?? p });
270
+ return p;
271
+ }
272
+
273
+ /** Re-check `when` fields beside the one that changed, redrawing if any
274
+ * appear or disappear. */
275
+ function settle(parentPath, siblings, key, focusId) {
276
+ if (!siblings.some((f) => f.when && Object.hasOwn(f.when, key))) return;
277
+ const obj = getAt(current, parentPath);
278
+ const settled = isObject(obj) ? settleWhen(siblings, obj) : obj;
279
+ if (settled !== obj) {
280
+ change(setAt(current, parentPath, settled));
281
+ redraw(() => document.getElementById(focusId));
282
+ }
283
+ }
284
+
285
+ /** extra: {limit, label} in place of the field's own. */
286
+ function renderText(field, path, siblings, extra = {}) {
287
+ const id = fieldId(path);
288
+ const key = pathToField(path);
289
+ const multiline = field.type === "textarea";
290
+ const limit = extra.limit ?? textLimit(field);
291
+ const kind = controlKind(field, limit);
292
+ const single = kind === "single";
293
+ const value = getAt(current, path);
294
+ const input = el(kind === "input" ? "input" : "textarea", {
295
+ id, class: single ? "input single" : "input", type: kind === "input" ? "text" : null,
296
+ rows: { input: null, single: 1, textarea: 5 }[kind], autocomplete: "off",
297
+ });
298
+ input.value = typeof value === "string" ? value : "";
299
+ const help = field.help ? el("p", { class: "help", id: `${id}--help`, text: field.help }) : null;
300
+ const problem = problemFor(key, id, input);
301
+ const count = el("p", { class: "count", id: `${id}--count` });
302
+
303
+ let tools = null;
304
+ let note = null;
305
+ let hint = null;
306
+ let formatting = false;
307
+ if (!field.plain) {
308
+ note = el("p", { class: "note", role: "status" });
309
+ const press = (style) => {
310
+ formatting = false;
311
+ const start = input.selectionStart ?? input.value.length;
312
+ const end = input.selectionEnd ?? start;
313
+ input.focus();
314
+ const why = refusal(input.value, start, end, style);
315
+ if (why !== null) {
316
+ note.textContent = why === "lines" ? TEXT.linkOneLine : TEXT.formatRefused;
317
+ input.setSelectionRange(start, end);
318
+ return;
319
+ }
320
+ const r = wrapSelection(input.value, start, end, style);
321
+ note.textContent = "";
322
+ input.value = r.value;
323
+ input.setSelectionRange(r.start, r.end);
324
+ if (single) fit(input);
325
+ change(setAt(current, path, r.value));
326
+ updateCount();
327
+ };
328
+ // Pressing a button must not take focus or the selection from the field.
329
+ const keep = (e) => {
330
+ formatting = true;
331
+ e.preventDefault();
332
+ };
333
+ tools = el("div", { class: "format" }, ["bold", "italic", "link"].map((style) =>
334
+ el("button", {
335
+ type: "button", class: "button format-button", "aria-controls": id,
336
+ // A colourable heading's emphasis shows in colour, not italic.
337
+ text: style === "italic" && field.accent === true ? TEXT.colour : TEXT[style],
338
+ on: { pointerdown: keep, mousedown: keep, click: () => press(style) },
339
+ })));
340
+ if (!hinted) {
341
+ hinted = true;
342
+ hint = el("p", {
343
+ class: "help hint", id: `${id}--hint`, text: field.accent === true ? TEXT.formatHintAccent : TEXT.formatHint,
344
+ });
345
+ }
346
+ }
347
+
348
+ input.setAttribute("aria-describedby", describe([
349
+ help && help.id, problem && problem.id, count.id, hint && hint.id,
350
+ ]));
351
+ if (problem) input.setAttribute("aria-invalid", "true");
352
+
353
+ function updateCount() {
354
+ const text = countText(input.value, limit);
355
+ count.textContent = text ?? "";
356
+ count.classList.toggle("over", [...input.value].length > limit);
357
+ }
358
+ updateCount();
359
+
360
+ if (single) {
361
+ // One line only: Enter adds nothing, and a pasted line break becomes a space.
362
+ input.addEventListener("keydown", (e) => {
363
+ if (e.key === "Enter" && !e.isComposing) e.preventDefault();
364
+ });
365
+ }
366
+ input.addEventListener("input", () => {
367
+ if (note) note.textContent = "";
368
+ if (single) {
369
+ if (/[\r\n]/.test(input.value)) {
370
+ const flat = flattenLines(input.value, input.selectionEnd ?? input.value.length);
371
+ input.value = flat.value;
372
+ input.setSelectionRange(flat.caret, flat.caret);
373
+ }
374
+ fit(input);
375
+ }
376
+ change(setAt(current, path, input.value));
377
+ updateCount();
378
+ settle(path.slice(0, -1), siblings, field.key, id);
379
+ });
380
+ input.addEventListener("blur", (e) => {
381
+ // Leave the text alone while a formatting button is being pressed.
382
+ if (formatting || (tools && tools.contains(e.relatedTarget))) {
383
+ formatting = false;
384
+ return;
385
+ }
386
+ const cleaned = cleanText(input.value, multiline);
387
+ if (cleaned !== input.value) {
388
+ input.value = cleaned;
389
+ if (single) fit(input);
390
+ change(setAt(current, path, cleaned));
391
+ updateCount();
392
+ }
393
+ });
394
+
395
+ return el("div", { class: "field" }, [
396
+ el("label", { for: id, class: "label", text: extra.label ?? field.label }),
397
+ help, problem, input, tools, note, count, hint,
398
+ ]);
399
+ }
400
+
401
+ function renderChoice(field, path, siblings) {
402
+ const id = fieldId(path);
403
+ const value = getAt(current, path);
404
+ const options = field.options ?? [];
405
+ const known = options.some((o) => o.value === value);
406
+ const select = el("select", { id, class: "input" });
407
+ if (!field.required || !known) select.append(el("option", { value: "", text: TEXT.chooseOne }));
408
+ for (const o of options) select.append(el("option", { value: o.value, text: o.label }));
409
+ select.value = known ? value : "";
410
+ const help = field.help ? el("p", { class: "help", id: `${id}--help`, text: field.help }) : null;
411
+ const problem = problemFor(pathToField(path), id, select);
412
+ const describedBy = describe([help && help.id, problem && problem.id]);
413
+ if (describedBy) select.setAttribute("aria-describedby", describedBy);
414
+ if (problem) select.setAttribute("aria-invalid", "true");
415
+ select.addEventListener("change", () => {
416
+ change(setAt(current, path, select.value));
417
+ settle(path.slice(0, -1), siblings, field.key, id);
418
+ });
419
+ return el("div", { class: "field" }, [
420
+ el("label", { for: id, class: "label", text: field.label }), help, problem, select,
421
+ ]);
422
+ }
423
+
424
+ function renderBoolean(field, path, siblings) {
425
+ const id = fieldId(path);
426
+ const box = el("input", { id, type: "checkbox", class: "checkbox" });
427
+ box.checked = getAt(current, path) === true;
428
+ const help = field.help ? el("p", { class: "help", id: `${id}--help`, text: field.help }) : null;
429
+ const problem = problemFor(pathToField(path), id, box);
430
+ const describedBy = describe([help && help.id, problem && problem.id]);
431
+ if (describedBy) box.setAttribute("aria-describedby", describedBy);
432
+ if (problem) box.setAttribute("aria-invalid", "true");
433
+ box.addEventListener("change", () => {
434
+ change(setAt(current, path, box.checked));
435
+ settle(path.slice(0, -1), siblings, field.key, id);
436
+ });
437
+ return el("div", { class: "field" }, [
438
+ el("div", { class: "check" }, [box, el("label", { for: id, text: field.label })]),
439
+ help, problem,
440
+ ]);
441
+ }
442
+
443
+ /** Point each photo being prepared inside the list at listPath at its
444
+ * item's new place: item i is now item mapIndex(i), or gone when null. */
445
+ function followPicks(listPath, mapIndex) {
446
+ const n = listPath.length;
447
+ for (const pick of picks) {
448
+ if (pick.path === null || pick.path.length <= n ||
449
+ !listPath.every((part, i) => pick.path[i] === part)) continue;
450
+ const to = mapIndex(pick.path[n]);
451
+ pick.path = to === null ? null : [...listPath, to, ...pick.path.slice(n + 1)];
452
+ }
453
+ }
454
+
455
+ /** True while a photo picked for the field at path is being prepared. */
456
+ function preparing(path) {
457
+ const key = pathToField(path);
458
+ return [...picks].some((pick) => pick.path !== null && pathToField(pick.path) === key);
459
+ }
460
+
461
+ /** Bring the picker of the photo at path, as it is on the page now, up to
462
+ * date: busy while a pick for it is prepared; message (unless null) in
463
+ * its note. The list may have been drawn again since the pick. */
464
+ function showPicker(path, message) {
465
+ const id = fieldId(path);
466
+ const button = document.getElementById(`${id}--pick`);
467
+ if (button) {
468
+ const busy = preparing(path);
469
+ button.disabled = busy;
470
+ button.textContent = busy ? TEXT.preparingPhoto
471
+ : isObject(getAt(current, path)) ? TEXT.replacePhoto : TEXT.choosePhoto;
472
+ }
473
+ const note = document.getElementById(`${id}--note`);
474
+ if (note && message !== null) note.textContent = message;
475
+ }
476
+
477
+ /** Prepare file for the photo at path, then put it in the page and draw
478
+ * the field again. The rest of the page stays usable meanwhile: the
479
+ * description may be typed and items moved, added or removed. */
480
+ async function choosePhoto(field, path, file) {
481
+ const pick = { path };
482
+ picks.add(pick);
483
+ showPicker(path, "");
484
+ let prepared = null;
485
+ let failure = null;
486
+ try {
487
+ prepared = await ctx.photos.prepare(file);
488
+ } catch (err) {
489
+ failure = err instanceof ImageError ? err.message : PHOTO_ERRORS.cannot_read;
490
+ }
491
+ picks.delete(pick);
492
+ // Whether the page was left or drawn again, or the item went, meanwhile.
493
+ const at = pick.path;
494
+ const live = container.isConnected && generations.get(container) === generation && at !== null;
495
+ if (failure !== null) {
496
+ if (live) showPicker(at, failure);
497
+ return;
498
+ }
499
+ if (!live || !isObject(getAt(current, at.slice(0, -1)))) {
500
+ ctx.photos.drop(prepared);
501
+ if (live) showPicker(at, null);
502
+ return;
503
+ }
504
+ // A description typed in this session stays, including one typed while
505
+ // this photo was prepared; one that is still the published photo's own
506
+ // describes the old photo, so the new one starts without it.
507
+ const now = getAt(current, at);
508
+ const kept = isObject(now) && typeof now.alt === "string" ? now.alt : prepared.field.alt;
509
+ const stale = isObject(now) && field.alt !== false &&
510
+ publishedAlts(ctx.published?.() ?? null, now.base).has(kept);
511
+ const alt = stale ? "" : kept;
512
+ ctx.photos.chosen(pathToField(at), prepared, now ?? null);
513
+ change(setAt(current, at, { ...prepared.field, alt }));
514
+ const id = fieldId(at);
515
+ const old = document.getElementById(id);
516
+ // Focus follows only from this field, or from nowhere: never from a box
517
+ // the owner is typing in elsewhere. In the description box it stays put.
518
+ const active = document.activeElement;
519
+ const nowhere = !active || active === document.body;
520
+ const within = Boolean(old && active && old.contains(active));
521
+ const typing = within && active.id === `${id}-alt` ? [active.selectionStart, active.selectionEnd] : null;
522
+ old?.replaceWith(renderImage(field, at));
523
+ if (typing) {
524
+ const box = document.getElementById(`${id}-alt`);
525
+ box?.focus();
526
+ box?.setSelectionRange(...typing);
527
+ } else if (within || nowhere) {
528
+ document.getElementById(`${id}--pick`)?.focus();
529
+ }
530
+ }
531
+
532
+ /** "Remove photo": an optional photo that holds one can be emptied. */
533
+ function removePhoto(field, path) {
534
+ const id = fieldId(path);
535
+ const key = pathToField(path);
536
+ return el("button", {
537
+ type: "button", class: "button", id: `${id}--remove`, "aria-describedby": `${id}--label`,
538
+ text: TEXT.removePhoto,
539
+ on: {
540
+ click: () => {
541
+ change(setAt(current, path, null));
542
+ // Nothing is waiting for a new photo here any more.
543
+ if (ctx.photos?.needsRepick(key)) ctx.photos.keepCurrent(key);
544
+ document.getElementById(id)?.replaceWith(renderImage(field, path));
545
+ (document.getElementById(`${id}--pick`) ?? document.getElementById(id))?.focus();
546
+ },
547
+ },
548
+ });
549
+ }
550
+
551
+ /** "Replace photo" (or "Choose photo"), a real button opening a hidden
552
+ * file picker. No `capture`: the owner picks from his photo library. */
553
+ function photoPicker(field, path, value) {
554
+ const id = fieldId(path);
555
+ const input = el("input", {
556
+ type: "file", accept: "image/*", class: "photo-file", tabindex: "-1", "aria-hidden": "true",
557
+ });
558
+ const busy = preparing(path);
559
+ const button = el("button", {
560
+ type: "button", class: "button photo-pick", id: `${id}--pick`, "aria-describedby": `${id}--label`,
561
+ text: busy ? TEXT.preparingPhoto : isObject(value) ? TEXT.replacePhoto : TEXT.choosePhoto,
562
+ disabled: busy,
563
+ on: { click: () => input.click() },
564
+ });
565
+ input.addEventListener("change", () => {
566
+ const file = input.files && input.files[0];
567
+ // Cleared, so picking the same file again still counts as a change.
568
+ input.value = "";
569
+ if (file) choosePhoto(field, path, file);
570
+ });
571
+ return el("div", { class: "actions photo-actions" }, [button, input]);
572
+ }
573
+
574
+ /** "Pick your new photo again.", with a way to keep the photo there. */
575
+ function repickNotice(key, id) {
576
+ const notice = el("div", { class: "notice repick" }, [
577
+ el("p", { text: TEXT.pickAgain }),
578
+ el("div", { class: "actions" }, [el("button", {
579
+ type: "button", class: "button keep-photo", text: TEXT.keepCurrentPhoto,
580
+ on: {
581
+ click: () => {
582
+ ctx.photos.keepCurrent(key);
583
+ notice.remove();
584
+ document.getElementById(`${id}--pick`)?.focus();
585
+ },
586
+ },
587
+ })]),
588
+ ]);
589
+ return notice;
590
+ }
591
+
592
+ function renderImage(field, path) {
593
+ const id = fieldId(path);
594
+ const key = pathToField(path);
595
+ const value = getAt(current, path);
596
+ // A photo picked in this session shows from memory; the site serves it
597
+ // only after its rebuild.
598
+ const src = ctx.photos?.previewFor(value) ?? photoSrc(value, ctx.assetMap);
599
+ // An uploaded photo the site does not serve yet (just published, then a
600
+ // reload) is on its way, not missing.
601
+ const coming = isObject(value) && typeof value.base === "string" && value.base.startsWith(UPLOAD_BASE);
602
+ const none = () => el("div", { class: "photo-preview photo-none", text: coming ? TEXT.photoComing : TEXT.noPhoto });
603
+ const picture = src
604
+ ? el("img", { src, alt: "", class: "photo-preview", loading: "lazy", decoding: "async" })
605
+ : none();
606
+ // A file the site cannot give shows the words instead.
607
+ if (src) picture.addEventListener("error", () => picture.replaceWith(none()), { once: true });
608
+ const help = field.help ? el("p", { class: "help", id: `${id}--help`, text: field.help }) : null;
609
+ // A problem with the photo sits beside the photo; one with its description
610
+ // (path "<photo>.alt") sits beside the description box, which renderText
611
+ // ties to it through the same path.
612
+ const problem = problemFor(key, id, null);
613
+ const again = ctx.photos?.needsRepick(key) ? repickNotice(key, id) : null;
614
+ // Why a picked photo cannot be used.
615
+ const note = el("p", { class: "note", role: "status", id: `${id}--note` });
616
+ let picker = ctx.photos ? photoPicker(field, path, value) : null;
617
+ if (!field.required && isObject(value)) {
618
+ const remove = removePhoto(field, path);
619
+ if (picker) picker.append(remove);
620
+ else picker = el("div", { class: "actions photo-actions" }, [remove]);
621
+ }
622
+ const alt = field.alt !== false && isObject(value)
623
+ ? renderText(
624
+ { key: "alt", type: "text", plain: true, label: TEXT.describePhoto, help: TEXT.describePhotoHelp },
625
+ [...path, "alt"], [], { limit: ALT_MAX })
626
+ : null;
627
+ return el("div", { class: "field photo", id }, [
628
+ el("p", { class: "label", id: `${id}--label`, text: field.label }),
629
+ help, problem, again, picture, picker, note, alt,
630
+ ]);
631
+ }
632
+
633
+ function objectBody(field, path) {
634
+ const obj = getAt(current, path);
635
+ const values = isObject(obj) ? obj : {};
636
+ return field.fields.map((child) => renderField(child, path, values, field.fields));
637
+ }
638
+
639
+ function renderObject(field, path) {
640
+ const id = fieldId(path);
641
+ return el("fieldset", { class: "object", id }, [
642
+ el("legend", { class: "legend", text: field.label }),
643
+ field.help ? el("p", { class: "help", text: field.help }) : null,
644
+ problemFor(pathToField(path), id, null),
645
+ ...objectBody(field, path),
646
+ ]);
647
+ }
648
+
649
+ function firstControl(blockId) {
650
+ const block = document.getElementById(blockId);
651
+ if (!block) return null;
652
+ // In page order; a photo's hidden file picker is reached by its button.
653
+ return [...block.querySelectorAll("input, textarea, select, button")]
654
+ .find((c) => !c.disabled && c.getAttribute("type") !== "file") ?? null;
655
+ }
656
+
657
+ function listBody(field, path, depth) {
658
+ const id = fieldId(path);
659
+ const list = getAt(current, path);
660
+ const items = Array.isArray(list) ? list : [];
661
+ const min = field.min ?? 0;
662
+ const max = field.maxItems ?? 50;
663
+ const label = field.itemLabel ?? field.label;
664
+ const kind = kindField(field.fields);
665
+ const addId = `${id}--add`;
666
+ const heading = `h${Math.min(depth + 2, 6)}`;
667
+ /** "Part 3", or "Part 3: Paragraph" when the item's kind is fixed. */
668
+ const nameOf = (item, n) => {
669
+ const option = kind && (kind.options ?? []).find((o) => o.value === item[kind.key]);
670
+ return option ? itemKindName(label, n, option.label) : itemName(label, n);
671
+ };
672
+ const focusItem = (index) => () =>
673
+ firstControl(fieldId([...path, index])) ?? document.getElementById(addId);
674
+
675
+ /** Apply a removal or move, and tell the photos where each item went. */
676
+ function reshape(next, mapIndex) {
677
+ if (next === current) return;
678
+ followPicks(path, mapIndex);
679
+ change(next);
680
+ ctx.photos?.listChanged(pathToField(path), mapIndex);
681
+ }
682
+
683
+ function remove(index) {
684
+ const left = items.length - 1;
685
+ reshape(listRemove(current, path, index, min), (i) => (i === index ? null : i > index ? i - 1 : i));
686
+ redraw(left === 0
687
+ ? () => document.getElementById(addId)
688
+ : focusItem(Math.min(index, left - 1)));
689
+ }
690
+
691
+ function move(index, delta) {
692
+ const to = index + delta;
693
+ reshape(listMove(current, path, index, delta), (i) => (i === index ? to : i === to ? index : i));
694
+ redraw(focusItem(to));
695
+ }
696
+
697
+ function confirmRow(index, controls) {
698
+ const n = index + 1;
699
+ const askId = `${fieldId([...path, index])}--confirm`;
700
+ const ask = el("p", { class: "confirm-text", id: askId, tabindex: "-1", text: confirmRemove(label, n) });
701
+ const row = el("div", { class: "confirm", role: "group", "aria-labelledby": askId }, [
702
+ ask,
703
+ el("div", { class: "actions" }, [
704
+ el("button", {
705
+ type: "button", class: "button danger", text: TEXT.confirmYes,
706
+ on: { click: () => remove(index) },
707
+ }),
708
+ el("button", {
709
+ type: "button", class: "button", text: TEXT.confirmNo,
710
+ on: {
711
+ click: () => {
712
+ row.replaceWith(controls);
713
+ controls.querySelector(".remove")?.focus();
714
+ },
715
+ },
716
+ }),
717
+ ]),
718
+ ]);
719
+ controls.replaceWith(row);
720
+ ask.focus();
721
+ }
722
+
723
+ const blocks = items.map((item, index) => {
724
+ const ipath = [...path, index];
725
+ const bid = fieldId(ipath);
726
+ const n = index + 1;
727
+ const values = isObject(item) ? item : {};
728
+ const controls = el("div", { class: "actions item-actions" }, [
729
+ el("button", {
730
+ type: "button", class: "button", "aria-label": moveUpName(label, n), text: TEXT.moveUp,
731
+ disabled: index === 0,
732
+ on: { click: () => move(index, -1) },
733
+ }),
734
+ el("button", {
735
+ type: "button", class: "button", "aria-label": moveDownName(label, n), text: TEXT.moveDown,
736
+ disabled: index === items.length - 1,
737
+ on: { click: () => move(index, 1) },
738
+ }),
739
+ el("button", {
740
+ type: "button", class: "button remove", "aria-label": removeName(label, n), text: TEXT.remove,
741
+ disabled: items.length <= min,
742
+ on: {
743
+ // The item as it is now, with whatever was typed since the last draw.
744
+ click: () => (itemHasContent(field.fields, getAt(current, ipath))
745
+ ? confirmRow(index, controls) : remove(index)),
746
+ },
747
+ }),
748
+ ]);
749
+ return el("div", { class: "item", id: bid, role: "group", "aria-labelledby": `${bid}--name` }, [
750
+ el(heading, { class: "item-name", id: `${bid}--name`, text: nameOf(values, n) }),
751
+ problemFor(pathToField(ipath), bid, null),
752
+ ...field.fields.map((child) => renderField(child, ipath, values, field.fields, depth + 1)),
753
+ controls,
754
+ ]);
755
+ });
756
+
757
+ const addButton = (text, preset, buttonId) => el("button", {
758
+ type: "button", class: "button add", id: buttonId, text,
759
+ disabled: items.length >= max,
760
+ on: {
761
+ click: () => {
762
+ const base = Array.isArray(getAt(current, path)) ? current : setAt(current, path, []);
763
+ const index = getAt(base, path).length;
764
+ change(listAdd(base, path, newItem(field.fields, preset), max));
765
+ // Every item stays where it was, but the list is no longer the one opened.
766
+ ctx.photos?.listChanged(pathToField(path), (i) => i);
767
+ redraw(focusItem(index));
768
+ },
769
+ },
770
+ });
771
+ // An item whose kind is fixed is added by kind, one button for each.
772
+ const add = kind
773
+ ? el("div", { class: "actions add-kinds" }, (kind.options ?? []).map((o, i) =>
774
+ addButton(addKindLabel(o.label), { [kind.key]: o.value }, i === 0 ? addId : null)))
775
+ : addButton(addLabel(label), {}, addId);
776
+ return [problemFor(pathToField(path), id, null), ...blocks, add];
777
+ }
778
+
779
+ function renderList(field, path, depth) {
780
+ return el("fieldset", { class: "list", id: fieldId(path) }, [
781
+ el("legend", { class: "legend", text: field.label }),
782
+ field.help ? el("p", { class: "help", text: field.help }) : null,
783
+ ...listBody(field, path, depth),
784
+ ]);
785
+ }
786
+
787
+ function renderField(field, parentPath, obj, siblings, depth = 0) {
788
+ // A fixed choice was made when the item was added; its heading names it.
789
+ if (!applies(field, obj) || (field.type === "choice" && field.fixed === true)) return null;
790
+ const path = [...parentPath, field.key];
791
+ switch (field.type) {
792
+ case "text":
793
+ case "textarea":
794
+ return renderText(field, path, siblings);
795
+ case "choice":
796
+ return renderChoice(field, path, siblings);
797
+ case "boolean":
798
+ return renderBoolean(field, path, siblings);
799
+ case "image":
800
+ return renderImage(field, path);
801
+ case "object":
802
+ return renderObject(field, path);
803
+ case "list":
804
+ return renderList(field, path, depth);
805
+ default:
806
+ return null;
807
+ }
808
+ }
809
+
810
+ /** A top-level object or list as a collapsible group. */
811
+ function renderGroup(field, path) {
812
+ const id = `${fieldId(path)}--group`;
813
+ const details = el("details", { class: "group", id });
814
+ details.open = hasProblemWithin(pathToField(path)) ||
815
+ (groupState.has(id) ? groupState.get(id) : Boolean(ctx.wide));
816
+ details.addEventListener("toggle", () => {
817
+ groupState.set(id, details.open);
818
+ if (details.open) fitAll(details);
819
+ });
820
+ const body = field.type === "object"
821
+ ? [problemFor(pathToField(path), fieldId(path), null), ...objectBody(field, path)]
822
+ : listBody(field, path, 0);
823
+ details.append(
824
+ el("summary", { class: "summary" }, [el("span", { text: field.label })]),
825
+ el("div", { class: "group-body" }, [
826
+ field.help ? el("p", { class: "help", text: field.help }) : null,
827
+ ...body,
828
+ ].filter(Boolean)),
829
+ );
830
+ return details;
831
+ }
832
+
833
+ function draw() {
834
+ marks = new Map();
835
+ targets = [];
836
+ hinted = false;
837
+ const values = isObject(current) ? current : {};
838
+ const nodes = [];
839
+ let loose = null;
840
+ for (const field of fields) {
841
+ if (!applies(field, values)) continue;
842
+ if (field.type === "object" || field.type === "list") {
843
+ loose = null;
844
+ nodes.push(renderGroup(field, [field.key]));
845
+ } else {
846
+ if (!loose) {
847
+ loose = el("div", { class: "loose" });
848
+ nodes.push(loose);
849
+ }
850
+ const node = renderField(field, [], values, fields);
851
+ if (node) loose.append(node);
852
+ }
853
+ }
854
+ // Problems with no control of their own are listed first.
855
+ const other = [...problems.keys()].filter((k) => !marks.has(k));
856
+ if (other.length > 0) {
857
+ const box = el("div", { class: "problems-other", tabindex: "-1" });
858
+ for (const key of other) {
859
+ const p = el("p", { class: "problem", text: problems.get(key).join(" ") });
860
+ marks.set(key, { p, controls: [] });
861
+ targets.unshift({ key, target: box });
862
+ box.append(p);
863
+ }
864
+ nodes.unshift(box);
865
+ }
866
+ container.replaceChildren(...nodes);
867
+ fitAll(container);
868
+ }
869
+
870
+ /** Redraw after a change of shape (add, remove, move, a `when` field
871
+ * appearing). Problems are dropped: their positions no longer hold. */
872
+ function redraw(focus) {
873
+ const hadProblems = problems.size > 0;
874
+ problems = new Map();
875
+ draw();
876
+ if (hadProblems && ctx.onProblems) ctx.onProblems(0);
877
+ const target = focus && focus();
878
+ if (target) target.focus();
879
+ }
880
+
881
+ draw();
882
+ if (typeof ResizeObserver !== "undefined") {
883
+ watchers.get(container)?.disconnect();
884
+ let width = 0;
885
+ // Refitting changes the container's height, so it waits for the next
886
+ // frame: doing it inside the callback makes the browser report a loop.
887
+ const frames = typeof requestAnimationFrame === "function";
888
+ let pending = false;
889
+ const refit = () => {
890
+ pending = false;
891
+ fitAll(container);
892
+ };
893
+ const watcher = new ResizeObserver(([entry]) => {
894
+ if (entry.contentRect.width === width) return;
895
+ width = entry.contentRect.width;
896
+ if (!frames) {
897
+ fitAll(container);
898
+ } else if (!pending) {
899
+ pending = true;
900
+ requestAnimationFrame(refit);
901
+ }
902
+ });
903
+ watcher.observe(container);
904
+ watchers.set(container, watcher);
905
+ }
906
+
907
+ return {
908
+ /** Move focus to the first problem in page order; false when none. */
909
+ focusFirstProblem() {
910
+ const found = targets.find((t) => marks.has(t.key) && t.target.isConnected);
911
+ if (!found) return false;
912
+ const { target } = found;
913
+ for (let d = target.closest("details"); d; d = d.parentElement?.closest("details")) d.open = true;
914
+ target.focus();
915
+ return true;
916
+ },
917
+ };
918
+ }