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

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 +34 -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,303 @@
1
+ // Content validator. tests/fixtures/validation.json holds the [field, code]
2
+ // pairs it reports for each case, for a site that repeats the check elsewhere.
3
+ // No Node or browser globals: the editor, the Functions and Node load it.
4
+ import { DOC_PATH_RE, badLinks } from "./rules.js";
5
+
6
+ // C0 controls except "\n", DEL, zero-width and bidi marks, line/paragraph
7
+ // separators, the byte-order mark and lone surrogates (a paired one is one
8
+ // code point under the u flag, so an emoji passes).
9
+ export const BAD_CHAR = /[\u0000-\u0009\u000b-\u001f\u007f\u200b\u200e\u200f\u2028\u2029\ufeff\p{Surrogate}]/u;
10
+ export const IMAGE_BASE = /^\/assets\/img\/(uploads\/)?[a-z0-9-]+$/;
11
+ const IMAGE_KEYS = ["base", "ext", "widths", "width", "height", "alt"];
12
+ const IMAGE_WIDTHS = [700, 1100, 1800];
13
+ /** The most characters a photo description may hold. */
14
+ export const ALT_MAX = 200;
15
+ const EMPTY = { text: "", textarea: "", choice: "", boolean: false, image: null };
16
+
17
+ const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
18
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19
+ const isBlank = (s) => s.trim() === "";
20
+ const length = (s) => [...s].length;
21
+ const join = (path, key) => (path ? `${path}.${key}` : key);
22
+ const label = (field) => `"${field.label ?? field.key}"`;
23
+ const items = (n) => (n === 1 ? "item" : "items");
24
+
25
+ const patterns = new Map();
26
+ function compile(pattern) {
27
+ if (!patterns.has(pattern)) patterns.set(pattern, new RegExp(pattern, "u"));
28
+ return patterns.get(pattern);
29
+ }
30
+
31
+ export function docTypeForPath(path) {
32
+ const m = typeof path === "string" ? DOC_PATH_RE.exec(path) : null;
33
+ if (!m) return null;
34
+ if (m[1] === "site") return "site";
35
+ return m[1].startsWith("pages/") ? m[1] : "custom";
36
+ }
37
+
38
+ /** True when field exists in obj: it has no `when`, or its sibling holds
39
+ * one of the listed values. */
40
+ export function applies(field, obj) {
41
+ if (!field.when) return true;
42
+ return Object.entries(field.when).every(
43
+ ([k, allowedValues]) => has(obj, k) && allowedValues.includes(obj[k]));
44
+ }
45
+
46
+ function checkText(field, value, path, out) {
47
+ const name = label(field);
48
+ if (typeof value !== "string") {
49
+ out.push({ field: path, code: "not_text", message: `${name} must be text.` });
50
+ return;
51
+ }
52
+ if (isBlank(value)) {
53
+ if (field.required) {
54
+ out.push({ field: path, code: "required", message: `${name} needs a value.` });
55
+ }
56
+ return;
57
+ }
58
+ if (field.type === "text" && value.includes("\n")) {
59
+ out.push({ field: path, code: "newline", message: `${name} must be on a single line.` });
60
+ return;
61
+ }
62
+ if (BAD_CHAR.test(value)) {
63
+ out.push({
64
+ field: path, code: "bad_char",
65
+ message: `${name} has a character that cannot be saved. Retype that part by hand.`,
66
+ });
67
+ return;
68
+ }
69
+ const limit = textLimit(field);
70
+ if (length(value) > limit) {
71
+ out.push({
72
+ field: path, code: "too_long",
73
+ message: `${name} is too long. The most it can hold is ${limit} characters.`,
74
+ });
75
+ return;
76
+ }
77
+ if (field.pattern && !compile(field.pattern).test(value)) {
78
+ out.push({
79
+ field: path, code: "pattern",
80
+ message: `${name} is not in the expected form.${field.patternHelp ? " " + field.patternHelp : ""}`,
81
+ });
82
+ return;
83
+ }
84
+ if (!field.plain && badLinks(value).length > 0) {
85
+ out.push({
86
+ field: path, code: "bad_link",
87
+ message: `${name} has a link that will not work. An address must start with /, ` +
88
+ "https://, mailto: or tel: and may not contain spaces, parentheses or *. " +
89
+ "If the address is empty, type it in or remove the link.",
90
+ });
91
+ }
92
+ }
93
+
94
+ /** The most characters a text or textarea field may hold. */
95
+ export function textLimit(field) {
96
+ return field.max ?? (field.type === "text" ? 200 : 2000);
97
+ }
98
+
99
+ const ALT_FIELD = {
100
+ key: "alt", type: "text", label: "Photo description", required: true, max: ALT_MAX, plain: true,
101
+ };
102
+
103
+ /** True when everything about the image except a described photo's
104
+ * description is valid; a decorative image's alt is checked here too. */
105
+ function imageOk(field, value) {
106
+ const decorative = field.alt === false;
107
+ if (!isObject(value)) return false;
108
+ const keys = Object.keys(value);
109
+ const sameKeys = (want) => keys.length === want.length && want.every((k) => has(value, k));
110
+ if (!sameKeys(IMAGE_KEYS) && !sameKeys(IMAGE_KEYS.filter((k) => k !== "alt"))) return false;
111
+ if (typeof value.base !== "string" || !IMAGE_BASE.test(value.base)) return false;
112
+ if (value.ext !== "webp" && value.ext !== "jpg") return false;
113
+ const widths = value.widths;
114
+ if (!(Array.isArray(widths) && widths.length > 0 &&
115
+ widths.every((w) => Number.isInteger(w) && IMAGE_WIDTHS.includes(w)) &&
116
+ widths.every((w, i) => i === 0 || widths[i - 1] < w) &&
117
+ widths[0] === 700)) return false;
118
+ if (!(Number.isInteger(value.width) && value.width === widths[widths.length - 1])) return false;
119
+ if (!(Number.isInteger(value.height) && value.height >= 1 && value.height <= 20000)) return false;
120
+ if (decorative) return !has(value, "alt") || value.alt === "";
121
+ return true;
122
+ }
123
+
124
+ function checkField(field, obj, path, out) {
125
+ const key = field.key;
126
+ const fpath = join(path, key);
127
+ if (!applies(field, obj)) {
128
+ if (has(obj, key)) {
129
+ out.push({ field: fpath, code: "unknown_field", message: `${label(field)} does not belong here.` });
130
+ }
131
+ return;
132
+ }
133
+ const name = label(field);
134
+ const type = field.type;
135
+ if (!has(obj, key)) {
136
+ // A missing object or list is checked as if it were {} or [].
137
+ if (type === "object") checkObject(field.fields, {}, fpath, out, field.label ?? key);
138
+ else if (type === "list") checkList(field, [], fpath, out);
139
+ else if (field.required) {
140
+ out.push({ field: fpath, code: "required", message: `${name} needs a value.` });
141
+ }
142
+ return;
143
+ }
144
+ const value = obj[key];
145
+ if (type === "text" || type === "textarea") {
146
+ checkText(field, value, fpath, out);
147
+ } else if (type === "boolean") {
148
+ if (typeof value !== "boolean") {
149
+ out.push({ field: fpath, code: "not_boolean", message: `${name} must be yes or no.` });
150
+ }
151
+ } else if (type === "choice") {
152
+ const choices = (field.options ?? []).map((o) => o.value);
153
+ if (typeof value !== "string") {
154
+ out.push({ field: fpath, code: "bad_choice", message: `${name} is not one of the choices.` });
155
+ } else if (value === "") {
156
+ if (field.required) {
157
+ out.push({ field: fpath, code: "required", message: `${name} needs a value.` });
158
+ }
159
+ } else if (!choices.includes(value)) {
160
+ out.push({ field: fpath, code: "bad_choice", message: `${name} is not one of the choices.` });
161
+ }
162
+ } else if (type === "image") {
163
+ if (value === null) {
164
+ if (field.required) {
165
+ out.push({ field: fpath, code: "required", message: `${name} needs a photo.` });
166
+ }
167
+ } else if (!imageOk(field, value)) {
168
+ out.push({
169
+ field: fpath, code: "bad_image",
170
+ message: `${name} has a photo that cannot be used. Choose it again.`,
171
+ });
172
+ } else if (field.alt !== false) {
173
+ // The photo is fine; a problem with its description belongs to the
174
+ // description. A missing one counts as empty.
175
+ checkText(ALT_FIELD, has(value, "alt") ? value.alt : "", `${fpath}.alt`, out);
176
+ }
177
+ } else if (type === "object") {
178
+ if (!isObject(value)) {
179
+ out.push({ field: fpath, code: "not_object", message: `${name} is not in the expected form.` });
180
+ } else {
181
+ checkObject(field.fields, value, fpath, out, field.label ?? key);
182
+ }
183
+ } else if (type === "list") {
184
+ checkList(field, value, fpath, out);
185
+ }
186
+ }
187
+
188
+ function checkList(field, value, path, out) {
189
+ const name = label(field);
190
+ if (!Array.isArray(value)) {
191
+ out.push({ field: path, code: "not_list", message: `${name} is not in the expected form.` });
192
+ return;
193
+ }
194
+ const low = field.min ?? 0;
195
+ const high = field.maxItems ?? 50;
196
+ if (value.length < low) {
197
+ out.push({
198
+ field: path, code: "too_few",
199
+ message: `${name} needs at least ${low} ${items(low)}.`,
200
+ });
201
+ }
202
+ if (value.length > high) {
203
+ out.push({
204
+ field: path, code: "too_many",
205
+ message: `${name} can have at most ${high} ${items(high)}.`,
206
+ });
207
+ }
208
+ value.forEach((item, i) => {
209
+ const ipath = `${path}[${i}]`;
210
+ if (!isObject(item)) {
211
+ out.push({
212
+ field: ipath, code: "not_object",
213
+ message: `Item ${i + 1} of ${name} is not in the expected form.`,
214
+ });
215
+ } else {
216
+ checkObject(field.fields, item, ipath, out, field.label ?? field.key);
217
+ }
218
+ });
219
+ }
220
+
221
+ function checkObject(fields, obj, path, out, ownerLabel) {
222
+ const known = new Set(fields.map((f) => f.key));
223
+ for (const key of Object.keys(obj)) {
224
+ if (!known.has(key)) {
225
+ out.push({
226
+ field: join(path, key), code: "unknown_field",
227
+ message: `"${ownerLabel}" has something that does not belong there.`,
228
+ });
229
+ }
230
+ }
231
+ for (const field of fields) checkField(field, obj, path, out);
232
+ }
233
+
234
+ /** Problems with doc, as [{field, code, message}]. Empty when it is valid. */
235
+ export function validateDoc(schema, docType, doc) {
236
+ const out = [];
237
+ if (!isObject(doc)) {
238
+ out.push({ field: "", code: "not_object", message: "This content is not in the expected form." });
239
+ return out;
240
+ }
241
+ const spec = has(schema.documents, docType) ? schema.documents[docType] : null;
242
+ if (spec === null) {
243
+ out.push({ field: "", code: "unknown_field", message: "This kind of content is not known." });
244
+ return out;
245
+ }
246
+ checkObject(spec.fields, doc, "", out, spec.label ?? "This page");
247
+ return out;
248
+ }
249
+
250
+ function collect(fields, obj, found) {
251
+ for (const field of fields) {
252
+ const value = has(obj, field.key) ? obj[field.key] : undefined;
253
+ if (field.type === "image") {
254
+ if (isObject(value)) found.push(value);
255
+ } else if (field.type === "object" && isObject(value)) {
256
+ collect(field.fields, value, found);
257
+ } else if (field.type === "list" && Array.isArray(value)) {
258
+ for (const item of value) if (isObject(item)) collect(field.fields, item, found);
259
+ }
260
+ }
261
+ }
262
+
263
+ /** Every image object in doc, in field order. */
264
+ export function collectImages(schema, docType, doc) {
265
+ const found = [];
266
+ if (isObject(doc)) collect(schema.documents[docType].fields, doc, found);
267
+ return found;
268
+ }
269
+
270
+ /** Repo-relative paths of every file of the image, in width order. */
271
+ export function imageFiles(image) {
272
+ return image.widths.map((w) => `${image.base}-${Math.trunc(w)}.${image.ext}`.replace(/^\/+/, ""));
273
+ }
274
+
275
+ function emptyObject(fields) {
276
+ const obj = {};
277
+ for (const field of fields) obj[field.key] = emptyValue(field);
278
+ // Drop what a `when` rules out, until nothing more changes.
279
+ let changed = true;
280
+ while (changed) {
281
+ changed = false;
282
+ for (const field of fields) {
283
+ if (has(obj, field.key) && !applies(field, obj)) {
284
+ delete obj[field.key];
285
+ changed = true;
286
+ }
287
+ }
288
+ }
289
+ return obj;
290
+ }
291
+
292
+ export function emptyValue(field) {
293
+ if (field.type === "object") return emptyObject(field.fields);
294
+ if (field.type === "list") {
295
+ return Array.from({ length: field.min ?? 0 }, () => emptyObject(field.fields));
296
+ }
297
+ return EMPTY[field.type];
298
+ }
299
+
300
+ /** A document with every field present and empty. */
301
+ export function emptyDoc(schema, docType) {
302
+ return emptyObject(schema.documents[docType].fields);
303
+ }
@@ -0,0 +1,154 @@
1
+ // The sign-in screen: the owner's email address, then the code emailed to
2
+ // it. The API is passed in; this module only draws and asks.
3
+ import { ApiError } from "./api.js";
4
+ import { el } from "./forms.js";
5
+ import { TEXT, codeSent } from "./copy.js";
6
+
7
+ // Refusals whose words are written for the owner (the site's sign-in
8
+ // sentences, and the editor's own when it cannot reach the site): shown as
9
+ // they are. Anything else is the site's side.
10
+ const OWN_WORDS = new Set(["bad_code", "too_many", "upstream", "not_configured", "forbidden", "offline"]);
11
+
12
+ const problemText = (err) => (err instanceof ApiError && OWN_WORDS.has(err.code) && err.message
13
+ ? err.message : TEXT.serverSide);
14
+
15
+ /**
16
+ * Draw the sign-in screen into root. api: {session: {request(email),
17
+ * verify(email, code)}}; onSignedIn() is called once the code is taken and
18
+ * the session cookie set. notice: a sentence to show above, or null.
19
+ */
20
+ export function renderSignIn(root, { api, onSignedIn, notice = null }) {
21
+ let busy = false;
22
+
23
+ /** A labelled box, the place for its problem beside it, and the means to
24
+ * show or clear that problem. */
25
+ function field(id, label, attrs, describedBy = []) {
26
+ const input = el("input", {
27
+ id, class: "input", ...attrs, "aria-describedby": [...describedBy, `${id}--problem`].join(" "),
28
+ });
29
+ const problem = el("p", { class: "problem", id: `${id}--problem`, role: "alert", hidden: true });
30
+ const show = (text) => {
31
+ problem.textContent = text;
32
+ problem.hidden = text === "";
33
+ if (text === "") input.removeAttribute("aria-invalid");
34
+ else input.setAttribute("aria-invalid", "true");
35
+ };
36
+ const node = el("div", { class: "field" }, [
37
+ el("label", { class: "label", for: id, text: label }), problem, input,
38
+ ]);
39
+ return { input, show, node };
40
+ }
41
+
42
+ /** Run ask() unless a request is out; every button waits while it is. */
43
+ async function once(ask) {
44
+ if (busy) return;
45
+ busy = true;
46
+ const buttons = root.querySelectorAll("button");
47
+ for (const b of buttons) b.disabled = true;
48
+ try {
49
+ await ask();
50
+ } finally {
51
+ busy = false;
52
+ for (const b of buttons) b.disabled = false;
53
+ }
54
+ }
55
+
56
+ const onEnter = (input, fn) => input.addEventListener("keydown", (e) => {
57
+ if (e.key === "Enter" && !e.isComposing) {
58
+ e.preventDefault();
59
+ fn();
60
+ }
61
+ });
62
+
63
+ function draw(children, focus) {
64
+ root.replaceChildren(
65
+ el("h1", { tabindex: "-1", text: TEXT.signInHeading }),
66
+ notice ? el("p", { class: "notice", text: notice }) : "",
67
+ ...children,
68
+ );
69
+ focus.focus();
70
+ }
71
+
72
+ // Step one: the address, filled in with value when going back to change it.
73
+ function askAddress(value = "") {
74
+ const email = field("signin-email", TEXT.emailLabel, { type: "email", autocomplete: "email" });
75
+ email.input.value = value;
76
+ const send = () => once(async () => {
77
+ const address = email.input.value.trim();
78
+ if (address === "") {
79
+ email.show(TEXT.enterEmail);
80
+ return;
81
+ }
82
+ try {
83
+ await api.session.request(address);
84
+ } catch (err) {
85
+ email.show(problemText(err));
86
+ return;
87
+ }
88
+ askCode(address);
89
+ });
90
+ onEnter(email.input, send);
91
+ draw([
92
+ el("p", { class: "lead", text: TEXT.signInIntro }),
93
+ email.node,
94
+ el("div", { class: "actions" }, [el("button", {
95
+ type: "button", class: "button primary", text: TEXT.sendCode, on: { click: send },
96
+ })]),
97
+ ], email.input);
98
+ }
99
+
100
+ // Step two: the code.
101
+ function askCode(address) {
102
+ const sent = el("p", { class: "lead", id: "signin-sent", text: codeSent(address) });
103
+ const code = field("signin-code", TEXT.codeLabel, {
104
+ type: "text", inputmode: "numeric", autocomplete: "one-time-code",
105
+ }, ["signin-sent"]);
106
+ const note = el("p", { class: "help", role: "status" });
107
+ const signIn = () => once(async () => {
108
+ note.textContent = "";
109
+ const value = code.input.value.trim();
110
+ if (value === "") {
111
+ code.show(TEXT.enterCode);
112
+ return;
113
+ }
114
+ try {
115
+ await api.session.verify(address, value);
116
+ } catch (err) {
117
+ code.show(problemText(err));
118
+ code.input.focus();
119
+ return;
120
+ }
121
+ onSignedIn();
122
+ });
123
+ const again = () => once(async () => {
124
+ note.textContent = "";
125
+ try {
126
+ await api.session.request(address);
127
+ } catch (err) {
128
+ code.show(problemText(err));
129
+ return;
130
+ }
131
+ code.show("");
132
+ code.input.value = "";
133
+ note.textContent = TEXT.newCodeSent;
134
+ code.input.focus();
135
+ });
136
+ onEnter(code.input, signIn);
137
+ draw([
138
+ sent,
139
+ code.node,
140
+ note,
141
+ el("div", { class: "actions" }, [
142
+ el("button", { type: "button", class: "button primary", text: TEXT.signIn, on: { click: signIn } }),
143
+ el("button", { type: "button", class: "button", text: TEXT.sendNewCode, on: { click: again } }),
144
+ // A mistyped address gets no code: the way back to correct it.
145
+ el("button", {
146
+ type: "button", class: "button", text: TEXT.otherAddress,
147
+ on: { click: () => { if (!busy) askAddress(address); } },
148
+ }),
149
+ ]),
150
+ ], code.input);
151
+ }
152
+
153
+ askAddress();
154
+ }
@@ -0,0 +1,90 @@
1
+ // The rules for the status line in the bottom bar. Pure: the app sends each
2
+ // event through nextStatus and shows what statusView returns.
3
+ // publish: the most recent publish, {path, url, phase} (url null for a
4
+ // page being deleted); phase is
5
+ // "uploading" (with {photo, photos}), "saving", "publishing", or
6
+ // how it ended ("live", "timeout").
7
+ // problems: the "needs fixing" count, {path, count}, for the open page.
8
+ // failure: a publish that failed after its page was left, {path, text}.
9
+ // Events: {type: "edit"}, {type: "open", path}, {type: "home"},
10
+ // {type: "publish", path, url}, {type: "uploading", path, url, photo, photos},
11
+ // {type: "phase", path, url, phase},
12
+ // {type: "failed", path, label, text, here, deleting}, {type: "problems", path, count},
13
+ // {type: "dismiss"}.
14
+ import { STATUS, TEXT, failedElsewhere, notDeleted, problemCount, uploadingPhoto } from "./copy.js";
15
+
16
+ export const EMPTY_STATUS = Object.freeze({ publish: null, problems: null, failure: null });
17
+
18
+ const ended = (s) => s.publish !== null && (s.publish.phase === "live" || s.publish.phase === "timeout");
19
+
20
+ /** The status after event. An ending (Live, or the timeout sentence) lasts
21
+ * until anything changes, a different page opens or another publish starts;
22
+ * Uploading, Saving and Publishing last until the publish ends. */
23
+ export function nextStatus(s, event) {
24
+ switch (event.type) {
25
+ case "edit":
26
+ return ended(s) ? { ...s, publish: null } : s;
27
+ case "open":
28
+ return {
29
+ publish: ended(s) && s.publish.path !== event.path ? null : s.publish,
30
+ problems: s.problems !== null && s.problems.path === event.path ? s.problems : null,
31
+ failure: s.failure !== null && s.failure.path === event.path ? null : s.failure,
32
+ };
33
+ case "home":
34
+ return { ...s, problems: null };
35
+ case "publish":
36
+ return {
37
+ ...s,
38
+ publish: { path: event.path, url: event.url, phase: "saving" },
39
+ problems: null,
40
+ };
41
+ case "uploading":
42
+ return {
43
+ ...s,
44
+ publish: {
45
+ path: event.path, url: event.url, phase: "uploading", photo: event.photo, photos: event.photos,
46
+ },
47
+ };
48
+ case "phase":
49
+ return { ...s, publish: { path: event.path, url: event.url, phase: event.phase } };
50
+ case "failed":
51
+ return {
52
+ ...s,
53
+ publish: null,
54
+ failure: event.here ? s.failure : {
55
+ path: event.path,
56
+ text: (event.deleting ? notDeleted : failedElsewhere)(event.label, event.text),
57
+ },
58
+ };
59
+ case "problems":
60
+ return {
61
+ ...s,
62
+ publish: ended(s) ? null : s.publish,
63
+ problems: event.count > 0 ? { path: event.path, count: event.count } : null,
64
+ };
65
+ case "dismiss":
66
+ return { ...s, failure: null };
67
+ default:
68
+ return s;
69
+ }
70
+ }
71
+
72
+ /** What to show with openPath open (null on Home): {line, failure}. line is
73
+ * a list of {text} and {text, href} parts; failure is {path, text} or null. */
74
+ export function statusView(s, openPath) {
75
+ const line = [];
76
+ const phase = s.publish?.phase;
77
+ if (phase === "uploading") line.push({ text: uploadingPhoto(s.publish.photo, s.publish.photos) });
78
+ else if (phase === "saving") line.push({ text: STATUS.saving });
79
+ else if (phase === "publishing") line.push({ text: STATUS.publishing });
80
+ else if (phase === "live") {
81
+ line.push({ text: STATUS.live });
82
+ // A deleted page has nothing to see.
83
+ if (s.publish.url) line.push({ text: TEXT.seePage, href: s.publish.url });
84
+ }
85
+ else if (phase === "timeout") line.push({ text: TEXT.timeout });
86
+ if (s.problems !== null && s.problems.path === openPath) {
87
+ line.push({ text: problemCount(s.problems.count) });
88
+ }
89
+ return { line, failure: s.failure };
90
+ }
@@ -0,0 +1,91 @@
1
+ // Sending a page's new photos to the site, one file at a time. Pure of the
2
+ // DOM: the API and the file reader are passed in.
3
+ import { ApiError } from "./api.js";
4
+ import { SHA_RE } from "./shared/rules.js";
5
+
6
+ export const UPLOAD_DIR = "assets/img/uploads/";
7
+
8
+ const BAD_ANSWER = "The site sent back something the editor could not read. Try again in a minute.";
9
+
10
+ /** A file of `photo` could not be sent. `cause` is what went wrong;
11
+ * `refused` is true when the site turned the file away (400 or 413), so
12
+ * sending it again would not help. */
13
+ export class UploadFailed extends Error {
14
+ constructor(photo, cause) {
15
+ super(cause instanceof Error ? cause.message : "The photo could not be sent.");
16
+ this.name = "UploadFailed";
17
+ this.photo = photo;
18
+ this.cause = cause;
19
+ this.refused = cause instanceof ApiError && (cause.status === 400 || cause.status === 413);
20
+ }
21
+ }
22
+
23
+ /** The base64 text of blob. FileReader does the work off the page's
24
+ * thread; building a binary string for btoa would stall a phone. */
25
+ export function blobToBase64(blob, Reader = globalThis.FileReader) {
26
+ return new Promise((resolve, reject) => {
27
+ const reader = new Reader();
28
+ reader.addEventListener("load", () => {
29
+ const url = String(reader.result);
30
+ resolve(url.slice(url.indexOf(",") + 1));
31
+ });
32
+ reader.addEventListener("error", () => reject(reader.error ?? new Error("The photo could not be read.")));
33
+ reader.readAsDataURL(blob);
34
+ });
35
+ }
36
+
37
+ /**
38
+ * One uploader per editor session. It remembers each file's {path, sha}
39
+ * once the site has it, so sending the same photos again after a failure
40
+ * sends only the files not yet up.
41
+ * api: {upload(name, base64) -> {path, sha}}; readBase64(blob) -> text.
42
+ */
43
+ export function createUploader(api, { readBase64 = blobToBase64 } = {}) {
44
+ const done = new WeakMap(); // file -> {path, sha}
45
+
46
+ async function sendFile(photo, file) {
47
+ let answer;
48
+ try {
49
+ answer = await api.upload(file.name, await readBase64(file.blob));
50
+ } catch (err) {
51
+ throw new UploadFailed(photo, err);
52
+ }
53
+ const ok = answer !== null && typeof answer === "object"
54
+ && answer.path === UPLOAD_DIR + file.name
55
+ && typeof answer.sha === "string" && SHA_RE.test(answer.sha);
56
+ if (!ok) {
57
+ throw new UploadFailed(photo, new ApiError({ status: 200, code: "upstream", message: BAD_ANSWER }));
58
+ }
59
+ const image = { path: answer.path, sha: answer.sha };
60
+ done.set(file, image);
61
+ return image;
62
+ }
63
+
64
+ return {
65
+ /**
66
+ * Send every file of photos ([{files: [{name, blob}]}], in page order)
67
+ * that the site does not have yet, one at a time. onProgress(n, total)
68
+ * is told before the first file sent for photo n (counting photos from
69
+ * 1). Returns the publish `images` list, [{path, sha}] for every file of
70
+ * every photo. Rejects with UploadFailed.
71
+ */
72
+ async send(photos, onProgress = () => {}) {
73
+ const images = [];
74
+ for (const [i, photo] of photos.entries()) {
75
+ let told = false;
76
+ for (const file of photo.files) {
77
+ let image = done.get(file);
78
+ if (!image) {
79
+ if (!told) {
80
+ told = true;
81
+ onProgress(i + 1, photos.length);
82
+ }
83
+ image = await sendFile(photo, file);
84
+ }
85
+ images.push(image);
86
+ }
87
+ }
88
+ return images;
89
+ },
90
+ };
91
+ }