feat: accept files and folders when uploading books

The picker could only choose folders: webkitdirectory switches the OS dialog
into folder mode rather than filtering, so one input cannot offer both. Adds
a drop zone with two browse buttons behind two inputs.

Dropping a folder never worked either — dataTransfer.files does not descend
into directories, so it arrived as one typeless entry and was rejected. Walks
dataTransfer.items instead.

Also collects skipped files into one expandable line rather than a toast each,
which a folder of covers and notes made unusable, and shows the file count and
total size before uploading.
This commit is contained in:
2026-08-12 12:04:14 -04:00
parent 5f2d68694d
commit d4bdb5ed42
2 changed files with 302 additions and 20 deletions
@@ -0,0 +1,223 @@
<script lang="ts">
import { FileUp, Folder, FileText } from '@lucide/svelte';
import { Button } from '$lib/components/ui/button/index.js';
import type { FileRejectedReason } from '$lib/components/ui/file-drop-zone';
import { cn } from '$lib/utils';
let {
onUpload,
onFileRejected,
accept,
maxFileSize,
disabled = false,
class: className
}: {
onUpload: (files: File[]) => Promise<void> | void;
onFileRejected?: (opts: { reason: FileRejectedReason; file: File }) => void;
/** Comma separated extensions and/or MIME types, as the `accept` attribute takes. */
accept?: string;
/** Bytes. */
maxFileSize?: number;
disabled?: boolean;
class?: string;
} = $props();
/**
* Two inputs rather than one.
*
* `webkitdirectory` is not a filter — it switches the picker into folder mode,
* so a single input can offer files or folders but never both. The drop target
* has no such constraint and stays one area.
*/
let fileInput = $state<HTMLInputElement>();
let folderInput = $state<HTMLInputElement>();
let dragging = $state(false);
let busy = $state(false);
const active = $derived(!disabled && !busy);
function accepts(file: File): FileRejectedReason | undefined {
if (maxFileSize !== undefined && file.size > maxFileSize) return 'Maximum file size exceeded';
if (!accept) return undefined;
const name = file.name.toLowerCase();
const type = file.type.toLowerCase();
const ok = accept
.split(',')
.map((pattern) => pattern.trim().toLowerCase())
.some((pattern) => {
// Match on the pattern, not the file's type. Testing `type` here is
// what makes MOBI fail: browsers report no MIME type for it, so a
// ".mobi" rule never gets compared against the filename.
if (pattern.startsWith('.')) return name.endsWith(pattern);
if (pattern.endsWith('/*')) return type.startsWith(pattern.slice(0, -1));
return type === pattern;
});
return ok ? undefined : 'File type not allowed';
}
/** readEntries hands back at most 100 at a time and signals the end with an empty batch. */
function readAll(reader: FileSystemDirectoryReader): Promise<FileSystemEntry[]> {
return new Promise((resolve, reject) => {
const entries: FileSystemEntry[] = [];
const next = () =>
reader.readEntries((batch) => {
if (batch.length === 0) return resolve(entries);
entries.push(...batch);
next();
}, reject);
next();
});
}
/**
* Flattens a dropped entry into files, naming each one with its path inside the
* dropped folder so it matches what the folder picker puts in
* `webkitRelativePath` — which is what the upload form reads to keep structure.
*/
async function walk(entry: FileSystemEntry, prefix = ''): Promise<File[]> {
if (entry.isFile) {
const file = await new Promise<File>((resolve, reject) =>
(entry as FileSystemFileEntry).file(resolve, reject)
);
return [new File([file], `${prefix}${file.name}`, { type: file.type })];
}
if (entry.isDirectory) {
const entries = await readAll((entry as FileSystemDirectoryEntry).createReader());
const nested = await Promise.all(entries.map((e) => walk(e, `${prefix}${entry.name}/`)));
return nested.flat();
}
return [];
}
async function handleDrop(event: DragEvent) {
event.preventDefault();
dragging = false;
if (!active) return;
// Read the entries synchronously: DataTransfer is emptied as soon as this
// handler yields, so awaiting first loses everything that was dropped.
const entries = Array.from(event.dataTransfer?.items ?? [])
.filter((item) => item.kind === 'file')
.map((item) => item.webkitGetAsEntry())
.filter((entry): entry is FileSystemEntry => entry !== null);
// Older engines expose no entries; fall back to the flat list, which cannot
// contain folders anyway.
if (entries.length === 0) {
await submit(Array.from(event.dataTransfer?.files ?? []));
return;
}
busy = true;
try {
const nested = await Promise.all(entries.map((entry) => walk(entry)));
await submit(nested.flat());
} finally {
busy = false;
}
}
async function handleChange(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const chosen = Array.from(input.files ?? []);
// Reset first so picking the same file twice still fires a change event.
input.value = '';
await submit(chosen);
}
async function submit(candidates: File[]) {
const accepted: File[] = [];
for (const file of candidates) {
const reason = accepts(file);
if (reason) onFileRejected?.({ file, reason });
else accepted.push(file);
}
if (accepted.length > 0) await onUpload(accepted);
}
</script>
<div
role="group"
aria-label="Add books"
aria-disabled={!active}
ondragover={(e) => {
e.preventDefault();
if (active) dragging = true;
}}
ondragleave={() => (dragging = false)}
ondrop={handleDrop}
class={cn(
'flex flex-col items-center gap-3 rounded-lg border-2 border-dashed border-border bg-accent/20 p-6 text-center transition-colors',
dragging && 'border-primary bg-accent/50',
!active && 'opacity-50',
className
)}
>
<div
class="flex size-12 place-items-center justify-center rounded-full border border-dashed border-border text-muted-foreground"
>
<FileUp class="size-5" />
</div>
<div class="flex flex-col gap-0.5">
<span class="font-medium">
{busy ? 'Reading folder…' : 'Drop books here'}
</span>
<span class="text-sm text-muted-foreground">A folder keeps its structure</span>
</div>
<span class="font-mono text-[10px] tracking-widest text-muted-foreground uppercase">or</span>
<div class="flex flex-wrap justify-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
disabled={!active}
onclick={() => fileInput?.click()}
>
<FileText class="size-4" />
Choose files
</Button>
<Button
type="button"
variant="outline"
size="sm"
disabled={!active}
onclick={() => folderInput?.click()}
>
<Folder class="size-4" />
Choose folder
</Button>
</div>
<input
bind:this={fileInput}
type="file"
multiple
{accept}
class="hidden"
onchange={handleChange}
/>
<!-- webkitdirectory is why this needs to be a second input: it turns the
picker into a folder chooser rather than filtering what it accepts. -->
<input
bind:this={folderInput}
type="file"
multiple
webkitdirectory
class="hidden"
onchange={handleChange}
/>
</div>
@@ -4,17 +4,14 @@
import * as Field from '$lib/components/ui/field/index.js';
import { Button } from '$lib/components/ui/button';
import * as NativeSelect from '$lib/components/ui/native-select/index.js';
import {
displaySize,
FileDropZone,
type FileDropZoneProps
} from '$lib/components/ui/file-drop-zone';
import { displaySize, type FileRejectedReason } from '$lib/components/ui/file-drop-zone';
import BookDropZone from './book-drop-zone.svelte';
import { X } from '@lucide/svelte';
import { toast } from 'svelte-sonner';
import { Switch } from '$lib/components/ui/switch/index';
import { tick } from 'svelte';
import { tick, untrack } from 'svelte';
import { Spinner } from '$lib/components/ui/spinner/index';
import { getLibraryState } from '$lib/state/library.svelte';
import { uploadBooks } from '$lib/api';
@@ -29,14 +26,20 @@
uploadBooks.fields.library_id.set(libraryState.activeLibrary!.id);
});
let files = $derived(uploadBooks.fields.files.value() ?? []);
// Narrowed once here rather than asserted at each use in the markup.
let files = $derived(
(uploadBooks.fields.files.value() ?? []).filter((file): file is File => Boolean(file))
);
let totalSize = $derived(files.reduce((sum, file) => sum + file.size, 0));
let autoUploadOnDrop = $state(true);
let navigateOnUpload = $state(true);
let formEl = $state<HTMLFormElement>();
const onUpload: FileDropZoneProps['onUpload'] = async (uploadedFiles) => {
// Rename files to use webkitRelativePath so directory structure is preserved through form submission
const onUpload = async (uploadedFiles: File[]) => {
// Rename files to use webkitRelativePath so directory structure is preserved
// through form submission. Dropped folders already arrive named that way,
// since the drop zone builds the path while walking them.
const renamedFiles = uploadedFiles.map(
(f) => new File([f], f.webkitRelativePath || f.name, { type: f.type })
);
@@ -47,10 +50,29 @@
}
};
const onFileRejected: FileDropZoneProps['onFileRejected'] = async ({ reason, file }) => {
toast.error(`${file.name} failed to upload!`, { description: reason });
/**
* Collected rather than raised one at a time. A folder of a few hundred books
* carries covers and notes alongside them, and a toast per rejected file
* buries the screen.
*/
let rejected = $state<{ name: string; reason: FileRejectedReason }[]>([]);
let showRejected = $state(false);
const onFileRejected = ({ reason, file }: { reason: FileRejectedReason; file: File }) => {
rejected = [...rejected, { name: file.webkitRelativePath || file.name, reason }];
};
// Start each visit clean — a skipped-files list left over from last time reads
// as though it applies to what was just chosen.
$effect(() => {
if (open) {
untrack(() => {
rejected = [];
showRejected = false;
});
}
});
function navigateToBooks(books: PaginatedResponse<Book>) {
open = false;
let libraryId = books.items[0].library_id;
@@ -59,7 +81,9 @@
goto(resolve('/(root)/(library)/book/[bookId]', { bookId: String(books.items[0].id) }));
} else {
// The path is resolved; the query string is what the rule cannot see past.
const view = resolve('/(root)/(library)/library/[libraryId]/view', { libraryId: String(libraryId) });
const view = resolve('/(root)/(library)/library/[libraryId]/view', {
libraryId: String(libraryId)
});
// eslint-disable-next-line svelte/no-navigation-without-resolve
goto(`${view}?orderBy=created_at&sortOrder=desc`);
}
@@ -81,7 +105,7 @@
</Dialog.Header>
<form
{...uploadBooks.enhance(async ({ submit, form }) => {
{...uploadBooks.enhance(async ({ submit }) => {
try {
await submit();
@@ -99,6 +123,7 @@
// Reset the files field
uploadBooks.fields.files.set([]);
rejected = [];
toast.success('Books successfully uploaded!');
if (navigateOnUpload) {
@@ -116,31 +141,40 @@
<!-- Library select field -->
<Field.Label for="library_id">Select Library</Field.Label>
<NativeSelect.Root {...uploadBooks.fields.library_id.as('select')} class="w-36">
{#each libraryState.libraries as library}
{#each libraryState.libraries as library (library.id)}
<NativeSelect.Option value={library.id}>
{library.name}
</NativeSelect.Option>
{/each}
</NativeSelect.Root>
<FileDropZone
<BookDropZone
{onUpload}
{onFileRejected}
directory={true}
accept=".pdf,.epub,.mobi,application/pdf,application/epub+zip,application/x-mobipocket-ebook"
sublabel="Only PDF, EPUB, and MOBI files supported"
/>
<input class="hidden" {...uploadBooks.fields.files.as('file multiple')} />
{#if files.length > 0}
<div class="flex items-baseline justify-between border-b pb-1 text-sm">
<span><strong class="tabular-nums">{files.length}</strong> ready to upload</span>
<span class="font-mono text-xs text-muted-foreground tabular-nums">
{displaySize(totalSize)}
</span>
</div>
{/if}
<div class="flex max-h-[300px] flex-col gap-2 overflow-y-auto">
{#each files as file, idx}
{#each files as file, idx (file.name)}
<div class="flex place-items-center justify-between gap-2">
<div class="flex flex-col">
<span>{file.name}</span>
<div class="flex min-w-0 flex-col">
<span class="truncate" title={file.name}>{file.name}</span>
<span class="text-xs text-muted-foreground">{displaySize(file.size)}</span>
</div>
<Button
variant="outline"
size="icon"
class="shrink-0"
onclick={() => {
uploadBooks.fields.files.set([
...Array.from(files).slice(0, idx),
@@ -149,11 +183,36 @@
}}
>
<X />
<span class="sr-only">Remove {file.name}</span>
</Button>
</div>
{/each}
</div>
{#if rejected.length > 0}
<div class="rounded-md border border-star/50 bg-star/10 p-2 text-sm">
<div class="flex items-center justify-between gap-2">
<span>
{rejected.length}
{rejected.length === 1 ? 'file was' : 'files were'} skipped
</span>
<Button variant="ghost" size="sm" onclick={() => (showRejected = !showRejected)}>
{showRejected ? 'Hide' : 'Show'}
</Button>
</div>
{#if showRejected}
<ul class="mt-2 flex max-h-32 flex-col gap-1 overflow-y-auto">
{#each rejected as entry (entry.name)}
<li class="flex justify-between gap-2 text-xs text-muted-foreground">
<span class="truncate" title={entry.name}>{entry.name}</span>
<span class="shrink-0">{entry.reason}</span>
</li>
{/each}
</ul>
{/if}
</div>
{/if}
<div class="flex flex-col gap-2">
<div class="flex items-center gap-2">
<Switch bind:checked={autoUploadOnDrop} />