@matterandmotion/emdash-comics 0.0.0-stage → 0.1.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 (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,1004 @@
1
+ import { Banner, Button, Checkbox, Input, Select, Text } from "@cloudflare/kumo";
2
+ import { fetchManifest } from "@emdash-cms/admin";
3
+ import { type DragEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import { BATCH_RETENTION_DAYS, type BatchInput } from "../batches.js";
5
+ import {
6
+ createComic,
7
+ deleteComicForGood,
8
+ type ExistingIndex,
9
+ fetchBatches,
10
+ listAll,
11
+ loadExisting,
12
+ publishComic,
13
+ recordBatch,
14
+ scheduleComic,
15
+ trashComic,
16
+ uploadPages,
17
+ } from "./bulk/api.js";
18
+ import { type ComicCollection, findComicCollections, type ManifestLike } from "./bulk/config.js";
19
+ import { filesFromDrop, fingerprintFiles, fromFileList, type UploadFile } from "./bulk/files.js";
20
+ import { type Batch, batchStatus } from "./bulk/history.js";
21
+ import {
22
+ type Cadence,
23
+ formatLocalDateTime,
24
+ type GroupMode,
25
+ groupFiles,
26
+ isDue,
27
+ nextNumber,
28
+ type PlannedRow,
29
+ type Publishing,
30
+ parseLocalDateTime,
31
+ planRows,
32
+ type RowOverride,
33
+ utcToZonedTime,
34
+ } from "./bulk/plan.js";
35
+
36
+ interface Option {
37
+ value: string;
38
+ label: string;
39
+ }
40
+
41
+ interface ChapterOption extends Option {
42
+ series?: string | undefined;
43
+ }
44
+
45
+ type BatchAction = "trash" | "delete";
46
+
47
+ type RowResult = { state: "done"; id: string } | { state: "failed"; message: string };
48
+
49
+ const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
50
+
51
+ const styles = {
52
+ page: { display: "grid", gap: "1.5rem", maxWidth: "72rem" },
53
+ section: {
54
+ display: "grid",
55
+ gap: "0.75rem",
56
+ padding: "1rem",
57
+ border: "1px solid color-mix(in srgb, currentColor 15%, transparent)",
58
+ borderRadius: "0.5rem",
59
+ },
60
+ row: { display: "flex", flexWrap: "wrap" as const, gap: "0.75rem", alignItems: "end" },
61
+ field: { minWidth: "14rem", flex: "1 1 14rem" },
62
+ drop: {
63
+ display: "flex",
64
+ flexWrap: "wrap" as const,
65
+ gap: "0.75rem",
66
+ alignItems: "center",
67
+ padding: "1rem",
68
+ border: "2px dashed color-mix(in srgb, currentColor 25%, transparent)",
69
+ borderRadius: "0.5rem",
70
+ },
71
+ tableWrap: { overflowX: "auto" as const },
72
+ table: { width: "100%", borderCollapse: "collapse" as const, fontSize: "0.875rem" },
73
+ cell: {
74
+ padding: "0.5rem",
75
+ borderTop: "1px solid color-mix(in srgb, currentColor 12%, transparent)",
76
+ verticalAlign: "top" as const,
77
+ textAlign: "start" as const,
78
+ },
79
+ thumb: {
80
+ width: "3.5rem",
81
+ height: "3.5rem",
82
+ objectFit: "cover" as const,
83
+ borderRadius: "0.25rem",
84
+ },
85
+ muted: { opacity: 0.55 },
86
+ };
87
+
88
+ const message = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause));
89
+
90
+ function titleOf(data: Record<string, unknown>, field: string, fallback: string): string {
91
+ const value = data[field];
92
+ return typeof value === "string" && value ? value : fallback;
93
+ }
94
+
95
+ /** Tomorrow at 09:00 in the site's timezone, for the schedule's first date. */
96
+ function defaultStart(timeZone?: string): string {
97
+ const now = utcToZonedTime(new Date(), timeZone);
98
+ const tomorrow = new Date(Date.UTC(now.year, now.month - 1, now.day + 1));
99
+ return formatLocalDateTime({
100
+ year: tomorrow.getUTCFullYear(),
101
+ month: tomorrow.getUTCMonth() + 1,
102
+ day: tomorrow.getUTCDate(),
103
+ hour: 9,
104
+ minute: 0,
105
+ });
106
+ }
107
+
108
+ /** Object URLs for thumbnails, released when their files go away. */
109
+ function useThumbnails(files: UploadFile[]) {
110
+ const urls = useRef(new Map<File, string>());
111
+ useEffect(() => {
112
+ const kept = new Set(files.map((item) => item.file));
113
+ for (const [file, url] of urls.current) {
114
+ if (kept.has(file)) continue;
115
+ URL.revokeObjectURL(url);
116
+ urls.current.delete(file);
117
+ }
118
+ }, [files]);
119
+ useEffect(() => {
120
+ const current = urls.current;
121
+ return () => {
122
+ for (const url of current.values()) URL.revokeObjectURL(url);
123
+ current.clear();
124
+ };
125
+ }, []);
126
+ return (file: File) => {
127
+ let url = urls.current.get(file);
128
+ if (!url) {
129
+ url = URL.createObjectURL(file);
130
+ urls.current.set(file, url);
131
+ }
132
+ return url;
133
+ };
134
+ }
135
+
136
+ function Picker({
137
+ label,
138
+ value,
139
+ options,
140
+ onChange,
141
+ placeholder,
142
+ }: {
143
+ label: string;
144
+ value: string;
145
+ options: Option[];
146
+ onChange: (value: string) => void;
147
+ placeholder?: string;
148
+ }) {
149
+ return (
150
+ <Select
151
+ label={label}
152
+ hideLabel={false}
153
+ value={value || null}
154
+ {...(placeholder !== undefined ? { placeholder } : {})}
155
+ renderValue={(selected: unknown) =>
156
+ options.find((option) => option.value === selected)?.label ?? placeholder ?? "None"
157
+ }
158
+ onValueChange={(next) => onChange(typeof next === "string" ? next : "")}
159
+ >
160
+ {placeholder !== undefined && <Select.Option value="">{placeholder}</Select.Option>}
161
+ {options.map((option) => (
162
+ <Select.Option key={option.value} value={option.value}>
163
+ {option.label}
164
+ </Select.Option>
165
+ ))}
166
+ </Select>
167
+ );
168
+ }
169
+
170
+ /**
171
+ * The admin page that turns many images into many comics: group the files,
172
+ * pick a series and chapter, review titles, slugs, numbers and dates, then
173
+ * create them as drafts, publish them, or schedule them on a cadence.
174
+ */
175
+ export function BulkUploadPage() {
176
+ const [timeZone, setTimeZone] = useState<string | undefined>();
177
+ const [configs, setConfigs] = useState<ComicCollection[] | null>(null);
178
+ const [collection, setCollection] = useState("");
179
+ const [loadError, setLoadError] = useState<string | null>(null);
180
+ const config = configs?.find((item) => item.collection === collection) ?? configs?.[0];
181
+
182
+ const [seriesOptions, setSeriesOptions] = useState<Option[]>([]);
183
+ const [chapterOptions, setChapterOptions] = useState<ChapterOption[]>([]);
184
+ const [existing, setExisting] = useState<ExistingIndex | null>(null);
185
+
186
+ const [files, setFiles] = useState<UploadFile[]>([]);
187
+ const [reading, setReading] = useState<{ done: number; total: number } | null>(null);
188
+ const [mode, setMode] = useState<GroupMode>("each");
189
+ const [dragging, setDragging] = useState(false);
190
+ const fileInput = useRef<HTMLInputElement>(null);
191
+ const folderInput = useRef<HTMLInputElement>(null);
192
+ const thumbnail = useThumbnails(files);
193
+
194
+ const [series, setSeries] = useState("");
195
+ const [chapter, setChapter] = useState("");
196
+ const [titleMode, setTitleMode] = useState<"filename" | "series-number">("filename");
197
+ const [firstNumber, setFirstNumber] = useState("");
198
+
199
+ const [publishMode, setPublishMode] = useState<"draft" | "publish" | "schedule">("draft");
200
+ const [start, setStart] = useState("");
201
+ const [cadenceKind, setCadenceKind] = useState<"days" | "weekdays">("days");
202
+ const [every, setEvery] = useState("1");
203
+ const [weekdays, setWeekdays] = useState<number[]>([1, 3, 5]);
204
+
205
+ const [overrides, setOverrides] = useState<Map<string, RowOverride>>(new Map());
206
+ const [results, setResults] = useState<Map<string, RowResult>>(new Map());
207
+ const [running, setRunning] = useState(false);
208
+ const [progress, setProgress] = useState<{ done: number; total: number; text: string } | null>(
209
+ null,
210
+ );
211
+ const stopRequested = useRef(false);
212
+
213
+ const [history, setHistory] = useState<Batch[]>([]);
214
+ const [confirm, setConfirm] = useState<{ batch: string; action: BatchAction } | null>(null);
215
+ const [busy, setBusy] = useState<string | null>(null);
216
+ const [batchError, setBatchError] = useState<string | null>(null);
217
+
218
+ // The manifest says which collections use the comic widgets.
219
+ useEffect(() => {
220
+ let active = true;
221
+ fetchManifest()
222
+ .then((manifest) => {
223
+ if (!active) return;
224
+ const found = findComicCollections(manifest as unknown as ManifestLike);
225
+ setTimeZone(manifest.timezone);
226
+ setStart(defaultStart(manifest.timezone));
227
+ setConfigs(found);
228
+ setCollection(found[0]?.collection ?? "");
229
+ })
230
+ .catch((cause: unknown) => active && setLoadError(message(cause)));
231
+ return () => {
232
+ active = false;
233
+ };
234
+ }, []);
235
+
236
+ const reloadExisting = useCallback(async () => {
237
+ if (!config) return;
238
+ setExisting(await loadExisting(config));
239
+ }, [config]);
240
+
241
+ // Recent uploads are a convenience: if they can't load, the page still works.
242
+ const reloadHistory = useCallback(async () => {
243
+ if (!config) return;
244
+ try {
245
+ setHistory(await fetchBatches(config.collection));
246
+ } catch (cause) {
247
+ setBatchError(`Couldn't load recent uploads: ${message(cause)}`);
248
+ }
249
+ }, [config]);
250
+
251
+ // Series, chapters and existing comics for the chosen collection.
252
+ useEffect(() => {
253
+ if (!config) return;
254
+ let active = true;
255
+ setExisting(null);
256
+ setHistory([]);
257
+ void reloadHistory();
258
+ const seriesCollection = config.seriesCollection;
259
+ const chaptersCollection = config.chaptersCollection;
260
+ Promise.all([
261
+ loadExisting(config),
262
+ seriesCollection ? listAll(seriesCollection) : Promise.resolve([]),
263
+ chaptersCollection ? listAll(chaptersCollection) : Promise.resolve([]),
264
+ ])
265
+ .then(([entries, seriesEntries, chapterEntries]) => {
266
+ if (!active) return;
267
+ setExisting(entries);
268
+ setSeriesOptions(
269
+ seriesEntries.map((entry) => ({
270
+ value: entry.slug,
271
+ label: titleOf(entry.data, "title", entry.slug),
272
+ })),
273
+ );
274
+ setChapterOptions(
275
+ chapterEntries
276
+ .map((entry) => ({
277
+ value: entry.slug,
278
+ label: titleOf(entry.data, "title", entry.slug),
279
+ series: typeof entry.data.series === "string" ? entry.data.series : undefined,
280
+ number: typeof entry.data.number === "number" ? entry.data.number : 0,
281
+ }))
282
+ .sort((a, b) => a.number - b.number),
283
+ );
284
+ })
285
+ .catch((cause: unknown) => active && setLoadError(message(cause)));
286
+ return () => {
287
+ active = false;
288
+ };
289
+ }, [config, reloadHistory]);
290
+
291
+ const groups = useMemo(() => groupFiles(files, mode), [files, mode]);
292
+ const seriesTitle = seriesOptions.find((option) => option.value === series)?.label;
293
+ const chaptersForSeries = chapterOptions.filter(
294
+ (option) => !series || !option.series || option.series === series,
295
+ );
296
+
297
+ const autoNumber = useMemo(() => {
298
+ if (!existing) return 1;
299
+ const used: number[] = [];
300
+ for (const entry of existing.entries.values()) {
301
+ const sameSeries = !config?.seriesField || entry.series === series;
302
+ if (entry.number !== undefined && sameSeries && !entry.trashed) {
303
+ used.push(entry.number);
304
+ }
305
+ }
306
+ return nextNumber(used);
307
+ }, [existing, series, config]);
308
+ const typedNumber = Number.parseInt(firstNumber, 10);
309
+ const startNumber = config?.numberField
310
+ ? Number.isFinite(typedNumber) && typedNumber > 0
311
+ ? typedNumber
312
+ : autoNumber
313
+ : null;
314
+
315
+ const startTime = parseLocalDateTime(start);
316
+ const publishing = useMemo((): Publishing => {
317
+ const time = parseLocalDateTime(start);
318
+ if (publishMode === "publish") return { mode: "publish" };
319
+ if (publishMode !== "schedule" || !time) return { mode: "draft" };
320
+ const cadence: Cadence =
321
+ cadenceKind === "days"
322
+ ? { kind: "days", every: Math.max(1, Number.parseInt(every, 10) || 1) }
323
+ : { kind: "weekdays", days: weekdays };
324
+ return { mode: "schedule", start: time, cadence, timeZone };
325
+ }, [publishMode, start, cadenceKind, every, weekdays, timeZone]);
326
+
327
+ const rows: PlannedRow<UploadFile>[] = useMemo(
328
+ () =>
329
+ existing
330
+ ? planRows(
331
+ groups,
332
+ {
333
+ series: config?.seriesField ? series : undefined,
334
+ seriesTitle,
335
+ titleMode,
336
+ startNumber,
337
+ existing: existing.entries,
338
+ fingerprints: existing.fingerprints,
339
+ publishing,
340
+ },
341
+ overrides,
342
+ )
343
+ : [],
344
+ [existing, groups, config, series, seriesTitle, titleMode, startNumber, overrides, publishing],
345
+ );
346
+ const toCreate = rows.filter((row) => row.state === "new");
347
+ const missingSeries = Boolean(config?.seriesField) && !series;
348
+ const badSchedule =
349
+ publishMode === "schedule" &&
350
+ (!startTime || (cadenceKind === "weekdays" && weekdays.length === 0));
351
+
352
+ const formatDate = (date: Date) =>
353
+ new Intl.DateTimeFormat(undefined, {
354
+ dateStyle: "medium",
355
+ timeStyle: "short",
356
+ ...(timeZone ? { timeZone } : {}),
357
+ }).format(date);
358
+
359
+ /** Reads the files' fingerprints, so the review can spot images already in a comic. */
360
+ async function addFiles(added: UploadFile[]) {
361
+ if (added.length === 0) return;
362
+ setResults(new Map());
363
+ const total = added.length;
364
+ setReading({ done: 0, total });
365
+ try {
366
+ const read = await fingerprintFiles(added, (done) => setReading({ done, total }));
367
+ setFiles((current) => {
368
+ const seen = new Set(current.map((item) => item.path));
369
+ return [...current, ...read.filter((item) => !seen.has(item.path))];
370
+ });
371
+ } finally {
372
+ setReading(null);
373
+ }
374
+ }
375
+
376
+ function override(key: string, change: RowOverride) {
377
+ setOverrides((current) => {
378
+ const next = new Map(current);
379
+ next.set(key, { ...current.get(key), ...change });
380
+ return next;
381
+ });
382
+ }
383
+
384
+ function startOver() {
385
+ setFiles([]);
386
+ setOverrides(new Map());
387
+ setResults(new Map());
388
+ }
389
+
390
+ async function run() {
391
+ if (!config || toCreate.length === 0) return;
392
+ const batch: BatchInput = {
393
+ id: crypto.randomUUID(),
394
+ collection: config.collection,
395
+ ...(config.seriesField && series ? { series } : {}),
396
+ entries: [],
397
+ };
398
+ // Each save sends the whole list, so one that fails is made good by the next.
399
+ let recordError: string | null = null;
400
+ const record = async (id: string, title: string) => {
401
+ batch.entries.push({ id, title });
402
+ try {
403
+ await recordBatch(batch);
404
+ recordError = null;
405
+ } catch (cause) {
406
+ recordError = message(cause);
407
+ }
408
+ };
409
+ const setResult = (key: string, result: RowResult) =>
410
+ setResults((current) => new Map(current).set(key, result));
411
+
412
+ stopRequested.current = false;
413
+ setRunning(true);
414
+ setResults(new Map());
415
+ setBatchError(null);
416
+ const total = toCreate.length;
417
+ for (const [index, row] of toCreate.entries()) {
418
+ if (stopRequested.current) break;
419
+ const step = (text: string) =>
420
+ setProgress({ done: index, total, text: `${row.title}: ${text}` });
421
+ let createdId: string | null = null;
422
+ try {
423
+ const pages = await uploadPages(row.files, step);
424
+ step("Creating");
425
+ createdId = await createComic(config, {
426
+ slug: row.slug,
427
+ title: row.title,
428
+ series: config.seriesField ? series : undefined,
429
+ chapter: chapter || undefined,
430
+ number: row.number,
431
+ pages,
432
+ });
433
+ await record(createdId, row.title);
434
+ if (publishMode === "publish") {
435
+ step("Publishing");
436
+ await publishComic(config.collection, createdId);
437
+ } else if (row.releaseAt) {
438
+ if (isDue(row.releaseAt)) {
439
+ step("Publishing (backdated)");
440
+ await publishComic(config.collection, createdId, row.releaseAt);
441
+ } else {
442
+ step("Scheduling");
443
+ await scheduleComic(config.collection, createdId, row.releaseAt);
444
+ }
445
+ }
446
+ setResult(row.key, { state: "done", id: createdId });
447
+ } catch (cause) {
448
+ setResult(row.key, {
449
+ state: "failed",
450
+ message: createdId ? `Created as a draft, but: ${message(cause)}` : message(cause),
451
+ });
452
+ }
453
+ }
454
+ setProgress(null);
455
+ setRunning(false);
456
+ if (recordError) {
457
+ setBatchError(
458
+ `This upload isn't in Recent uploads, so it can't be undone from here: ${recordError}`,
459
+ );
460
+ }
461
+ // Created comics now show as existing, and the next number moves on.
462
+ try {
463
+ await Promise.all([reloadExisting(), reloadHistory()]);
464
+ } catch (cause) {
465
+ setLoadError(message(cause));
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Undo moves a batch's live comics to the trash. Deleting for good (once
471
+ * none is live) frees their slugs, so the same files can be uploaded again.
472
+ */
473
+ async function batchAction(batch: Batch, action: BatchAction) {
474
+ if (!existing) return;
475
+ setConfirm(null);
476
+ setBusy(batch.id);
477
+ setBatchError(null);
478
+ const { live, trashed } = batchStatus(batch, existing.states);
479
+ try {
480
+ for (const entry of action === "trash" ? live : trashed) {
481
+ if (action === "trash") await trashComic(batch.collection, entry.id);
482
+ else await deleteComicForGood(batch.collection, entry.id);
483
+ }
484
+ setResults(new Map());
485
+ await reloadExisting();
486
+ } catch (cause) {
487
+ setBatchError(message(cause));
488
+ } finally {
489
+ setBusy(null);
490
+ }
491
+ }
492
+
493
+ const onDrop = (event: DragEvent<HTMLDivElement>) => {
494
+ event.preventDefault();
495
+ setDragging(false);
496
+ filesFromDrop(event.dataTransfer)
497
+ .then((list) => addFiles(list))
498
+ .catch((cause: unknown) => setLoadError(message(cause)));
499
+ };
500
+
501
+ if (loadError) {
502
+ return (
503
+ <div style={styles.page}>
504
+ <Text variant="heading1" as="h1">
505
+ Bulk upload
506
+ </Text>
507
+ <Banner variant="error" title="Something went wrong" description={loadError} />
508
+ </div>
509
+ );
510
+ }
511
+ if (configs === null) {
512
+ return (
513
+ <div style={styles.page}>
514
+ <Text variant="heading1" as="h1">
515
+ Bulk upload
516
+ </Text>
517
+ <Text variant="secondary">Loading…</Text>
518
+ </div>
519
+ );
520
+ }
521
+ if (!config) {
522
+ return (
523
+ <div style={styles.page}>
524
+ <Text variant="heading1" as="h1">
525
+ Bulk upload
526
+ </Text>
527
+ <Banner
528
+ variant="alert"
529
+ title="No comic collection found"
530
+ description='Bulk upload needs a collection whose pages field uses the "mm-comics:comic-pages" widget.'
531
+ />
532
+ </div>
533
+ );
534
+ }
535
+
536
+ // Batches whose comics are all deleted for good have nothing left to act on.
537
+ const recent = existing
538
+ ? history
539
+ .map((batch) => ({ batch, ...batchStatus(batch, existing.states) }))
540
+ .filter(({ live, trashed }) => live.length + trashed.length > 0)
541
+ : [];
542
+
543
+ const groupedBy = {
544
+ each: "One comic per image",
545
+ name: "Group pages by file name",
546
+ folder: "One comic per folder",
547
+ };
548
+
549
+ return (
550
+ <div style={styles.page}>
551
+ <div>
552
+ <Text variant="heading1" as="h1">
553
+ Bulk upload
554
+ </Text>
555
+ <Text variant="secondary">
556
+ Turn many images into many {config.label.toLowerCase()} at once. Review everything below
557
+ before anything is created.
558
+ </Text>
559
+ </div>
560
+
561
+ {configs.length > 1 && (
562
+ <div style={styles.field}>
563
+ <Picker
564
+ label="Collection"
565
+ value={config.collection}
566
+ options={configs.map((item) => ({ value: item.collection, label: item.label }))}
567
+ onChange={setCollection}
568
+ />
569
+ </div>
570
+ )}
571
+
572
+ <section style={styles.section}>
573
+ <Text variant="heading3" as="h2">
574
+ 1. Images
575
+ </Text>
576
+ {/* biome-ignore lint/a11y/noStaticElementInteractions: a drop target for mouse users; the buttons inside are the keyboard and screen-reader way in */}
577
+ <div
578
+ style={{ ...styles.drop, ...(dragging ? { borderStyle: "solid" } : {}) }}
579
+ onDragOver={(event) => {
580
+ event.preventDefault();
581
+ setDragging(true);
582
+ }}
583
+ onDragLeave={() => setDragging(false)}
584
+ onDrop={onDrop}
585
+ >
586
+ <Button
587
+ variant="secondary"
588
+ onClick={() => fileInput.current?.click()}
589
+ disabled={running || reading !== null}
590
+ >
591
+ Choose images
592
+ </Button>
593
+ <Button
594
+ variant="secondary"
595
+ onClick={() => folderInput.current?.click()}
596
+ disabled={running || reading !== null}
597
+ >
598
+ Choose a folder
599
+ </Button>
600
+ <input
601
+ ref={fileInput}
602
+ type="file"
603
+ accept="image/*"
604
+ multiple
605
+ hidden
606
+ onChange={(event) => {
607
+ if (event.target.files) void addFiles(fromFileList(event.target.files));
608
+ event.target.value = "";
609
+ }}
610
+ />
611
+ <input
612
+ ref={(element) => {
613
+ folderInput.current = element;
614
+ element?.setAttribute("webkitdirectory", "");
615
+ }}
616
+ type="file"
617
+ multiple
618
+ hidden
619
+ onChange={(event) => {
620
+ if (event.target.files) void addFiles(fromFileList(event.target.files));
621
+ event.target.value = "";
622
+ }}
623
+ />
624
+ <Text variant="secondary" size="sm">
625
+ or drop images or folders here. Images taller than 4000 px are split into segments when
626
+ they're uploaded.
627
+ </Text>
628
+ </div>
629
+ <div style={styles.row}>
630
+ <div style={styles.field}>
631
+ <Picker
632
+ label="Comics from"
633
+ value={mode}
634
+ options={Object.entries(groupedBy).map(([value, label]) => ({ value, label }))}
635
+ onChange={(value) => {
636
+ setMode(value as GroupMode);
637
+ setOverrides(new Map());
638
+ }}
639
+ />
640
+ </div>
641
+ {files.length > 0 && (
642
+ <Button variant="ghost" onClick={startOver} disabled={running}>
643
+ Clear {files.length} {files.length === 1 ? "image" : "images"}
644
+ </Button>
645
+ )}
646
+ </div>
647
+ <Text variant="secondary" size="sm">
648
+ {mode === "each" && "Each image becomes a single-page comic."}
649
+ {mode === "name" &&
650
+ "Images that differ only by a trailing page number become one comic: ep01-1.png and ep01-2.png make “ep01”."}
651
+ {mode === "folder" &&
652
+ "Each folder becomes one comic, with its images as pages in name order."}
653
+ </Text>
654
+ </section>
655
+
656
+ <section style={styles.section}>
657
+ <Text variant="heading3" as="h2">
658
+ 2. Details
659
+ </Text>
660
+ <div style={styles.row}>
661
+ {config.seriesField && (
662
+ <div style={styles.field}>
663
+ <Picker
664
+ label="Series"
665
+ value={series}
666
+ options={seriesOptions}
667
+ placeholder="Choose a series"
668
+ onChange={(value) => {
669
+ setSeries(value);
670
+ setChapter("");
671
+ setFirstNumber("");
672
+ }}
673
+ />
674
+ </div>
675
+ )}
676
+ {config.chapterField && (
677
+ <div style={styles.field}>
678
+ <Picker
679
+ label="Chapter"
680
+ value={chapter}
681
+ options={chaptersForSeries}
682
+ placeholder="No chapter"
683
+ onChange={setChapter}
684
+ />
685
+ </div>
686
+ )}
687
+ </div>
688
+ <div style={styles.row}>
689
+ <div style={styles.field}>
690
+ <Picker
691
+ label="Titles"
692
+ value={titleMode}
693
+ options={[
694
+ { value: "filename", label: "From file names" },
695
+ { value: "series-number", label: "Series title and number" },
696
+ ]}
697
+ onChange={(value) => {
698
+ setTitleMode(value as "filename" | "series-number");
699
+ setOverrides(new Map());
700
+ }}
701
+ />
702
+ </div>
703
+ {config.numberField && (
704
+ <div style={styles.field}>
705
+ <Input
706
+ label="First number"
707
+ type="number"
708
+ min={1}
709
+ value={firstNumber}
710
+ placeholder={String(autoNumber)}
711
+ description={`Leave empty to continue the series at ${autoNumber}.`}
712
+ onChange={(event) => setFirstNumber(event.target.value)}
713
+ />
714
+ </div>
715
+ )}
716
+ </div>
717
+ </section>
718
+
719
+ <section style={styles.section}>
720
+ <Text variant="heading3" as="h2">
721
+ 3. Publishing
722
+ </Text>
723
+ <div style={styles.row}>
724
+ <div style={styles.field}>
725
+ <Picker
726
+ label="When"
727
+ value={publishMode}
728
+ options={[
729
+ { value: "draft", label: "Save as drafts" },
730
+ { value: "publish", label: "Publish now" },
731
+ { value: "schedule", label: "Release on a schedule" },
732
+ ]}
733
+ onChange={(value) => setPublishMode(value as "draft" | "publish" | "schedule")}
734
+ />
735
+ </div>
736
+ {publishMode === "schedule" && (
737
+ <div style={styles.field}>
738
+ <Input
739
+ label="First release"
740
+ type="datetime-local"
741
+ value={start}
742
+ description={timeZone ? `In the site's timezone, ${timeZone}.` : undefined}
743
+ onChange={(event) => setStart(event.target.value)}
744
+ />
745
+ </div>
746
+ )}
747
+ </div>
748
+ {publishMode === "schedule" && (
749
+ <>
750
+ <div style={styles.row}>
751
+ <div style={styles.field}>
752
+ <Picker
753
+ label="Then"
754
+ value={cadenceKind}
755
+ options={[
756
+ { value: "days", label: "Every few days" },
757
+ { value: "weekdays", label: "On set weekdays" },
758
+ ]}
759
+ onChange={(value) => setCadenceKind(value as "days" | "weekdays")}
760
+ />
761
+ </div>
762
+ {cadenceKind === "days" && (
763
+ <div style={styles.field}>
764
+ <Input
765
+ label="Days between releases"
766
+ type="number"
767
+ min={1}
768
+ value={every}
769
+ onChange={(event) => setEvery(event.target.value)}
770
+ />
771
+ </div>
772
+ )}
773
+ </div>
774
+ {cadenceKind === "weekdays" && (
775
+ <div style={styles.row}>
776
+ {WEEKDAYS.map((name, day) => (
777
+ <Checkbox
778
+ key={name}
779
+ label={name}
780
+ checked={weekdays.includes(day)}
781
+ onCheckedChange={(checked) =>
782
+ setWeekdays((current) =>
783
+ checked ? [...current, day].sort() : current.filter((item) => item !== day),
784
+ )
785
+ }
786
+ />
787
+ ))}
788
+ </div>
789
+ )}
790
+ <Text variant="secondary" size="sm">
791
+ Dates in the past are published straight away with that date (backdated); future ones
792
+ are scheduled.
793
+ </Text>
794
+ </>
795
+ )}
796
+ </section>
797
+
798
+ <section style={styles.section}>
799
+ <Text variant="heading3" as="h2">
800
+ 4. Review
801
+ </Text>
802
+ {existing === null ? (
803
+ <Text variant="secondary">Checking existing {config.label.toLowerCase()}…</Text>
804
+ ) : reading ? (
805
+ <Text variant="secondary">
806
+ Reading images: {reading.done} of {reading.total}…
807
+ </Text>
808
+ ) : rows.length === 0 ? (
809
+ <Text variant="secondary">Add images to see what will be created.</Text>
810
+ ) : (
811
+ <div style={styles.tableWrap}>
812
+ <table style={styles.table}>
813
+ <thead>
814
+ <tr>
815
+ <th style={styles.cell}>Create</th>
816
+ <th style={styles.cell}>Pages</th>
817
+ <th style={styles.cell}>Title</th>
818
+ <th style={styles.cell}>Slug</th>
819
+ {config.numberField && <th style={styles.cell}>No.</th>}
820
+ {publishMode === "schedule" && <th style={styles.cell}>Release</th>}
821
+ <th style={styles.cell}>Status</th>
822
+ </tr>
823
+ </thead>
824
+ <tbody>
825
+ {rows.map((row, index) => {
826
+ const result = results.get(row.key);
827
+ const first = row.files[0];
828
+ const inactive = row.state !== "new" && !result;
829
+ return (
830
+ <tr key={row.key} style={inactive ? styles.muted : undefined}>
831
+ <td style={styles.cell}>
832
+ <Checkbox
833
+ label={String(index + 1)}
834
+ checked={row.state !== "skipped"}
835
+ disabled={running}
836
+ onCheckedChange={(checked) => override(row.key, { skip: !checked })}
837
+ />
838
+ </td>
839
+ <td style={styles.cell}>
840
+ {first && <img src={thumbnail(first.file)} alt="" style={styles.thumb} />}
841
+ <Text variant="secondary" size="xs">
842
+ {row.files.length} {row.files.length === 1 ? "image" : "images"}
843
+ </Text>
844
+ </td>
845
+ <td style={styles.cell}>
846
+ <Input
847
+ aria-label={`Title for row ${index + 1}`}
848
+ size="sm"
849
+ value={row.title}
850
+ disabled={running}
851
+ onChange={(event) => override(row.key, { title: event.target.value })}
852
+ />
853
+ </td>
854
+ <td style={styles.cell}>
855
+ <Input
856
+ aria-label={`Slug for row ${index + 1}`}
857
+ size="sm"
858
+ value={row.slug}
859
+ disabled={running}
860
+ onChange={(event) => override(row.key, { slug: event.target.value })}
861
+ />
862
+ </td>
863
+ {config.numberField && <td style={styles.cell}>{row.number ?? "–"}</td>}
864
+ {publishMode === "schedule" && (
865
+ <td style={styles.cell}>
866
+ {row.releaseAt
867
+ ? `${formatDate(row.releaseAt)}${isDue(row.releaseAt) ? " (backdated)" : ""}`
868
+ : "–"}
869
+ </td>
870
+ )}
871
+ <td style={styles.cell}>
872
+ {result?.state === "done" && <Text variant="success">Created</Text>}
873
+ {result?.state === "failed" && (
874
+ <Text variant="error">Failed: {result.message}</Text>
875
+ )}
876
+ {!result && (
877
+ <Text variant={row.state === "conflict" ? "error" : "secondary"}>
878
+ {row.state === "new" ? (row.note ?? "Ready") : row.note}
879
+ </Text>
880
+ )}
881
+ </td>
882
+ </tr>
883
+ );
884
+ })}
885
+ </tbody>
886
+ </table>
887
+ </div>
888
+ )}
889
+
890
+ {progress && (
891
+ <div style={{ display: "grid", gap: "0.25rem" }}>
892
+ <progress max={progress.total} value={progress.done} style={{ width: "100%" }} />
893
+ <Text variant="secondary" size="sm">
894
+ {progress.done + 1} of {progress.total}: {progress.text}
895
+ </Text>
896
+ </div>
897
+ )}
898
+
899
+ <div style={styles.row}>
900
+ <Button
901
+ variant="primary"
902
+ onClick={() => void run()}
903
+ disabled={
904
+ running || reading !== null || toCreate.length === 0 || missingSeries || badSchedule
905
+ }
906
+ >
907
+ {running
908
+ ? "Creating…"
909
+ : `Create ${toCreate.length} ${toCreate.length === 1 ? "comic" : "comics"}`}
910
+ </Button>
911
+ {running && (
912
+ <Button
913
+ variant="secondary"
914
+ onClick={() => {
915
+ stopRequested.current = true;
916
+ }}
917
+ >
918
+ Stop after this one
919
+ </Button>
920
+ )}
921
+ {missingSeries && <Text variant="secondary">Choose a series first.</Text>}
922
+ {badSchedule && <Text variant="secondary">Set the first release and the weekdays.</Text>}
923
+ </div>
924
+ </section>
925
+
926
+ {recent.length > 0 && (
927
+ <section style={styles.section}>
928
+ <Text variant="heading3" as="h2">
929
+ Recent uploads
930
+ </Text>
931
+ <Text variant="secondary" size="sm">
932
+ Uploads from the last {BATCH_RETENTION_DAYS} days, by anyone. Undo moves a batch's
933
+ comics to the trash, where they can be restored. Deleting them for good from here frees
934
+ their slugs for a fresh upload. Their images stay in the media library either way.
935
+ </Text>
936
+ {batchError && (
937
+ <Banner variant="error" title="That didn't finish" description={batchError} />
938
+ )}
939
+ {recent.map(({ batch, live, trashed }) => {
940
+ const action: BatchAction = live.length > 0 ? "trash" : "delete";
941
+ const count = action === "trash" ? live.length : trashed.length;
942
+ const comics = `${count} ${count === 1 ? "comic" : "comics"}`;
943
+ const total = batch.entries.length;
944
+ const seriesName = seriesOptions.find((option) => option.value === batch.series)?.label;
945
+ const asking = confirm?.batch === batch.id && confirm.action === action;
946
+ return (
947
+ <div key={batch.id} style={styles.row}>
948
+ <Text>
949
+ {formatDate(new Date(batch.createdAt))} · {total}{" "}
950
+ {total === 1 ? "comic" : "comics"}
951
+ {batch.series ? ` in ${seriesName ?? batch.series}` : ""}
952
+ {batch.by.name ? ` · by ${batch.by.name}` : ""}
953
+ {live.length === 0
954
+ ? " · in the trash"
955
+ : trashed.length > 0
956
+ ? ` · ${trashed.length} in the trash`
957
+ : ""}
958
+ </Text>
959
+ {asking ? (
960
+ <>
961
+ <Button
962
+ variant="destructive"
963
+ size="sm"
964
+ onClick={() => void batchAction(batch, action)}
965
+ disabled={busy !== null || running}
966
+ >
967
+ {action === "trash"
968
+ ? `Move ${comics} to the trash`
969
+ : `Delete ${comics} for good`}
970
+ </Button>
971
+ <Button variant="ghost" size="sm" onClick={() => setConfirm(null)}>
972
+ Cancel
973
+ </Button>
974
+ {action === "delete" && (
975
+ <Text variant="secondary" size="sm">
976
+ This can't be undone.
977
+ </Text>
978
+ )}
979
+ </>
980
+ ) : (
981
+ <Button
982
+ variant="secondary"
983
+ size="sm"
984
+ onClick={() => setConfirm({ batch: batch.id, action })}
985
+ disabled={busy !== null || running}
986
+ >
987
+ {busy === batch.id
988
+ ? "Working…"
989
+ : action === "trash"
990
+ ? "Undo"
991
+ : "Delete for good"}
992
+ </Button>
993
+ )}
994
+ </div>
995
+ );
996
+ })}
997
+ </section>
998
+ )}
999
+ {recent.length === 0 && batchError && (
1000
+ <Banner variant="error" title="That didn't finish" description={batchError} />
1001
+ )}
1002
+ </div>
1003
+ );
1004
+ }