feat: run book uploads in a background tray

One request per book instead of one for everything, queued in state above the
dialog so closing it no longer cancels the import. A docked tray reports each
book and offers a retry; it clears itself after a clean run, stays put if
anything failed, and holds while hovered.

Also fixes the dialog overflowing on long filenames — Dialog.Content is a grid
and its body needed min-w-0 to shrink below the content's intrinsic width.
This commit is contained in:
2026-08-12 13:42:40 -04:00
parent d4bdb5ed42
commit 96789620bb
4 changed files with 530 additions and 174 deletions
@@ -1,54 +1,31 @@
<script lang="ts">
import { untrack } from 'svelte';
import { goto } from '$app/navigation';
import { resolve } from '$app/paths';
import { X } from '@lucide/svelte';
import * as Dialog from '$lib/components/ui/dialog/index.js';
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 { Button } from '$lib/components/ui/button';
import { Switch } from '$lib/components/ui/switch/index';
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, untrack } from 'svelte';
import { Spinner } from '$lib/components/ui/spinner/index';
import { getLibraryState } from '$lib/state/library.svelte';
import { uploadBooks } from '$lib/api';
import type { Book, PaginatedResponse } from '$lib/schema';
import { goto } from '$app/navigation';
import { getUploadQueueState } from '$lib/state/upload-queue.svelte';
let { open = $bindable() }: { open?: boolean } = $props();
let libraryState = getLibraryState();
$effect(() => {
uploadBooks.fields.library_id.set(libraryState.activeLibrary!.id);
});
// 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));
const libraryState = getLibraryState();
const queue = getUploadQueueState();
let libraryId = $state<number>(untrack(() => libraryState.activeLibrary!.id));
let files = $state<File[]>([]);
let autoUploadOnDrop = $state(true);
let navigateOnUpload = $state(true);
let formEl = $state<HTMLFormElement>();
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 })
);
uploadBooks.fields.files.set([...Array.from(files), ...renamedFiles]);
if (autoUploadOnDrop && files.length > 0) {
await tick();
formEl?.requestSubmit();
}
};
const totalSize = $derived(files.reduce((sum, file) => sum + file.size, 0));
/**
* Collected rather than raised one at a time. A folder of a few hundred books
@@ -58,173 +35,197 @@
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.
// Start each visit clean — a list left over from last time reads as though it
// applies to what was just chosen.
$effect(() => {
if (open) {
untrack(() => {
files = [];
rejected = [];
showRejected = false;
libraryId = libraryState.activeLibrary!.id;
});
}
});
function navigateToBooks(books: PaginatedResponse<Book>) {
const onUpload = async (uploadedFiles: File[]) => {
// Rename to the path relative to the chosen folder, which is what decides
// how the API groups files into books. Dropped folders already arrive named
// this way, since the drop zone builds the path while walking them.
const named = uploadedFiles.map(
(file) => new File([file], file.webkitRelativePath || file.name, { type: file.type })
);
// Same relative path twice is the same file — dropping a folder a second
// time should not queue everything again.
const seen = new Set(files.map((file) => file.name));
files = [...files, ...named.filter((file) => !seen.has(file.name))];
if (autoUploadOnDrop) await startUpload();
};
const onFileRejected = ({ reason, file }: { reason: FileRejectedReason; file: File }) => {
rejected = [...rejected, { name: file.webkitRelativePath || file.name, reason }];
};
/**
* Files picked from a folder carry their whole relative path as the name, so
* truncating the end would cut off the filename — the only part worth reading.
* Split it and let the folder sit on its own, quieter line.
*/
function splitPath(path: string) {
const cut = path.lastIndexOf('/');
return cut === -1
? { dir: '', name: path }
: { dir: path.slice(0, cut), name: path.slice(cut + 1) };
}
/**
* Hands the books to the queue and closes.
*
* Nothing is awaited here: the queue lives in the root layout and reports
* through the tray, so the import carries on while the library stays usable.
*/
function startUpload() {
if (files.length === 0) return;
const queued = files;
const target = libraryId;
files = [];
rejected = [];
open = false;
let libraryId = books.items[0].library_id;
libraryState.setActive(libraryId);
if (books.items.length === 1) {
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)
});
// eslint-disable-next-line svelte/no-navigation-without-resolve
goto(`${view}?orderBy=created_at&sortOrder=desc`);
}
queue.enqueue(target, queued, ({ created, firstBook }) => {
if (created === 0) return;
const library = libraryState.libraries.find((lib) => lib.id === target);
if (library) library.total = (library.total ?? 0) + created;
// Only for a single book. Jumping somewhere after a bulk import would
// land minutes after the reader moved on.
if (navigateOnUpload && created === 1 && firstBook) {
libraryState.setActive(target);
void goto(resolve('/(root)/(library)/book/[bookId]', { bookId: String(firstBook.id) }));
}
});
}
</script>
<Dialog.Root bind:open>
<Dialog.Content>
{#if uploadBooks.pending}
<div class="flex flex-col items-center gap-4">
<span class="text-lg font-semibold"
>Uploading {uploadBooks.fields.files.value().length} files...</span
>
<Spinner class="scale-150" />
</div>
{:else}
<Dialog.Header>
<Dialog.Title>Upload Books</Dialog.Title>
</Dialog.Header>
<!--
Wider than the default lg: a folder's worth of rows needs the room.
<form
{...uploadBooks.enhance(async ({ submit }) => {
try {
await submit();
overflow-hidden and the min-w-0 on the body below are what keep a long
filename inside the dialog. Dialog.Content is a grid, and grid and flex
items default to min-width:auto — they refuse to shrink below their
content's intrinsic width, so one long name widened the body and pushed it
straight through the dialog's edge regardless of any truncate further down.
-->
<Dialog.Content class="overflow-hidden sm:max-w-2xl">
<Dialog.Header>
<Dialog.Title>Add books</Dialog.Title>
<Dialog.Description>
Files or a folder. A folder becomes one book per directory.
</Dialog.Description>
</Dialog.Header>
// Check if there are any validation issues
const issues = uploadBooks.fields.allIssues();
if (issues && issues.length > 0) {
return;
}
// Update library book count
const count = uploadBooks.result.total;
libraryState.libraries.find(
(lib) => uploadBooks.fields.library_id.value() == lib.id.toString()
)!.total += count;
// Reset the files field
uploadBooks.fields.files.set([]);
rejected = [];
toast.success('Books successfully uploaded!');
if (navigateOnUpload) {
navigateToBooks(uploadBooks.result);
}
} catch (error) {
console.error('Failed to upload book: ', error);
toast.error('Failed to upload books');
}
})}
bind:this={formEl}
enctype="multipart/form-data"
class="flex w-full flex-col gap-2 p-4"
>
<!-- Library select field -->
<Field.Label for="library_id">Select Library</Field.Label>
<NativeSelect.Root {...uploadBooks.fields.library_id.as('select')} class="w-36">
<div class="flex w-full min-w-0 flex-col gap-3">
<div class="flex flex-col gap-1.5">
<Field.Label for="library_id">Library</Field.Label>
<NativeSelect.Root id="library_id" bind:value={libraryId} class="w-48">
{#each libraryState.libraries as library (library.id)}
<NativeSelect.Option value={library.id}>
{library.name}
</NativeSelect.Option>
<NativeSelect.Option value={library.id}>{library.name}</NativeSelect.Option>
{/each}
</NativeSelect.Root>
</div>
<BookDropZone
{onUpload}
{onFileRejected}
accept=".pdf,.epub,.mobi,application/pdf,application/epub+zip,application/x-mobipocket-ebook"
/>
<input class="hidden" {...uploadBooks.fields.files.as('file multiple')} />
<BookDropZone
{onUpload}
{onFileRejected}
accept=".pdf,.epub,.mobi,application/pdf,application/epub+zip,application/x-mobipocket-ebook"
/>
{#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 (file.name)}
<div class="flex place-items-center justify-between gap-2">
<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),
...Array.from(files).slice(idx + 1)
]);
}}
>
<X />
<span class="sr-only">Remove {file.name}</span>
</Button>
</div>
{/each}
{#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}
{#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
<div class="flex max-h-[300px] min-w-0 flex-col gap-2 overflow-y-auto">
{#each files as file, idx (file.name)}
{@const location = splitPath(file.name)}
<div class="flex min-w-0 items-center justify-between gap-2">
<!-- flex-1 as well as min-w-0: without a constrained width there is
nothing for truncate to act against and the row pushes the dialog wide -->
<div class="flex min-w-0 flex-1 flex-col">
<span class="truncate text-sm" title={file.name}>{location.name}</span>
<span class="flex min-w-0 items-baseline gap-2 text-xs text-muted-foreground">
{#if location.dir}
<span class="truncate font-mono" title={location.dir}>{location.dir}</span>
{/if}
<span class="shrink-0 tabular-nums">{displaySize(file.size)}</span>
</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}
<Button
variant="outline"
size="icon"
class="shrink-0"
onclick={() => (files = files.filter((_, i) => i !== idx))}
>
<X />
<span class="sr-only">Remove {file.name}</span>
</Button>
</div>
{/if}
{/each}
</div>
<div class="flex flex-col gap-2">
<div class="flex items-center gap-2">
<Switch bind:checked={autoUploadOnDrop} />
<Field.Label for="auto-upload-on-drop">Auto upload on file drop</Field.Label>
<Button type="submit" class="ml-auto w-fit">Upload</Button>
</div>
<div class="flex items-center gap-2">
<Switch bind:checked={navigateOnUpload} />
<Field.Label for="navigate-to-book">Navigate to book on upload</Field.Label>
{#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 min-w-0 flex-col gap-1 overflow-y-auto">
{#each rejected as entry (entry.name)}
<li class="flex min-w-0 justify-between gap-2 text-xs text-muted-foreground">
<span class="min-w-0 flex-1 truncate" title={entry.name}>
{splitPath(entry.name).name}
</span>
<span class="shrink-0">{entry.reason}</span>
</li>
{/each}
</ul>
{/if}
</div>
</form>
{/if}
{/if}
<div class="flex flex-col gap-2 border-t pt-3">
<div class="flex items-center gap-2">
<Switch id="auto-upload-on-drop" bind:checked={autoUploadOnDrop} />
<Field.Label for="auto-upload-on-drop" class="font-normal">
Start as soon as books are added
</Field.Label>
<Button class="ml-auto w-fit" disabled={files.length === 0} onclick={startUpload}>
Upload
</Button>
</div>
<div class="flex items-center gap-2">
<Switch id="navigate-to-book" bind:checked={navigateOnUpload} />
<Field.Label for="navigate-to-book" class="font-normal">
Open the book when a single one is added
</Field.Label>
</div>
</div>
</div>
</Dialog.Content>
</Dialog.Root>