-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathCatalog.svelte
More file actions
381 lines (340 loc) · 12.8 KB
/
Copy pathCatalog.svelte
File metadata and controls
381 lines (340 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<script lang="ts">
import { onMount } from 'svelte';
import { catalog } from '$lib/catalog';
import { Button, Listgroup, Search } from 'flowbite-svelte';
import CatalogItem from './CatalogItem.svelte';
import Loader from './Loader.svelte';
import {
GridOutline,
ListOutline,
SortOutline,
DownloadSolid,
UploadSolid
} from 'flowbite-svelte-icons';
import { miscSettings, updateMiscSetting, volumes } from '$lib/settings';
import CatalogListItem from './CatalogListItem.svelte';
import { isUpgrading } from '$lib/catalog/db';
import { unifiedCloudManager } from '$lib/util/sync/unified-cloud-manager';
import { queueSeriesVolumes } from '$lib/util/download-queue';
import { getCloudProvider } from '$lib/util/cloud-fields';
import { showSnackbar } from '$lib/util';
import type { ProviderType } from '$lib/util/sync/provider-interface';
const CATALOG_SCROLL_Y_KEY = 'mokuro:catalog:scroll-y';
let search = $state('');
let pendingRestoreY = $state<number | null>(null);
let restoringScroll = $state(false);
let restoreAttempts = $state(0);
let restoreRaf: number | null = null;
function getScrollingElement(): HTMLElement {
return (document.scrollingElement as HTMLElement) || document.documentElement || document.body;
}
function getScrollY(): number {
const scroller = getScrollingElement();
return window.scrollY || scroller.scrollTop || document.documentElement.scrollTop || document.body.scrollTop || 0;
}
function getMaxScrollY(): number {
const scroller = getScrollingElement();
const scrollerMax = scroller.scrollHeight - scroller.clientHeight;
const docMax = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const bodyMax = document.body.scrollHeight - document.body.clientHeight;
return Math.max(0, scrollerMax, docMax, bodyMax);
}
function setScrollY(y: number) {
window.scrollTo(0, y);
const scroller = getScrollingElement();
if (scroller.scrollTop !== y) {
scroller.scrollTop = y;
}
}
function persistCatalogScrollPosition() {
try {
sessionStorage.setItem(CATALOG_SCROLL_Y_KEY, String(getScrollY()));
} catch (error) {
console.debug('Failed to persist catalog scroll position:', error);
}
}
function loadPendingCatalogScrollPosition() {
try {
const saved = sessionStorage.getItem(CATALOG_SCROLL_Y_KEY);
if (!saved) return;
const y = Number(saved);
if (!Number.isFinite(y) || y < 0) return;
pendingRestoreY = y;
} catch (error) {
console.debug('Failed to restore catalog scroll position:', error);
}
}
function stopRestoreLoop() {
restoringScroll = false;
restoreAttempts = 0;
if (restoreRaf !== null) {
cancelAnimationFrame(restoreRaf);
restoreRaf = null;
}
}
function restoreCatalogScrollStep() {
if (pendingRestoreY === null) {
stopRestoreLoop();
return;
}
const maxY = getMaxScrollY();
const targetY = Math.min(pendingRestoreY, maxY);
setScrollY(targetY);
const reachedTarget = Math.abs(getScrollY() - targetY) <= 2;
const enoughHeight = maxY >= pendingRestoreY - 2;
restoreAttempts += 1;
if ((reachedTarget && enoughHeight) || restoreAttempts >= 240) {
pendingRestoreY = null;
stopRestoreLoop();
return;
}
restoreRaf = requestAnimationFrame(restoreCatalogScrollStep);
}
function startRestoreLoop() {
if (pendingRestoreY === null || restoringScroll) return;
restoringScroll = true;
restoreAttempts = 0;
restoreRaf = requestAnimationFrame(restoreCatalogScrollStep);
}
onMount(() => {
loadPendingCatalogScrollPosition();
startRestoreLoop();
const onScroll = () => {
persistCatalogScrollPosition();
};
window.addEventListener('scroll', onScroll, { passive: true });
return () => {
stopRestoreLoop();
window.removeEventListener('scroll', onScroll);
};
});
// Check if any cloud provider is authenticated
let hasAuthenticatedProvider = $derived(unifiedCloudManager.getDefaultProvider() !== null);
// Get active provider's display name
let providerDisplayName = $derived.by(() => {
const provider = unifiedCloudManager.getActiveProvider();
return provider?.name || 'cloud storage';
});
function onLayout() {
if ($miscSettings.galleryLayout === 'list') {
updateMiscSetting('galleryLayout', 'grid');
} else {
updateMiscSetting('galleryLayout', 'list');
}
}
function onOrder() {
if ($miscSettings.gallerySorting === 'SMART') {
updateMiscSetting('gallerySorting', 'ASC');
} else if ($miscSettings.gallerySorting === 'ASC') {
updateMiscSetting('gallerySorting', 'DESC');
} else {
updateMiscSetting('gallerySorting', 'SMART');
}
}
let sortedCatalog = $derived.by(() => {
if ($catalog === null) return [];
// Snapshot volumes state before sorting to prevent race conditions.
// Reading $volumes inside the sort comparator can cause deadlocks if the
// store updates mid-sort, violating the comparator's transitivity requirement.
const volumesSnapshot = $volumes;
return [...$catalog]
.sort((a, b) => {
if ($miscSettings.gallerySorting === 'ASC') {
return a.title.localeCompare(b.title, undefined, { numeric: true, sensitivity: 'base' });
} else if ($miscSettings.gallerySorting === 'DESC') {
return b.title.localeCompare(a.title, undefined, { numeric: true, sensitivity: 'base' });
} else {
// SMART sorting
// Check if series are completed
const aVolumes = a.volumes.map((vol) => vol.volume_uuid);
const bVolumes = b.volumes.map((vol) => vol.volume_uuid);
const aCompleted = aVolumes.every((volId) => volumesSnapshot[volId]?.completed);
const bCompleted = bVolumes.every((volId) => volumesSnapshot[volId]?.completed);
// If completion status differs, completed series go to the end
if (aCompleted !== bCompleted) {
return aCompleted ? 1 : -1;
}
// If both have the same completion status, sort by last updated date
// Only consider volumes with actual progress (page > 1)
const aLastUpdated = Math.max(
...aVolumes
.filter((volId) => (volumesSnapshot[volId]?.progress || 0) > 1)
.map((volId) => new Date(volumesSnapshot[volId]?.lastProgressUpdate || 0).getTime()),
0 // Default to 0 if no volumes have progress
);
const bLastUpdated = Math.max(
...bVolumes
.filter((volId) => (volumesSnapshot[volId]?.progress || 0) > 1)
.map((volId) => new Date(volumesSnapshot[volId]?.lastProgressUpdate || 0).getTime()),
0 // Default to 0 if no volumes have progress
);
if (aLastUpdated !== bLastUpdated) {
// Most recently read first
return bLastUpdated - aLastUpdated;
}
// If all else is equal, use natural sorting on title
return a.title.localeCompare(b.title, undefined, { numeric: true, sensitivity: 'base' });
}
})
.filter((item) => {
return item.title.toLowerCase().indexOf(search.toLowerCase()) !== -1;
});
});
// Separate local series from placeholder-only series
let localSeries = $derived(
sortedCatalog.filter((series) => series.volumes.some((vol) => !vol.isPlaceholder))
);
let placeholderSeries = $derived(
sortedCatalog.filter((series) => series.volumes.every((vol) => vol.isPlaceholder))
);
// Collect all placeholder volumes from the entire catalog
let allPlaceholderVolumes = $derived(
sortedCatalog.flatMap((series) => series.volumes.filter((vol) => vol.isPlaceholder))
);
// Count placeholders by provider for UI display
let placeholdersByProvider = $derived.by(() => {
const counts: Record<string, number> = {};
for (const vol of allPlaceholderVolumes) {
const provider = getCloudProvider(vol) || 'unknown';
counts[provider] = (counts[provider] || 0) + 1;
}
return counts;
});
// Format provider breakdown for display (e.g., "3 Drive • 2 MEGA")
let providerBreakdown = $derived.by(() => {
const providerNames: Record<string, string> = {
'google-drive': 'Drive',
mega: 'MEGA',
webdav: 'WebDAV'
};
return Object.entries(placeholdersByProvider)
.map(([provider, count]) => `${count} ${providerNames[provider] || provider}`)
.join(' • ');
});
$effect(() => {
// Re-attempt restoration as catalog data/layout changes while loading.
sortedCatalog.length;
$miscSettings.galleryLayout;
$miscSettings.gallerySorting;
startRestoreLoop();
});
async function downloadAllPlaceholders() {
if (!allPlaceholderVolumes || allPlaceholderVolumes.length === 0) return;
if (!hasAuthenticatedProvider) {
showSnackbar('Please connect to a cloud storage provider first');
return;
}
try {
queueSeriesVolumes(allPlaceholderVolumes);
} catch (error) {
console.error('Failed to queue placeholders for download:', error);
}
}
</script>
{#if $catalog === null}
<Loader>Loading catalog...</Loader>
{:else if $catalog.length > 0}
<div class="flex flex-col gap-5">
<div class="flex w-full gap-1 py-2">
<div class="flex-grow">
<Search bind:value={search} class="w-full [&>div>input]:h-10" size="md" />
</div>
<Button
size="sm"
color="alternative"
onclick={onLayout}
class="flex h-10 min-w-10 items-center justify-center"
>
{#if $miscSettings.galleryLayout === 'list'}
<GridOutline class="h-5 w-5" />
{:else}
<ListOutline class="h-5 w-5" />
{/if}
</Button>
<Button
size="sm"
color="alternative"
onclick={onOrder}
class="flex h-10 min-w-10 items-center justify-center"
>
<SortOutline class="h-5 w-5" />
<span class="ml-1 text-xs">
{#if $miscSettings.gallerySorting === 'ASC'}
A-Z
{:else if $miscSettings.gallerySorting === 'DESC'}
Z-A
{:else}
Smart
{/if}
</span>
</Button>
</div>
{#if search && sortedCatalog.length === 0}
<div class="p-20 text-center">
<p>No results found.</p>
</div>
{:else}
<!-- Local series -->
<div class="flex flex-col flex-wrap justify-center gap-[3px] sm:flex-row sm:justify-start">
{#if $miscSettings.galleryLayout === 'grid'}
{#each localSeries as { title, volumes } (title)}
<CatalogItem {volumes} providerName={providerDisplayName} />
{/each}
{:else}
<Listgroup active class="w-full">
{#each localSeries as { title, volumes } (title)}
<CatalogListItem {volumes} providerName={providerDisplayName} />
{/each}
</Listgroup>
{/if}
</div>
<!-- Placeholder series (Cloud providers) -->
{#if placeholderSeries && placeholderSeries.length > 0}
<div class="mt-8">
<div class="mb-4 flex items-center justify-between px-4">
<div>
<h4 class="text-lg font-semibold text-gray-400">
Available in {providerDisplayName} ({placeholderSeries.length} series)
</h4>
{#if providerBreakdown}
<p class="mt-1 text-sm text-gray-500">{providerBreakdown}</p>
{/if}
</div>
{#if hasAuthenticatedProvider && allPlaceholderVolumes.length > 0}
<Button size="sm" color="blue" onclick={downloadAllPlaceholders}>
<DownloadSolid class="me-1 h-3 w-3" />
Download all
</Button>
{/if}
</div>
<div
class="flex flex-col flex-wrap justify-center gap-[3px] sm:flex-row sm:justify-start"
>
{#if $miscSettings.galleryLayout === 'grid'}
{#each placeholderSeries as { title, volumes } (title)}
<CatalogItem {volumes} providerName={providerDisplayName} />
{/each}
{:else}
<Listgroup active class="w-full">
{#each placeholderSeries as { title, volumes } (title)}
<CatalogListItem {volumes} providerName={providerDisplayName} />
{/each}
</Listgroup>
{/if}
</div>
</div>
{/if}
{/if}
</div>
{:else}
<div class="p-20 text-center">
{#if $isUpgrading}
<p>Upgrading and optimizing manga catalog... Please wait.</p>
{:else}
<p>Your catalog is currently empty.</p>
<p class="text-sm text-gray-500">
To add manga, click the <UploadSolid class="inline h-4 w-4" /> button in the top right.
</p>
{/if}
</div>
{/if}