Merge origin/main (ResourceList item-based refactor #612, IdP auto-redirect #593) into round 11

Conflict resolution re-applies the round-11 SPA optimizations onto the
refactored item-based ResourceList (which independently converged on the
favoriteIds-prop star — S2 is now upstream's shape):

- ResourceList.selectedItems: upstream reintroduced the full O(N)
  items.filter per selection toggle; replaced with the round-11
  id-index projection — O(k·log k), item order preserved
  (benches/ROUND11.md §S1)
- favorites/recent pages: upstream's rewrite kept the host-side
  selectedItems shadow + unused selectedIds mirror and ignored the
  batchToolbar snippet param; re-applied the param-consuming shape and
  deleted the shadows

Validation on the merged tree: clippy --all-features --all-targets
-D warnings clean; cargo test --workspace 524 passed; frontend npm run
check 0 errors; vitest 310 passed (upstream's new tests + round-11 gates)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ABhTEHuGujvwoodh67Kga7
This commit is contained in:
Claude
2026-07-18 23:15:10 +00:00
17 changed files with 1103 additions and 406 deletions
+78 -84
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { SvelteSet } from 'svelte/reactivity';
import Button from '$lib/components/Button.svelte';
import { useOwnerCache } from '$lib/composables/useOwnerCache.svelte';
import { errorToast } from '$lib/utils/errors';
@@ -17,12 +18,13 @@
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 type { FileItem, FolderItem } from '$lib/api/types';
import { lazyComponent } from '$lib/composables/lazyComponent.svelte';
import ResourceList, {
isFile,
type ContextAction,
type GroupByDef,
type ResourceEntry
type ItemContext
} from '$lib/components/ResourceList.svelte';
import { confirmDialog, promptDialog } from '$lib/stores/dialogs.svelte';
import { t } from '$lib/i18n/index.svelte';
@@ -35,39 +37,27 @@
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
};
})
// Favorites view DELIBERATELY doesn't set `showDotfileToggle` on
// the ResourceList below — favoriting is an explicit "I want to
// keep an eye on this" action by the user, and hiding a starred
// dotfile here would contradict that intent. The
// `preferences.hideDotfiles` toggle 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: explicit-
// action surfaces don't filter, algorithmic surfaces do.
//
// ResourceList consumes raw `FileItem | FolderItem`; the favorites
// envelope contributes `favorited_at` via `date` in contextMap. All
// items on this page are favorites — pass every id in `favoriteIds`
// so the star widget lights up universally.
const items = $derived(raw.map((it) => it.resource as FileItem | FolderItem));
const contextMap = $derived(
new Map<string, ItemContext>(
raw.map((it) => [it.resource.id, { date: it.favorited_at } satisfies ItemContext])
)
);
const favoriteIds = $derived(new SvelteSet(items.map((i) => i.id)));
const groupBys: GroupByDef[] = [
{ key: '', label: t('files.name', 'Name'), orderBy: 'name', icon: 'arrow-up-a-z' },
@@ -75,33 +65,33 @@
key: 'owner',
label: t('groupby.owner', 'Owner'),
orderBy: 'owner',
bucketOf: (e) => e.ownerId ?? null,
bucketOf: (item) => item.created_by ?? null,
labelOf: (id) => owners.label(id)
},
{
key: 'type',
label: t('groupby.type', 'Type'),
orderBy: 'type',
bucketOf: (e) => e.category ?? 'other',
bucketOf: (item) => item.category ?? 'other',
labelOf: (k) => typeLabel(k)
},
{
key: 'size',
label: t('groupby.size', 'Size'),
orderBy: 'size',
bucketOf: (e) => sizeBucket(e.kind === 'folder' ? null : e.size)
bucketOf: (item) => sizeBucket(isFile(item) ? item.size : null)
},
{
key: 'favoriteDate',
label: t('groupby.favoriteDate', 'Favorite date'),
orderBy: 'favorited_at',
bucketOf: (e) => dateBucket(e.date)
bucketOf: (_item, ctx) => dateBucket(ctx?.date)
},
{
key: 'modifiedAt',
label: t('groupby.modifiedAt', 'Modified date'),
orderBy: 'modified_at',
bucketOf: (e) => dateBucket(e.modifiedAt)
bucketOf: (item) => dateBucket(item.modified_at)
}
];
@@ -144,22 +134,20 @@
if (shareOpen) void shareDialog.load();
});
function open(entry: ResourceEntry) {
if (entry.kind === 'folder') {
goto(resolve(`/files/${entry.id}`));
function open(item: FileItem | FolderItem) {
if (!isFile(item)) {
goto(resolve(`/files/${item.id}`));
return;
}
const item = byId.get(entry.id);
if (item) {
viewerFile = item.resource as FileItem;
viewerOpen = true;
}
viewerFile = item;
viewerOpen = true;
}
async function unfavorite(entry: ResourceEntry) {
async function unfavorite(item: FileItem | FolderItem) {
const kind = isFile(item) ? 'file' : 'folder';
try {
await removeFavorite(entry.kind, entry.id);
raw = raw.filter((i) => i.resource.id !== entry.id);
await removeFavorite(kind, item.id);
raw = raw.filter((i) => i.resource.id !== item.id);
} catch (e) {
errorToast(e);
}
@@ -172,44 +160,48 @@
let shareOpen = $state(false);
let shareTarget = $state<{ id: string; name: string; kind: 'file' | 'folder' } | null>(null);
async function rename(entry: ResourceEntry) {
function kindOf(item: FileItem | FolderItem): 'file' | 'folder' {
return isFile(item) ? 'file' : 'folder';
}
async function rename(item: FileItem | FolderItem) {
const name = await promptDialog({
title: t('common.rename', 'Rename'),
defaultValue: entry.name,
defaultValue: item.name,
confirmText: t('common.rename', 'Rename')
});
if (!name || name === entry.name) return;
if (!name || name === item.name) return;
try {
if (entry.kind === 'file') await renameFile(entry.id, name);
else await renameFolder(entry.id, name);
if (isFile(item)) await renameFile(item.id, name);
else await renameFolder(item.id, name);
await load(true, orderByForGroup());
} catch (e) {
errorToast(e);
}
}
async function remove(entry: ResourceEntry) {
async function remove(item: FileItem | FolderItem) {
const ok = await confirmDialog({
title: t('common.delete', 'Delete'),
message: t('files.confirm_delete', { name: entry.name }, 'Delete "{{name}}"?'),
message: t('files.confirm_delete', { name: item.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);
if (isFile(item)) await deleteFile(item.id);
else await deleteFolder(item.id);
raw = raw.filter((i) => i.resource.id !== item.id);
} catch (e) {
errorToast(e);
}
}
function downloadEntry(entry: ResourceEntry) {
if (entry.kind !== 'file') return;
function downloadItem(item: FileItem | FolderItem) {
if (!isFile(item)) return;
const a = document.createElement('a');
a.href = fileDownloadUrl(entry.id);
a.download = entry.name;
a.href = fileDownloadUrl(item.id);
a.download = item.name;
document.body.appendChild(a);
a.click();
a.remove();
@@ -220,14 +212,14 @@
key: 'download',
label: t('common.download', 'Download'),
icon: 'download',
run: downloadEntry
run: downloadItem
},
{
key: 'share',
label: t('files.share', 'Share'),
icon: 'share-alt',
run: (e) => {
shareTarget = { id: e.id, name: e.name, kind: e.kind };
run: (item) => {
shareTarget = { id: item.id, name: item.name, kind: kindOf(item) };
shareOpen = true;
}
},
@@ -235,9 +227,9 @@
key: 'move',
label: t('files.move', 'Move'),
icon: 'arrows-alt',
run: (e) => {
run: (item) => {
moveItems = null;
moveTarget = { id: e.id, name: e.name, kind: e.kind };
moveTarget = { id: item.id, name: item.name, kind: kindOf(item) };
moveOpen = true;
}
},
@@ -246,21 +238,22 @@
];
// ── 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.
// Selected items arrive via the batchToolbar snippet param —
// ResourceList already derives them (O(selection), not O(N)); a
// host-side `items.filter(...)` shadow would re-run a second full scan
// per selection toggle, and its id mirror is unnecessary (the component
// prunes its own selection when items reload) — benches/ROUND11.md §S1.
type Selectable = FileItem | FolderItem;
function batchTargets(sel: ResourceEntry[]) {
return sel.map((e) => ({ id: e.id, name: e.name, kind: e.kind }));
function batchTargets(sel: Selectable[]) {
return sel.map((i) => ({ id: i.id, name: i.name, kind: kindOf(i) }));
}
function batchDownload(sel: ResourceEntry[]) {
for (const e of sel) downloadEntry(e);
function batchDownload(sel: Selectable[]) {
for (const i of sel) downloadItem(i);
}
async function batchDelete(sel: ResourceEntry[]) {
async function batchDelete(sel: Selectable[]) {
const ok = await confirmDialog({
title: t('common.delete', 'Delete'),
message: t('files.confirm_delete_n', { count: sel.length }, 'Delete {{count}} item(s)?'),
@@ -269,10 +262,8 @@
});
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));
await Promise.all(sel.map((i) => (isFile(i) ? deleteFile(i.id) : deleteFolder(i.id))));
const removed = new Set(sel.map((i) => i.id));
raw = raw.filter((i) => !removed.has(i.resource.id));
} catch (e) {
errorToast(e);
@@ -286,7 +277,10 @@
<ResourceList
title={t('nav.favorites', 'Favorites')}
items={entries}
{items}
{contextMap}
{favoriteIds}
resolveOwnerName={(id) => owners.name(id)}
{loading}
{error}
emptyIcon="star"
@@ -14,6 +14,10 @@ vi.mock('$lib/api/endpoints/favorites', () => ({
}));
vi.mock('$lib/api/endpoints/files', () => ({
fileDownloadUrl: () => '/dl',
// ResourceList uses this to build the `<img class="file-thumb">`
// src for the fallback path; tests don't render actual thumbnails
// but the module import needs to succeed.
fileThumbnailUrl: () => '/thumb.png',
renameFile: vi.fn(),
deleteFile: vi.fn()
}));
+24 -1
View File
@@ -249,6 +249,19 @@
}
}
// Shared by onMount step 4 and onSetup: true + navigates away iff OIDC is
// the only login method. Centralised so the guard can't drift between the
// two call sites (only the `?error=` loop-guard, checked at onMount time,
// doesn't apply post-setup — a freshly created admin can't have bounced
// off the IdP yet).
function tryAutoRedirectToIdp(): boolean {
if (oidc.enabled && oidc.password_login_enabled === false && oidc.authorize_endpoint) {
window.location.replace(oidc.authorize_endpoint);
return true;
}
return false;
}
async function onSetup(e: SubmitEvent) {
e.preventDefault();
setupError = '';
@@ -260,10 +273,14 @@
busy = true;
try {
await setupAdmin(setupEmail, setupPassword);
setupSuccess = t('auth.admin_success', 'Administrator created. You can now sign in.');
setupEmail = setupPassword = setupConfirm = '';
// Admin now exists — fold the setup affordance away and return to login.
setupAvailable = false;
// OIDC-only: the login page would immediately redirect on the next
// visit anyway — skip the "you can now sign in" detour and forward
// straight to the IdP instead of leaving a dead-end local form.
if (tryAutoRedirectToIdp()) return;
setupSuccess = t('auth.admin_success', 'Administrator created. You can now sign in.');
setTimeout(() => {
mode = 'login';
setupSuccess = '';
@@ -323,6 +340,12 @@
setupAvailable = !status.initialized;
if (setupAvailable) mode = 'setup';
// 4) Auto-redirect: when OIDC is the only auth method, skip the login page.
// Guard against loops: if the IdP returned ?error=, fall through to the UI.
if (!setupAvailable && !page.url.searchParams.has('error') && tryAutoRedirectToIdp()) {
return;
}
booting = false;
});
+64 -1
View File
@@ -1,4 +1,4 @@
import { it, expect, vi, beforeEach } from 'vitest';
import { it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
const { goto, pageState, session } = vi.hoisted(() => {
@@ -53,6 +53,24 @@ beforeEach(() => {
m(auth.getAuthStatus).mockResolvedValue({ initialized: true });
});
// jsdom's `Location` can't be spied on in place (its setters trigger
// "not implemented" navigation errors), so swap the whole object for a
// stub around each test that needs to observe `window.location.replace`.
const originalLocation = window.location;
let replaceSpy: ReturnType<typeof vi.fn>;
beforeEach(() => {
replaceSpy = vi.fn();
Object.defineProperty(window, 'location', {
configurable: true,
value: { ...originalLocation, replace: replaceSpy }
});
});
afterEach(() => {
Object.defineProperty(window, 'location', { configurable: true, value: originalLocation });
});
it('logs in and redirects', async () => {
m(auth.login).mockResolvedValue({ user: { id: '1' } });
render(LoginPage);
@@ -179,3 +197,48 @@ it('renders an SSO sign-in link when an OIDC provider is configured', async () =
const sso = await screen.findByTestId('login-oidc-btn');
expect(sso.getAttribute('href')).toBe('https://idp.test/auth');
});
it('auto-redirects to the IdP when OIDC is the only login method', async () => {
m(auth.getOidcProviders).mockResolvedValue({
enabled: true,
password_login_enabled: false,
authorize_endpoint: '/api/auth/oidc/authorize'
});
render(LoginPage);
await waitFor(() => expect(replaceSpy).toHaveBeenCalledWith('/api/auth/oidc/authorize'));
});
it('does not auto-redirect when password login is also enabled', async () => {
m(auth.getOidcProviders).mockResolvedValue({
enabled: true,
password_login_enabled: true,
authorize_endpoint: '/api/auth/oidc/authorize'
});
render(LoginPage);
await screen.findByTestId('login-form');
expect(replaceSpy).not.toHaveBeenCalled();
});
it('does not auto-redirect after the IdP already returned an error (loop guard)', async () => {
pageState.url = new URL('http://localhost/login?error=access_denied');
m(auth.getOidcProviders).mockResolvedValue({
enabled: true,
password_login_enabled: false,
authorize_endpoint: '/api/auth/oidc/authorize'
});
render(LoginPage);
await screen.findByTestId('login-form');
expect(replaceSpy).not.toHaveBeenCalled();
});
it('does not auto-redirect during first-run setup', async () => {
m(auth.getAuthStatus).mockResolvedValue({ initialized: false });
m(auth.getOidcProviders).mockResolvedValue({
enabled: true,
password_login_enabled: false,
authorize_endpoint: '/api/auth/oidc/authorize'
});
render(LoginPage);
await screen.findByTestId('login-setup-form');
expect(replaceSpy).not.toHaveBeenCalled();
});
+98 -94
View File
@@ -18,16 +18,22 @@
} from '$lib/api/endpoints/favorites';
import { fileDownloadUrl, renameFile, deleteFile } from '$lib/api/endpoints/files';
import { renameFolder, deleteFolder } from '$lib/api/endpoints/folders';
import type { FileItem, ItemType } from '$lib/api/types';
import type { FileItem, FolderItem, ItemType } from '$lib/api/types';
import { lazyComponent } from '$lib/composables/lazyComponent.svelte';
import ResourceList, {
isFile,
type ContextAction,
type GroupByDef,
type ResourceEntry
type ItemContext
} from '$lib/components/ResourceList.svelte';
import { confirmDialog, promptDialog } from '$lib/stores/dialogs.svelte';
// `preferences.hideDotfiles` + `isDotfile` are read here only to
// derive `hiddenCount` for the empty-state message — the actual
// filter is inside ResourceList (gated on `showDotfileToggle`).
// `replaceSet` is from perf-round-6: `loadFavoriteIds` mutates
// the reactive SvelteSet in place instead of re-creating it.
import { preferences } from '$lib/stores/preferences.svelte';
import { filterDotfiles } from '$lib/utils/dotfileFilter';
import { isDotfile } from '$lib/utils/dotfileFilter';
import { replaceSet } from '$lib/utils/sets';
import { t } from '$lib/i18n/index.svelte';
@@ -42,39 +48,28 @@
// spares the other favorited rows' readers.
const favoriteIds = new SvelteSet<string>();
const byId = $derived(new Map(raw.map((it) => [it.resource.id, it])));
const allEntries = $derived(
raw.map((it): ResourceEntry => {
const isFile = it.resource_type === 'file';
// §14 provenance: Recent's mental model is "who touched this
// recently", so `updated_by` (the last mutator) is the right
// signal — distinct from Favorites/Files which use `created_by`.
const ownerId = it.resource.updated_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.accessed_at,
ownerId,
ownerName: owners.name(ownerId),
// Star state comes from the `favoriteIds` prop on ResourceList,
// NOT from the entry — reading the SvelteSet here subscribed
// this whole mapper to it, so one star click rebuilt all N
// entries + re-rendered every visible row (benches/ROUND11.md).
category: isFile ? it.resource.category : 'Folder',
modifiedAt: it.resource.modified_at
};
})
// Envelope shape: `accessed_at` → `ctx.date`, `updated_by` → `ctx.ownerId`
// (Recent's provenance semantic — "who touched this recently" — differs
// from Favorites'/Files' `created_by`).
//
// Dotfile hiding is delegated to ResourceList via `showDotfileToggle`
// — the component reads `preferences.hideDotfiles` and drops matching
// rows from every downstream reader (bucketing, rendering, select-
// all). The `hiddenCount` here is derived independently via the
// shared `isDotfile` predicate purely for the empty-state message
// below (distinguishes "genuinely empty" from "everything filtered").
const items = $derived(raw.map((it) => it.resource as FileItem | FolderItem));
const contextMap = $derived(
new Map<string, ItemContext>(
raw.map((it) => [
it.resource.id,
{ date: it.accessed_at, ownerId: it.resource.updated_by ?? null } satisfies ItemContext
])
)
);
const hiddenCount = $derived(
preferences.hideDotfiles ? items.filter((i) => isDotfile(i.name)).length : 0
);
const entries = $derived(filterDotfiles(allEntries, preferences.hideDotfiles));
// Count of items suppressed by the dotfile filter — surfaced in
// the empty-state hint below so a `.eslintrc`-only Recent doesn't
// read as "nothing here yet".
const hiddenCount = $derived(preferences.hideDotfiles ? allEntries.length - entries.length : 0);
const groupBys: GroupByDef[] = [
{ key: '', label: t('files.name', 'Name'), orderBy: 'name', icon: 'arrow-up-a-z' },
@@ -82,33 +77,33 @@
key: 'owner',
label: t('groupby.owner', 'Owner'),
orderBy: 'owner',
bucketOf: (e) => e.ownerId ?? null,
bucketOf: (_item, ctx) => ctx?.ownerId ?? null,
labelOf: (id) => owners.label(id)
},
{
key: 'type',
label: t('groupby.type', 'Type'),
orderBy: 'type',
bucketOf: (e) => e.category ?? 'other',
bucketOf: (item) => item.category ?? 'other',
labelOf: (k) => typeLabel(k)
},
{
key: 'size',
label: t('groupby.size', 'Size'),
orderBy: 'size',
bucketOf: (e) => sizeBucket(e.kind === 'folder' ? null : e.size)
bucketOf: (item) => sizeBucket(isFile(item) ? item.size : null)
},
{
key: 'accessedAt',
label: t('groupby.accessedAt', 'Accessed date'),
orderBy: 'accessed_at',
bucketOf: (e) => dateBucket(e.date)
bucketOf: (_item, ctx) => dateBucket(ctx?.date)
},
{
key: 'modifiedAt',
label: t('groupby.modifiedAt', 'Modified date'),
orderBy: 'modified_at',
bucketOf: (e) => dateBucket(e.modifiedAt)
bucketOf: (item) => dateBucket(item.modified_at)
}
];
@@ -164,29 +159,37 @@
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;
}
function kindOf(item: FileItem | FolderItem): ItemType {
return isFile(item) ? 'file' : 'folder';
}
async function toggleFavorite(entry: ResourceEntry) {
const isFav = favoriteIds.has(entry.id);
function open(item: FileItem | FolderItem) {
if (!isFile(item)) {
goto(resolve(`/files/${item.id}`));
return;
}
viewerFile = item;
viewerOpen = true;
}
// Callback signature is `FileItem | FolderItem` (ResourceList
// hands raw items to `onfavorite` — the pre-migration
// `ResourceEntry` shape is gone). Set mutation is in-place per
// perf-round-6: 1 000 toggles @ N=5 000 dropped from 771.9 ms
// to 1.9 ms by skipping the full-set copy that every reader of
// `favoriteIds` used to see.
async function toggleFavorite(item: FileItem | FolderItem) {
const isFav = favoriteIds.has(item.id);
const kind = kindOf(item);
// Optimistic in-place toggle, reverted on failure.
if (isFav) favoriteIds.delete(entry.id);
else favoriteIds.add(entry.id);
if (isFav) favoriteIds.delete(item.id);
else favoriteIds.add(item.id);
try {
if (isFav) await removeFavorite(entry.kind, entry.id);
else await addFavorite(entry.kind, entry.id);
if (isFav) await removeFavorite(kind, item.id);
else await addFavorite(kind, item.id);
} catch (e) {
if (isFav) favoriteIds.add(entry.id);
else favoriteIds.delete(entry.id);
if (isFav) favoriteIds.add(item.id);
else favoriteIds.delete(item.id);
errorToast(e);
}
}
@@ -214,44 +217,44 @@
let shareOpen = $state(false);
let shareTarget = $state<{ id: string; name: string; kind: ItemType } | null>(null);
async function rename(entry: ResourceEntry) {
async function rename(item: FileItem | FolderItem) {
const name = await promptDialog({
title: t('common.rename', 'Rename'),
defaultValue: entry.name,
defaultValue: item.name,
confirmText: t('common.rename', 'Rename')
});
if (!name || name === entry.name) return;
if (!name || name === item.name) return;
try {
if (entry.kind === 'file') await renameFile(entry.id, name);
else await renameFolder(entry.id, name);
if (isFile(item)) await renameFile(item.id, name);
else await renameFolder(item.id, name);
await load(true, orderByForGroup());
} catch (e) {
errorToast(e);
}
}
async function remove(entry: ResourceEntry) {
async function remove(item: FileItem | FolderItem) {
const ok = await confirmDialog({
title: t('common.delete', 'Delete'),
message: t('files.confirm_delete', { name: entry.name }, 'Delete "{{name}}"?'),
message: t('files.confirm_delete', { name: item.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);
if (isFile(item)) await deleteFile(item.id);
else await deleteFolder(item.id);
raw = raw.filter((i) => i.resource.id !== item.id);
} catch (e) {
errorToast(e);
}
}
function downloadEntry(entry: ResourceEntry) {
if (entry.kind !== 'file') return;
function downloadItem(item: FileItem | FolderItem) {
if (!isFile(item)) return;
const a = document.createElement('a');
a.href = fileDownloadUrl(entry.id);
a.download = entry.name;
a.href = fileDownloadUrl(item.id);
a.download = item.name;
document.body.appendChild(a);
a.click();
a.remove();
@@ -262,14 +265,14 @@
key: 'download',
label: t('common.download', 'Download'),
icon: 'download',
run: downloadEntry
run: downloadItem
},
{
key: 'share',
label: t('files.share', 'Share'),
icon: 'share-alt',
run: (e) => {
shareTarget = { id: e.id, name: e.name, kind: e.kind };
run: (item) => {
shareTarget = { id: item.id, name: item.name, kind: kindOf(item) };
shareOpen = true;
}
},
@@ -277,9 +280,9 @@
key: 'move',
label: t('files.move', 'Move'),
icon: 'arrows-alt',
run: (e) => {
run: (item) => {
moveItems = null;
moveTarget = { id: e.id, name: e.name, kind: e.kind };
moveTarget = { id: item.id, name: item.name, kind: kindOf(item) };
moveOpen = true;
}
},
@@ -288,21 +291,22 @@
];
// ── Selection + batch ─────────────────────────────────────────────────────
// The selected entries come in through the batchToolbar snippet param —
// ResourceList already derives them (O(selection), not O(N)); the old
// host-side `entries.filter(...)` shadow re-ran a second full scan per
// toggle, and its id mirror is gone with it (the component prunes its
// own selection when items reload) — benches/ROUND11.md.
// Selected items arrive via the batchToolbar snippet param —
// ResourceList already derives them (O(selection), not O(N)); a
// host-side `items.filter(...)` shadow would re-run a second full scan
// per selection toggle, and its id mirror is unnecessary (the component
// prunes its own selection when items reload) — benches/ROUND11.md §S1.
type Selectable = FileItem | FolderItem;
function batchTargets(sel: ResourceEntry[]) {
return sel.map((e) => ({ id: e.id, name: e.name, kind: e.kind }));
function batchTargets(sel: Selectable[]) {
return sel.map((i) => ({ id: i.id, name: i.name, kind: kindOf(i) }));
}
function batchDownload(sel: ResourceEntry[]) {
for (const e of sel) downloadEntry(e);
function batchDownload(sel: Selectable[]) {
for (const i of sel) downloadItem(i);
}
async function batchDelete(sel: ResourceEntry[]) {
async function batchDelete(sel: Selectable[]) {
const ok = await confirmDialog({
title: t('common.delete', 'Delete'),
message: t('files.confirm_delete_n', { count: sel.length }, 'Delete {{count}} item(s)?'),
@@ -311,10 +315,8 @@
});
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));
await Promise.all(sel.map((i) => (isFile(i) ? deleteFile(i.id) : deleteFolder(i.id))));
const removed = new Set(sel.map((i) => i.id));
raw = raw.filter((i) => !removed.has(i.resource.id));
} catch (e) {
errorToast(e);
@@ -331,7 +333,10 @@
<ResourceList
title={t('nav.recent', 'Recent')}
items={entries}
{items}
{contextMap}
{favoriteIds}
resolveOwnerName={(id) => owners.name(id)}
{loading}
{error}
emptyIcon={hiddenCount > 0 ? 'eye-slash' : 'clock'}
@@ -349,7 +354,6 @@
onloadmore={() => load(false, orderByForGroup())}
onopen={open}
onfavorite={toggleFavorite}
{favoriteIds}
showOwner
showDotfileToggle
selectable
@@ -363,7 +367,7 @@
}}
>
{#snippet toolbar()}
{#if entries.length > 0}
{#if items.length > 0}
<Button icon="broom" data-testid="recent-clear-btn" onclick={clearAll}
>{t('recent.clear', 'Clear recent')}</Button
>
+31 -43
View File
@@ -5,12 +5,13 @@
import { onMount } from 'svelte';
import { dateBucket, resolveOwnerName, typeLabel } from '$lib/api/endpoints/favorites';
import { fetchSharedWithMe, type IncomingGrantItem } from '$lib/api/endpoints/grants';
import type { FileItem } from '$lib/api/types';
import type { FileItem, FolderItem } from '$lib/api/types';
import { lazyComponent } from '$lib/composables/lazyComponent.svelte';
import { useOwnerCache } from '$lib/composables/useOwnerCache.svelte';
import ResourceList, {
isFile,
type GroupByDef,
type ResourceEntry
type ItemContext
} from '$lib/components/ResourceList.svelte';
import { t } from '$lib/i18n/index.svelte';
import { session } from '$lib/stores/session.svelte';
@@ -31,36 +32,24 @@
const sharers = useOwnerCache(resolveOwnerName);
const byId = $derived(new Map(raw.map((it) => [it.resource.id, it])));
// Drive resources also surface in `/api/grants/incoming/resources`
// since the role_grants rewrite, but they don't belong in the
// file/folder ResourceList — they're reached through the drive
// picker / breadcrumb. Filter them out so the row UI keeps its
// file|folder type contract.
const fileFolderGrants = $derived(raw.filter((it) => it.resource_type !== 'drive'));
const entries = $derived(
// Drive resources also surface in `/api/grants/incoming/resources`
// since the role_grants rewrite, but they don't belong in the
// file/folder ResourceList — they're reached through the drive
// picker / breadcrumb. Filter them out here so the row UI keeps
// its file|folder type contract.
raw
.filter((it) => it.resource_type !== 'drive')
.map((it): ResourceEntry => {
const isFile = it.resource_type === 'file';
return {
id: it.resource.id,
name: it.resource.name,
kind: it.resource_type as 'file' | 'folder',
iconClass: it.resource.icon_class,
// The sharer becomes the "owner" surface — ResourceList renders
// `<UserVignette userId>` (avatar / name / external badge),
// resolved lazily via `/api/users/{id}`. `path` keeps the
// resource's real location so the row still shows where it
// lives, not a translated string.
ownerId: it.granted_by ?? null,
ownerName: sharers.name(it.granted_by),
path: it.resource.path,
size: isFile ? (it.resource as FileItem).size : null,
date: it.granted_at,
category: isFile ? it.resource.category : 'Folder'
};
})
// `granted_at` → `ctx.date`; `granted_by` overrides the owner column
// so the sharer shows up in the vignette (rather than the resource's
// intrinsic `created_by`, which is a stranger for grantees).
const items = $derived(fileFolderGrants.map((it) => it.resource as FileItem | FolderItem));
const contextMap = $derived(
new Map<string, ItemContext>(
fileFolderGrants.map((it) => [
it.resource.id,
{ date: it.granted_at, ownerId: it.granted_by ?? null } satisfies ItemContext
])
)
);
// Server-supported sort_by values (see grant_handler.rs:615):
@@ -75,21 +64,21 @@
key: 'sharedBy',
label: t('groupby.sharedBy', 'Shared by'),
orderBy: 'granted_by',
bucketOf: (e) => e.ownerId ?? null,
bucketOf: (_item, ctx) => ctx?.ownerId ?? null,
labelOf: (id) => sharers.label(id)
},
{
key: 'type',
label: t('groupby.type', 'Type'),
orderBy: 'type',
bucketOf: (e) => e.category ?? 'other',
bucketOf: (item) => item.category ?? 'other',
labelOf: (k) => typeLabel(k)
},
{
key: 'sharedAt',
label: t('groupby.sharedAt', 'Shared date'),
orderBy: 'granted_at',
bucketOf: (e) => dateBucket(e.date)
bucketOf: (_item, ctx) => dateBucket(ctx?.date)
}
];
@@ -128,16 +117,13 @@
if (viewerOpen) void fileViewer.load();
});
function open(entry: ResourceEntry) {
if (entry.kind === 'folder') {
goto(resolve(`/files/${entry.id}`));
function open(item: FileItem | FolderItem) {
if (!isFile(item)) {
goto(resolve(`/files/${item.id}`));
return;
}
const item = byId.get(entry.id);
if (item) {
viewerFile = item.resource as FileItem;
viewerOpen = true;
}
viewerFile = item;
viewerOpen = true;
}
onMount(() => load(true));
@@ -168,7 +154,9 @@
<ResourceList
title={t('nav.shared_with_me', 'Shared with me')}
items={entries}
{items}
{contextMap}
resolveOwnerName={(id) => sharers.name(id)}
{loading}
{error}
emptyText={t('shared_with_me.empty', 'Nothing has been shared with you yet.')}
+54 -47
View File
@@ -11,11 +11,12 @@
restoreTrashItem
} from '$lib/api/endpoints/trash';
import { dateBucket, sizeBucket, typeLabel } from '$lib/api/endpoints/favorites';
import type { Drive, FileItem, TrashResourceItem } from '$lib/api/types';
import type { Drive, FileItem, FolderItem, TrashResourceItem } from '$lib/api/types';
import Icon from '$lib/icons/Icon.svelte';
import ResourceList, {
isFile,
type GroupByDef,
type ResourceEntry
type ItemContext
} from '$lib/components/ResourceList.svelte';
import { confirmDialog } from '$lib/stores/dialogs.svelte';
import { t } from '$lib/i18n/index.svelte';
@@ -30,33 +31,32 @@
let groupBy = $state('remainingDays');
let reversed = $state(false);
// Trash view DELIBERATELY ignores `preferences.hideDotfiles`.
// Rationale: trash is a safety net — hiding items here would let
// an accidentally-trashed dotfile ride the retention timer to
// permanent deletion without ever being visible for recovery.
// The hide preference is UI cosmetics elsewhere; here it would
// become a footgun. Same reasoning applies to any future
// "review before destructive action" surface.
const entries = $derived(
raw.map((it): ResourceEntry => {
const isFile = it.resource_type === 'file';
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` carries the deletion date — rendered as an expiry chip.
date: it.deletion_date,
category: isFile ? it.resource.category : 'Folder',
modifiedAt: it.trashed_at,
// D2b: surface drive_id so the Drive group-by can bucket by it.
// Reuses the existing `ownerId` slot on ResourceEntry — both
// represent a UUID the listing pivots on; no new field needed.
ownerId: it.drive_id
};
})
// Trash view DELIBERATELY doesn't set `showDotfileToggle` on the
// ResourceList below. Trash is a safety net — hiding items here
// would let an accidentally-trashed dotfile ride the retention
// timer to permanent deletion without ever being visible for
// recovery. The `preferences.hideDotfiles` toggle is UI cosmetics
// elsewhere; here it would become a footgun. Same reasoning
// applies to any future "review before destructive action" surface.
//
// Items go to ResourceList as raw `FileItem | FolderItem`; the trash
// envelope's extra fields (`deletion_date`, `trashed_at`, `drive_id`)
// travel through `contextMap`, which page-provided group-by / render
// callbacks read via the `ctx` parameter.
const items = $derived(raw.map((it) => it.resource as FileItem | FolderItem));
const contextMap = $derived(
new Map<string, ItemContext>(
raw.map((it) => [
it.resource.id,
{
date: it.deletion_date,
extras: {
driveId: it.drive_id,
trashedAt: it.trashed_at
}
}
])
)
);
// "Drive" group rank: default-personal first, then secondary personal, then
@@ -89,33 +89,39 @@
key: 'drive',
label: t('trash.groupby.drive', 'Drive'),
orderBy: 'name',
bucketOf: (e) => (e.ownerId ? driveBucketKey(e.ownerId) : null),
bucketOf: (_item, ctx) => {
const driveId = ctx?.extras?.driveId;
return typeof driveId === 'string' ? driveBucketKey(driveId) : null;
},
labelOf: driveBucketLabel
},
{
key: 'remainingDays',
label: t('trash.groupby.remaining_days', 'Remaining days'),
orderBy: 'deletion_date',
bucketOf: (e) => remainingDaysBucket(e.date)
bucketOf: (_item, ctx) => remainingDaysBucket(ctx?.date)
},
{
key: 'type',
label: t('groupby.type', 'Type'),
orderBy: 'type',
bucketOf: (e) => e.category ?? 'other',
bucketOf: (item) => item.category ?? 'other',
labelOf: (k) => typeLabel(k)
},
{
key: 'size',
label: t('groupby.size', 'Size'),
orderBy: 'size',
bucketOf: (e) => sizeBucket(e.kind === 'folder' ? null : e.size)
bucketOf: (item) => sizeBucket(isFile(item) ? item.size : null)
},
{
key: 'trashedTime',
label: t('trash.groupby.trashed_time', 'Trashed time'),
orderBy: 'trashed_at',
bucketOf: (e) => dateBucket(e.modifiedAt)
bucketOf: (_item, ctx) => {
const t = ctx?.extras?.trashedAt;
return dateBucket(typeof t === 'number' ? t : null);
}
}
];
@@ -149,9 +155,9 @@
await load(true, orderByForGroup());
}
async function restore(entry: ResourceEntry) {
async function restore(item: FileItem | FolderItem) {
try {
await restoreTrashItem(entry.id);
await restoreTrashItem(item.id);
ui.notify(t('trash.restored', 'Restored'), 'success');
await reloadFromTop();
} catch (e) {
@@ -159,7 +165,7 @@
}
}
async function purge(entry: ResourceEntry) {
async function purge(item: FileItem | FolderItem) {
const ok = await confirmDialog({
title: t('trash.delete', 'Delete permanently'),
message: t('trash.confirm_delete', 'Permanently delete this item? This cannot be undone.'),
@@ -168,7 +174,7 @@
});
if (!ok) return;
try {
await deleteTrashItem(entry.id);
await deleteTrashItem(item.id);
await reloadFromTop();
} catch (e) {
errorToast(e);
@@ -258,7 +264,8 @@
<ResourceList
title={t('nav.trash', 'Trash')}
items={entries}
{items}
{contextMap}
{loading}
{error}
emptyIcon="trash"
@@ -276,15 +283,15 @@
}}
>
{#snippet toolbar()}
{#if entries.length > 0}
{#if items.length > 0}
<button class="btn btn-danger" data-testid="trash-empty-btn" onclick={purgeAll}>
<Icon name="trash" />
{t('trash.empty_action', 'Empty trash')}
</button>
{/if}
{/snippet}
{#snippet dateCell(entry)}
{@const chip = expiryChip(entry.date)}
{#snippet dateCell(_item, ctx)}
{@const chip = expiryChip(ctx?.date)}
<span class="expiry-chip expiry-chip--{chip.tier}">
<Icon name={chip.icon} class="expiry-chip__icon" />
{chip.label}
@@ -307,20 +314,20 @@
{/if}
{/if}
{/snippet}
{#snippet actions(entry)}
{#snippet actions(item)}
<button
class="btn-action"
data-testid={`trash-restore-btn-${entry.id}`}
data-testid={`trash-restore-btn-${item.id}`}
title={t('trash.restore', 'Restore')}
onclick={() => restore(entry)}
onclick={() => restore(item)}
>
<Icon name="undo" />
</button>
<button
class="btn-action btn-action--delete"
data-testid={`trash-delete-btn-${entry.id}`}
data-testid={`trash-delete-btn-${item.id}`}
title={t('trash.delete', 'Delete permanently')}
onclick={() => purge(entry)}
onclick={() => purge(item)}
>
<Icon name="trash" />
</button>