Feat: Extension of Download Features, Batch Select, Error/Retry (#38)

This commit is contained in:
Youwes09
2026-04-21 10:57:29 -05:00
parent 2d3a4d0e57
commit 86c78689df
9 changed files with 626 additions and 68 deletions
-3
View File
@@ -30,9 +30,6 @@ In-Progress:
- Folders Slide
- Dropdown Formatting (Repositories, Etc)
- Extensions Revamps
- Notification on Extension Added
- Notification on Extension Refresh
- Notification on Extension Update
- Fix Pill-Shaped Language Filter
- Fix ALL ALL EN Tag Issue
- Search QOL Animations
+17 -1
View File
@@ -1,7 +1,7 @@
const QUEUE_FRAGMENT = `
state
queue {
progress state
progress state tries
chapter {
id name pageCount mangaId
manga { id title thumbnailUrl }
@@ -33,6 +33,22 @@ export const DEQUEUE_DOWNLOAD = `
}
`;
export const DEQUEUE_CHAPTERS_DOWNLOAD = `
mutation DequeueChaptersDownload($chapterIds: [Int!]!) {
dequeueChapterDownloads(input: { ids: $chapterIds }) {
downloadStatus { ${QUEUE_FRAGMENT} }
}
}
`;
export const REORDER_DOWNLOAD = `
mutation ReorderDownload($chapterId: Int!, $to: Int!) {
reorderChapterDownload(input: { chapterId: $chapterId, to: $to }) {
downloadStatus { ${QUEUE_FRAGMENT} }
}
}
`;
export const START_DOWNLOADER = `
mutation StartDownloader {
startDownloader(input: {}) {
@@ -1,51 +1,224 @@
<script lang="ts">
import { CircleNotch, X } from "phosphor-svelte";
import { CircleNotch, ArrowUp, ArrowDown, ArrowClockwise, X } from "phosphor-svelte";
import Thumbnail from "@shared/manga/Thumbnail.svelte";
import ContextMenu from "@shared/ui/ContextMenu.svelte";
import type { MenuEntry } from "@shared/ui/ContextMenu.svelte";
import type { DownloadQueueItem } from "@types/index";
import { pageProgress } from "../lib/downloadQueue";
interface Props {
item: DownloadQueueItem;
index: number;
isActive: boolean;
isFirst: boolean;
isLast: boolean;
isRemoving: boolean;
isSelected: boolean;
selectedCount: number;
selectedErrorCount: number;
batchWorking: boolean;
onRemove: (chapterId: number) => void;
onRetry: (chapterId: number) => void;
onReorder: (chapterId: number, dir: "up" | "down") => void;
onSelect: (chapterId: number, e: MouseEvent | { shiftKey: boolean; ctrlKey: boolean; metaKey: boolean }) => void;
onBatchRemove: () => void;
onBatchRetry: () => void;
onBatchReorder: (dir: "up" | "down") => void;
onClearSelect: () => void;
}
const { item, isActive, isRemoving, onRemove }: Props = $props();
const {
item, index, isActive, isFirst, isLast, isRemoving,
isSelected, selectedCount, selectedErrorCount, batchWorking,
onRemove, onRetry, onReorder, onSelect,
onBatchRemove, onBatchRetry, onBatchReorder, onClearSelect,
}: Props = $props();
const manga = $derived(item.chapter.manga);
const pages = $derived(item.chapter.pageCount ?? 0);
const prog = $derived(pageProgress(item.progress, pages));
const isError = $derived(item.state === "ERROR");
const pct = $derived(Math.round(item.progress * 100));
let menuX = $state(0);
let menuY = $state(0);
let menuOpen = $state(false);
function openMenu(e: MouseEvent) {
e.preventDefault();
menuX = e.clientX;
menuY = e.clientY;
menuOpen = true;
}
let longPressTimer: ReturnType<typeof setTimeout> | null = null;
let touchMoved = false;
function onTouchStart(e: TouchEvent) {
touchMoved = false;
const touch = e.touches[0];
longPressTimer = setTimeout(() => {
longPressTimer = null;
if (touchMoved) return;
if (selectedCount === 0) {
onSelect(item.chapter.id, { shiftKey: false, ctrlKey: false, metaKey: false });
} else {
menuX = touch.clientX;
menuY = touch.clientY;
menuOpen = true;
}
}, 500);
}
function onTouchMove() {
touchMoved = true;
cancelLongPress();
}
function cancelLongPress() {
if (longPressTimer !== null) {
clearTimeout(longPressTimer);
longPressTimer = null;
}
}
const menuItems = $derived.by<MenuEntry[]>(() => {
const inBatch = isSelected && selectedCount > 1;
const entries: MenuEntry[] = [];
if (inBatch) {
entries.push({
label: `Move up (${selectedCount})`,
icon: ArrowUp,
onClick: () => onBatchReorder("up"),
disabled: batchWorking,
});
entries.push({
label: `Move down (${selectedCount})`,
icon: ArrowDown,
onClick: () => onBatchReorder("down"),
disabled: batchWorking,
});
entries.push({ separator: true });
if (selectedErrorCount > 0) {
entries.push({
label: `Retry errors (${selectedErrorCount})`,
icon: ArrowClockwise,
onClick: onBatchRetry,
disabled: batchWorking,
});
}
entries.push({
label: `Remove selected (${selectedCount})`,
icon: X,
onClick: onBatchRemove,
danger: true,
disabled: batchWorking,
});
entries.push({ separator: true });
entries.push({ label: "Deselect all", onClick: onClearSelect });
} else {
if (isError) {
entries.push({
label: "Retry",
icon: ArrowClockwise,
onClick: () => onRetry(item.chapter.id),
disabled: isRemoving,
});
entries.push({ separator: true });
}
entries.push({
label: "Move up",
icon: ArrowUp,
onClick: () => onReorder(item.chapter.id, "up"),
disabled: isFirst || isActive,
});
entries.push({
label: "Move down",
icon: ArrowDown,
onClick: () => onReorder(item.chapter.id, "down"),
disabled: isLast || isActive,
});
entries.push({ separator: true });
entries.push({
label: "Remove",
icon: X,
onClick: () => onRemove(item.chapter.id),
danger: true,
disabled: isRemoving || isActive,
});
}
return entries;
});
</script>
<div class="row" class:row-active={isActive} class:row-removing={isRemoving}>
<div
class="row"
class:row-active={isActive}
class:row-error={isError}
class:row-selected={isSelected}
class:row-removing={isRemoving}
onclick={(e) => { e.stopPropagation(); onSelect(item.chapter.id, e); }}
oncontextmenu={openMenu}
ontouchstart={onTouchStart}
ontouchend={cancelLongPress}
ontouchmove={onTouchMove}
>
{#if manga?.thumbnailUrl}
<div class="thumb">
<Thumbnail src={manga.thumbnailUrl} alt={manga.title} class="thumb-img" />
</div>
{/if}
<div class="info">
{#if manga?.title}<span class="manga-title">{manga.title}</span>{/if}
<span class="chapter-name">{item.chapter.name}</span>
{#if pages > 0}
<span class="pages-label">{isActive ? `${prog.done} / ${prog.total} pages` : `${prog.total} pages`}</span>
{/if}
{#if isActive}
<div class="progress-row">
<div class="progress-wrap">
<div class="progress-bar" style="width:{Math.round(item.progress * 100)}%"></div>
<div class="progress-bar" class:progress-error={isError} style="width:{pct}%"></div>
</div>
<span class="pages-label">
{#if isActive}
{prog.done}/{prog.total}
{:else if isError}
failed · {item.tries} {item.tries === 1 ? "try" : "tries"}
{:else}
{prog.total}p
{/if}
</span>
</div>
{/if}
</div>
<div class="row-right">
<span class="state-label">{item.state}</span>
<span class="state-label" class:state-error={isError}>{item.state}</span>
<div class="actions">
{#if isError}
<button class="action-btn retry" onclick={(e) => { e.stopPropagation(); onRetry(item.chapter.id); }} disabled={isRemoving} title="Retry">
{#if isRemoving}<CircleNotch size={11} weight="light" class="anim-spin" />{:else}<ArrowClockwise size={11} weight="bold" />{/if}
</button>
{/if}
{#if !isActive}
<button class="remove-btn" onclick={() => onRemove(item.chapter.id)} disabled={isRemoving} title="Remove from queue">
<button class="action-btn" onclick={(e) => { e.stopPropagation(); onReorder(item.chapter.id, "up"); }} disabled={isFirst} title="Move up">
<ArrowUp size={11} weight="light" />
</button>
<button class="action-btn" onclick={(e) => { e.stopPropagation(); onReorder(item.chapter.id, "down"); }} disabled={isLast} title="Move down">
<ArrowDown size={11} weight="light" />
</button>
<button class="action-btn remove" onclick={(e) => { e.stopPropagation(); onRemove(item.chapter.id); }} disabled={isRemoving} title="Remove">
{#if isRemoving}<CircleNotch size={11} weight="light" class="anim-spin" />{:else}<X size={12} weight="light" />{/if}
</button>
{/if}
</div>
</div>
</div>
{#if menuOpen}
<ContextMenu x={menuX} y={menuY} items={menuItems} onClose={() => (menuOpen = false)} />
{/if}
<style>
.row {
display: flex;
@@ -55,9 +228,16 @@
background: var(--bg-raised);
border: 1px solid var(--border-dim);
border-radius: var(--radius-md);
transition: border-color var(--t-fast), opacity var(--t-base);
transition: border-color var(--t-fast), opacity var(--t-base), background var(--t-fast);
cursor: default;
user-select: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
}
.row.row-active { border-color: var(--accent-dim); }
.row.row-error { border-color: color-mix(in srgb, var(--color-error) 30%, transparent); }
.row.row-selected { background: var(--bg-elevated); border-color: var(--border-strong); }
.row.row-removing { opacity: 0.4; pointer-events: none; }
.thumb {
@@ -75,10 +255,11 @@
flex: 1;
display: flex;
flex-direction: column;
gap: 3px;
gap: 4px;
overflow: hidden;
min-width: 0;
}
.manga-title {
font-size: var(--text-sm);
font-weight: var(--weight-medium);
@@ -87,6 +268,7 @@
overflow: hidden;
text-overflow: ellipsis;
}
.chapter-name {
font-size: var(--text-xs);
color: var(--text-muted);
@@ -94,25 +276,38 @@
overflow: hidden;
text-overflow: ellipsis;
}
.pages-label {
font-family: var(--font-ui);
font-size: var(--text-2xs);
color: var(--text-faint);
letter-spacing: var(--tracking-wide);
.progress-row {
display: flex;
align-items: center;
gap: var(--sp-2);
}
.progress-wrap {
flex: 1;
height: 2px;
background: var(--border-base);
border-radius: var(--radius-full);
overflow: hidden;
margin-top: 4px;
}
.progress-bar {
height: 100%;
background: var(--accent);
border-radius: var(--radius-full);
transition: width 0.4s ease;
opacity: 0.5;
}
.row-active .progress-bar { opacity: 1; }
.progress-bar.progress-error { background: var(--color-error); opacity: 0.7; }
.pages-label {
font-family: var(--font-ui);
font-size: var(--text-2xs);
color: var(--text-faint);
letter-spacing: var(--tracking-wide);
flex-shrink: 0;
white-space: nowrap;
}
.row-right {
@@ -122,6 +317,7 @@
gap: var(--sp-1);
flex-shrink: 0;
}
.state-label {
font-family: var(--font-ui);
font-size: var(--text-2xs);
@@ -129,8 +325,15 @@
letter-spacing: var(--tracking-wider);
text-transform: uppercase;
}
.state-label.state-error { color: var(--color-error); opacity: 0.8; }
.remove-btn {
.actions {
display: flex;
align-items: center;
gap: 2px;
}
.action-btn {
display: flex;
align-items: center;
justify-content: center;
@@ -138,8 +341,14 @@
height: 20px;
border-radius: var(--radius-sm);
color: var(--text-faint);
background: none;
border: none;
cursor: pointer;
padding: 0;
transition: color var(--t-base), background var(--t-base);
}
.remove-btn:hover:not(:disabled) { color: var(--color-error); background: var(--color-error-bg); }
.remove-btn:disabled { opacity: 0.5; cursor: default; }
.action-btn:hover:not(:disabled) { color: var(--text-secondary); background: var(--bg-overlay); }
.action-btn:disabled { opacity: 0.25; cursor: default; }
.action-btn.remove:hover:not(:disabled) { color: var(--color-error); background: var(--color-error-bg); }
.action-btn.retry:hover:not(:disabled) { color: var(--accent-fg); background: var(--accent-muted); }
</style>
@@ -8,14 +8,33 @@
loading: boolean;
isRunning: boolean;
dequeueing: Set<number>;
selected: Set<number>;
batchWorking: boolean;
onRemove: (chapterId: number) => void;
onRetry: (chapterId: number) => void;
onReorder: (chapterId: number, dir: "up" | "down") => void;
onSelect: (chapterId: number, e: MouseEvent) => void;
onClearSelect: () => void;
onBatchRemove: () => void;
onBatchRetry: () => void;
onBatchReorder: (dir: "up" | "down") => void;
}
const { queue, loading, isRunning, dequeueing, onRemove }: Props = $props();
const {
queue, loading, isRunning, dequeueing, selected, batchWorking,
onRemove, onRetry, onReorder, onSelect, onClearSelect,
onBatchRemove, onBatchRetry, onBatchReorder,
}: Props = $props();
const selectedErrorCount = $derived(
queue.filter((i) => selected.has(i.chapter.id) && i.state === "ERROR").length,
);
</script>
{#if loading}
<div class="empty"><CircleNotch size={16} weight="light" class="anim-spin" style="color:var(--text-faint)" /></div>
<div class="empty">
<CircleNotch size={16} weight="light" class="anim-spin" style="color:var(--text-faint)" />
</div>
{:else if queue.length === 0}
<div class="empty">Queue is empty.</div>
{:else}
@@ -23,9 +42,23 @@
{#each queue as item, i (item.chapter.id)}
<DownloadItem
{item}
index={i}
isActive={i === 0 && isRunning}
isFirst={i === 0}
isLast={i === queue.length - 1}
isRemoving={dequeueing.has(item.chapter.id)}
isSelected={selected.has(item.chapter.id)}
selectedCount={selected.size}
{selectedErrorCount}
{batchWorking}
{onRemove}
{onRetry}
{onReorder}
{onSelect}
{onClearSelect}
{onBatchRemove}
{onBatchRetry}
{onBatchReorder}
/>
{/each}
</div>
@@ -1,38 +1,90 @@
<script lang="ts">
import { Play, Pause, Trash, CircleNotch } from "phosphor-svelte";
import { Play, Pause, Trash, CircleNotch, ArrowClockwise } from "phosphor-svelte";
import DownloadQueue from "./DownloadQueue.svelte";
import { downloadStore } from "../store/downloadState.svelte";
import { formatEta } from "../lib/downloadQueue";
$effect(() => {
downloadStore.poll();
const interval = setInterval(() => downloadStore.poll(), 2000);
return () => clearInterval(interval);
});
let selectAnchor = $state<number | null>(null);
function handleSelect(chapterId: number, e: MouseEvent | { shiftKey: boolean; ctrlKey: boolean; metaKey: boolean }) {
const ctrl = e.ctrlKey || e.metaKey;
if (e.shiftKey && selectAnchor !== null) {
downloadStore.selectRange(selectAnchor, chapterId);
} else if (ctrl) {
downloadStore.toggleSelect(chapterId);
selectAnchor = chapterId;
} else {
if (downloadStore.selected.size > 1) {
downloadStore.toggleSelect(chapterId);
selectAnchor = chapterId;
} else if (downloadStore.selected.size === 1 && downloadStore.selected.has(chapterId)) {
downloadStore.clearSelection();
selectAnchor = null;
} else {
downloadStore.selectOnly(chapterId);
selectAnchor = chapterId;
}
}
}
function handleClickOff() {
if (downloadStore.selected.size > 0) {
downloadStore.clearSelection();
selectAnchor = null;
}
}
</script>
<div class="root">
<div class="header">
<h1 class="heading">Downloads</h1>
<div class="header-actions">
<button class="icon-btn" class:loading={downloadStore.togglingPlay}
{#if downloadStore.hasErrored}
<button
class="icon-btn"
onclick={() => downloadStore.retryAllErrored()}
disabled={downloadStore.batchWorking}
title="Retry all errored"
>
{#if downloadStore.batchWorking}
<CircleNotch size={14} weight="light" class="anim-spin" />
{:else}
<ArrowClockwise size={14} weight="bold" />
{/if}
</button>
{/if}
<button
class="icon-btn"
class:loading={downloadStore.togglingPlay}
onclick={() => downloadStore.togglePlay()}
disabled={downloadStore.togglingPlay || (downloadStore.queue.length === 0 && !downloadStore.isRunning)}
title={downloadStore.isRunning ? "Pause" : "Resume"}>
title={downloadStore.isRunning ? "Pause" : "Resume"}
>
{#if downloadStore.togglingPlay}<CircleNotch size={14} weight="light" class="anim-spin" />
{:else if downloadStore.isRunning}<Pause size={14} weight="fill" />
{:else}<Play size={14} weight="fill" />{/if}
</button>
<button class="icon-btn" class:loading={downloadStore.clearing}
<button
class="icon-btn"
class:loading={downloadStore.clearing}
onclick={() => downloadStore.clear()}
disabled={downloadStore.clearing || downloadStore.queue.length === 0}
title="Clear queue">
title="Clear queue"
>
{#if downloadStore.clearing}<CircleNotch size={14} weight="light" class="anim-spin" />
{:else}<Trash size={14} weight="regular" />{/if}
</button>
</div>
</div>
<div class="content">
<div class="content" onclick={handleClickOff}>
<div class="status-bar">
<div class="status-dot" class:active={downloadStore.isRunning}></div>
<span class="status-text">
@@ -40,15 +92,29 @@
? (downloadStore.isRunning ? "Pausing…" : "Starting…")
: downloadStore.isRunning ? "Downloading" : "Paused"}
</span>
<div class="status-right">
{#if downloadStore.isRunning && downloadStore.eta !== null}
<span class="status-eta">{formatEta(downloadStore.eta)} left</span>
{/if}
<span class="status-count">{downloadStore.queue.length} queued</span>
</div>
</div>
<DownloadQueue
queue={downloadStore.queue}
loading={downloadStore.loading}
isRunning={downloadStore.isRunning}
dequeueing={downloadStore.dequeueing}
selected={downloadStore.selected}
batchWorking={downloadStore.batchWorking}
onRemove={(id) => downloadStore.dequeue(id)}
onRetry={(id) => downloadStore.retryOne(id)}
onReorder={(id, dir) => downloadStore.reorder(id, dir)}
onSelect={handleSelect}
onClearSelect={() => { downloadStore.clearSelection(); selectAnchor = null; }}
onBatchRemove={() => downloadStore.dequeueSelected()}
onBatchRetry={() => downloadStore.retrySelected()}
onBatchReorder={(dir) => downloadStore.reorderSelected(dir)}
/>
</div>
</div>
@@ -70,6 +136,7 @@
border-bottom: 1px solid var(--border-dim);
flex-shrink: 0;
}
.heading {
font-family: var(--font-ui);
font-size: var(--text-xs);
@@ -78,6 +145,7 @@
letter-spacing: var(--tracking-wider);
text-transform: uppercase;
}
.header-actions { display: flex; gap: var(--sp-2); }
.content {
@@ -98,6 +166,8 @@
border-radius: var(--radius-md);
border: 1px solid var(--border-dim);
color: var(--text-muted);
background: none;
cursor: pointer;
transition: color var(--t-base), border-color var(--t-base), background var(--t-base);
}
.icon-btn:hover:not(:disabled) { color: var(--text-secondary); border-color: var(--border-strong); background: var(--bg-raised); }
@@ -113,6 +183,7 @@
border: 1px solid var(--border-dim);
border-radius: var(--radius-md);
}
.status-dot {
width: 6px;
height: 6px;
@@ -130,6 +201,21 @@
flex: 1;
letter-spacing: var(--tracking-wide);
}
.status-right {
display: flex;
align-items: center;
gap: var(--sp-3);
}
.status-eta {
font-family: var(--font-ui);
font-size: var(--text-xs);
color: var(--accent-fg);
letter-spacing: var(--tracking-wide);
opacity: 0.8;
}
.status-count {
font-family: var(--font-ui);
font-size: var(--text-xs);
+39 -2
View File
@@ -12,14 +12,51 @@ export function optimisticRemove(queue: DownloadQueueItem[], chapterId: number):
return queue.filter((i) => i.chapter.id !== chapterId);
}
export function optimisticToggle(state: string, wasRunning: boolean): string {
return wasRunning ? "STOPPED" : "STARTED";
export function optimisticRemoveMany(queue: DownloadQueueItem[], chapterIds: Set<number>): DownloadQueueItem[] {
return queue.filter((i) => !chapterIds.has(i.chapter.id));
}
export function isRunning(state: string | undefined): boolean {
return state === "STARTED";
}
export function getErrored(queue: DownloadQueueItem[]): DownloadQueueItem[] {
return queue.filter((i) => i.state === "ERROR");
}
export function pageProgress(progress: number, pageCount: number): { done: number; total: number } {
return { done: Math.round(progress * pageCount), total: pageCount };
}
export interface SpeedSample {
ts: number;
progress: number;
pages: number;
}
export function calcSpeed(prev: SpeedSample | null, current: SpeedSample): number | null {
if (!prev) return null;
const dt = (current.ts - prev.ts) / 1000;
if (dt <= 0) return null;
const prevDone = Math.round(prev.progress * prev.pages);
const curDone = Math.round(current.progress * current.pages);
const delta = curDone - prevDone;
if (delta <= 0) return null;
return delta / dt;
}
export function estimateEta(pagesPerSec: number, queue: DownloadQueueItem[]): number | null {
if (pagesPerSec <= 0 || queue.length === 0) return null;
let remaining = 0;
for (const item of queue) {
const pages = item.chapter.pageCount ?? 0;
remaining += pages - Math.round(item.progress * pages);
}
return remaining / pagesPerSec;
}
export function formatEta(seconds: number): string {
if (seconds < 60) return `~${Math.ceil(seconds)}s`;
if (seconds < 3600) return `~${Math.ceil(seconds / 60)}m`;
return `~${(seconds / 3600).toFixed(1)}h`;
}
@@ -1,9 +1,17 @@
import { gql } from "@api/client";
import { GET_DOWNLOAD_STATUS } from "@api/queries";
import { START_DOWNLOADER, STOP_DOWNLOADER, CLEAR_DOWNLOADER, DEQUEUE_DOWNLOAD } from "@api/mutations";
import {
START_DOWNLOADER, STOP_DOWNLOADER, CLEAR_DOWNLOADER,
DEQUEUE_DOWNLOAD, DEQUEUE_CHAPTERS_DOWNLOAD,
ENQUEUE_DOWNLOAD, REORDER_DOWNLOAD,
} from "@api/mutations";
import { setActiveDownloads } from "@store/state.svelte";
import type { DownloadStatus } from "@types/index";
import { toActiveDownloads, optimisticRemove, isRunning } from "../lib/downloadQueue";
import {
toActiveDownloads, optimisticRemove, optimisticRemoveMany,
isRunning, getErrored, calcSpeed, estimateEta,
type SpeedSample,
} from "../lib/downloadQueue";
class DownloadStore {
status: DownloadStatus | null = $state(null);
@@ -11,20 +19,50 @@ class DownloadStore {
togglingPlay = $state(false);
clearing = $state(false);
dequeueing = $state(new Set<number>());
selected = $state(new Set<number>());
batchWorking = $state(false);
pagesPerSec: number | null = $state(null);
eta: number | null = $state(null);
private lastSample: SpeedSample | null = null;
get queue() { return this.status?.queue ?? []; }
get isRunning() { return isRunning(this.status?.state); }
get erroredIds() { return new Set(getErrored(this.queue).map((i) => i.chapter.id)); }
get hasErrored() { return this.erroredIds.size > 0; }
applyStatus(ds: DownloadStatus) {
this.status = ds;
setActiveDownloads(toActiveDownloads(ds.queue));
this.updateSpeed(ds);
}
private updateSpeed(ds: DownloadStatus) {
const active = ds.queue[0];
if (!active || active.state !== "DOWNLOADING") {
this.lastSample = null;
this.pagesPerSec = null;
this.eta = null;
return;
}
const sample: SpeedSample = {
ts: Date.now(),
progress: active.progress,
pages: active.chapter.pageCount ?? 0,
};
const speed = calcSpeed(this.lastSample, sample);
this.lastSample = sample;
if (speed !== null) {
this.pagesPerSec = speed;
this.eta = estimateEta(speed, ds.queue);
}
}
async poll() {
gql<{ downloadStatus: DownloadStatus }>(GET_DOWNLOAD_STATUS)
.then((d) => this.applyStatus(d.downloadStatus))
.catch(console.error)
.finally(() => this.loading = false);
.finally(() => { this.loading = false; });
}
async togglePlay() {
@@ -47,6 +85,7 @@ class DownloadStore {
async clear() {
if (this.clearing) return;
this.clearing = true;
this.selected = new Set();
if (this.status) this.status = { ...this.status, queue: [] };
setActiveDownloads([]);
try {
@@ -60,10 +99,144 @@ class DownloadStore {
if (this.dequeueing.has(chapterId)) return;
this.dequeueing = new Set(this.dequeueing).add(chapterId);
if (this.status) this.status = { ...this.status, queue: optimisticRemove(this.status.queue, chapterId) };
this.selected.delete(chapterId);
this.selected = new Set(this.selected);
try { await gql(DEQUEUE_DOWNLOAD, { chapterId }); this.poll(); }
catch (e) { console.error(e); this.poll(); }
finally { this.dequeueing.delete(chapterId); this.dequeueing = new Set(this.dequeueing); }
}
async dequeueSelected() {
if (this.batchWorking || this.selected.size === 0) return;
this.batchWorking = true;
const ids = [...this.selected];
if (this.status) this.status = { ...this.status, queue: optimisticRemoveMany(this.status.queue, this.selected) };
this.selected = new Set();
try {
await gql(DEQUEUE_CHAPTERS_DOWNLOAD, { chapterIds: ids });
this.poll();
} catch (e) { console.error(e); this.poll(); }
finally { this.batchWorking = false; }
}
async retryOne(chapterId: number) {
if (this.dequeueing.has(chapterId)) return;
this.dequeueing = new Set(this.dequeueing).add(chapterId);
try {
await gql(DEQUEUE_DOWNLOAD, { chapterId });
await gql(ENQUEUE_DOWNLOAD, { chapterId });
this.poll();
} catch (e) { console.error(e); this.poll(); }
finally { this.dequeueing.delete(chapterId); this.dequeueing = new Set(this.dequeueing); }
}
async retryAllErrored() {
if (this.batchWorking || !this.hasErrored) return;
this.batchWorking = true;
const ids = [...this.erroredIds];
try {
await gql(DEQUEUE_CHAPTERS_DOWNLOAD, { chapterIds: ids });
for (const id of ids) await gql(ENQUEUE_DOWNLOAD, { chapterId: id });
this.poll();
} catch (e) { console.error(e); this.poll(); }
finally { this.batchWorking = false; }
}
async retrySelected() {
if (this.batchWorking || this.selected.size === 0) return;
this.batchWorking = true;
const ids = [...this.selected].filter((id) => this.erroredIds.has(id));
this.selected = new Set();
try {
if (ids.length > 0) {
await gql(DEQUEUE_CHAPTERS_DOWNLOAD, { chapterIds: ids });
for (const id of ids) await gql(ENQUEUE_DOWNLOAD, { chapterId: id });
}
this.poll();
} catch (e) { console.error(e); this.poll(); }
finally { this.batchWorking = false; }
}
async reorder(chapterId: number, direction: "up" | "down") {
const idx = this.queue.findIndex((i) => i.chapter.id === chapterId);
if (idx === -1) return;
const to = direction === "up" ? idx - 1 : idx + 1;
if (to < 0 || to >= this.queue.length) return;
const newQueue = [...this.queue];
[newQueue[idx], newQueue[to]] = [newQueue[to], newQueue[idx]];
if (this.status) this.status = { ...this.status, queue: newQueue };
try {
const d = await gql<{ reorderChapterDownload: { downloadStatus: DownloadStatus } }>(
REORDER_DOWNLOAD, { chapterId, to },
);
this.applyStatus(d.reorderChapterDownload.downloadStatus);
} catch (e) { console.error(e); this.poll(); }
}
selectOnly(chapterId: number) {
this.selected = new Set([chapterId]);
}
async reorderSelected(direction: "up" | "down") {
if (this.batchWorking || this.selected.size === 0) return;
this.batchWorking = true;
const queue = [...this.queue];
const selectedIndices = queue
.map((item, i) => ({ id: item.chapter.id, i }))
.filter(({ id }) => this.selected.has(id))
.map(({ i }) => i)
.sort((a, b) => direction === "up" ? a - b : b - a);
if (direction === "up" && selectedIndices[0] === 0) { this.batchWorking = false; return; }
if (direction === "down" && selectedIndices[0] === queue.length - 1) { this.batchWorking = false; return; }
const newQueue = [...queue];
for (const idx of selectedIndices) {
const to = direction === "up" ? idx - 1 : idx + 1;
if (to < 0 || to >= newQueue.length) break;
[newQueue[idx], newQueue[to]] = [newQueue[to], newQueue[idx]];
}
if (this.status) this.status = { ...this.status, queue: newQueue };
try {
for (const idx of selectedIndices) {
const to = direction === "up" ? idx - 1 : idx + 1;
if (to < 0 || to >= queue.length) break;
const chapterId = queue[idx].chapter.id;
await gql<{ reorderChapterDownload: { downloadStatus: DownloadStatus } }>(
REORDER_DOWNLOAD, { chapterId, to },
);
}
this.poll();
} catch (e) { console.error(e); this.poll(); }
finally { this.batchWorking = false; }
}
toggleSelect(chapterId: number) {
const next = new Set(this.selected);
if (next.has(chapterId)) next.delete(chapterId);
else next.add(chapterId);
this.selected = next;
}
selectRange(fromId: number, toId: number) {
const ids = this.queue.map((i) => i.chapter.id);
const a = ids.indexOf(fromId), b = ids.indexOf(toId);
if (a === -1 || b === -1) return;
const [lo, hi] = a < b ? [a, b] : [b, a];
const next = new Set(this.selected);
for (let i = lo; i <= hi; i++) next.add(ids[i]);
this.selected = next;
}
selectAll() {
this.selected = new Set(this.queue.map((i) => i.chapter.id));
}
clearSelection() {
this.selected = new Set();
}
}
export const downloadStore = new DownloadStore();
+6
View File
@@ -45,6 +45,10 @@
if (el && !el.contains(e.target as Node)) onClose();
}
function onTouchStartOutside(e: TouchEvent) {
if (el && !el.contains(e.target as Node)) onClose();
}
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") { e.stopPropagation(); onClose(); return; }
if (e.key === "ArrowDown") {
@@ -68,9 +72,11 @@
$effect(() => {
document.addEventListener("mousedown", onMouseDown, true);
document.addEventListener("touchstart", onTouchStartOutside, true);
document.addEventListener("keydown", onKey, true);
return () => {
document.removeEventListener("mousedown", onMouseDown, true);
document.removeEventListener("touchstart", onTouchStartOutside, true);
document.removeEventListener("keydown", onKey, true);
};
});
+1
View File
@@ -1,6 +1,7 @@
export interface DownloadQueueItem {
progress: number;
state: "QUEUED" | "DOWNLOADING" | "FINISHED" | "ERROR";
tries: number;
chapter: {
id: number;
name: string;