@matterandmotion/emdash-comics 0.0.0-stage → 0.1.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 (67) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -2
  3. package/dist/batches.d.ts +84 -0
  4. package/dist/batches.d.ts.map +1 -0
  5. package/dist/batches.js +101 -0
  6. package/dist/batches.js.map +1 -0
  7. package/dist/blocks.d.ts +26 -0
  8. package/dist/blocks.d.ts.map +1 -0
  9. package/dist/blocks.js +45 -0
  10. package/dist/blocks.js.map +1 -0
  11. package/dist/id.d.ts +3 -0
  12. package/dist/id.d.ts.map +1 -0
  13. package/dist/id.js +3 -0
  14. package/dist/id.js.map +1 -0
  15. package/dist/index.d.ts +48 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +122 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/legacy-redirects.d.ts +15 -0
  20. package/dist/legacy-redirects.d.ts.map +1 -0
  21. package/dist/legacy-redirects.js +58 -0
  22. package/dist/legacy-redirects.js.map +1 -0
  23. package/dist/media.d.ts +26 -0
  24. package/dist/media.d.ts.map +1 -0
  25. package/dist/media.js +48 -0
  26. package/dist/media.js.map +1 -0
  27. package/dist/transcripts.d.ts +10 -0
  28. package/dist/transcripts.d.ts.map +1 -0
  29. package/dist/transcripts.js +22 -0
  30. package/dist/transcripts.js.map +1 -0
  31. package/package.json +67 -3
  32. package/profile/index.d.mts +46 -0
  33. package/profile/index.mjs +197 -0
  34. package/src/admin/BulkUploadPage.tsx +1004 -0
  35. package/src/admin/ComicPagesField.tsx +202 -0
  36. package/src/admin/bulk/api.ts +215 -0
  37. package/src/admin/bulk/config.ts +87 -0
  38. package/src/admin/bulk/files.ts +76 -0
  39. package/src/admin/bulk/history.ts +45 -0
  40. package/src/admin/bulk/plan.ts +446 -0
  41. package/src/admin/fingerprint.ts +26 -0
  42. package/src/admin/index.tsx +19 -0
  43. package/src/admin/media.ts +75 -0
  44. package/src/admin/pickers.tsx +132 -0
  45. package/src/admin/segments.ts +36 -0
  46. package/src/admin/slice.ts +46 -0
  47. package/src/admin/types.ts +47 -0
  48. package/src/astro/AgeGate.astro +85 -0
  49. package/src/astro/ArchiveGrid.astro +79 -0
  50. package/src/astro/CastGrid.astro +63 -0
  51. package/src/astro/ChapterList.astro +57 -0
  52. package/src/astro/CharacterCard.astro +54 -0
  53. package/src/astro/ComicEmbed.astro +55 -0
  54. package/src/astro/ComicNav.astro +131 -0
  55. package/src/astro/ComicReader.astro +193 -0
  56. package/src/astro/ContentWarnings.astro +61 -0
  57. package/src/astro/Transcript.astro +43 -0
  58. package/src/astro/astro-modules.d.ts +6 -0
  59. package/src/astro/blocks.ts +11 -0
  60. package/src/astro/index.ts +20 -0
  61. package/src/batches.ts +154 -0
  62. package/src/blocks.ts +46 -0
  63. package/src/id.ts +2 -0
  64. package/src/index.ts +152 -0
  65. package/src/legacy-redirects.ts +59 -0
  66. package/src/media.ts +60 -0
  67. package/src/transcripts.ts +20 -0
@@ -0,0 +1,446 @@
1
+ /**
2
+ * Planning a bulk upload: grouping image files into comics, titles and slugs,
3
+ * numbering, publishing dates, and spotting duplicates. Everything here is
4
+ * pure, so the page recomputes the plan on every change and the tests cover it
5
+ * without a browser.
6
+ */
7
+
8
+ /** How files become comics. */
9
+ export type GroupMode = "each" | "name" | "folder";
10
+
11
+ /** The parts of a `File` the planner reads. `path` is `webkitRelativePath`. */
12
+ export interface SourceFile {
13
+ name: string;
14
+ path?: string | undefined;
15
+ /** The file's fingerprint (see ../fingerprint.ts), once it's been read. */
16
+ hash?: string | undefined;
17
+ }
18
+
19
+ export interface FileGroup<F> {
20
+ /** Identifies the group; also the source of the default title. */
21
+ key: string;
22
+ files: F[];
23
+ }
24
+
25
+ const naturalOrder = (a: string, b: string) =>
26
+ a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" });
27
+
28
+ export function stripExtension(name: string): string {
29
+ const dot = name.lastIndexOf(".");
30
+ return dot > 0 ? name.slice(0, dot) : name;
31
+ }
32
+
33
+ /** A trailing page number: `-2`, `_02`, ` p2`, `.page-3`. */
34
+ const PAGE_SUFFIX = /[-_. ]+(?:p|pg|page)?[-_ ]?\d{1,4}$/i;
35
+
36
+ function fullPath(file: SourceFile): string {
37
+ return file.path || file.name;
38
+ }
39
+
40
+ /** The comic a file belongs to, for the given mode. */
41
+ export function groupKey(file: SourceFile, mode: GroupMode): string {
42
+ const base = stripExtension(file.name);
43
+ if (mode === "name") return base.replace(PAGE_SUFFIX, "") || base;
44
+ if (mode === "folder") {
45
+ const parts = fullPath(file).split("/");
46
+ return parts.length > 1 ? parts.slice(0, -1).join("/") : base;
47
+ }
48
+ const path = fullPath(file);
49
+ return stripExtension(path);
50
+ }
51
+
52
+ /** Groups files into comics, in natural name order (2 before 10). */
53
+ export function groupFiles<F extends SourceFile>(files: F[], mode: GroupMode): FileGroup<F>[] {
54
+ const groups = new Map<string, F[]>();
55
+ const sorted = [...files].sort((a, b) => naturalOrder(fullPath(a), fullPath(b)));
56
+ for (const file of sorted) {
57
+ const key = groupKey(file, mode);
58
+ const list = groups.get(key);
59
+ if (list) list.push(file);
60
+ else groups.set(key, [file]);
61
+ }
62
+ return [...groups.entries()]
63
+ .sort(([a], [b]) => naturalOrder(a, b))
64
+ .map(([key, list]) => ({ key, files: list }));
65
+ }
66
+
67
+ /**
68
+ * A readable title from a file or folder name: `012-the-keeper` becomes
69
+ * "The keeper". Returns "" when nothing but numbers is left, so the caller can
70
+ * fall back to the series title and number.
71
+ */
72
+ export function titleFromKey(key: string): string {
73
+ const last = key.split("/").pop() ?? key;
74
+ let words = last.replace(/[-_]+/g, " ").replace(/\s+/g, " ").trim();
75
+ const withoutNumber = words.replace(/^(?:#|no\.?\s*|ep\.?\s*|episode\s+)?\d+[.:)]?\s+/i, "");
76
+ if (withoutNumber) words = withoutNumber;
77
+ if (/^[\d\s.#]*$/.test(words)) return "";
78
+ return words.charAt(0).toUpperCase() + words.slice(1);
79
+ }
80
+
81
+ /** URL slug: lower case, ASCII letters and digits, single dashes. */
82
+ export function slugify(text: string): string {
83
+ return text
84
+ .normalize("NFKD")
85
+ .replace(/[̀-ͯ]/g, "")
86
+ .toLowerCase()
87
+ .replace(/[^a-z0-9]+/g, "-")
88
+ .replace(/^-+|-+$/g, "")
89
+ .slice(0, 80)
90
+ .replace(/-+$/g, "");
91
+ }
92
+
93
+ /** The next free number: one more than the highest used, or 1. */
94
+ export function nextNumber(used: Iterable<number>): number {
95
+ let max = 0;
96
+ for (const value of used) if (Number.isFinite(value) && value > max) max = value;
97
+ return Math.floor(max) + 1;
98
+ }
99
+
100
+ // ── Dates ────────────────────────────────────────────────────────────────
101
+
102
+ /** A wall-clock date and time, read in the site's timezone. */
103
+ export interface LocalDateTime {
104
+ year: number;
105
+ month: number;
106
+ day: number;
107
+ hour: number;
108
+ minute: number;
109
+ }
110
+
111
+ /** Parses a `datetime-local` input value (`2026-12-24T09:30`). */
112
+ export function parseLocalDateTime(value: string): LocalDateTime | null {
113
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(value);
114
+ if (!match) return null;
115
+ const [year, month, day, hour, minute] = match.slice(1).map(Number) as [
116
+ number,
117
+ number,
118
+ number,
119
+ number,
120
+ number,
121
+ ];
122
+ if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59) return null;
123
+ return { year, month, day, hour, minute };
124
+ }
125
+
126
+ /** Formats a wall-clock time for a `datetime-local` input. */
127
+ export function formatLocalDateTime(value: LocalDateTime): string {
128
+ const pad = (n: number, width = 2) => String(n).padStart(width, "0");
129
+ return `${pad(value.year, 4)}-${pad(value.month)}-${pad(value.day)}T${pad(value.hour)}:${pad(value.minute)}`;
130
+ }
131
+
132
+ /** How far a timezone is ahead of UTC at an instant, in minutes. */
133
+ function offsetMinutes(instant: number, timeZone: string): number {
134
+ const parts = new Intl.DateTimeFormat("en-US", {
135
+ timeZone,
136
+ hourCycle: "h23",
137
+ year: "numeric",
138
+ month: "2-digit",
139
+ day: "2-digit",
140
+ hour: "2-digit",
141
+ minute: "2-digit",
142
+ second: "2-digit",
143
+ }).formatToParts(new Date(instant));
144
+ const get = (type: string) => Number(parts.find((part) => part.type === type)?.value);
145
+ const wall = Date.UTC(
146
+ get("year"),
147
+ get("month") - 1,
148
+ get("day"),
149
+ get("hour"),
150
+ get("minute"),
151
+ get("second"),
152
+ );
153
+ return Math.round((wall - Math.floor(instant / 1000) * 1000) / 60_000);
154
+ }
155
+
156
+ /**
157
+ * The instant a wall-clock time happens in a timezone (an IANA name such as
158
+ * "Asia/Dhaka"). Without a timezone, or with one the browser doesn't know, the
159
+ * browser's own timezone is used.
160
+ */
161
+ export function zonedTimeToUtc(local: LocalDateTime, timeZone?: string): Date {
162
+ const { year, month, day, hour, minute } = local;
163
+ if (timeZone) {
164
+ try {
165
+ const guess = Date.UTC(year, month - 1, day, hour, minute);
166
+ const first = offsetMinutes(guess, timeZone);
167
+ let result = guess - first * 60_000;
168
+ const second = offsetMinutes(result, timeZone);
169
+ // Across a daylight-saving change the first guess used the wrong offset.
170
+ if (second !== first) result = guess - second * 60_000;
171
+ return new Date(result);
172
+ } catch {
173
+ // Unknown timezone: fall through to the browser's.
174
+ }
175
+ }
176
+ return new Date(year, month - 1, day, hour, minute);
177
+ }
178
+
179
+ /** The wall-clock time of an instant in a timezone. */
180
+ export function utcToZonedTime(instant: Date, timeZone?: string): LocalDateTime {
181
+ if (timeZone) {
182
+ try {
183
+ const shifted = new Date(
184
+ instant.getTime() + offsetMinutes(instant.getTime(), timeZone) * 60_000,
185
+ );
186
+ return {
187
+ year: shifted.getUTCFullYear(),
188
+ month: shifted.getUTCMonth() + 1,
189
+ day: shifted.getUTCDate(),
190
+ hour: shifted.getUTCHours(),
191
+ minute: shifted.getUTCMinutes(),
192
+ };
193
+ } catch {
194
+ // Unknown timezone: fall through to the browser's.
195
+ }
196
+ }
197
+ return {
198
+ year: instant.getFullYear(),
199
+ month: instant.getMonth() + 1,
200
+ day: instant.getDate(),
201
+ hour: instant.getHours(),
202
+ minute: instant.getMinutes(),
203
+ };
204
+ }
205
+
206
+ /** How often scheduled comics come out. Weekdays: 0 is Sunday … 6 is Saturday. */
207
+ export type Cadence = { kind: "days"; every: number } | { kind: "weekdays"; days: number[] };
208
+
209
+ /**
210
+ * The wall-clock release times for `count` comics, starting at `start` (which
211
+ * counts as the first release on a weekday schedule only if its day is picked).
212
+ */
213
+ export function releaseTimes(
214
+ start: LocalDateTime,
215
+ cadence: Cadence,
216
+ count: number,
217
+ ): LocalDateTime[] {
218
+ const times: LocalDateTime[] = [];
219
+ if (count <= 0) return times;
220
+ // Calendar arithmetic on a UTC date, so daylight saving can't shift days.
221
+ const day = new Date(Date.UTC(start.year, start.month - 1, start.day));
222
+ const at = (date: Date): LocalDateTime => ({
223
+ year: date.getUTCFullYear(),
224
+ month: date.getUTCMonth() + 1,
225
+ day: date.getUTCDate(),
226
+ hour: start.hour,
227
+ minute: start.minute,
228
+ });
229
+ if (cadence.kind === "days") {
230
+ const every = Math.max(1, Math.floor(cadence.every) || 1);
231
+ for (let i = 0; i < count; i++) {
232
+ times.push(at(day));
233
+ day.setUTCDate(day.getUTCDate() + every);
234
+ }
235
+ return times;
236
+ }
237
+ const days = new Set(cadence.days.filter((d) => d >= 0 && d <= 6));
238
+ if (days.size === 0) return times;
239
+ while (times.length < count) {
240
+ if (days.has(day.getUTCDay())) times.push(at(day));
241
+ day.setUTCDate(day.getUTCDate() + 1);
242
+ }
243
+ return times;
244
+ }
245
+
246
+ // ── The plan ─────────────────────────────────────────────────────────────
247
+
248
+ /** An entry already in the collection, by slug. */
249
+ export interface ExistingEntry {
250
+ id: string;
251
+ title?: string | undefined;
252
+ /** In the trash, where it still holds its slug. */
253
+ trashed?: boolean | undefined;
254
+ series?: string | undefined;
255
+ number?: number | undefined;
256
+ }
257
+
258
+ export type Publishing =
259
+ | { mode: "draft" }
260
+ | { mode: "publish" }
261
+ | { mode: "schedule"; start: LocalDateTime; cadence: Cadence; timeZone?: string | undefined };
262
+
263
+ export interface PlanOptions {
264
+ /** The series slug, when the collection has a series field. */
265
+ series?: string | undefined;
266
+ seriesTitle?: string | undefined;
267
+ titleMode: "filename" | "series-number";
268
+ /** The first new comic's number, or null when the collection has no number field. */
269
+ startNumber: number | null;
270
+ /** Every entry in the collection, by slug (drafts and scheduled ones too). */
271
+ existing: ReadonlyMap<string, ExistingEntry>;
272
+ /** The slugs of the entries (not trashed) whose pages came from each fingerprint. */
273
+ fingerprints?: ReadonlyMap<string, readonly string[]> | undefined;
274
+ publishing: Publishing;
275
+ }
276
+
277
+ /** Changes the editor made to a row in the preview. */
278
+ export interface RowOverride {
279
+ title?: string;
280
+ slug?: string;
281
+ skip?: boolean;
282
+ }
283
+
284
+ export type RowState =
285
+ /** Will be created. */
286
+ | "new"
287
+ /** An entry with these images or this slug exists already; skipped, so re-running a batch is safe. */
288
+ | "exists"
289
+ /** Can't be created as it stands (no slug, or the same slug as an earlier row). */
290
+ | "conflict"
291
+ /** Unticked by the editor. */
292
+ | "skipped";
293
+
294
+ export interface PlannedRow<F> {
295
+ key: string;
296
+ files: F[];
297
+ title: string;
298
+ slug: string;
299
+ /** True when the slug was typed rather than derived from the title. */
300
+ slugEdited: boolean;
301
+ number: number | null;
302
+ /** When it's published (past: backdated) or scheduled (future). Null for drafts and "publish now". */
303
+ releaseAt: Date | null;
304
+ state: RowState;
305
+ /** Why the row is skipped or in conflict, or a warning for a new row. */
306
+ note?: string;
307
+ existingId?: string;
308
+ }
309
+
310
+ function defaultTitle(key: string, options: PlanOptions, number: number | null): string {
311
+ const byNumber = () => {
312
+ const name = options.seriesTitle?.trim() || "Comic";
313
+ return number === null ? name : `${name} #${number}`;
314
+ };
315
+ if (options.titleMode === "series-number") return byNumber();
316
+ return titleFromKey(key) || byNumber();
317
+ }
318
+
319
+ /**
320
+ * The entry holding the most of these files' images, by fingerprint, and how
321
+ * many of the files it holds. Null when none of them is in an entry.
322
+ */
323
+ export function imageMatch(
324
+ files: readonly SourceFile[],
325
+ fingerprints: ReadonlyMap<string, readonly string[]>,
326
+ ): { slug: string; count: number } | null {
327
+ const counts = new Map<string, number>();
328
+ for (const file of files) {
329
+ if (!file.hash) continue;
330
+ for (const slug of new Set(fingerprints.get(file.hash))) {
331
+ counts.set(slug, (counts.get(slug) ?? 0) + 1);
332
+ }
333
+ }
334
+ let best: { slug: string; count: number } | null = null;
335
+ for (const [slug, count] of counts) if (!best || count > best.count) best = { slug, count };
336
+ return best;
337
+ }
338
+
339
+ /**
340
+ * Turns file groups into the rows the page previews and then creates. Numbers
341
+ * and release dates go to new rows only, in order, so re-running a batch after
342
+ * a failure fills in what's missing without renumbering what's there.
343
+ *
344
+ * Duplicates are found by their images first: a group whose images are all in
345
+ * one entry already is that entry, whatever its title or slug. Typing a slug
346
+ * for the row creates it anyway (with a warning). Then by slug, which also
347
+ * catches entries made before pages kept fingerprints.
348
+ */
349
+ export function planRows<F extends SourceFile>(
350
+ groups: FileGroup<F>[],
351
+ options: PlanOptions,
352
+ overrides: ReadonlyMap<string, RowOverride> = new Map(),
353
+ ): PlannedRow<F>[] {
354
+ const usedNumbers = new Set<number>();
355
+ for (const entry of options.existing.values()) {
356
+ const sameSeries = options.series === undefined || entry.series === options.series;
357
+ if (entry.number !== undefined && sameSeries && !entry.trashed) usedNumbers.add(entry.number);
358
+ }
359
+
360
+ let next = options.startNumber;
361
+ const seen = new Map<string, number>();
362
+ const rows = groups.map((group, index): PlannedRow<F> => {
363
+ const override = overrides.get(group.key) ?? {};
364
+ const match = options.fingerprints ? imageMatch(group.files, options.fingerprints) : null;
365
+ const matched = match ? options.existing.get(match.slug) : undefined;
366
+ const sameImages =
367
+ match !== null &&
368
+ matched !== undefined &&
369
+ !matched.trashed &&
370
+ match.count === group.files.length &&
371
+ override.slug === undefined;
372
+ // Title and slug as if the row takes the next number.
373
+ const title = override.title ?? defaultTitle(group.key, options, next);
374
+ const row: PlannedRow<F> = {
375
+ key: group.key,
376
+ files: group.files,
377
+ title,
378
+ slug: sameImages ? match.slug : slugify(override.slug ?? title),
379
+ slugEdited: override.slug !== undefined,
380
+ number: null,
381
+ releaseAt: null,
382
+ state: "new",
383
+ };
384
+ const existing = row.slug ? options.existing.get(row.slug) : undefined;
385
+ if (override.skip) {
386
+ row.state = "skipped";
387
+ row.note = "Unticked";
388
+ } else if (existing?.trashed) {
389
+ row.state = "conflict";
390
+ row.existingId = existing.id;
391
+ row.note = "A comic in the trash has this slug: delete it for good, or change the slug";
392
+ } else if (existing) {
393
+ row.state = "exists";
394
+ row.existingId = existing.id;
395
+ row.number = existing.number ?? null;
396
+ row.note = sameImages ? "Already uploaded (same images)" : "Already exists";
397
+ } else if (!row.slug) {
398
+ row.state = "conflict";
399
+ row.note = "Needs a slug";
400
+ } else if (seen.has(row.slug)) {
401
+ row.state = "conflict";
402
+ row.note = `Same slug as row ${(seen.get(row.slug) ?? 0) + 1}`;
403
+ }
404
+ if (row.slug && !seen.has(row.slug)) seen.set(row.slug, index);
405
+
406
+ if (row.state === "new") {
407
+ const warnings: string[] = [];
408
+ if (match && matched && !matched.trashed) {
409
+ const name = `“${matched.title || match.slug}”`;
410
+ const total = group.files.length;
411
+ warnings.push(
412
+ match.count === total
413
+ ? `Same images as ${name}`
414
+ : `${match.count} of ${total} images are already in ${name}`,
415
+ );
416
+ }
417
+ if (next !== null) {
418
+ row.number = next;
419
+ if (usedNumbers.has(next)) warnings.push(`Number ${next} is already used`);
420
+ next++;
421
+ }
422
+ if (warnings.length > 0) row.note = warnings.join(". ");
423
+ } else if (override.title === undefined) {
424
+ // Rows that won't be created don't take a number, so don't show one.
425
+ row.title = existing?.title || defaultTitle(group.key, options, row.number);
426
+ }
427
+ return row;
428
+ });
429
+
430
+ // Release times for rows that will be created.
431
+ if (options.publishing.mode === "schedule") {
432
+ const { start, cadence, timeZone } = options.publishing;
433
+ const creating = rows.filter((row) => row.state === "new");
434
+ const times = releaseTimes(start, cadence, creating.length);
435
+ creating.forEach((row, i) => {
436
+ const time = times[i];
437
+ row.releaseAt = time ? zonedTimeToUtc(time, timeZone) : null;
438
+ });
439
+ }
440
+ return rows;
441
+ }
442
+
443
+ /** Whether a release time is due now (published, backdated) rather than scheduled. */
444
+ export function isDue(releaseAt: Date, now: Date = new Date()): boolean {
445
+ return releaseAt.getTime() <= now.getTime() + 60_000;
446
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Image fingerprints: a hash of an image file's bytes, in the format EmDash
3
+ * uses for media (`sha1:<hex>`). Each comic page keeps the fingerprint of the
4
+ * file it came from (`sourceHash`), and the segments of a split strip all keep
5
+ * the original file's. The bulk uploader compares them to spot images that are
6
+ * already in a comic, whatever the comic's title or slug.
7
+ *
8
+ * SHA-1 only tells identical files apart here; nothing relies on it being
9
+ * hard to forge.
10
+ */
11
+ export const FINGERPRINT = /^sha1:[0-9a-f]{40}$/;
12
+
13
+ export async function fingerprint(file: Blob): Promise<string> {
14
+ const digest = await crypto.subtle.digest("SHA-1", await file.arrayBuffer());
15
+ const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0"));
16
+ return `sha1:${hex.join("")}`;
17
+ }
18
+
19
+ /** Like `fingerprint`, but undefined when the file can't be read. */
20
+ export async function tryFingerprint(file: Blob): Promise<string | undefined> {
21
+ try {
22
+ return await fingerprint(file);
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The admin entry (`adminEntry`): field widgets for the comic editor and the
3
+ * bulk upload page. A schema field opts in with `"widget": "mm-comics:<name>"`.
4
+ * The site's build bundles this with the admin's own React and Kumo.
5
+ */
6
+ import { BulkUploadPage } from "./BulkUploadPage.js";
7
+ import { ComicPagesField } from "./ComicPagesField.js";
8
+ import { ChapterField, SeriesField } from "./pickers.js";
9
+
10
+ export const fields = {
11
+ "comic-pages": ComicPagesField,
12
+ series: SeriesField,
13
+ chapter: ChapterField,
14
+ };
15
+
16
+ /** Admin pages, by path (see `adminPages()` in the plugin entry). */
17
+ export const pages = {
18
+ "/bulk-upload": BulkUploadPage,
19
+ };
@@ -0,0 +1,75 @@
1
+ import { FINGERPRINT } from "./fingerprint.js";
2
+ import type { ImageValue, PageItem } from "./types.js";
3
+
4
+ /** The fields of an uploaded media item that an image value keeps. */
5
+ export interface UploadedMedia {
6
+ id: string;
7
+ filename: string;
8
+ mimeType: string;
9
+ url: string;
10
+ storageKey?: string | undefined;
11
+ width?: number | undefined;
12
+ height?: number | undefined;
13
+ alt?: string | undefined;
14
+ blurhash?: string | undefined;
15
+ dominantColor?: string | undefined;
16
+ provider?: string | undefined;
17
+ meta?: Record<string, unknown> | null | undefined;
18
+ }
19
+
20
+ /**
21
+ * Builds an image field value from an uploaded media item, the same way
22
+ * EmDash's own image field does, so templates render it with `<Image>`.
23
+ */
24
+ export function toImageValue(item: UploadedMedia): ImageValue {
25
+ const provider = !item.provider || item.provider === "local" ? "local" : item.provider;
26
+ const local = provider === "local";
27
+ const external = provider === "external";
28
+ const value: ImageValue = {
29
+ id: item.id,
30
+ provider,
31
+ alt: item.alt ?? "",
32
+ filename: item.filename,
33
+ mimeType: item.mimeType,
34
+ meta: local ? { ...item.meta, storageKey: item.storageKey } : (item.meta ?? {}),
35
+ };
36
+ if (external) value.src = item.url;
37
+ if (!local && !external) value.previewUrl = item.url;
38
+ if (item.width !== undefined) value.width = item.width;
39
+ if (item.height !== undefined) value.height = item.height;
40
+ if (item.blurhash) value.blurhash = item.blurhash;
41
+ if (item.dominantColor) value.dominantColor = item.dominantColor;
42
+ return value;
43
+ }
44
+
45
+ /** A URL the admin can show as a thumbnail. */
46
+ export function previewUrl(value: ImageValue | null | undefined): string | undefined {
47
+ if (!value) return undefined;
48
+ const storageKey = value.meta?.storageKey;
49
+ if (typeof storageKey === "string" && storageKey) {
50
+ return `/_emdash/api/media/file/${encodeURIComponent(storageKey)}`;
51
+ }
52
+ return (
53
+ value.previewUrl ?? value.src ?? (value.id ? `/_emdash/api/media/file/${value.id}` : undefined)
54
+ );
55
+ }
56
+
57
+ /** Normalizes a stored `pages` value into page items, dropping anything malformed. */
58
+ export function readPages(value: unknown): PageItem[] {
59
+ if (!Array.isArray(value)) return [];
60
+ return value
61
+ .filter((item): item is Record<string, unknown> => typeof item === "object" && item !== null)
62
+ .map((item) => {
63
+ const page: PageItem = {
64
+ image:
65
+ typeof item.image === "object" && item.image !== null ? (item.image as ImageValue) : null,
66
+ alt: typeof item.alt === "string" ? item.alt : "",
67
+ transcript: typeof item.transcript === "string" ? item.transcript : "",
68
+ hovertext: typeof item.hovertext === "string" ? item.hovertext : "",
69
+ };
70
+ if (typeof item.sourceHash === "string" && FINGERPRINT.test(item.sourceHash)) {
71
+ page.sourceHash = item.sourceHash;
72
+ }
73
+ return page;
74
+ });
75
+ }
@@ -0,0 +1,132 @@
1
+ import { Select, Text } from "@cloudflare/kumo";
2
+ import { fetchContentList } from "@emdash-cms/admin";
3
+ import { useEffect, useState } from "react";
4
+ import { type FieldWidgetProps, stringOption } from "./types.js";
5
+
6
+ interface Entry {
7
+ slug: string;
8
+ title: string;
9
+ series?: string;
10
+ number?: number;
11
+ }
12
+
13
+ function useEntries(collection: string) {
14
+ const [entries, setEntries] = useState<Entry[] | null>(null);
15
+ const [error, setError] = useState<string | null>(null);
16
+ useEffect(() => {
17
+ let active = true;
18
+ fetchContentList(collection, { limit: 100 })
19
+ .then((result) => {
20
+ if (!active) return;
21
+ setEntries(
22
+ result.items
23
+ .filter((item) => item.slug)
24
+ .map((item) => ({
25
+ slug: item.slug as string,
26
+ title: typeof item.data.title === "string" ? item.data.title : (item.slug as string),
27
+ ...(typeof item.data.series === "string" ? { series: item.data.series } : {}),
28
+ ...(typeof item.data.number === "number" ? { number: item.data.number } : {}),
29
+ })),
30
+ );
31
+ })
32
+ .catch((cause: unknown) => {
33
+ if (active) setError(cause instanceof Error ? cause.message : String(cause));
34
+ });
35
+ return () => {
36
+ active = false;
37
+ };
38
+ }, [collection]);
39
+ return { entries, error };
40
+ }
41
+
42
+ function Picker({
43
+ label,
44
+ value,
45
+ onChange,
46
+ options,
47
+ error,
48
+ loading,
49
+ }: {
50
+ label: string;
51
+ value: string;
52
+ onChange: (value: unknown) => void;
53
+ options: Array<{ value: string; label: string }>;
54
+ error: string | null;
55
+ loading: boolean;
56
+ }) {
57
+ // Keep a saved value selectable even if its entry isn't in the list.
58
+ const all =
59
+ value && !options.some((option) => option.value === value)
60
+ ? [{ value, label: `${value} (not found)` }, ...options]
61
+ : options;
62
+ return (
63
+ <div style={{ display: "grid", gap: "0.25rem" }}>
64
+ <Select
65
+ label={label}
66
+ hideLabel={false}
67
+ value={value || null}
68
+ placeholder={loading ? "Loading…" : "None"}
69
+ // Show the entry's title, not the stored slug.
70
+ renderValue={(selected: unknown) =>
71
+ all.find((option) => option.value === selected)?.label ?? (loading ? "Loading…" : "None")
72
+ }
73
+ onValueChange={(next) => onChange(typeof next === "string" && next ? next : null)}
74
+ >
75
+ <Select.Option value="">{loading ? "Loading…" : "None"}</Select.Option>
76
+ {all.map((option) => (
77
+ <Select.Option key={option.value} value={option.value}>
78
+ {option.label}
79
+ </Select.Option>
80
+ ))}
81
+ </Select>
82
+ {error && <Text variant="error">{error}</Text>}
83
+ </div>
84
+ );
85
+ }
86
+
87
+ /**
88
+ * Picks a series for the indexed `series` field, from the series collection
89
+ * (schema option `collection`, default "series"). Stores the series slug.
90
+ */
91
+ export function SeriesField({ value, onChange, label, options }: FieldWidgetProps) {
92
+ const { entries, error } = useEntries(stringOption(options, "collection") ?? "series");
93
+ return (
94
+ <Picker
95
+ label={label}
96
+ value={typeof value === "string" ? value : ""}
97
+ onChange={onChange}
98
+ loading={entries === null && !error}
99
+ error={error}
100
+ options={(entries ?? []).map((entry) => ({ value: entry.slug, label: entry.title }))}
101
+ />
102
+ );
103
+ }
104
+
105
+ /**
106
+ * Picks a chapter for the indexed `chapter` field, from the chapters collection
107
+ * (schema option `collection`, default "chapters"), labelled with its series'
108
+ * title (from `seriesCollection`, default "series").
109
+ */
110
+ export function ChapterField({ value, onChange, label, options }: FieldWidgetProps) {
111
+ const { entries, error } = useEntries(stringOption(options, "collection") ?? "chapters");
112
+ const { entries: series } = useEntries(stringOption(options, "seriesCollection") ?? "series");
113
+ const seriesTitle = new Map((series ?? []).map((entry) => [entry.slug, entry.title]));
114
+ const sorted = [...(entries ?? [])].sort(
115
+ (a, b) => (a.series ?? "").localeCompare(b.series ?? "") || (a.number ?? 0) - (b.number ?? 0),
116
+ );
117
+ return (
118
+ <Picker
119
+ label={label}
120
+ value={typeof value === "string" ? value : ""}
121
+ onChange={onChange}
122
+ loading={entries === null && !error}
123
+ error={error}
124
+ options={sorted.map((entry) => ({
125
+ value: entry.slug,
126
+ label: entry.series
127
+ ? `${seriesTitle.get(entry.series) ?? entry.series} · ${entry.title}`
128
+ : entry.title,
129
+ }))}
130
+ />
131
+ );
132
+ }