Files
Oxicloud/frontend/src/routes/favorites/+page.svelte
T
Claude 221c1f31b0 perf: round 11 — StoragePath joined-only, classifier fusion, memoized bodies, query-shape pack, SPA fine-grained stars
Backend (each change benchmark-gated with BEFORE replicas + equivalence
gates; see examples/bench_round11_micro.rs, bench_round11_queries.rs,
bench_log_writer.rs and benches/ROUND11.md — final numbers land in the
follow-up doc commit):

- StoragePath re-representation: single canonical joined String, segments
  derived on demand; File/Folder drop the duplicated path_string field
  (4000→1000 allocs per 500-row listing page)
- Display classifier fusion: classify_display shares one stack-lowered
  extension across the three decision trees; call sites in FileDto,
  folder/favorites/recent handlers, trash, path-resolver (+ interning
  where Arc::from was still used)
- /status.php and /openapi.json memoized into OnceLock<Bytes> (openapi
  rebuilt a 171 KiB spec per request: 2.8 ms → 18 ns)
- NC upload-session PROPFIND: write! + pre-sized body + stack RFC2822
  dates (2.3-2.6x, 2582→772 allocs at 256 chunks)
- REST download: dead FileDto clone removed (capture mime/size + move)
- CalendarEventDto/TrashedItem into_parts moves (11 KiB ical_data memcpy
  gone per CalDAV row); CardDAV getlastmodified stack render
- 4xx path: borrowed ErrorResponse serialize, ErrorKind::as_str,
  not_found/already_exists clone kill
- vCard emit via write!; search page moved out with into_iter skip/take;
  content-hit UUIDs parsed once; group last-user check via HashSet
- RateLimiter: lock-free get + insert (and_upsert_with variant REJECTED
  by benchmark); CSRF token borrow-compare + borrowed cookie extraction
- Thumbnail/preview ETags built from as_str (Debug-identical bytes)
- Encrypted backend: encrypt_in_place_detached single-buffer write path,
  chunk-sized reserve in collect_stream; retry labels made lazy
- PG: deferred upload registration 3→1 round-trips (persist_file CTE
  template); direct_grant_cache for Calendar/AddressBook/Playlist authz
  (single-flight + set_role/clear_role invalidation); expand_user
  tokio::join!; geo clusters min(uuid)::text; recluster face assignment
  batched into one UNNEST update
- People recluster cosine: norms precomputed once (bit-identical gate)
- NC capabilities poll logs demoted to debug; tracing-appender dep added
  for the log-writer benchmark

Frontend:
- ResourceList.selectedEntries O(N)-per-toggle → id-index projection
  O(k log k); favorites/recent consume the batchToolbar snippet param and
  drop their duplicate filter + dead selectedIds mirror
- Recent: star state via new favoriteIds prop — a star click no longer
  rebuilds all N entries
- admin timeAgo >30d fallback uses the cached Intl.DateTimeFormat
- vitest gates in src/lib/components/round11.bench.test.ts

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ABhTEHuGujvwoodh67Kga7
2026-07-18 22:02:00 +00:00

351 lines
11 KiB
Svelte

<script lang="ts">
import Button from '$lib/components/Button.svelte';
import { useOwnerCache } from '$lib/composables/useOwnerCache.svelte';
import { errorToast } from '$lib/utils/errors';
import { goto } from '$app/navigation';
import { resolve } from '$app/paths';
import { onMount } from 'svelte';
import {
dateBucket,
fetchFavoritesPage,
removeFavorite,
resolveOwnerName,
sizeBucket,
typeLabel,
type FavoritesResourceItem
} from '$lib/api/endpoints/favorites';
import { fileDownloadUrl } from '$lib/api/endpoints/files';
import { renameFile, deleteFile } from '$lib/api/endpoints/files';
import { renameFolder, deleteFolder } from '$lib/api/endpoints/folders';
import type { FileItem } from '$lib/api/types';
import { lazyComponent } from '$lib/composables/lazyComponent.svelte';
import ResourceList, {
type ContextAction,
type GroupByDef,
type ResourceEntry
} from '$lib/components/ResourceList.svelte';
import { confirmDialog, promptDialog } from '$lib/stores/dialogs.svelte';
import { t } from '$lib/i18n/index.svelte';
let raw = $state<FavoritesResourceItem[]>([]);
let cursor = $state<string | undefined>(undefined);
let loading = $state(false);
let error = $state<string | null>(null);
let groupBy = $state('');
let reversed = $state(false);
const owners = useOwnerCache(resolveOwnerName);
const byId = $derived(new Map(raw.map((it) => [it.resource.id, it])));
// Favorites view DELIBERATELY ignores `preferences.hideDotfiles`.
// Rationale: favoriting is an explicit "I want to keep an eye on
// this" action by the user — hiding a starred item on a different
// listing page because it starts with `.` contradicts that intent.
// The hide preference is for reducing incidental clutter in
// algorithmic listings (files/recent/photos), not for overriding
// user-intentional pins. Trash follows the same principle for a
// safety-net reason; the general rule shaping up: explicit-action
// surfaces don't filter, algorithmic surfaces do.
const entries = $derived(
raw.map((it): ResourceEntry => {
const isFile = it.resource_type === 'file';
// §14 provenance: `created_by` names who put the item into
// the system (Files browser / Favorites / Shared semantic).
const ownerId = it.resource.created_by ?? null;
return {
id: it.resource.id,
name: it.resource.name,
kind: it.resource_type,
iconClass: it.resource.icon_class,
path: it.resource.path,
size: isFile ? (it.resource as FileItem).size : null,
date: it.favorited_at,
ownerId,
ownerName: owners.name(ownerId),
isFavorite: true,
category: isFile ? it.resource.category : 'Folder',
modifiedAt: it.resource.modified_at
};
})
);
const groupBys: GroupByDef[] = [
{ key: '', label: t('files.name', 'Name'), orderBy: 'name', icon: 'arrow-up-a-z' },
{
key: 'owner',
label: t('groupby.owner', 'Owner'),
orderBy: 'owner',
bucketOf: (e) => e.ownerId ?? null,
labelOf: (id) => owners.label(id)
},
{
key: 'type',
label: t('groupby.type', 'Type'),
orderBy: 'type',
bucketOf: (e) => e.category ?? 'other',
labelOf: (k) => typeLabel(k)
},
{
key: 'size',
label: t('groupby.size', 'Size'),
orderBy: 'size',
bucketOf: (e) => sizeBucket(e.kind === 'folder' ? null : e.size)
},
{
key: 'favoriteDate',
label: t('groupby.favoriteDate', 'Favorite date'),
orderBy: 'favorited_at',
bucketOf: (e) => dateBucket(e.date)
},
{
key: 'modifiedAt',
label: t('groupby.modifiedAt', 'Modified date'),
orderBy: 'modified_at',
bucketOf: (e) => dateBucket(e.modifiedAt)
}
];
async function load(reset = false, orderBy = 'name', rev = reversed) {
loading = true;
error = null;
try {
const page = await fetchFavoritesPage({
cursor: reset ? undefined : cursor,
orderBy,
reverse: rev,
resourceTypes: ['file', 'folder']
});
raw = reset ? page.items : [...raw, ...page.items];
cursor = page.next_cursor;
void owners.resolve(page.items.map((i) => i.resource.created_by));
} catch (e) {
console.error('favorites: load error', e);
error = t('errors_loadFailed', 'Failed to load items');
} finally {
loading = false;
}
}
function orderByForGroup(): string {
return groupBys.find((g) => g.key === groupBy)?.orderBy ?? 'name';
}
let viewerOpen = $state(false);
let viewerFile = $state<FileItem | null>(null);
// The file preview is loaded the first time a file is opened, keeping its
// module out of this route's initial chunk.
const fileViewer = lazyComponent(() => import('$lib/components/FileViewer.svelte'));
const moveDialog = lazyComponent(() => import('$lib/components/MoveDialog.svelte'));
const shareDialog = lazyComponent(() => import('$lib/components/ShareDialog.svelte'));
$effect(() => {
if (viewerOpen) void fileViewer.load();
if (moveOpen) void moveDialog.load();
if (shareOpen) void shareDialog.load();
});
function open(entry: ResourceEntry) {
if (entry.kind === 'folder') {
goto(resolve(`/files/${entry.id}`));
return;
}
const item = byId.get(entry.id);
if (item) {
viewerFile = item.resource as FileItem;
viewerOpen = true;
}
}
async function unfavorite(entry: ResourceEntry) {
try {
await removeFavorite(entry.kind, entry.id);
raw = raw.filter((i) => i.resource.id !== entry.id);
} catch (e) {
errorToast(e);
}
}
// ── Context-menu actions ──────────────────────────────────────────────────
let moveOpen = $state(false);
let moveTarget = $state<{ id: string; name: string; kind: 'file' | 'folder' } | null>(null);
let moveItems = $state<{ id: string; name: string; kind: 'file' | 'folder' }[] | null>(null);
let shareOpen = $state(false);
let shareTarget = $state<{ id: string; name: string; kind: 'file' | 'folder' } | null>(null);
async function rename(entry: ResourceEntry) {
const name = await promptDialog({
title: t('common.rename', 'Rename'),
defaultValue: entry.name,
confirmText: t('common.rename', 'Rename')
});
if (!name || name === entry.name) return;
try {
if (entry.kind === 'file') await renameFile(entry.id, name);
else await renameFolder(entry.id, name);
await load(true, orderByForGroup());
} catch (e) {
errorToast(e);
}
}
async function remove(entry: ResourceEntry) {
const ok = await confirmDialog({
title: t('common.delete', 'Delete'),
message: t('files.confirm_delete', { name: entry.name }, 'Delete "{{name}}"?'),
confirmText: t('common.delete', 'Delete'),
danger: true
});
if (!ok) return;
try {
if (entry.kind === 'file') await deleteFile(entry.id);
else await deleteFolder(entry.id);
raw = raw.filter((i) => i.resource.id !== entry.id);
} catch (e) {
errorToast(e);
}
}
function downloadEntry(entry: ResourceEntry) {
if (entry.kind !== 'file') return;
const a = document.createElement('a');
a.href = fileDownloadUrl(entry.id);
a.download = entry.name;
document.body.appendChild(a);
a.click();
a.remove();
}
const contextActions: ContextAction[] = [
{
key: 'download',
label: t('common.download', 'Download'),
icon: 'download',
run: downloadEntry
},
{
key: 'share',
label: t('files.share', 'Share'),
icon: 'share-alt',
run: (e) => {
shareTarget = { id: e.id, name: e.name, kind: e.kind };
shareOpen = true;
}
},
{
key: 'move',
label: t('files.move', 'Move'),
icon: 'arrows-alt',
run: (e) => {
moveItems = null;
moveTarget = { id: e.id, name: e.name, kind: e.kind };
moveOpen = true;
}
},
{ key: 'rename', label: t('common.rename', 'Rename'), icon: 'pen', run: rename },
{ key: 'delete', label: t('common.delete', 'Delete'), icon: 'trash', danger: true, run: remove }
];
// ── Selection + batch ─────────────────────────────────────────────────────
// Selected entries arrive via the batchToolbar snippet param —
// ResourceList derives them once (O(selection)); the old host-side
// `entries.filter(...)` shadow re-ran a second full O(N) scan per
// selection toggle, and its id mirror is gone with it (the component
// prunes its own selection when items reload) — benches/ROUND11.md.
function batchTargets(sel: ResourceEntry[]) {
return sel.map((e) => ({ id: e.id, name: e.name, kind: e.kind }));
}
function batchDownload(sel: ResourceEntry[]) {
for (const e of sel) downloadEntry(e);
}
async function batchDelete(sel: ResourceEntry[]) {
const ok = await confirmDialog({
title: t('common.delete', 'Delete'),
message: t('files.confirm_delete_n', { count: sel.length }, 'Delete {{count}} item(s)?'),
confirmText: t('common.delete', 'Delete'),
danger: true
});
if (!ok) return;
try {
await Promise.all(
sel.map((e) => (e.kind === 'file' ? deleteFile(e.id) : deleteFolder(e.id)))
);
const removed = new Set(sel.map((e) => e.id));
raw = raw.filter((i) => !removed.has(i.resource.id));
} catch (e) {
errorToast(e);
}
}
onMount(() => load(true));
</script>
<svelte:head><title>{t('nav.favorites', 'Favorites')} · OxiCloud</title></svelte:head>
<ResourceList
title={t('nav.favorites', 'Favorites')}
items={entries}
{loading}
{error}
emptyIcon="star"
emptyText={t('favorites.empty_state', 'No favorites yet')}
emptyHint={t('favorites.empty_hint', 'Star files and folders to find them here quickly')}
hasMore={!!cursor}
onloadmore={() => load(false, orderByForGroup())}
onopen={open}
onfavorite={unfavorite}
showOwner
selectable
{contextActions}
{groupBys}
bind:groupBy
bind:reversed
onreload={(orderBy, rev) => {
cursor = undefined;
load(true, orderBy, rev);
}}
>
{#snippet batchToolbar(sel)}
<Button
icon="download"
data-testid="favorites-batch-download-btn"
onclick={() => batchDownload(sel)}>{t('common.download', 'Download')}</Button
>
<Button
icon="arrows-alt"
data-testid="favorites-batch-move-btn"
onclick={() => {
moveTarget = null;
moveItems = batchTargets(sel);
moveOpen = true;
}}>{t('files.move', 'Move')}</Button
>
<Button
variant="danger"
icon="trash"
data-testid="favorites-batch-delete-btn"
onclick={() => batchDelete(sel)}>{t('common.delete', 'Delete')}</Button
>
{/snippet}
</ResourceList>
{#if fileViewer.component}
{@const FileViewer = fileViewer.component}
<FileViewer bind:open={viewerOpen} file={viewerFile} />
{/if}
{#if moveDialog.component}
{@const MoveDialog = moveDialog.component}
<MoveDialog
bind:open={moveOpen}
item={moveTarget}
items={moveItems}
onmoved={() => load(true, orderByForGroup())}
/>
{/if}
{#if shareDialog.component}
{@const ShareDialog = shareDialog.component}
<ShareDialog bind:open={shareOpen} item={shareTarget} />
{/if}