@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,38 @@
1
+ // The site's map of photo addresses, for a site whose build names each photo
2
+ // file by its content (photos "asset-map"): {"<base>-700.webp":
3
+ // "<base>-700.<hash>.webp", ...}. forms.js's photoSrc reads it.
4
+ export const ASSET_MAP = "/admin/asset-map.json";
5
+ // The longest a page's opening waits for the map.
6
+ export const ASSET_MAP_TIMEOUT_MS = 10 * 1000;
7
+
8
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
9
+
10
+ /** The site's map of photo addresses, or null when it cannot be read within
11
+ * ASSET_MAP_TIMEOUT_MS. env: {fetch, setTimeout, clearTimeout}. */
12
+ export async function loadAssetMap({ fetch, setTimeout, clearTimeout }) {
13
+ const controller = new AbortController();
14
+ let timer;
15
+ const expired = new Promise((resolve) => {
16
+ timer = setTimeout(() => {
17
+ controller.abort();
18
+ resolve(null);
19
+ }, ASSET_MAP_TIMEOUT_MS);
20
+ });
21
+ const read = (async () => {
22
+ try {
23
+ const res = await fetch(ASSET_MAP, {
24
+ cache: "no-store", credentials: "same-origin", redirect: "manual", signal: controller.signal,
25
+ });
26
+ if (!res.ok) return null;
27
+ const map = await res.json();
28
+ return isObject(map) ? map : null;
29
+ } catch {
30
+ return null;
31
+ }
32
+ })();
33
+ try {
34
+ return await Promise.race([read, expired]);
35
+ } finally {
36
+ clearTimeout(timer);
37
+ }
38
+ }
package/editor/boot.js ADDED
@@ -0,0 +1,72 @@
1
+ // The editor page's only script. It reads the site's config, which the site's
2
+ // build writes next to this file as site-config.json, and only then loads the
3
+ // editor, so every module reads a configured SITE. Without a usable config it
4
+ // says so in one sentence and loads nothing more; an editor that fails to
5
+ // load (a file missing mid-deploy, an error as it starts) gets one too.
6
+ import { SITE, configureSite, siteProblems } from "./shared/site.js";
7
+
8
+ export const NOT_SET_UP = "The editor is not set up yet. Ask your web developer to finish the setup.";
9
+ /** The sentence for an editor that failed to load, naming who to tell. */
10
+ const notLoaded = (developer) => "The editor could not load. Reload the page; " +
11
+ `if it keeps happening, let ${developer} know.`;
12
+ /** That sentence for a site that names no developer. */
13
+ export const NOT_LOADED = notLoaded("your web developer");
14
+
15
+ /** Beside this file, whatever address the page itself was opened at. */
16
+ const CONFIG_URL = new URL("./site-config.json", import.meta.url);
17
+
18
+ /** The config in the text of site-config.json: {config}, or {problems}, the
19
+ * names of what is wrong with it. */
20
+ export function readSiteConfig(text) {
21
+ let values;
22
+ try {
23
+ values = JSON.parse(text);
24
+ } catch {
25
+ return { problems: ["(not JSON)"] };
26
+ }
27
+ const problems = siteProblems(values);
28
+ return problems.length > 0 ? { problems } : { config: values };
29
+ }
30
+
31
+ /** The page's main element holding only sentence. */
32
+ function say(document, sentence) {
33
+ const p = document.createElement("p");
34
+ p.setAttribute("class", "lead");
35
+ p.textContent = sentence;
36
+ document.getElementById("main").replaceChildren(p);
37
+ }
38
+
39
+ /** Configure the site and start the editor; true when it started.
40
+ * fetch: window.fetch; log: console.error; start: loads the editor. */
41
+ export async function boot({ document, fetch, log, start }) {
42
+ let read;
43
+ try {
44
+ const res = await fetch(CONFIG_URL, { cache: "no-store", credentials: "same-origin" });
45
+ read = res.ok ? readSiteConfig(await res.text()) : { problems: [`(answered ${res.status})`] };
46
+ } catch {
47
+ read = { problems: ["(could not be read)"] };
48
+ }
49
+ if (read.problems) {
50
+ say(document, NOT_SET_UP);
51
+ log(`site-config.json: ${read.problems.join(", ")}`);
52
+ return false;
53
+ }
54
+ configureSite(read.config);
55
+ try {
56
+ await start();
57
+ } catch (err) {
58
+ say(document, notLoaded(SITE.developer));
59
+ log(err);
60
+ return false;
61
+ }
62
+ return true;
63
+ }
64
+
65
+ if (typeof document !== "undefined") {
66
+ boot({
67
+ document,
68
+ fetch: (...args) => window.fetch(...args),
69
+ log: (...args) => console.error(...args),
70
+ start: () => import("./app.js"),
71
+ });
72
+ }
package/editor/copy.js ADDED
@@ -0,0 +1,239 @@
1
+ // Every sentence the editor shows that does not come from the schema, in one
2
+ // place so the wording can be read and changed together. Pure: no DOM.
3
+ // The person reading these is the site's owner, on a phone, between jobs:
4
+ // plain words, and a problem is described by what to do about it.
5
+ // A site may reword any TEXT sentence (its config's `text`); configureText
6
+ // rebuilds TEXT and STATUS when the config is set, so read them when used.
7
+ import { ApiError, SessionExpired } from "./api.js";
8
+
9
+ /** Who the owner is told to tell when something needs a person: the site
10
+ * config's `developer`, unless it sets one. */
11
+ export const DEFAULT_DEVELOPER = "your web developer";
12
+
13
+ /** The editor's sentences, the seven that send the owner to the site's
14
+ * developer naming `developer`. */
15
+ const textFor = (developer) => Object.freeze({
16
+ publishing: "Publishing. This takes about a minute.",
17
+ loading: "Loading",
18
+ homeHeading: "Your pages",
19
+ homeIntro: "Choose a page to change its words. Nothing changes on the site until you publish.",
20
+ unpublished: "Unpublished changes",
21
+ back: "Back to all pages",
22
+ publish: "Publish",
23
+ seePage: "See the page",
24
+ restored: "Your unpublished changes from last time are back.",
25
+ timeout: `Your change is saved but is not showing on the site yet. Please let ${developer} know.`,
26
+ signedOut: "You've been signed out. Your changes are safe.",
27
+ stale: "This page was changed somewhere else.",
28
+ staleKeep: "If you keep your changes, they will replace the other change when you publish.",
29
+ connection: "Couldn't save. Check your connection and try again.",
30
+ connectionLoading: "Couldn't load. Check your connection and try again.",
31
+ serverSide: "Something went wrong on the site's side. Try again in a minute; " +
32
+ `if it keeps happening, let ${developer} know.`,
33
+ // A sign-in in front of the site that the site could not confirm.
34
+ unconfirmed: "The editor could not confirm your sign-in. Try again; " +
35
+ `if it keeps happening, let ${developer} know.`,
36
+ // Opened at a host serving the site without its sign-in; the editor's
37
+ // address follows, as a link.
38
+ wrongHost: "Use the editor at",
39
+ crashed: "Something went wrong in the editor. Reload the page; " +
40
+ "your changes are kept on this device.",
41
+ notSetUp: `The editor isn't set up for you yet. Please let ${developer} know.`,
42
+ invalid: `The site would not accept this page as it is. Please let ${developer} know.`,
43
+ tooLarge: `This page is too big to publish in one go. Please let ${developer} know.`,
44
+ notFound: "This page can't be found on the site any more. Go back and choose it again.",
45
+ storageRefused:
46
+ "Your changes can't be kept if you close this page. Publish before you leave.",
47
+ formatHint: "To make words bold or italic, or to turn them into a link, " +
48
+ "select them and tap Bold, Italic or Link.",
49
+ // A heading whose emphasis shows in the site's accent colour.
50
+ formatHintAccent: "To make words bold or coloured, or to turn them into a link, " +
51
+ "select them and tap Bold, Colour or Link.",
52
+ formatRefused: "Select plain words first, without * or [ ] in them.",
53
+ linkOneLine: "A link has to be on one line. Select words on a single line.",
54
+ dismiss: "Dismiss",
55
+ openFailed: "Open the page",
56
+ bold: "Bold",
57
+ italic: "Italic",
58
+ colour: "Colour",
59
+ link: "Link",
60
+ describePhoto: "Describe this photo",
61
+ describePhotoHelp: "Read out to people who cannot see the photo.",
62
+ noPhoto: "No photo to show",
63
+ photoComing: "This photo is being added to the site. It will show here in a minute.",
64
+ chooseOne: "Choose one",
65
+ moveUp: "Move up",
66
+ moveDown: "Move down",
67
+ remove: "Remove",
68
+ confirmYes: "Yes, remove",
69
+ confirmNo: "Keep it",
70
+ replacePhoto: "Replace photo",
71
+ choosePhoto: "Choose photo",
72
+ preparingPhoto: "Preparing photo…",
73
+ pickAgain: "Pick your new photo again.",
74
+ keepCurrentPhoto: "Keep the current photo",
75
+ photoNotSaved: "That photo could not be saved. Pick it again.",
76
+ removePhoto: "Remove photo",
77
+ discardAsk: "Throw away your changes to this page?",
78
+ discardYes: "Yes, discard",
79
+ discardNo: "Keep editing",
80
+ // Simple pages ("Extra pages").
81
+ extraPages: "Extra pages",
82
+ notPublishedYet: "Not published yet",
83
+ addPage: "Add a page",
84
+ newPageTitle: "Page title",
85
+ addressFixed: "This can't be changed later.",
86
+ createPage: "Create page",
87
+ cancel: "Cancel",
88
+ pageCap: "You have 30 extra pages, the most the site allows. Delete one to add another.",
89
+ cannotKeepNewPage: "This browser can't keep a new page until it is published, " +
90
+ `so it can't be added here. Please let ${developer} know.`,
91
+ discardNewAsk: "Throw away this page? It has never been published, so it will be gone.",
92
+ deletePage: "Delete this page",
93
+ deleteYes: "Yes, delete it",
94
+ deleteNo: "Keep the page",
95
+ deleteChanged: "This page was changed somewhere else. Check it, then delete it if you still want to.",
96
+ deleteChangedLost: "This page was changed somewhere else, so your unpublished changes to it were not kept. " +
97
+ "Check it, then delete it if you still want to.",
98
+ deletedElsewhere: "This page was deleted somewhere else.",
99
+ // The site's own refusals of a new page (server/handlers.js sends these
100
+ // words); errorView shows them, in the site's wording when it has one.
101
+ badAddress: "That page address can't be used. Delete this page and add it again with a different title.",
102
+ tooManyPages: "The site can hold 30 extra pages. Delete one before adding another.",
103
+ // Signing in (signin.js) and out.
104
+ signInHeading: "Sign in",
105
+ signInIntro: "Enter your email address and we'll email you a code to sign in with.",
106
+ emailLabel: "Email address",
107
+ sendCode: "Email me a code",
108
+ codeLabel: "Code",
109
+ signIn: "Sign in",
110
+ sendNewCode: "Send a new code",
111
+ otherAddress: "Use a different address",
112
+ newCodeSent: "We sent a new code. Use the newest one.",
113
+ enterEmail: "Enter your email address.",
114
+ enterCode: "Enter the code from the email.",
115
+ signOut: "Sign out",
116
+ });
117
+
118
+ const DEFAULT_TEXT = textFor(DEFAULT_DEVELOPER);
119
+
120
+ /** The keys of the editor's words that only one kind of sign-in (the site
121
+ * config's signIn) ever shows: the emailed-code screens and the Sign out
122
+ * button belong to "code"; the message for a sign-in in front of the site
123
+ * that could not be confirmed belongs to "access". Every other key is shown
124
+ * under both. Nothing at run time reads this; guide/check.js does. */
125
+ export const SIGN_IN_KEYS = Object.freeze({
126
+ code: Object.freeze(["signInHeading", "signInIntro", "emailLabel", "sendCode", "codeLabel", "signIn",
127
+ "sendNewCode", "otherAddress", "newCodeSent", "enterEmail", "enterCode", "signOut"]),
128
+ access: Object.freeze(["unconfirmed"]),
129
+ });
130
+
131
+ const statusFrom = (text) => Object.freeze({
132
+ saving: "Saving",
133
+ publishing: text.publishing,
134
+ live: "Live",
135
+ });
136
+
137
+ export let TEXT = DEFAULT_TEXT;
138
+ export let STATUS = statusFrom(TEXT);
139
+ // What ends a page's address: "/" where the site serves "/<slug>/".
140
+ let addressEnd = "";
141
+
142
+ /** Called by configureSite (shared/site.js) with the site's config, and by
143
+ * nothing else: a site's wording is set only with the rest of its config. */
144
+ export function configureText(site) {
145
+ TEXT = Object.freeze({ ...textFor(site.developer ?? DEFAULT_DEVELOPER), ...site.text });
146
+ STATUS = statusFrom(TEXT);
147
+ addressEnd = site.trailingSlash ? "/" : "";
148
+ }
149
+
150
+ /** Why a picked photo cannot be used, by ImageError code (see images.js). */
151
+ export const PHOTO_ERRORS = Object.freeze({
152
+ cannot_read: "We couldn't read that photo. Pick it from your phone's photo library, " +
153
+ "or export it as a JPEG and try again.",
154
+ too_big: "That file is over 25 MB. Pick a smaller photo.",
155
+ too_small: "That photo is too small. It needs to be at least 700 pixels wide.",
156
+ too_heavy: "That photo is too detailed to upload. Try a different photo.",
157
+ });
158
+
159
+ /** The labels of the actions errorView names. */
160
+ export const ACTIONS = Object.freeze({
161
+ signin: "Sign in again",
162
+ retry: "Retry",
163
+ keep: "Keep my changes",
164
+ discard: "Discard my changes",
165
+ reload: "Reload",
166
+ });
167
+
168
+ const lower = (label) => label.toLowerCase();
169
+
170
+ export const itemName = (itemLabel, n) => `${itemLabel} ${n}`;
171
+ /** An item whose kind was set when it was added: "Part 3: Paragraph". */
172
+ export const itemKindName = (itemLabel, n, kindLabel) => `${itemLabel} ${n}: ${kindLabel}`;
173
+ export const addLabel = (itemLabel) => `Add ${lower(itemLabel)}`;
174
+ /** The button adding an item of one kind: "Add a bullet list". */
175
+ export const addKindLabel = (kindLabel) => `Add a ${lower(kindLabel)}`;
176
+ export const moveUpName = (itemLabel, n) => `Move ${lower(itemLabel)} ${n} up`;
177
+ export const moveDownName = (itemLabel, n) => `Move ${lower(itemLabel)} ${n} down`;
178
+ export const removeName = (itemLabel, n) => `Remove ${lower(itemLabel)} ${n}`;
179
+ export const confirmRemove = (itemLabel, n) =>
180
+ `Remove ${lower(itemLabel)} ${n}? Everything in it will be lost.`;
181
+ export const characters = (n, max) => `${n} of ${max} characters`;
182
+ export const failedElsewhere = (label, text) => `${label} was not published. ${text}`;
183
+ /** A page's deletion that failed after the owner left it. */
184
+ export const notDeleted = (title, text) => `The page \u201c${title}\u201d was not deleted. ${text}`;
185
+ /** Where a new page will be, while its title is typed. */
186
+ export const newPageAddress = (host, slug) => `Its address will be ${host}/${slug}${addressEnd}`;
187
+ /** Home's last line, when site-editor copy wrote the version. */
188
+ export const editorVersion = (version) => `Editor version ${version}`;
189
+ /** Step two of signing in. */
190
+ export const codeSent = (address) =>
191
+ `We sent a code to ${address}. It can take a minute. If it doesn't arrive, check your spam folder.`;
192
+ export const deleteAsk = (title) =>
193
+ `Delete the page \u201c${title}\u201d? Its address will stop working.`;
194
+ /** The status line while a page's new photos go up; n counts photos, not files. */
195
+ export const uploadingPhoto = (n, total) => `Uploading photo ${n} of ${total}`;
196
+ export const problemCount = (n) => (n === 1
197
+ ? "1 thing needs fixing before this page can be published."
198
+ : `${n} things need fixing before this page can be published.`);
199
+
200
+ const view = (text, actions = [], detail) =>
201
+ (detail === undefined ? { text, actions } : { text, detail, actions });
202
+
203
+ /** What to show for a failed request: {text, actions}, plus `detail`, a
204
+ * second sentence, where one is needed. `actions` names the choices to
205
+ * offer, from ACTIONS. With `loading`, the request was reading, not saving.
206
+ * The server's own message is never shown. */
207
+ export function errorView(error, { loading = false } = {}) {
208
+ if (error instanceof SessionExpired) return view(TEXT.signedOut, ["signin", "retry"]);
209
+ const code = error instanceof ApiError ? error.code : undefined;
210
+ switch (code) {
211
+ // Only a sign-in in front of the site answers this (see api.js).
212
+ case "unauthorized":
213
+ return view(TEXT.unconfirmed, ["retry", "signin"]);
214
+ case "stale":
215
+ return view(TEXT.stale, ["keep", "discard"], TEXT.staleKeep);
216
+ case "forbidden":
217
+ case "not_configured":
218
+ return view(TEXT.notSetUp);
219
+ case "invalid":
220
+ return view(TEXT.invalid);
221
+ case "too_large":
222
+ return view(TEXT.tooLarge);
223
+ case "not_found":
224
+ return view(TEXT.notFound);
225
+ case "offline":
226
+ return view(loading ? TEXT.connectionLoading : TEXT.connection, ["retry"]);
227
+ case "busy":
228
+ return view(TEXT.connection, ["retry"]);
229
+ case "bad_request":
230
+ // A new page the site will not take. The server always sends the
231
+ // default sentence; the owner sees the site's wording of it.
232
+ if (error.message === DEFAULT_TEXT.badAddress) return view(TEXT.badAddress);
233
+ if (error.message === DEFAULT_TEXT.tooManyPages) return view(TEXT.tooManyPages);
234
+ return view(TEXT.serverSide, ["retry"]);
235
+ default:
236
+ // upstream, server_error and anything new.
237
+ return view(TEXT.serverSide, ["retry"]);
238
+ }
239
+ }
@@ -0,0 +1,67 @@
1
+ // Local drafts in a Storage-like object (passed in). Nothing here throws.
2
+ import { SHA_RE } from "./shared/rules.js";
3
+
4
+ const PREFIX = "chs-admin-draft:";
5
+
6
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7
+
8
+ /** Store a draft; true when kept, false when storage refused it. repick
9
+ * names the photo fields whose new photo could not be kept (a file cannot
10
+ * be stored), so the owner is asked to pick them again. photosOnly marks a
11
+ * draft whose doc is the published page itself: only new photos differed,
12
+ * so the stored doc holds nothing of the owner's own. */
13
+ export function saveDraft(storage, path, base, doc, now = Date.now(), repick = [], photosOnly = false) {
14
+ const value = { base, doc, savedAt: now };
15
+ if (repick.length > 0) value.repick = repick;
16
+ if (photosOnly) value.photosOnly = true;
17
+ try {
18
+ storage.setItem(PREFIX + path, JSON.stringify(value));
19
+ return true;
20
+ } catch {
21
+ return false;
22
+ }
23
+ }
24
+
25
+ /** {base, doc, repick, photosOnly} for a stored draft, or null for none or
26
+ * an unusable one. A draft from before photos could be picked has repick []
27
+ * and photosOnly false. */
28
+ export function loadDraft(storage, path) {
29
+ try {
30
+ const raw = storage.getItem(PREFIX + path);
31
+ if (raw === null || raw === undefined) return null;
32
+ const value = JSON.parse(raw);
33
+ if (!isObject(value) || !isObject(value.doc)) return null;
34
+ const { base } = value;
35
+ if (base !== null && !(typeof base === "string" && SHA_RE.test(base))) return null;
36
+ const repick = Array.isArray(value.repick)
37
+ ? value.repick.filter((name) => typeof name === "string" && name !== "") : [];
38
+ return { base, doc: value.doc, repick, photosOnly: value.photosOnly === true };
39
+ } catch {
40
+ return null;
41
+ }
42
+ }
43
+
44
+ export function clearDraft(storage, path) {
45
+ try {
46
+ storage.removeItem(PREFIX + path);
47
+ } catch {
48
+ // Nothing to clear if storage is unavailable.
49
+ }
50
+ }
51
+
52
+ /** Paths that have a usable stored draft. */
53
+ export function draftPaths(storage) {
54
+ const paths = [];
55
+ try {
56
+ for (let i = 0; i < storage.length; i++) {
57
+ const key = storage.key(i);
58
+ if (typeof key === "string" && key.startsWith(PREFIX)) {
59
+ const path = key.slice(PREFIX.length);
60
+ if (loadDraft(storage, path) !== null) paths.push(path);
61
+ }
62
+ }
63
+ } catch {
64
+ return paths;
65
+ }
66
+ return paths;
67
+ }
@@ -0,0 +1,80 @@
1
+ // The text-formatting buttons. The site reads **x** and *x* as bold and
2
+ // italic only when no whitespace sits just inside the markers, and neither
3
+ // marker pair can span a line, so whitespace is moved outside and a
4
+ // multi-line selection is wrapped line by line.
5
+
6
+ const MARKERS = { bold: "**", italic: "*" };
7
+ const PLACEHOLDER = { bold: "bold text", italic: "italic text", link: "link text" };
8
+ // Characters that would turn the wrapped text into something else on the site.
9
+ const CLASHES = { bold: /\*/, italic: /\*/, link: /[[\]]/ };
10
+
11
+ /** Split text into leading whitespace, core and trailing whitespace. */
12
+ function parts(text) {
13
+ const core = text.trim();
14
+ if (core === "") return { lead: text, core: "", trail: "" };
15
+ const lead = text.slice(0, text.indexOf(core));
16
+ return { lead, core, trail: text.slice(lead.length + core.length) };
17
+ }
18
+
19
+ /** Where the wrap ends: a triple-click selects the line with its line
20
+ * break, which is left outside. */
21
+ function wrapEnd(value, start, end) {
22
+ const trimmed = value.slice(start, end).replace(/\n+$/, "");
23
+ return trimmed.trim() === "" ? end : start + trimmed.length;
24
+ }
25
+
26
+ /**
27
+ * Why wrapping value[start, end) as kind would change nothing, or null when
28
+ * it would wrap: "kind" (not bold, italic or link), "lines" (a link across
29
+ * lines) or "markers" (the selection already holds "*" for bold and italic,
30
+ * or "[" / "]" for a link).
31
+ */
32
+ export function refusal(value, start, end, kind) {
33
+ if (!Object.hasOwn(CLASHES, kind)) return "kind";
34
+ const selected = value.slice(start, wrapEnd(value, start, end));
35
+ if (kind === "link" && selected.includes("\n") && selected.trim() !== "") return "lines";
36
+ return CLASHES[kind].test(selected) ? "markers" : null;
37
+ }
38
+
39
+ /**
40
+ * Wrap value[start, end) as bold, italic or a link.
41
+ * Returns {value, start, end}: the new text and the selection to restore.
42
+ * The input comes back unchanged whenever refusal() names a reason.
43
+ */
44
+ export function wrapSelection(value, start, end, kind, url) {
45
+ if (refusal(value, start, end, kind) !== null) return { value, start, end };
46
+ const stop = wrapEnd(value, start, end);
47
+ const before = value.slice(0, start);
48
+ const after = value.slice(stop);
49
+ const selected = value.slice(start, stop);
50
+
51
+ if (selected.includes("\n") && selected.trim() !== "") {
52
+ const m = MARKERS[kind];
53
+ const out = selected.split("\n").map((line) => {
54
+ const p = parts(line);
55
+ return p.core === "" ? line : `${p.lead}${m}${p.core}${m}${p.trail}`;
56
+ }).join("\n");
57
+ return { value: before + out + after, start, end: start + out.length };
58
+ }
59
+
60
+ const { lead, core, trail } = parts(selected);
61
+ const text = core === "" ? PLACEHOLDER[kind] : core;
62
+ const keptBefore = core === "" ? selected : lead;
63
+ const keptAfter = core === "" ? "" : trail;
64
+ const at = before.length + keptBefore.length;
65
+
66
+ if (kind === "link") {
67
+ const address = url === undefined ? "https://" : url;
68
+ const out = `[${text}](${address})`;
69
+ const sel = url === undefined
70
+ ? { start: at + text.length + 3, end: at + text.length + 3 + address.length }
71
+ : { start: at + 1, end: at + 1 + text.length };
72
+ return { value: before + keptBefore + out + keptAfter + after, ...sel };
73
+ }
74
+ const m = MARKERS[kind];
75
+ return {
76
+ value: before + keptBefore + m + text + m + keptAfter + after,
77
+ start: at + m.length,
78
+ end: at + m.length + text.length,
79
+ };
80
+ }