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:
@@ -1,54 +1,31 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { untrack } from 'svelte';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
|
import { X } from '@lucide/svelte';
|
||||||
|
|
||||||
import * as Dialog from '$lib/components/ui/dialog/index.js';
|
import * as Dialog from '$lib/components/ui/dialog/index.js';
|
||||||
import * as Field from '$lib/components/ui/field/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 * 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 { displaySize, type FileRejectedReason } from '$lib/components/ui/file-drop-zone';
|
||||||
import BookDropZone from './book-drop-zone.svelte';
|
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 { getLibraryState } from '$lib/state/library.svelte';
|
||||||
import { uploadBooks } from '$lib/api';
|
import { getUploadQueueState } from '$lib/state/upload-queue.svelte';
|
||||||
import type { Book, PaginatedResponse } from '$lib/schema';
|
|
||||||
import { goto } from '$app/navigation';
|
|
||||||
|
|
||||||
let { open = $bindable() }: { open?: boolean } = $props();
|
let { open = $bindable() }: { open?: boolean } = $props();
|
||||||
|
|
||||||
let libraryState = getLibraryState();
|
const libraryState = getLibraryState();
|
||||||
|
const queue = getUploadQueueState();
|
||||||
$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));
|
|
||||||
|
|
||||||
|
let libraryId = $state<number>(untrack(() => libraryState.activeLibrary!.id));
|
||||||
|
let files = $state<File[]>([]);
|
||||||
let autoUploadOnDrop = $state(true);
|
let autoUploadOnDrop = $state(true);
|
||||||
let navigateOnUpload = $state(true);
|
let navigateOnUpload = $state(true);
|
||||||
let formEl = $state<HTMLFormElement>();
|
|
||||||
|
|
||||||
const onUpload = async (uploadedFiles: File[]) => {
|
const totalSize = $derived(files.reduce((sum, file) => sum + file.size, 0));
|
||||||
// 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();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Collected rather than raised one at a time. A folder of a few hundred books
|
* 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 rejected = $state<{ name: string; reason: FileRejectedReason }[]>([]);
|
||||||
let showRejected = $state(false);
|
let showRejected = $state(false);
|
||||||
|
|
||||||
const onFileRejected = ({ reason, file }: { reason: FileRejectedReason; file: File }) => {
|
// Start each visit clean — a list left over from last time reads as though it
|
||||||
rejected = [...rejected, { name: file.webkitRelativePath || file.name, reason }];
|
// applies to what was just chosen.
|
||||||
};
|
|
||||||
|
|
||||||
// Start each visit clean — a skipped-files list left over from last time reads
|
|
||||||
// as though it applies to what was just chosen.
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (open) {
|
if (open) {
|
||||||
untrack(() => {
|
untrack(() => {
|
||||||
|
files = [];
|
||||||
rejected = [];
|
rejected = [];
|
||||||
showRejected = false;
|
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;
|
open = false;
|
||||||
let libraryId = books.items[0].library_id;
|
|
||||||
libraryState.setActive(libraryId);
|
queue.enqueue(target, queued, ({ created, firstBook }) => {
|
||||||
if (books.items.length === 1) {
|
if (created === 0) return;
|
||||||
goto(resolve('/(root)/(library)/book/[bookId]', { bookId: String(books.items[0].id) }));
|
|
||||||
} else {
|
const library = libraryState.libraries.find((lib) => lib.id === target);
|
||||||
// The path is resolved; the query string is what the rule cannot see past.
|
if (library) library.total = (library.total ?? 0) + created;
|
||||||
const view = resolve('/(root)/(library)/library/[libraryId]/view', {
|
|
||||||
libraryId: String(libraryId)
|
// Only for a single book. Jumping somewhere after a bulk import would
|
||||||
});
|
// land minutes after the reader moved on.
|
||||||
// eslint-disable-next-line svelte/no-navigation-without-resolve
|
if (navigateOnUpload && created === 1 && firstBook) {
|
||||||
goto(`${view}?orderBy=created_at&sortOrder=desc`);
|
libraryState.setActive(target);
|
||||||
}
|
void goto(resolve('/(root)/(library)/book/[bookId]', { bookId: String(firstBook.id) }));
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Dialog.Root bind:open>
|
<Dialog.Root bind:open>
|
||||||
<Dialog.Content>
|
<!--
|
||||||
{#if uploadBooks.pending}
|
Wider than the default lg: a folder's worth of rows needs the room.
|
||||||
<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>
|
|
||||||
|
|
||||||
<form
|
overflow-hidden and the min-w-0 on the body below are what keep a long
|
||||||
{...uploadBooks.enhance(async ({ submit }) => {
|
filename inside the dialog. Dialog.Content is a grid, and grid and flex
|
||||||
try {
|
items default to min-width:auto — they refuse to shrink below their
|
||||||
await submit();
|
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
|
<div class="flex w-full min-w-0 flex-col gap-3">
|
||||||
const issues = uploadBooks.fields.allIssues();
|
<div class="flex flex-col gap-1.5">
|
||||||
if (issues && issues.length > 0) {
|
<Field.Label for="library_id">Library</Field.Label>
|
||||||
return;
|
<NativeSelect.Root id="library_id" bind:value={libraryId} class="w-48">
|
||||||
}
|
|
||||||
|
|
||||||
// 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">
|
|
||||||
{#each libraryState.libraries as library (library.id)}
|
{#each libraryState.libraries as library (library.id)}
|
||||||
<NativeSelect.Option value={library.id}>
|
<NativeSelect.Option value={library.id}>{library.name}</NativeSelect.Option>
|
||||||
{library.name}
|
|
||||||
</NativeSelect.Option>
|
|
||||||
{/each}
|
{/each}
|
||||||
</NativeSelect.Root>
|
</NativeSelect.Root>
|
||||||
|
</div>
|
||||||
|
|
||||||
<BookDropZone
|
<BookDropZone
|
||||||
{onUpload}
|
{onUpload}
|
||||||
{onFileRejected}
|
{onFileRejected}
|
||||||
accept=".pdf,.epub,.mobi,application/pdf,application/epub+zip,application/x-mobipocket-ebook"
|
accept=".pdf,.epub,.mobi,application/pdf,application/epub+zip,application/x-mobipocket-ebook"
|
||||||
/>
|
/>
|
||||||
<input class="hidden" {...uploadBooks.fields.files.as('file multiple')} />
|
|
||||||
|
|
||||||
{#if files.length > 0}
|
{#if files.length > 0}
|
||||||
<div class="flex items-baseline justify-between border-b pb-1 text-sm">
|
<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><strong class="tabular-nums">{files.length}</strong> ready to upload</span>
|
||||||
<span class="font-mono text-xs text-muted-foreground tabular-nums">
|
<span class="font-mono text-xs text-muted-foreground tabular-nums">
|
||||||
{displaySize(totalSize)}
|
{displaySize(totalSize)}
|
||||||
</span>
|
</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}
|
|
||||||
</div>
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
{#if rejected.length > 0}
|
<div class="flex max-h-[300px] min-w-0 flex-col gap-2 overflow-y-auto">
|
||||||
<div class="rounded-md border border-star/50 bg-star/10 p-2 text-sm">
|
{#each files as file, idx (file.name)}
|
||||||
<div class="flex items-center justify-between gap-2">
|
{@const location = splitPath(file.name)}
|
||||||
<span>
|
<div class="flex min-w-0 items-center justify-between gap-2">
|
||||||
{rejected.length}
|
<!-- flex-1 as well as min-w-0: without a constrained width there is
|
||||||
{rejected.length === 1 ? 'file was' : 'files were'} skipped
|
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>
|
</span>
|
||||||
<Button variant="ghost" size="sm" onclick={() => (showRejected = !showRejected)}>
|
|
||||||
{showRejected ? 'Hide' : 'Show'}
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
{#if showRejected}
|
<Button
|
||||||
<ul class="mt-2 flex max-h-32 flex-col gap-1 overflow-y-auto">
|
variant="outline"
|
||||||
{#each rejected as entry (entry.name)}
|
size="icon"
|
||||||
<li class="flex justify-between gap-2 text-xs text-muted-foreground">
|
class="shrink-0"
|
||||||
<span class="truncate" title={entry.name}>{entry.name}</span>
|
onclick={() => (files = files.filter((_, i) => i !== idx))}
|
||||||
<span class="shrink-0">{entry.reason}</span>
|
>
|
||||||
</li>
|
<X />
|
||||||
{/each}
|
<span class="sr-only">Remove {file.name}</span>
|
||||||
</ul>
|
</Button>
|
||||||
{/if}
|
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/each}
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-col gap-2">
|
{#if rejected.length > 0}
|
||||||
<div class="flex items-center gap-2">
|
<div class="rounded-md border border-star/50 bg-star/10 p-2 text-sm">
|
||||||
<Switch bind:checked={autoUploadOnDrop} />
|
<div class="flex items-center justify-between gap-2">
|
||||||
<Field.Label for="auto-upload-on-drop">Auto upload on file drop</Field.Label>
|
<span>
|
||||||
<Button type="submit" class="ml-auto w-fit">Upload</Button>
|
{rejected.length}
|
||||||
</div>
|
{rejected.length === 1 ? 'file was' : 'files were'} skipped
|
||||||
<div class="flex items-center gap-2">
|
</span>
|
||||||
<Switch bind:checked={navigateOnUpload} />
|
<Button variant="ghost" size="sm" onclick={() => (showRejected = !showRejected)}>
|
||||||
<Field.Label for="navigate-to-book">Navigate to book on upload</Field.Label>
|
{showRejected ? 'Hide' : 'Show'}
|
||||||
|
</Button>
|
||||||
</div>
|
</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>
|
</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.Content>
|
||||||
</Dialog.Root>
|
</Dialog.Root>
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { fly } from 'svelte/transition';
|
||||||
|
import { prefersReducedMotion } from 'svelte/motion';
|
||||||
|
import { ChevronDown, CircleAlert, RotateCcw, X } from '@lucide/svelte';
|
||||||
|
|
||||||
|
import { Button } from '$lib/components/ui/button/index.js';
|
||||||
|
import { Spinner } from '$lib/components/ui/spinner/index';
|
||||||
|
import { getUploadQueueState } from '$lib/state/upload-queue.svelte';
|
||||||
|
import { formatFileSize } from '$lib/utils';
|
||||||
|
|
||||||
|
const queue = getUploadQueueState();
|
||||||
|
|
||||||
|
// A clean run clears itself after a few seconds, so it needs to leave rather
|
||||||
|
// than blink out. Nothing to animate for anyone who asked not to see it.
|
||||||
|
const motion = $derived(prefersReducedMotion.current ? 0 : 200);
|
||||||
|
|
||||||
|
const percent = $derived(queue.total === 0 ? 0 : Math.round((queue.settled / queue.total) * 100));
|
||||||
|
|
||||||
|
const heading = $derived.by(() => {
|
||||||
|
const noun = queue.total === 1 ? 'book' : 'books';
|
||||||
|
if (queue.active) return `Adding ${queue.settled} of ${queue.total} ${noun}`;
|
||||||
|
if (queue.failed === 0) return `Added ${queue.done} ${noun}`;
|
||||||
|
if (queue.done === 0) return `Couldn't add ${queue.failed} ${noun}`;
|
||||||
|
return `Added ${queue.done}, ${queue.failed} failed`;
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
{#if queue.total > 0}
|
||||||
|
<!--
|
||||||
|
Docked rather than a toast. This runs for minutes and carries a row per
|
||||||
|
book, which a notification surface is not built to hold still for.
|
||||||
|
-->
|
||||||
|
<aside
|
||||||
|
aria-label="Uploads"
|
||||||
|
transition:fly={{ y: 12, duration: motion }}
|
||||||
|
onmouseenter={() => queue.hold()}
|
||||||
|
onmouseleave={() => queue.release()}
|
||||||
|
onfocusin={() => queue.hold()}
|
||||||
|
onfocusout={() => queue.release()}
|
||||||
|
class="fixed right-4 bottom-4 z-50 w-80 max-w-[calc(100vw-2rem)] overflow-hidden rounded-lg border bg-card shadow-lg"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2 border-b px-3 py-2">
|
||||||
|
{#if queue.active}
|
||||||
|
<Spinner class="size-4 shrink-0" />
|
||||||
|
{:else if queue.failed > 0}
|
||||||
|
<CircleAlert class="size-4 shrink-0 text-destructive" />
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<span class="min-w-0 flex-1 truncate text-sm font-medium">{heading}</span>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="size-7 shrink-0"
|
||||||
|
onclick={() => (queue.collapsed = !queue.collapsed)}
|
||||||
|
>
|
||||||
|
<ChevronDown class="size-4 transition-transform {queue.collapsed ? '' : 'rotate-180'}" />
|
||||||
|
<span class="sr-only">{queue.collapsed ? 'Show' : 'Hide'} the list</span>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<!-- Only once nothing is in flight: dismissing mid-run would suggest it
|
||||||
|
stopped the upload, which it does not. -->
|
||||||
|
{#if !queue.active}
|
||||||
|
<Button variant="ghost" size="icon" class="size-7 shrink-0" onclick={() => queue.dismiss()}>
|
||||||
|
<X class="size-4" />
|
||||||
|
<span class="sr-only">Dismiss</span>
|
||||||
|
</Button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="h-1 bg-muted">
|
||||||
|
<div
|
||||||
|
class="h-full bg-primary transition-[width] duration-300"
|
||||||
|
style="width: {percent}%"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if !queue.collapsed}
|
||||||
|
<ul class="flex max-h-64 flex-col divide-y overflow-y-auto">
|
||||||
|
{#each queue.jobs as job (job.id)}
|
||||||
|
<li class="flex min-w-0 items-center gap-2 px-3 py-2">
|
||||||
|
<span class="min-w-0 flex-1">
|
||||||
|
<span class="block truncate text-sm" title={job.label}>{job.label}</span>
|
||||||
|
<span class="block font-mono text-[10px] text-muted-foreground tabular-nums">
|
||||||
|
{job.error ?? formatFileSize(job.size)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<span
|
||||||
|
class="shrink-0 font-mono text-[10px] tracking-wider uppercase
|
||||||
|
{job.status === 'done' ? 'text-primary' : ''}
|
||||||
|
{job.status === 'failed' ? 'text-destructive' : ''}
|
||||||
|
{job.status !== 'done' && job.status !== 'failed' ? 'text-muted-foreground' : ''}"
|
||||||
|
>
|
||||||
|
{#if job.status === 'uploading'}
|
||||||
|
Adding
|
||||||
|
{:else if job.status === 'done'}
|
||||||
|
Done
|
||||||
|
{:else if job.status === 'failed'}
|
||||||
|
Failed
|
||||||
|
{:else}
|
||||||
|
Queued
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
{/each}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
{#if !queue.active && queue.failed > 0}
|
||||||
|
<div class="border-t p-2">
|
||||||
|
<Button variant="outline" size="sm" class="w-full" onclick={() => queue.retryFailed()}>
|
||||||
|
<RotateCcw class="size-4" />
|
||||||
|
Retry {queue.failed} failed
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</aside>
|
||||||
|
{/if}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import { getContext, setContext } from 'svelte';
|
||||||
|
import { invalidate } from '$app/navigation';
|
||||||
|
|
||||||
|
import type { Book, PaginatedResponse } from '$lib/schema';
|
||||||
|
|
||||||
|
export type UploadStatus = 'queued' | 'uploading' | 'done' | 'failed';
|
||||||
|
|
||||||
|
export interface UploadJob {
|
||||||
|
id: string;
|
||||||
|
/** The book's folder, or the filename for a book that is a single file. */
|
||||||
|
label: string;
|
||||||
|
libraryId: number | string;
|
||||||
|
files: File[];
|
||||||
|
size: number;
|
||||||
|
status: UploadStatus;
|
||||||
|
error?: string;
|
||||||
|
book?: Book;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UploadSummary {
|
||||||
|
created: number;
|
||||||
|
failed: number;
|
||||||
|
firstBook?: Book;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches the grouping in BookService.create_books_from_files: files are grouped
|
||||||
|
* by their parent directory, except those at the root, which each become their
|
||||||
|
* own book. Diverging from it would split one book across two records.
|
||||||
|
*/
|
||||||
|
function groupByBook(files: File[]): [key: string, files: File[]][] {
|
||||||
|
// A plain record rather than a Map: this is a throwaway local, and Svelte's
|
||||||
|
// lint rule steers any Map towards the reactive SvelteMap.
|
||||||
|
const groups: Record<string, File[]> = {};
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
const cut = file.name.lastIndexOf('/');
|
||||||
|
const key = cut === -1 ? file.name : file.name.slice(0, cut);
|
||||||
|
|
||||||
|
(groups[key] ??= []).push(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.entries(groups);
|
||||||
|
}
|
||||||
|
|
||||||
|
function label(key: string) {
|
||||||
|
const cut = key.lastIndexOf('/');
|
||||||
|
return cut === -1 ? key : key.slice(cut + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function warnBeforeUnload(event: BeforeUnloadEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How long a clean run stays on screen before clearing itself. */
|
||||||
|
const DISMISS_AFTER_MS = 6000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uploads books one request at a time and keeps the result on screen.
|
||||||
|
*
|
||||||
|
* Lives above the dialog so a run outlives it — the dialog only adds to the
|
||||||
|
* queue, and the tray in the root layout is what reports on it. This is why
|
||||||
|
* uploads do not go through a remote function: one request per book is what
|
||||||
|
* makes progress real, bounds how much any single request buffers, and stops
|
||||||
|
* one bad file taking the whole import with it.
|
||||||
|
*/
|
||||||
|
export class UploadQueueState {
|
||||||
|
jobs = $state<UploadJob[]>([]);
|
||||||
|
collapsed = $state(false);
|
||||||
|
|
||||||
|
readonly total = $derived(this.jobs.length);
|
||||||
|
readonly done = $derived(this.jobs.filter((job) => job.status === 'done').length);
|
||||||
|
readonly failed = $derived(this.jobs.filter((job) => job.status === 'failed').length);
|
||||||
|
readonly active = $derived(
|
||||||
|
this.jobs.some((job) => job.status === 'queued' || job.status === 'uploading')
|
||||||
|
);
|
||||||
|
readonly current = $derived(this.jobs.find((job) => job.status === 'uploading'));
|
||||||
|
readonly settled = $derived(this.done + this.failed);
|
||||||
|
|
||||||
|
#running = false;
|
||||||
|
#dismissTimer: ReturnType<typeof setTimeout> | undefined;
|
||||||
|
#held = false;
|
||||||
|
|
||||||
|
/** Adds one job per book and starts the runner if it is not already going. */
|
||||||
|
enqueue(
|
||||||
|
libraryId: number | string,
|
||||||
|
files: File[],
|
||||||
|
onFinished?: (summary: UploadSummary) => void
|
||||||
|
) {
|
||||||
|
const added = groupByBook(files).map(([key, group]) => ({
|
||||||
|
id: `${libraryId}:${key}`,
|
||||||
|
label: label(key),
|
||||||
|
libraryId,
|
||||||
|
files: group,
|
||||||
|
size: group.reduce((sum, file) => sum + file.size, 0),
|
||||||
|
status: 'queued' as UploadStatus
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (added.length === 0) return;
|
||||||
|
|
||||||
|
clearTimeout(this.#dismissTimer);
|
||||||
|
|
||||||
|
// A finished run stays on screen until dismissed; adding to it starts fresh
|
||||||
|
// rather than appending to a report the reader has already read.
|
||||||
|
if (!this.active) this.jobs = [];
|
||||||
|
|
||||||
|
this.jobs = [...this.jobs, ...added];
|
||||||
|
this.collapsed = false;
|
||||||
|
|
||||||
|
void this.#run(onFinished);
|
||||||
|
}
|
||||||
|
|
||||||
|
dismiss() {
|
||||||
|
if (this.active) return;
|
||||||
|
clearTimeout(this.#dismissTimer);
|
||||||
|
this.jobs = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holds a finished run on screen while the pointer is over it.
|
||||||
|
*
|
||||||
|
* Without this the tray can vanish from under a reader who is part-way
|
||||||
|
* through reading which books were added.
|
||||||
|
*/
|
||||||
|
hold() {
|
||||||
|
this.#held = true;
|
||||||
|
clearTimeout(this.#dismissTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
release() {
|
||||||
|
this.#held = false;
|
||||||
|
if (!this.active && this.failed === 0 && this.total > 0) this.#scheduleDismiss();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clears itself only when everything worked. A run with failures stays until
|
||||||
|
* dismissed — it is the only record of what did not make it in, and the only
|
||||||
|
* place to retry from.
|
||||||
|
*/
|
||||||
|
#scheduleDismiss() {
|
||||||
|
clearTimeout(this.#dismissTimer);
|
||||||
|
if (this.#held) return;
|
||||||
|
|
||||||
|
this.#dismissTimer = setTimeout(() => {
|
||||||
|
if (!this.active && this.failed === 0) this.jobs = [];
|
||||||
|
}, DISMISS_AFTER_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Re-queues everything that failed, so one bad book is not a reason to start over. */
|
||||||
|
retryFailed() {
|
||||||
|
this.jobs = this.jobs.map((job) =>
|
||||||
|
job.status === 'failed' ? { ...job, status: 'queued' as UploadStatus, error: undefined } : job
|
||||||
|
);
|
||||||
|
void this.#run();
|
||||||
|
}
|
||||||
|
|
||||||
|
async #run(onFinished?: (summary: UploadSummary) => void) {
|
||||||
|
if (this.#running) return;
|
||||||
|
this.#running = true;
|
||||||
|
|
||||||
|
// Nothing here is resumable, so leaving mid-run loses whatever is left.
|
||||||
|
window.addEventListener('beforeunload', warnBeforeUnload);
|
||||||
|
|
||||||
|
let created = 0;
|
||||||
|
let firstBook: Book | undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const index = this.jobs.findIndex((job) => job.status === 'queued');
|
||||||
|
if (index === -1) break;
|
||||||
|
|
||||||
|
this.#patch(index, { status: 'uploading' });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = new FormData();
|
||||||
|
for (const file of this.jobs[index].files) body.append('files', file);
|
||||||
|
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/books/fromFiles?library_id=${encodeURIComponent(String(this.jobs[index].libraryId))}`,
|
||||||
|
{ method: 'POST', body }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!response.ok) throw new Error(`The server returned ${response.status}`);
|
||||||
|
|
||||||
|
const result: PaginatedResponse<Book> = await response.json();
|
||||||
|
const book = result.items[0];
|
||||||
|
|
||||||
|
created += result.total ?? result.items.length;
|
||||||
|
firstBook ??= book;
|
||||||
|
|
||||||
|
this.#patch(index, { status: 'done', book });
|
||||||
|
} catch (error) {
|
||||||
|
// One bad book must not take the rest of the queue with it.
|
||||||
|
console.error(`Failed to upload ${this.jobs[index].label}`, error);
|
||||||
|
this.#patch(index, {
|
||||||
|
status: 'failed',
|
||||||
|
error: error instanceof Error ? error.message : 'Upload failed'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this.#running = false;
|
||||||
|
window.removeEventListener('beforeunload', warnBeforeUnload);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (created > 0) await invalidate('app:books');
|
||||||
|
|
||||||
|
if (this.failed === 0) this.#scheduleDismiss();
|
||||||
|
|
||||||
|
onFinished?.({ created, failed: this.failed, firstBook });
|
||||||
|
}
|
||||||
|
|
||||||
|
#patch(index: number, changes: Partial<UploadJob>) {
|
||||||
|
this.jobs[index] = { ...this.jobs[index], ...changes };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const UPLOAD_QUEUE_KEY = Symbol('UPLOAD_QUEUE');
|
||||||
|
|
||||||
|
export function setUploadQueueState() {
|
||||||
|
return setContext(UPLOAD_QUEUE_KEY, new UploadQueueState());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getUploadQueueState() {
|
||||||
|
return getContext<ReturnType<typeof setUploadQueueState>>(UPLOAD_QUEUE_KEY);
|
||||||
|
}
|
||||||
@@ -2,12 +2,14 @@
|
|||||||
import { listBookshelves } from '$lib/api';
|
import { listBookshelves } from '$lib/api';
|
||||||
import AppSidebar from '$lib/components/layout/app-sidebar.svelte';
|
import AppSidebar from '$lib/components/layout/app-sidebar.svelte';
|
||||||
import SiteHeader from '$lib/components/layout/site-header.svelte';
|
import SiteHeader from '$lib/components/layout/site-header.svelte';
|
||||||
|
import UploadTray from '$lib/components/layout/upload-tray.svelte';
|
||||||
import { Loading } from '$lib/components/ui/command';
|
import { Loading } from '$lib/components/ui/command';
|
||||||
import * as Sidebar from '$lib/components/ui/sidebar/index.js';
|
import * as Sidebar from '$lib/components/ui/sidebar/index.js';
|
||||||
import type { Library, PaginatedResponse } from '$lib/schema';
|
import type { Library, PaginatedResponse } from '$lib/schema';
|
||||||
import { setBookOperationsState } from '$lib/state/bookOperations.svelte';
|
import { setBookOperationsState } from '$lib/state/bookOperations.svelte';
|
||||||
import { setBookshelfState } from '$lib/state/bookshelf.svelte';
|
import { setBookshelfState } from '$lib/state/bookshelf.svelte';
|
||||||
import { setLibraryState } from '$lib/state/library.svelte.js';
|
import { setLibraryState } from '$lib/state/library.svelte.js';
|
||||||
|
import { setUploadQueueState } from '$lib/state/upload-queue.svelte';
|
||||||
import { setThemeState } from '$lib/theme/theme.svelte';
|
import { setThemeState } from '$lib/theme/theme.svelte';
|
||||||
import type { ThemeConfig } from '$lib/theme/presets';
|
import type { ThemeConfig } from '$lib/theme/presets';
|
||||||
|
|
||||||
@@ -30,6 +32,10 @@
|
|||||||
const bookOps = setBookOperationsState(libraryState.activeLibrary!.id);
|
const bookOps = setBookOperationsState(libraryState.activeLibrary!.id);
|
||||||
const theme = setThemeState(untrack(() => data.theme));
|
const theme = setThemeState(untrack(() => data.theme));
|
||||||
|
|
||||||
|
// Set here rather than beside the upload dialog so a running import survives
|
||||||
|
// the dialog closing and any navigation within the app shell.
|
||||||
|
setUploadQueueState();
|
||||||
|
|
||||||
// Inline custom properties live on :root and so are mode-blind. When the
|
// Inline custom properties live on :root and so are mode-blind. When the
|
||||||
// light/dark switch flips, rewrite them for the mode now showing.
|
// light/dark switch flips, rewrite them for the mode now showing.
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
@@ -52,3 +58,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</Sidebar.Provider>
|
</Sidebar.Provider>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Outside the sidebar shell: an import keeps running while you browse, so the
|
||||||
|
tray must not sit anywhere a page swap can take away. -->
|
||||||
|
<UploadTray />
|
||||||
|
|||||||
Reference in New Issue
Block a user