@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,202 @@
1
+ import { Button, Input, InputArea, Text } from "@cloudflare/kumo";
2
+ import { uploadMedia } from "@emdash-cms/admin";
3
+ import { type ChangeEvent, type DragEvent, useRef, useState } from "react";
4
+ import { tryFingerprint } from "./fingerprint.js";
5
+ import { previewUrl, readPages, toImageValue, type UploadedMedia } from "./media.js";
6
+ import { splitTallImage } from "./slice.js";
7
+ import type { FieldWidgetProps, PageItem } from "./types.js";
8
+
9
+ const byName = (a: File, b: File) => a.name.localeCompare(b.name, undefined, { numeric: true });
10
+
11
+ const styles = {
12
+ root: { display: "grid", gap: "0.75rem" },
13
+ page: {
14
+ display: "grid",
15
+ gridTemplateColumns: "6rem 1fr auto",
16
+ gap: "0.75rem",
17
+ alignItems: "start",
18
+ padding: "0.75rem",
19
+ border: "1px solid color-mix(in srgb, currentColor 15%, transparent)",
20
+ borderRadius: "0.5rem",
21
+ },
22
+ thumb: { width: "6rem", height: "auto", borderRadius: "0.25rem", display: "block" },
23
+ fields: { display: "grid", gap: "0.5rem" },
24
+ actions: { display: "grid", gap: "0.25rem" },
25
+ drop: {
26
+ display: "flex",
27
+ flexWrap: "wrap" as const,
28
+ gap: "0.75rem",
29
+ alignItems: "center",
30
+ padding: "1rem",
31
+ border: "2px dashed color-mix(in srgb, currentColor 25%, transparent)",
32
+ borderRadius: "0.5rem",
33
+ },
34
+ };
35
+
36
+ /**
37
+ * The editor for a comic's `pages` repeater: add many images at once (drop or
38
+ * pick), tall strips split into segments of at most 4000 px, reorder, remove,
39
+ * and edit each page's alt text, hover text and transcript.
40
+ */
41
+ export function ComicPagesField({ value, onChange, label, id }: FieldWidgetProps) {
42
+ const pages = readPages(value);
43
+ const latest = useRef(pages);
44
+ latest.current = pages;
45
+ const fileInput = useRef<HTMLInputElement>(null);
46
+ const [status, setStatus] = useState<string | null>(null);
47
+ const [error, setError] = useState<string | null>(null);
48
+ const [dragging, setDragging] = useState(false);
49
+
50
+ const save = (next: PageItem[]) => onChange(next);
51
+ const patch = (index: number, change: Partial<PageItem>) =>
52
+ save(latest.current.map((page, i) => (i === index ? { ...page, ...change } : page)));
53
+ const move = (index: number, step: -1 | 1) => {
54
+ const next = [...latest.current];
55
+ const target = index + step;
56
+ if (target < 0 || target >= next.length) return;
57
+ [next[index], next[target]] = [next[target] as PageItem, next[index] as PageItem];
58
+ save(next);
59
+ };
60
+ const remove = (index: number) => save(latest.current.filter((_, i) => i !== index));
61
+
62
+ async function addFiles(list: FileList | File[]) {
63
+ const files = [...list].filter((file) => file.type.startsWith("image/")).sort(byName);
64
+ if (files.length === 0) return;
65
+ setError(null);
66
+ let uploaded = 0;
67
+ try {
68
+ for (const file of files) {
69
+ setStatus(`Preparing ${file.name}…`);
70
+ const sourceHash = await tryFingerprint(file);
71
+ const parts = await splitTallImage(file);
72
+ for (const part of parts) {
73
+ uploaded++;
74
+ setStatus(`Uploading ${part.name} (${uploaded})…`);
75
+ const item: UploadedMedia = await uploadMedia(part);
76
+ // Save after every upload, so a failure later keeps what's done.
77
+ const page: PageItem = {
78
+ image: toImageValue(item),
79
+ alt: "",
80
+ transcript: "",
81
+ hovertext: "",
82
+ };
83
+ if (sourceHash) page.sourceHash = sourceHash;
84
+ save([...latest.current, page]);
85
+ }
86
+ }
87
+ } catch (cause) {
88
+ setError(cause instanceof Error ? cause.message : String(cause));
89
+ } finally {
90
+ setStatus(null);
91
+ }
92
+ }
93
+
94
+ const onPick = (event: ChangeEvent<HTMLInputElement>) => {
95
+ if (event.target.files) void addFiles(event.target.files);
96
+ event.target.value = "";
97
+ };
98
+ const onDrop = (event: DragEvent<HTMLDivElement>) => {
99
+ event.preventDefault();
100
+ setDragging(false);
101
+ void addFiles(event.dataTransfer.files);
102
+ };
103
+
104
+ return (
105
+ <div style={styles.root}>
106
+ <label htmlFor={id}>
107
+ <Text variant="heading3" as="span">
108
+ {label}
109
+ </Text>
110
+ </label>
111
+ {pages.length === 0 && <Text variant="secondary">No pages yet.</Text>}
112
+ {pages.map((page, index) => (
113
+ <div key={page.image?.id ?? `page-${index}`} style={styles.page}>
114
+ <div>
115
+ {page.image ? <img src={previewUrl(page.image)} alt="" style={styles.thumb} /> : null}
116
+ <Text variant="secondary" size="xs">
117
+ Page {index + 1}
118
+ {page.image?.height ? ` · ${page.image.width}×${page.image.height}` : ""}
119
+ </Text>
120
+ </div>
121
+ <div style={styles.fields}>
122
+ <Input
123
+ label="Alt text"
124
+ size="sm"
125
+ value={page.alt}
126
+ placeholder="What a reader who can't see the page needs to know"
127
+ onChange={(event) => patch(index, { alt: event.target.value })}
128
+ />
129
+ <Input
130
+ label="Hover text"
131
+ size="sm"
132
+ value={page.hovertext}
133
+ onChange={(event) => patch(index, { hovertext: event.target.value })}
134
+ />
135
+ <InputArea
136
+ label="Transcript"
137
+ size="sm"
138
+ autoResize
139
+ minRows={2}
140
+ value={page.transcript}
141
+ onChange={(event) => patch(index, { transcript: event.target.value })}
142
+ />
143
+ </div>
144
+ <div style={styles.actions}>
145
+ <Button
146
+ size="sm"
147
+ variant="ghost"
148
+ onClick={() => move(index, -1)}
149
+ disabled={index === 0}
150
+ >
151
+ Up
152
+ </Button>
153
+ <Button
154
+ size="sm"
155
+ variant="ghost"
156
+ onClick={() => move(index, 1)}
157
+ disabled={index === pages.length - 1}
158
+ >
159
+ Down
160
+ </Button>
161
+ <Button size="sm" variant="secondary-destructive" onClick={() => remove(index)}>
162
+ Remove
163
+ </Button>
164
+ </div>
165
+ </div>
166
+ ))}
167
+ {/* biome-ignore lint/a11y/noStaticElementInteractions: a drop target for mouse users; the "Add pages" button inside is the keyboard and screen-reader way in */}
168
+ <div
169
+ style={{ ...styles.drop, ...(dragging ? { borderStyle: "solid" } : {}) }}
170
+ onDragOver={(event) => {
171
+ event.preventDefault();
172
+ setDragging(true);
173
+ }}
174
+ onDragLeave={() => setDragging(false)}
175
+ onDrop={onDrop}
176
+ >
177
+ <Button
178
+ variant="secondary"
179
+ onClick={() => fileInput.current?.click()}
180
+ disabled={status !== null}
181
+ >
182
+ Add pages
183
+ </Button>
184
+ <input
185
+ ref={fileInput}
186
+ id={id}
187
+ type="file"
188
+ accept="image/*"
189
+ multiple
190
+ hidden
191
+ onChange={onPick}
192
+ />
193
+ <Text variant="secondary" size="sm">
194
+ or drop images here. Files are added in name order; images taller than 4000 px are split
195
+ into segments.
196
+ </Text>
197
+ </div>
198
+ {status && <Text variant="secondary">{status}</Text>}
199
+ {error && <Text variant="error">{error}</Text>}
200
+ </div>
201
+ );
202
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Server calls for the bulk uploader, through the admin's own API helpers, so
3
+ * they carry the editor's session and EmDash's request headers.
4
+ */
5
+ import {
6
+ API_BASE,
7
+ ApiResponseError,
8
+ apiFetch,
9
+ createContent,
10
+ deleteContent,
11
+ fetchContentList,
12
+ fetchTrashedContent,
13
+ parseApiResponse,
14
+ permanentDeleteContent,
15
+ publishContent,
16
+ scheduleContent,
17
+ uploadMedia,
18
+ } from "@emdash-cms/admin";
19
+ import type { BatchInput } from "../../batches.js";
20
+ import { PLUGIN_ID } from "../../id.js";
21
+ import { readPages, toImageValue, type UploadedMedia } from "../media.js";
22
+ import { splitTallImage } from "../slice.js";
23
+ import type { PageItem } from "../types.js";
24
+ import type { ComicCollection } from "./config.js";
25
+ import { type Batch, type EntryState, parseBatches } from "./history.js";
26
+ import type { ExistingEntry } from "./plan.js";
27
+
28
+ /** Stops runaway paging on a very large collection. */
29
+ const MAX_ENTRIES = 20_000;
30
+
31
+ export interface ListedEntry {
32
+ id: string;
33
+ slug: string;
34
+ data: Record<string, unknown>;
35
+ }
36
+
37
+ /** Every entry in a collection (all statuses), or in its trash, 100 at a time. */
38
+ export async function listAll(collection: string, trash = false): Promise<ListedEntry[]> {
39
+ const entries: ListedEntry[] = [];
40
+ let cursor: string | undefined;
41
+ do {
42
+ const options = { limit: 100, ...(cursor ? { cursor } : {}) };
43
+ const page = trash
44
+ ? await fetchTrashedContent(collection, options)
45
+ : await fetchContentList(collection, options);
46
+ for (const item of page.items) {
47
+ if (item.slug) entries.push({ id: item.id, slug: item.slug, data: item.data });
48
+ }
49
+ cursor = page.nextCursor;
50
+ } while (cursor && entries.length < MAX_ENTRIES);
51
+ return entries;
52
+ }
53
+
54
+ /** What's in the comic collection already. */
55
+ export interface ExistingIndex {
56
+ /** Every entry by slug, with its series and number. Trashed ones keep their slugs, so they're here too. */
57
+ entries: Map<string, ExistingEntry>;
58
+ /** For each image fingerprint, the slugs of the live entries whose pages came from it. */
59
+ fingerprints: Map<string, string[]>;
60
+ /** Each entry's ID, live or in the trash. */
61
+ states: Map<string, EntryState>;
62
+ }
63
+
64
+ export async function loadExisting(config: ComicCollection): Promise<ExistingIndex> {
65
+ const index: ExistingIndex = { entries: new Map(), fingerprints: new Map(), states: new Map() };
66
+ const [live, trashed] = await Promise.all([
67
+ listAll(config.collection),
68
+ listAll(config.collection, true),
69
+ ]);
70
+ const tagged = [
71
+ ...trashed.map((entry) => ({ entry, trashed: true })),
72
+ // Live entries win if a slug is somehow in both.
73
+ ...live.map((entry) => ({ entry, trashed: false })),
74
+ ];
75
+ for (const { entry, trashed: inTrash } of tagged) {
76
+ const title = entry.data[config.titleField];
77
+ const series = config.seriesField ? entry.data[config.seriesField] : undefined;
78
+ const number = config.numberField ? entry.data[config.numberField] : undefined;
79
+ index.entries.set(entry.slug, {
80
+ id: entry.id,
81
+ title: typeof title === "string" ? title : undefined,
82
+ series: typeof series === "string" ? series : undefined,
83
+ number: typeof number === "number" ? number : undefined,
84
+ trashed: inTrash,
85
+ });
86
+ index.states.set(entry.id, inTrash ? "trashed" : "live");
87
+ if (inTrash) continue;
88
+ for (const page of readPages(entry.data[config.pagesField])) {
89
+ if (!page.sourceHash) continue;
90
+ const slugs = index.fingerprints.get(page.sourceHash) ?? [];
91
+ if (!slugs.includes(entry.slug)) slugs.push(entry.slug);
92
+ index.fingerprints.set(page.sourceHash, slugs);
93
+ }
94
+ }
95
+ return index;
96
+ }
97
+
98
+ /**
99
+ * Uploads a comic's images in order, splitting tall strips, as `pages` items
100
+ * that keep each file's fingerprint.
101
+ *
102
+ * If one fails, the ones already uploaded stay in the media library. They
103
+ * can't safely be deleted: EmDash hands back the existing media item when the
104
+ * same file is uploaded again, so an image may belong to another comic too.
105
+ * A retry reuses them for the same reason.
106
+ */
107
+ export async function uploadPages(
108
+ files: Array<{ file: File; hash?: string | undefined }>,
109
+ onProgress: (message: string) => void,
110
+ ): Promise<PageItem[]> {
111
+ const pages: PageItem[] = [];
112
+ for (const { file, hash } of files) {
113
+ onProgress(`Preparing ${file.name}`);
114
+ for (const part of await splitTallImage(file)) {
115
+ onProgress(`Uploading ${part.name}`);
116
+ const item: UploadedMedia = await uploadMedia(part);
117
+ const page: PageItem = { image: toImageValue(item), alt: "", transcript: "", hovertext: "" };
118
+ if (hash) page.sourceHash = hash;
119
+ pages.push(page);
120
+ }
121
+ }
122
+ return pages;
123
+ }
124
+
125
+ export interface NewComic {
126
+ slug: string;
127
+ title: string;
128
+ series?: string | undefined;
129
+ chapter?: string | undefined;
130
+ number: number | null;
131
+ pages: PageItem[];
132
+ }
133
+
134
+ /** Creates a comic as a draft and returns its ID. */
135
+ export async function createComic(config: ComicCollection, comic: NewComic): Promise<string> {
136
+ const data: Record<string, unknown> = {
137
+ [config.titleField]: comic.title,
138
+ [config.pagesField]: comic.pages,
139
+ };
140
+ if (config.seriesField && comic.series) data[config.seriesField] = comic.series;
141
+ if (config.chapterField && comic.chapter) data[config.chapterField] = comic.chapter;
142
+ if (config.numberField && comic.number !== null) data[config.numberField] = comic.number;
143
+ const item = await createContent(config.collection, { slug: comic.slug, data });
144
+ return item.id;
145
+ }
146
+
147
+ /**
148
+ * Publishes now, or with a past date (backdating, which needs the
149
+ * `content:publish_any` permission). The admin's `publishContent` helper
150
+ * can't send a date, so this calls the same endpoint directly.
151
+ */
152
+ export async function publishComic(
153
+ collection: string,
154
+ id: string,
155
+ publishedAt?: Date,
156
+ ): Promise<void> {
157
+ if (!publishedAt) {
158
+ await publishContent(collection, id);
159
+ return;
160
+ }
161
+ const response = await apiFetch(
162
+ `${API_BASE}/content/${encodeURIComponent(collection)}/${encodeURIComponent(id)}/publish`,
163
+ {
164
+ method: "POST",
165
+ headers: { "Content-Type": "application/json" },
166
+ body: JSON.stringify({ publishedAt: publishedAt.toISOString() }),
167
+ },
168
+ );
169
+ await parseApiResponse(response, "Couldn't publish");
170
+ }
171
+
172
+ export async function scheduleComic(collection: string, id: string, at: Date): Promise<void> {
173
+ await scheduleContent(collection, id, at.toISOString());
174
+ }
175
+
176
+ /** Deletes a trashed entry for good; one that's already gone counts as done. */
177
+ export async function deleteComicForGood(collection: string, id: string): Promise<void> {
178
+ try {
179
+ await permanentDeleteContent(collection, id);
180
+ } catch (cause) {
181
+ if (cause instanceof ApiResponseError && cause.status === 404) return;
182
+ throw cause;
183
+ }
184
+ }
185
+
186
+ /** Moves an entry to the trash; one that's already gone counts as done. */
187
+ export async function trashComic(collection: string, id: string): Promise<void> {
188
+ try {
189
+ await deleteContent(collection, id);
190
+ } catch (cause) {
191
+ if (cause instanceof ApiResponseError && cause.status === 404) return;
192
+ throw cause;
193
+ }
194
+ }
195
+
196
+ const ROUTES = `${API_BASE}/plugins/${PLUGIN_ID}`;
197
+
198
+ /** The collection's recent bulk uploads, newest first. */
199
+ export async function fetchBatches(collection: string): Promise<Batch[]> {
200
+ const response = await apiFetch(`${ROUTES}/batches?${new URLSearchParams({ collection })}`);
201
+ const data = (await parseApiResponse(response, "Couldn't load recent uploads")) as {
202
+ batches?: unknown;
203
+ } | null;
204
+ return parseBatches(data?.batches);
205
+ }
206
+
207
+ /** Records a bulk upload with the comics it has created so far. */
208
+ export async function recordBatch(batch: BatchInput): Promise<void> {
209
+ const response = await apiFetch(`${ROUTES}/save-batch`, {
210
+ method: "POST",
211
+ headers: { "Content-Type": "application/json" },
212
+ body: JSON.stringify(batch),
213
+ });
214
+ await parseApiResponse(response, "Couldn't record the upload");
215
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Finds the comic collections in the admin manifest, and their fields, from
3
+ * the widgets the schema already uses. No plugin options to keep in step.
4
+ */
5
+
6
+ /** The parts of EmDash's admin manifest this reads. */
7
+ export interface ManifestLike {
8
+ timezone?: string | undefined;
9
+ collections: Record<
10
+ string,
11
+ {
12
+ label: string;
13
+ titleField?: string | undefined;
14
+ fields: Record<
15
+ string,
16
+ {
17
+ kind: string;
18
+ type?: string | undefined;
19
+ widget?: string | undefined;
20
+ options?: unknown;
21
+ }
22
+ >;
23
+ }
24
+ >;
25
+ }
26
+
27
+ export interface ComicCollection {
28
+ collection: string;
29
+ label: string;
30
+ titleField: string;
31
+ pagesField: string;
32
+ seriesField?: string | undefined;
33
+ seriesCollection?: string | undefined;
34
+ chapterField?: string | undefined;
35
+ chaptersCollection?: string | undefined;
36
+ numberField?: string | undefined;
37
+ }
38
+
39
+ const PLUGIN = "mm-comics";
40
+
41
+ function optionString(options: unknown, key: string): string | undefined {
42
+ if (!options || typeof options !== "object" || Array.isArray(options)) return undefined;
43
+ const value = (options as Record<string, unknown>)[key];
44
+ return typeof value === "string" && value ? value : undefined;
45
+ }
46
+
47
+ /**
48
+ * Every collection with a field using the comic pages widget. Series and
49
+ * chapter fields are found by their pickers (or the names `series` and
50
+ * `chapter`), the number field by the name `number`.
51
+ */
52
+ export function findComicCollections(manifest: ManifestLike): ComicCollection[] {
53
+ const found: ComicCollection[] = [];
54
+ for (const [collection, info] of Object.entries(manifest.collections)) {
55
+ const fields = Object.entries(info.fields);
56
+ const byWidget = (name: string) =>
57
+ fields.find(([, field]) => field.widget === `${PLUGIN}:${name}`);
58
+ const pages = byWidget("comic-pages");
59
+ if (!pages) continue;
60
+
61
+ const named = (slug: string, kind: string) =>
62
+ fields.find(([name, field]) => name === slug && field.kind === kind);
63
+ const series = byWidget("series") ?? named("series", "string");
64
+ const chapter = byWidget("chapter") ?? named("chapter", "string");
65
+ const number = named("number", "number");
66
+ const existing = (slug: string | undefined) =>
67
+ slug && manifest.collections[slug] ? slug : undefined;
68
+
69
+ const titleField = info.titleField ?? (info.fields.title ? "title" : undefined);
70
+ found.push({
71
+ collection,
72
+ label: info.label,
73
+ titleField: titleField ?? "title",
74
+ pagesField: pages[0],
75
+ seriesField: series?.[0],
76
+ seriesCollection: series
77
+ ? existing(optionString(series[1].options, "collection") ?? "series")
78
+ : undefined,
79
+ chapterField: chapter?.[0],
80
+ chaptersCollection: chapter
81
+ ? existing(optionString(chapter[1].options, "collection") ?? "chapters")
82
+ : undefined,
83
+ numberField: number?.[0],
84
+ });
85
+ }
86
+ return found;
87
+ }
@@ -0,0 +1,76 @@
1
+ /** Collecting image files from pickers and drops, including whole folders. */
2
+ import { tryFingerprint } from "../fingerprint.js";
3
+ import type { SourceFile } from "./plan.js";
4
+
5
+ export interface UploadFile extends SourceFile {
6
+ file: File;
7
+ /** Path inside a picked or dropped folder, else the file name. */
8
+ path: string;
9
+ }
10
+
11
+ const IMAGE_NAME = /\.(png|jpe?g|gif|webp|avif)$/i;
12
+
13
+ export function isImage(file: File): boolean {
14
+ return file.type.startsWith("image/") || IMAGE_NAME.test(file.name);
15
+ }
16
+
17
+ function toUploadFile(file: File, path?: string): UploadFile {
18
+ return { file, name: file.name, path: path || file.webkitRelativePath || file.name };
19
+ }
20
+
21
+ export function fromFileList(list: FileList | File[]): UploadFile[] {
22
+ return [...list].filter(isImage).map((file) => toUploadFile(file));
23
+ }
24
+
25
+ function readFile(entry: FileSystemFileEntry): Promise<File> {
26
+ return new Promise((resolve, reject) => entry.file(resolve, reject));
27
+ }
28
+
29
+ function readBatch(reader: FileSystemDirectoryReader): Promise<FileSystemEntry[]> {
30
+ return new Promise((resolve, reject) => reader.readEntries(resolve, reject));
31
+ }
32
+
33
+ async function walk(entry: FileSystemEntry, out: UploadFile[]): Promise<void> {
34
+ if (entry.isFile) {
35
+ const file = await readFile(entry as FileSystemFileEntry);
36
+ if (isImage(file)) out.push(toUploadFile(file, entry.fullPath.replace(/^\//, "")));
37
+ return;
38
+ }
39
+ if (entry.isDirectory) {
40
+ const reader = (entry as FileSystemDirectoryEntry).createReader();
41
+ // readEntries returns a directory's entries in batches until it's empty.
42
+ for (let batch = await readBatch(reader); batch.length > 0; batch = await readBatch(reader)) {
43
+ for (const child of batch) await walk(child, out);
44
+ }
45
+ }
46
+ }
47
+
48
+ /**
49
+ * The images in a drop, walking into dropped folders. Call it from the drop
50
+ * handler itself: the browser clears the drop's items once the handler ends,
51
+ * so the entries are taken before the first `await`.
52
+ */
53
+ export function filesFromDrop(transfer: DataTransfer): Promise<UploadFile[]> {
54
+ const entries = [...transfer.items]
55
+ .map((item) => (item.kind === "file" ? item.webkitGetAsEntry() : null))
56
+ .filter((entry): entry is FileSystemEntry => entry !== null);
57
+ if (entries.length === 0) return Promise.resolve(fromFileList(transfer.files));
58
+ return (async () => {
59
+ const out: UploadFile[] = [];
60
+ for (const entry of entries) await walk(entry, out);
61
+ return out;
62
+ })();
63
+ }
64
+
65
+ /** Adds each file's fingerprint, reading the files one at a time. */
66
+ export async function fingerprintFiles(
67
+ files: UploadFile[],
68
+ onProgress?: (done: number) => void,
69
+ ): Promise<UploadFile[]> {
70
+ const out: UploadFile[] = [];
71
+ for (const item of files) {
72
+ out.push({ ...item, hash: await tryFingerprint(item.file) });
73
+ onProgress?.(out.length);
74
+ }
75
+ return out;
76
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Recent bulk uploads, as the plugin's `batches` route returns them (see
3
+ * ../../batches.ts), and what has become of their comics since.
4
+ */
5
+ import type { Batch, BatchEntry } from "../../batches.js";
6
+
7
+ export type { Batch, BatchEntry };
8
+
9
+ function isEntry(value: unknown): value is BatchEntry {
10
+ if (!value || typeof value !== "object") return false;
11
+ const entry = value as Partial<BatchEntry>;
12
+ return typeof entry.id === "string" && typeof entry.title === "string";
13
+ }
14
+
15
+ function isBatch(value: unknown): value is Batch {
16
+ if (!value || typeof value !== "object") return false;
17
+ const batch = value as Partial<Batch>;
18
+ return (
19
+ typeof batch.id === "string" &&
20
+ typeof batch.collection === "string" &&
21
+ typeof batch.createdAt === "string" &&
22
+ typeof batch.by?.id === "string" &&
23
+ Array.isArray(batch.entries) &&
24
+ batch.entries.every(isEntry)
25
+ );
26
+ }
27
+
28
+ /** Reads the route's `batches`, dropping anything malformed. */
29
+ export function parseBatches(value: unknown): Batch[] {
30
+ return Array.isArray(value) ? value.filter(isBatch) : [];
31
+ }
32
+
33
+ /** Where an entry is now. Entries deleted for good are in neither state. */
34
+ export type EntryState = "live" | "trashed";
35
+
36
+ /** A batch's comics that are still live, and those in the trash. */
37
+ export function batchStatus(
38
+ batch: Batch,
39
+ states: ReadonlyMap<string, EntryState>,
40
+ ): { live: BatchEntry[]; trashed: BatchEntry[] } {
41
+ return {
42
+ live: batch.entries.filter((entry) => states.get(entry.id) === "live"),
43
+ trashed: batch.entries.filter((entry) => states.get(entry.id) === "trashed"),
44
+ };
45
+ }