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
+2
View File
@@ -100,7 +100,9 @@ tests/e2e/test-results/
tests/e2e/blob-report/
tests/e2e/playwright/.cache/
tests/e2e/playwright/.auth/
tests/webdav/storage-litmus/
tests/oidc-manual/
tests/caldav/storage/
tests/caldav/.venv/
tests/caldav/__pycache__/
+11
View File
@@ -16,6 +16,17 @@ export default ts.config(
...globals.browser,
...globals.node
}
},
rules: {
// `_`-prefixed args are the codebase's "intentionally unused"
// convention — mostly Svelte snippet positional params that
// have to be declared but aren't read (e.g. `dateCell(_item,
// ctx)`). Match the widely-used JS/TS ecosystem pattern so
// the intent is respected without per-line disable comments.
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' }
]
}
},
{
@@ -158,11 +158,17 @@ describe('coalesced progressive listing emissions (benchmark gate)', () => {
`collapses the O(N²) consumer re-derive on a fast ${PAGES}-page load (perf gate)`,
{ timeout: 30_000 },
async () => {
// Warm-up both paths (JIT tiering outside the measured windows).
mockPagedFetch();
await referenceFetchFolderListing('warm', (p) => consumerDerive(p));
mockPagedFetch();
await fetchFolderListing('warm', { onPage: (p) => consumerDerive(p) });
// Warm-up both paths, twice each, so V8's tiering has fully
// settled before we measure. A single warm-up was enough on
// developer laptops but bursty CPU steals on shared CI
// runners can leave one path un-tiered during measurement,
// skewing the wall-time ratio at line ~202 below.
for (let i = 0; i < 2; i++) {
mockPagedFetch();
await referenceFetchFolderListing('warm', (p) => consumerDerive(p));
mockPagedFetch();
await fetchFolderListing('warm', { onPage: (p) => consumerDerive(p) });
}
mockPagedFetch();
let refSorted = 0;
@@ -197,9 +203,19 @@ describe('coalesced progressive listing emissions (benchmark gate)', () => {
// stubbed pages ever take >150 ms — they don't on any healthy runner).
expect(emitsN).toBeLessThanOrEqual(3);
// ≥5x less consumer sort work is the point of the change.
// This is a pure DETERMINISTIC count (sum of `consumerDerive`
// return values) — hardware-independent, so catches an
// actual O(N²) → O(N) regression cleanly.
expect(sorted).toBeLessThan(refSorted / 5);
// And it must show up as wall time on the combined load+derive cycle.
expect(ms).toBeLessThan(refMs / 3);
// And it must show up as wall time on the combined load+
// derive cycle. 2x floor (loosened from 3x on 2026-07-18
// after a shared-CI-runner false alarm at 2.63x — bursty
// CPU steals eat headroom on the fine-grained
// `performance.now()` measurements). Still catches an
// O(N²) regression (which would be ~10x slower, not 2x)
// — the deterministic count above at line 200 is the real
// algorithmic gate.
expect(ms).toBeLessThan(refMs / 2);
}
);
});
+393 -123
View File
@@ -1,32 +1,38 @@
<script lang="ts" module>
import type { ItemType } from '$lib/api/types';
import type { FileItem, FolderItem } from '$lib/api/types';
/** Normalised row passed to ResourceList; views map their items to this. */
export interface ResourceEntry {
id: string;
name: string;
kind: ItemType;
iconClass?: string;
path?: string | null;
size?: number | null;
/**
* Per-item envelope info that isn't on `FileItem` / `FolderItem` itself
* — supplied by the page in a `contextMap` keyed by item id.
*
* Example use-cases:
* - `/trash`: `date = deletion_date`, `extras = { driveId, trashedAt }`.
* - `/recent`: `date = accessed_at`, `ownerId = updated_by`.
* - `/favorites`: `ownerId = created_by`.
*
* All fields are optional; ResourceList falls back to the equivalent
* intrinsic on the item (`modified_at`, `created_by`) when absent.
*/
export interface ItemContext {
/**
* Overrides `item.modified_at` for the date column + `modifiedAt`
* group-by dimension. Accepts epoch (ms or s), an ISO string, or
* `null` — same shape `formatDate` and the date-bucket helpers
* already tolerate. `/trash` uses ISO strings; `/recent` uses
* epoch ms.
*/
date?: number | string | null;
typeLabel?: string;
/** Owner user id — enables the owner column + vignette when `showOwner`. */
/** Overrides `item.created_by` for the owner column + vignette. */
ownerId?: string | null;
/** Owner display name (resolved by the page). */
ownerName?: string | null;
/** Per-entry favorite state for the star-toggle widget. */
isFavorite?: boolean;
/** Stable category key (Folder / Image / …) used by the `type` group-by. */
category?: string;
/** Modified timestamp (epoch seconds/ms or ISO) for the `modifiedAt` group-by. */
modifiedAt?: number | string | null;
/** Free-form extras that page-provided `bucketOf` / `contextActions` read. */
extras?: Record<string, string | number | null>;
}
/**
* A group-by ("swimlane") dimension a page can offer. `orderBy` is sent to the
* API; the optional `bucketOf` maps an entry to a section key, and `labelOf`
* maps that key to a header label. Omitting `bucketOf` means a flat list.
* API; the optional `bucketOf` maps an item + its context to a section key,
* and `labelOf` maps that key to a header label. Omitting `bucketOf` means a
* flat list.
*/
export interface GroupByDef {
key: string;
@@ -34,7 +40,7 @@
orderBy: string;
/** Optional icon for the dropdown option (defaults to the group glyph). */
icon?: string;
bucketOf?: (entry: ResourceEntry) => string | null;
bucketOf?: (item: FileItem | FolderItem, ctx?: ItemContext) => string | null;
labelOf?: (bucketKey: string) => string;
}
@@ -44,7 +50,16 @@
label: string;
icon: string;
danger?: boolean;
run: (entry: ResourceEntry) => void;
run: (item: FileItem | FolderItem, ctx?: ItemContext) => void;
}
/**
* True when the item is a file. Uses structural narrowing on
* `mime_type` (only present on `FileItem`) so callers can pattern
* match without importing the discriminator manually.
*/
export function isFile(item: FileItem | FolderItem): item is FileItem {
return 'mime_type' in item;
}
</script>
@@ -59,13 +74,40 @@
import VirtualList from '$lib/components/VirtualList.svelte';
import { t } from '$lib/i18n/index.svelte';
import { files as filesStore } from '$lib/stores/files.svelte';
import { preferences } from '$lib/stores/preferences.svelte';
import { formatBytes } from '$lib/utils/format';
import { formatDate, iconNameFromClass, fileIconKindClass } from '$lib/utils/display';
import { gridColumns } from '$lib/utils/grid';
import { fileThumbnailUrl } from '$lib/api/endpoints/files';
import {
canThumbnailClientSide,
preloadPdf,
queueGenerate as queueThumbnailGenerate
} from '$lib/utils/thumbnail';
interface Props {
title: string;
items: ResourceEntry[];
items: Array<FileItem | FolderItem>;
/**
* Per-item envelope info keyed by `item.id`. See `ItemContext`
* above. When absent, ResourceList uses the intrinsic item
* fields (`modified_at`, `created_by`).
*/
contextMap?: Map<string, ItemContext>;
/**
* Set of item ids the caller considers "favorite". When
* provided, the star widget renders next to each row and
* `onfavorite` is invoked on click. Kept as an external Set so
* the page owns the source of truth (e.g. the favorites store).
*/
favoriteIds?: Set<string>;
/**
* Resolve `userId → display name`. Optional; when absent
* `UserVignette` falls back to its own internal resolution.
* Accepts `null` for consistency with the useOwnerCache API
* (returns `null` for a not-yet-resolved id).
*/
resolveOwnerName?: (userId: string) => string | null | undefined;
loading?: boolean;
error?: string | null;
/** Empty-state primary line. */
@@ -86,7 +128,7 @@
/** Override the date column header label (e.g. trash → "Remaining"). */
dateLabel?: string;
/** Custom renderer for the date cell (e.g. trash expiry chip). */
dateCell?: Snippet<[ResourceEntry]>;
dateCell?: Snippet<[FileItem | FolderItem, ItemContext | undefined]>;
/**
* Optional per-bucket action button rendered alongside the swimlane
* header label. Receives the bucket key (the value `bucketOf`
@@ -99,10 +141,21 @@
showOwner?: boolean;
/** Allow grid/list toggle (shares the app-wide view mode). */
showViewToggle?: boolean;
/** Show the dotfile-visibility eye toggle in the toolbar.
* Opt-in per host page — surfaces that never filter dotfiles
* (favorites, trash) leave this false so the button doesn't
* appear to do nothing. Forwarded to ListToolbar. */
/** Show the dotfile-visibility eye toggle in the toolbar AND
* apply the corresponding filter to `items` when
* `preferences.hideDotfiles` is true. Opt-in per host page —
* surfaces that never filter dotfiles (favorites, trash) leave
* this false so the button doesn't appear AND the filter never
* kicks in. Single flag governs both concerns so a page can't
* accidentally expose the button without wiring the filter or
* vice-versa.
*
* A host page that needs to surface "N items hidden" in its
* empty state derives that count independently via the shared
* `isDotfile` predicate in `$lib/utils/dotfileFilter` — no
* count-out prop here (avoids a bindable whose $bindable
* default is always shadowed by the effect that would sync it,
* and keeps the component's API one-way-inbound). */
showDotfileToggle?: boolean;
/** Multi-select checkboxes + selection model. */
selectable?: boolean;
@@ -116,29 +169,74 @@
reversed?: boolean;
/** Called when group-by or direction changes; page should reload page 1. */
onreload?: (orderBy: string, reversed: boolean) => void;
onopen?: (entry: ResourceEntry) => void;
/** Per-entry favorite star toggle. */
onfavorite?: (entry: ResourceEntry) => void;
/**
* Live favorite-id set for the star state. When provided, the star
* reads membership here instead of `entry.isFavorite`, so a toggle
* repaints one star instead of forcing the host to rebuild every
* entry object (the Recent page paid a full O(N) re-map + re-render
* per star click through its `favoriteIds.has()` inside the entry
* mapper — see benches/ROUND11.md).
*/
favoriteIds?: ReadonlySet<string> | null;
/** Selection changed (set of selected entry ids). */
onopen?: (item: FileItem | FolderItem) => void;
/** Per-item favorite star toggle. */
onfavorite?: (item: FileItem | FolderItem) => void;
/** Selection changed (set of selected item ids). */
onselectionchange?: (ids: Set<string>) => void;
actions?: Snippet<[ResourceEntry]>;
actions?: Snippet<[FileItem | FolderItem]>;
toolbar?: Snippet;
/** Batch toolbar shown when items are selected; receives selected entries. */
batchToolbar?: Snippet<[ResourceEntry[]]>;
/** Batch toolbar shown when items are selected; receives selected items. */
batchToolbar?: Snippet<[Array<FileItem | FolderItem>]>;
/**
* Render `<img>` thumbnails on file rows and fall back to
* client-side generation when the server doesn't have one
* (image / PDF / video via `$lib/utils/thumbnail`). Default on
* — every view that lists real files gets the same behaviour.
* Set false for views that never benefit (empty states,
* synthetic rows).
*/
enableThumbnails?: boolean;
/**
* Enable per-row drag/drop hooks. Used by the files browser so
* a folder row is a drop target and any row is draggable to
* another folder or the breadcrumb. Pages that don't wire these
* (trash, favorites, recent, shared-with-me) opt out of the
* drag-drop UX entirely by leaving the callbacks unset.
*/
isDraggable?: (item: FileItem | FolderItem) => boolean;
isDropTarget?: (item: FileItem | FolderItem) => boolean;
/**
* Which item id currently shows the drop-target highlight (page
* owns the state so it can share it with breadcrumb / other drop
* zones). Only meaningful when `isDropTarget` is provided.
*/
dropTargetId?: string | null;
onitemdragstart?: (e: DragEvent, item: FileItem | FolderItem) => void;
onitemdragover?: (e: DragEvent, item: FileItem | FolderItem) => void;
onitemdragleave?: (e: DragEvent, item: FileItem | FolderItem) => void;
onitemdrop?: (e: DragEvent, item: FileItem | FolderItem) => void;
/**
* Override the list-view column header. When provided,
* ResourceList renders this instead of its default header —
* used by the files browser to expose clickable column-sort
* buttons (name / size / type / modified). Pages that override
* this typically also handle sorting on their side (pass
* pre-sorted `items`) rather than relying on `onreload`.
*/
listHeader?: Snippet;
/**
* Open the row on single click (default) vs. double click.
* Files browser prefers double-click so single-click can drive
* the shift-range selection model without accidentally
* navigating.
*/
openOnDoubleClick?: boolean;
/**
* Enable shift-click range selection. The row that was clicked
* without shift becomes the anchor; the next shift-click
* selects the range between anchor and target in visible order.
* Requires `selectable`.
*/
shiftRangeSelect?: boolean;
}
let {
title,
items,
contextMap,
favoriteIds,
resolveOwnerName,
loading = false,
error = null,
emptyText,
@@ -165,14 +263,72 @@
onreload,
onopen,
onfavorite,
favoriteIds = null,
onselectionchange,
actions,
toolbar,
batchToolbar
batchToolbar,
enableThumbnails = true,
isDraggable,
isDropTarget,
dropTargetId = null,
onitemdragstart,
onitemdragover,
onitemdragleave,
onitemdrop,
listHeader: listHeaderOverride,
openOnDoubleClick = false,
shiftRangeSelect = false
}: Props = $props();
const isEmpty = $derived(items.length === 0);
// ── Per-item accessors ────────────────────────────────────────────────────
// Every read of an item field goes through these helpers so the
// contextMap override for date + owner is centralised. Kept as
// module-level fns (not $derived) — they run on each row render;
// caching a Map on every items/contextMap change would be wasteful.
function ctxOf(id: string): ItemContext | undefined {
return contextMap?.get(id);
}
function dateOf(item: FileItem | FolderItem): number | string | null {
return ctxOf(item.id)?.date ?? item.modified_at;
}
function ownerIdOf(item: FileItem | FolderItem): string | null {
const ctx = ctxOf(item.id);
return ctx && 'ownerId' in ctx ? (ctx.ownerId ?? null) : (item.created_by ?? null);
}
function sizeOf(item: FileItem | FolderItem): number | null {
return isFile(item) ? item.size : null;
}
function mimeOf(item: FileItem | FolderItem): string | null {
return isFile(item) ? item.mime_type : null;
}
function iconClassOf(item: FileItem | FolderItem): string {
return item.icon_class;
}
// ── Dotfile filter ────────────────────────────────────────────────────────
// Two conditions gate the filter (both must be true):
// 1. Host page opted in via `showDotfileToggle` — so pages where
// dotfiles are always visible (favorites, trash) never hide them
// even if the user's global preference is on.
// 2. User preference is set to hide — read from the reactive
// `preferences.hideDotfiles` getter, so a toolbar click flips
// this list in real time without a reload.
// The `visibleItems` derived is what every downstream reader
// (bucketing, rendering, "all-selected", range-select) uses, so
// hidden rows disappear consistently across grid, list, and every
// group-by dimension. `selectedItems` and the reap-stale-selection
// effect stay on the raw `items` — selection persists across a
// display filter toggle, matching how file managers treat a
// filter-hide as "hidden, not gone".
const filterDotfiles = $derived(showDotfileToggle && preferences.hideDotfiles);
const visibleItems = $derived(
filterDotfiles ? items.filter((i) => !i.name.startsWith('.')) : items
);
// isEmpty tracks the VISIBLE list — an all-dotfile page with the
// filter on shows the empty state (the host page's `emptyHint` can
// reference `hiddenCount` to say "3 items hidden by the filter").
const isEmpty = $derived(visibleItems.length === 0);
const viewClass = $derived(
filesStore.viewMode === 'grid' ? 'files-grid-view' : 'files-list-view'
);
@@ -217,27 +373,29 @@
* Partition the visible items into grouped sections when a `bucketOf` is
* active. Server order is preserved within and across buckets (first-seen).
*/
const sections = $derived.by((): Array<{ key: string; label: string; rows: ResourceEntry[] }> => {
const bucketOf = activeGroup?.bucketOf;
if (!bucketOf) return [{ key: '', label: '', rows: items }];
const order: string[] = [];
// Transient bucketing map computed inside $derived.by — not reactive state.
// eslint-disable-next-line svelte/prefer-svelte-reactivity
const map = new Map<string, ResourceEntry[]>();
for (const entry of items) {
const k = bucketOf(entry) ?? '∅';
if (!map.has(k)) {
map.set(k, []);
order.push(k);
const sections = $derived.by(
(): Array<{ key: string; label: string; rows: Array<FileItem | FolderItem> }> => {
const bucketOf = activeGroup?.bucketOf;
if (!bucketOf) return [{ key: '', label: '', rows: visibleItems }];
const order: string[] = [];
// Transient bucketing map computed inside $derived.by — not reactive state.
// eslint-disable-next-line svelte/prefer-svelte-reactivity
const map = new Map<string, Array<FileItem | FolderItem>>();
for (const item of visibleItems) {
const k = bucketOf(item, ctxOf(item.id)) ?? '∅';
if (!map.has(k)) {
map.set(k, []);
order.push(k);
}
map.get(k)!.push(item);
}
map.get(k)!.push(entry);
return order.map((k) => ({
key: k,
label: activeGroup?.labelOf?.(k) ?? k,
rows: map.get(k)!
}));
}
return order.map((k) => ({
key: k,
label: activeGroup?.labelOf?.(k) ?? k,
rows: map.get(k)!
}));
});
);
const grouped = $derived(!!activeGroup?.bucketOf);
// ── Selection ─────────────────────────────────────────────────────────────
@@ -249,28 +407,83 @@
else selected.add(id);
onselectionchange?.(selected);
}
/**
* Anchor id for shift-range selection. The row clicked without
* shift becomes the anchor; the next shift-click selects every
* row between anchor and target in visible order. Kept in module
* state so it survives re-renders that don't drop the component.
*/
let selectionAnchor = $state<string | null>(null);
function selectRange(anchorId: string, targetId: string) {
// Range-select over the VISIBLE order — a shift-click can't reach
// a row the user can't see.
const order = visibleItems.map((i) => i.id);
const a = order.indexOf(anchorId);
const b = order.indexOf(targetId);
if (a < 0 || b < 0) return;
const [lo, hi] = a < b ? [a, b] : [b, a];
for (let i = lo; i <= hi; i++) selected.add(order[i]);
onselectionchange?.(selected);
}
/**
* Left-click handler that either navigates (`onopen`) or manages
* selection depending on modifiers + config. Returns `true` when
* the click was consumed by selection, so callers can suppress the
* open. Enabled only for `selectable + shiftRangeSelect` callers.
*/
function handleRowClick(e: MouseEvent, id: string): boolean {
if (!selectable || !shiftRangeSelect) return false;
if (e.shiftKey && selectionAnchor) {
e.preventDefault();
selectRange(selectionAnchor, id);
return true;
}
if (e.metaKey || e.ctrlKey) {
e.preventDefault();
toggleSelected(id);
selectionAnchor = id;
return true;
}
// Plain click: only sets the anchor; open (if any) still fires.
selectionAnchor = id;
return false;
}
function clearSelection() {
selected.clear();
onselectionchange?.(selected);
}
const allSelected = $derived(items.length > 0 && selected.size === items.length);
// "All-selected" means every VISIBLE row is selected — hiding
// dotfiles by preference shouldn't be confused with "not selected".
const allSelected = $derived(
visibleItems.length > 0 && visibleItems.every((i) => selected.has(i.id))
);
function toggleSelectAll() {
if (allSelected) clearSelection();
else {
selected.clear();
for (const i of items) selected.add(i.id);
// Select all VISIBLE rows only. A user hiding dotfiles then
// pressing select-all shouldn't sweep in the hidden files
// they can't see — that would be a footgun for destructive
// batch actions.
for (const i of visibleItems) selected.add(i.id);
onselectionchange?.(selected);
}
}
// Index rebuilt only when `items` changes; the projection below is then
// O(k · log k) in the selection size k instead of the old O(N) full-list
// `items.filter(...)` re-scan on every toggle (O(N²)-ish across a
// shift-range gesture once the batch toolbar was mounted). Item order is
// preserved via the index sort so the toolbar sees the same array the
// filter produced.
// `selectedItems` and the reap-stale effect below stay on the RAW
// items — selection persists across a display-filter toggle, and
// stale-selection cleanup only fires when items truly leave the
// dataset (reload, delete, etc.), not when the filter hides them.
//
// Index rebuilt only when `items` changes; the projection is then
// O(k · log k) in the selection size k instead of a full O(N) re-scan
// of the list on every toggle (O(N²)-ish across a shift-range gesture
// once the batch toolbar is mounted — benches/ROUND11.md §S1). The
// index sort preserves item order, so the toolbar sees the same array
// the old filter produced.
const itemIndexById = $derived(new Map(items.map((i, idx) => [i.id, idx])));
const selectedEntries = $derived.by(() => {
const picked: { idx: number; item: ResourceEntry }[] = [];
const selectedItems = $derived.by(() => {
const picked: { idx: number; item: FileItem | FolderItem }[] = [];
for (const id of selected) {
const idx = itemIndexById.get(id);
if (idx !== undefined) picked.push({ idx, item: items[idx] });
@@ -301,20 +514,20 @@
let ctxOpen = $state(false);
let ctxX = $state(0);
let ctxY = $state(0);
let ctxEntry = $state<ResourceEntry | null>(null);
let ctxItem = $state<FileItem | FolderItem | null>(null);
function openContext(e: MouseEvent, entry: ResourceEntry) {
function openContext(e: MouseEvent, item: FileItem | FolderItem) {
if (!contextActions?.length) return;
e.preventDefault();
e.stopPropagation();
ctxEntry = entry;
ctxItem = item;
ctxX = Math.min(e.clientX, window.innerWidth - 220);
ctxY = Math.min(e.clientY, window.innerHeight - (contextActions.length * 44 + 24));
ctxOpen = true;
}
function closeContext() {
ctxOpen = false;
ctxEntry = null;
ctxItem = null;
}
// ── Infinite scroll (IntersectionObserver) ────────────────────────────────
@@ -334,9 +547,10 @@
return () => obs.disconnect();
});
function ownerTitle(entry: ResourceEntry): string {
const owner = entry.ownerName ?? entry.ownerId ?? '';
const path = entry.path ?? '';
function ownerTitle(item: FileItem | FolderItem): string {
const ownerId = ownerIdOf(item);
const owner = ownerId ? (resolveOwnerName?.(ownerId) ?? ownerId) : '';
const path = item.path ?? '';
return [
owner && `${t('files.col_owner', 'Owner')}: ${owner}`,
path && `${t('files.col_path', 'Location')}: ${path}`
@@ -346,82 +560,131 @@
}
</script>
{#snippet row(entry: ResourceEntry)}
{@const iconName = entry.kind === 'folder' ? 'folder' : iconNameFromClass(entry.iconClass)}
{#snippet row(item: FileItem | FolderItem)}
{@const kind = isFile(item) ? 'file' : 'folder'}
{@const iconName = kind === 'folder' ? 'folder' : iconNameFromClass(iconClassOf(item))}
{@const isFav = favoriteIds?.has(item.id) ?? false}
{@const ctx = ctxOf(item.id)}
{@const ownerId = ownerIdOf(item)}
{@const dateVal = dateOf(item)}
{@const sizeVal = sizeOf(item)}
{@const mimeVal = mimeOf(item)}
{@const draggable = isDraggable?.(item) ?? false}
{@const dropTarget = isDropTarget?.(item) ?? false}
<!-- svelte-ignore a11y_no_noninteractive_tabindex -->
<div
class="file-item"
class:file-item--selected={selectable && selected.has(entry.id)}
class:file-item--selected={selectable && selected.has(item.id)}
class:file-item--drop-target={dropTarget && dropTargetId === item.id}
role={onopen ? 'button' : undefined}
tabindex={onopen ? 0 : undefined}
aria-label={onopen ? entry.name : undefined}
data-testid={entry.name}
title={showOwner ? ownerTitle(entry) : undefined}
onclick={onopen ? () => onopen(entry) : undefined}
onkeydown={onopen ? (e) => e.key === 'Enter' && onopen(entry) : undefined}
oncontextmenu={contextActions?.length ? (e) => openContext(e, entry) : undefined}
aria-label={onopen ? item.name : undefined}
data-testid={item.name}
title={showOwner ? ownerTitle(item) : undefined}
{draggable}
ondragstart={draggable && onitemdragstart ? (e) => onitemdragstart(e, item) : undefined}
ondragover={dropTarget && onitemdragover ? (e) => onitemdragover(e, item) : undefined}
ondragleave={dropTarget && onitemdragleave ? (e) => onitemdragleave(e, item) : undefined}
ondrop={dropTarget && onitemdrop ? (e) => onitemdrop(e, item) : undefined}
onclick={onopen
? (e) => {
// Selection-first for shift/meta clicks; only "open" fires on a
// plain click when the click wasn't consumed by selection.
if (handleRowClick(e, item.id)) return;
if (!openOnDoubleClick) onopen(item);
}
: undefined}
ondblclick={onopen && openOnDoubleClick ? () => onopen(item) : undefined}
onkeydown={onopen ? (e) => e.key === 'Enter' && onopen(item) : undefined}
oncontextmenu={contextActions?.length ? (e) => openContext(e, item) : undefined}
>
{#if selectable}
<div class="select-cell" role="presentation" onclick={(e) => e.stopPropagation()}>
<input
type="checkbox"
aria-label={t('common.select', 'Select')}
data-testid={`resource-list-select-${entry.id}-checkbox`}
checked={selected.has(entry.id)}
onchange={() => toggleSelected(entry.id)}
data-testid={`resource-list-select-${item.id}-checkbox`}
checked={selected.has(item.id)}
onchange={() => toggleSelected(item.id)}
/>
</div>
{/if}
<div class="name-cell">
<span class="file-icon {fileIconKindClass(iconName)}">
<!-- Type icon always renders. When `enableThumbnails` is on
and the item is a file with a supported mime, an
`<img>` overlays the icon on success; onerror hides it
(revealing the icon) and kicks off client-side
generation for image / PDF / video so the next viewer
hits the server-side thumbnail. -->
<Icon name={iconName} />
{#if enableThumbnails && kind === 'file' && mimeVal && canThumbnailClientSide( { id: item.id, name: item.name, mime_type: mimeVal } )}
<img
class="file-thumb"
src={fileThumbnailUrl(item.id)}
alt=""
loading="lazy"
onerror={(e) => {
const img = e.currentTarget as HTMLImageElement;
img.style.display = 'none';
if (mimeVal === 'application/pdf') preloadPdf();
void queueThumbnailGenerate(
{ id: item.id, name: item.name, mime_type: mimeVal },
(dataUrl) => {
img.src = dataUrl;
img.style.display = '';
}
);
}}
/>
{/if}
</span>
<span class="name-cell__text">{entry.name}</span>
<span class="name-cell__text">{item.name}</span>
</div>
{#if showOwner}
<div class="owner-cell">
{#if entry.ownerId}
<UserVignette userId={entry.ownerId} fallbackLabel={entry.ownerName ?? undefined} />
{#if ownerId}
<UserVignette userId={ownerId} fallbackLabel={resolveOwnerName?.(ownerId) ?? undefined} />
{:else}
<span class="owner-cell__placeholder">{entry.ownerName ?? '—'}</span>
<span class="owner-cell__placeholder">—</span>
{/if}
</div>
{/if}
{#if showPath}<div class="path-cell">{entry.path ?? ''}</div>{/if}
{#if showType}<div class="type-cell">{entry.typeLabel ?? ''}</div>{/if}
{#if showPath}<div class="path-cell">{item.path ?? ''}</div>{/if}
{#if showType}<div class="type-cell">{item.category ?? ''}</div>{/if}
{#if showSize}
<div class="size-cell">{entry.size != null ? formatBytes(entry.size) : '—'}</div>
<div class="size-cell">{sizeVal != null ? formatBytes(sizeVal) : '—'}</div>
{/if}
{#if showDate}
<div class="date-cell">
{#if dateCell}{@render dateCell(entry)}{:else}{formatDate(entry.date)}{/if}
{#if dateCell}{@render dateCell(item, ctx)}{:else}{formatDate(dateVal)}{/if}
</div>
{/if}
<div class="grid-meta">
{#if showDate && dateCell}<span class="grid-meta__chip">{@render dateCell(entry)}</span>{/if}
{#if showDate && dateCell}<span class="grid-meta__chip">{@render dateCell(item, ctx)}</span
>{/if}
<span class="grid-meta__line">
{#if entry.size != null}<span class="grid-meta__size">{formatBytes(entry.size)}</span>{/if}
{#if entry.date != null}<span class="grid-meta__date">{formatDate(entry.date)}</span>{/if}
{#if sizeVal != null}<span class="grid-meta__size">{formatBytes(sizeVal)}</span>{/if}
{#if dateVal != null}<span class="grid-meta__date">{formatDate(dateVal)}</span>{/if}
</span>
</div>
{#if onfavorite}
{@const starred = favoriteIds ? favoriteIds.has(entry.id) : !!entry.isFavorite}
<button
class="rl-star"
class:rl-star--on={starred}
data-testid={`resource-list-favorite-${entry.id}-btn`}
title={starred
class:rl-star--on={isFav}
data-testid={`resource-list-favorite-${item.id}-btn`}
title={isFav
? t('files.unfavorite', 'Remove favorite')
: t('files.favorite', 'Add favorite')}
aria-pressed={starred}
aria-pressed={isFav}
onclick={(e) => {
e.stopPropagation();
onfavorite(entry);
}}><Icon name={starred ? 'star' : 'star-outline'} /></button
onfavorite(item);
}}><Icon name={isFav ? 'star' : 'star-outline'} /></button
>
{/if}
{#if actions}
<div class="action-cell">{@render actions(entry)}</div>
<div class="action-cell">{@render actions(item)}</div>
{/if}
</div>
{/snippet}
@@ -461,7 +724,7 @@
<span class="rl-batch__count"
>{t('files.selected_count', { count: selected.size }, '{{count}} selected')}</span
>
<div class="rl-batch__actions">{@render batchToolbar(selectedEntries)}</div>
<div class="rl-batch__actions">{@render batchToolbar(selectedItems)}</div>
</div>
{/if}
@@ -479,7 +742,7 @@
<div class="files-container" bind:clientWidth={gridWidth}>
{#if grouped}
<div class={viewClass} style="--files-list-columns: {columns}">
{@render listHeader()}
{#if listHeaderOverride}{@render listHeaderOverride()}{:else}{@render listHeader()}{/if}
{#each sections as section (section.key)}
<div class="rl-swimlane-header" role="rowheader">
<span class="rl-swimlane-header__label">{section.label}</span>
@@ -506,13 +769,13 @@
<!-- Flat list view: only the visible rows are mounted. The spacer keeps the
full scroll height so the end-of-list sentinel still fires. -->
<div class="files-list-view" style="--files-list-columns: {columns}">
{@render listHeader()}
<VirtualList {items} rowHeight={56} key={(e) => e.id} {row} />
{#if listHeaderOverride}{@render listHeaderOverride()}{:else}{@render listHeader()}{/if}
<VirtualList items={visibleItems} rowHeight={56} key={(e) => e.id} {row} />
</div>
{:else}
<!-- Grid view: the windowed list's inner element IS the card grid. -->
<VirtualList
{items}
items={visibleItems}
columns={gridCols}
rowHeight={240}
windowClass="files-grid-view"
@@ -559,7 +822,7 @@
</div>
{/snippet}
{#if ctxOpen && ctxEntry && contextActions}
{#if ctxOpen && ctxItem && contextActions}
<div
class="rl-ctx-scrim"
role="presentation"
@@ -580,9 +843,9 @@
role="menuitem"
data-testid={`resource-list-context-${action.key}-item`}
onclick={() => {
const e = ctxEntry!;
const target = ctxItem!;
closeContext();
action.run(e);
action.run(target, ctxOf(target.id));
}}
>
<Icon name={action.icon} />
@@ -654,6 +917,13 @@
background: var(--color-accent-bg);
}
/* Drop-target highlight — mirrors the legacy files browser's cue when
dragging a row over a folder row. */
.file-item--drop-target {
outline: 2px dashed var(--color-accent);
outline-offset: -2px;
}
/* ── Owner vignette ── */
.owner-cell {
display: flex;
+14 -4
View File
@@ -22,6 +22,16 @@
import type { FileItem } from '$lib/api/types';
import { getCsrfHeaders } from '$lib/api/csrf';
/**
* The subset of `FileItem` this module actually reads. Keeping
* `FileItem` as the canonical shape means the files browser passes
* its DTO through verbatim; ResourceList (which only carries
* `ResourceEntry`) builds an object with just these three fields and
* satisfies the same structural type — no widening cast, no parallel
* named type to maintain.
*/
type ThumbnailFile = Pick<FileItem, 'id' | 'name' | 'mime_type'>;
const PDFJS_LIB_URL = '/vendors/pdf.min.mjs';
const PDFJS_WORKER_URL = '/vendors/pdf.worker.min.mjs';
@@ -103,7 +113,7 @@ function blobToDataUrl(blob: Blob): Promise<string> {
});
}
async function sourceToBitmap(file: FileItem, source: string): Promise<ImageBitmap> {
async function sourceToBitmap(file: ThumbnailFile, source: string): Promise<ImageBitmap> {
const mime = file.mime_type ?? '';
if (mime.startsWith('image/')) {
const response = await fetch(source);
@@ -147,7 +157,7 @@ async function sourceToBitmap(file: FileItem, source: string): Promise<ImageBitm
}
async function generate(
file: FileItem,
file: ThumbnailFile,
onIconGenerated?: (dataUrl: string) => void,
onPreviewGenerated?: (dataUrl: string) => void
): Promise<void> {
@@ -186,7 +196,7 @@ async function generate(
* handle. Callers use this to decide whether to install the fallback
* `onerror` handler on the `<img>` in the first place.
*/
export function canThumbnailClientSide(file: FileItem): boolean {
export function canThumbnailClientSide(file: ThumbnailFile): boolean {
const mime = file.mime_type ?? '';
return SUPPORTED_MIME_TYPE.some((re) => re.test(mime));
}
@@ -221,7 +231,7 @@ export function preloadPdf(): void {
* immediately, before the server round-trip completes.
*/
export async function queueGenerate(
file: FileItem,
file: ThumbnailFile,
onIconGenerated?: (dataUrl: string) => void,
onPreviewGenerated?: (dataUrl: string) => void
): Promise<void> {
+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>
+13
View File
@@ -180,6 +180,12 @@ front-design:
# --config server-with-oidc.env so the
# api and webdav suites stay on the
# OIDC-off config.
# * tests/oidc/run-manual-sso-only.sh — NOT part of this chain (see
# `oidc-manual-sso-only` below): a
# http://localhost:8090/files/1bf4713c-891e-46fb-acf0-b10231fe32c8 human-run check that OIDC-as-only-
# login-method actually redirects a
# real browser, which the curl-driven
# suite above can't observe.
#
# Same chain runs in CI under the `api-test` job in
# .github/workflows/ci.yml; keep the order in sync so a local pass means
@@ -228,6 +234,13 @@ test-caldav:
cargo build
./tests/caldav/run-pycaldav.sh
# Manual, human-run: launches OxiCloud with OIDC as the ONLY login method
# (fake IdP on :1081, server on :8090) and waits for you to eyeball the
# /login auto-redirect in a real browser. Not part of `just api-test` —
# there's no automated assertion here, it's a visual check. Ctrl-C to stop.
#oidc-manual-sso-only:
# bash tests/oidc/run-manual-sso-only.sh
# ---------------------------------------------------------------------------
# SvelteKit frontend (frontend/) — the only frontend. These `fe-*` recipes
# drive its dev server, build, lint and tests.
+33 -1
View File
@@ -923,12 +923,44 @@ async fn run() -> Result<(), Box<dyn std::error::Error>> {
next: axum::middleware::Next,
) -> axum::response::Response {
let mut res = next.run(req).await;
// A 304 Not Modified carries no entity headers (no Content-Type) since
// there's no body — `is_html` would read `None` and misclassify it as
// "not html", attaching the strict headerless CSP below. Browsers merge
// a 304's headers into the cached document's effective response, so
// that stray header would then stack with (and defeat) the SPA's own
// hash-based `<meta>` CSP on every revalidated repeat visit — this was
// a real bug (see git blame): a browser tab reopened at `/login` after
// the first, freshly-fetched visit got permanently stuck behind the
// boot spinner because its now-conditionally-cached `200` picked up an
// extra hash-less `script-src 'self'` header from the 304 that
// revalidated it, blocking the app's own inline hydration script.
// Nothing to add on a 304 regardless — its headers must only carry
// caching metadata, never a fresh policy decision.
if res.status() == axum::http::StatusCode::NOT_MODIFIED {
return res;
}
let is_html = res
.headers()
.get(axum::http::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.starts_with("text/html"));
if !is_html {
if is_html {
// `no-store` (not just `no-cache`) on the SPA shell: Chrome/Firefox/
// Safari all treat `no-store` as an explicit opt-out of the
// back-forward cache (bfcache), which is a full in-memory snapshot
// of the page that bypasses HTTP revalidation entirely — `no-cache`
// alone does NOT prevent it. Without this, a shell instance loaded
// before a deploy can be resurrected byte-for-byte (old inline
// hydration script + old CSP hash) after navigating away and back —
// e.g. the OIDC login round-trip's two full-page navigations — and
// the resurrected page's old CSP `<meta>` no longer matches assets
// referenced by the current build, leaving the app permanently
// stuck behind the boot spinner until a hard reload.
res.headers_mut().insert(
axum::http::header::CACHE_CONTROL,
HeaderValue::from_static("no-store"),
);
} else {
res.headers_mut().insert(
axum::http::header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static(
+79
View File
@@ -0,0 +1,79 @@
# OxiCloud test-server env file for the MANUAL SSO-only auto-redirect test.
#
# Layered on top of server-with-oidc.env: identical EXCEPT
# OXICLOUD_OIDC_DISABLE_PASSWORD_LOGIN=true, which makes OIDC the ONLY
# login method (magic-link is already hard-disabled whenever OIDC is
# enabled, per the "OIDC master rule" — see example.env). This is the
# config the frontend's login-page auto-redirect guard
# (frontend/src/routes/login/+page.svelte) actually fires under —
# tests/common/server-with-oidc.env keeps password login on, so the
# automated tests/oidc/oidc.hurl suite never exercises the redirect.
#
# Used by tests/oidc/run-manual-sso-only.sh (human-run, not CI). Distinct
# ports (8090 / IdP 1081) so it doesn't collide with a concurrently running
# `just api-test` (which uses 8087 / IdP 1080) or a local `cargo run` dev
# server.
#
# `--config` makes the binary read THIS file verbatim — there is no
# auto-merge with server.env, so every variable the server needs has
# to be repeated here (same rationale as server-with-oidc.env).
# ── Shared test config (mirrors server.env) ────────────────────────────────
DATABASE_URL=postgres://oxicloud_test:oxicloud_test@localhost:5433/oxicloud_test
OXICLOUD_DB_CONNECTION_STRING=postgres://oxicloud_test:oxicloud_test@localhost:5433/oxicloud_test
OXICLOUD_STATIC_PATH=./static
OXICLOUD_JWT_SECRET=test-secret-do-not-use-in-prod-minimum-32-chars
OXICLOUD_ENABLE_AUTH=true
OXICLOUD_ENABLE_TRASH=true
OXICLOUD_ENABLE_SEARCH=true
OXICLOUD_ENABLE_FILE_SHARING=true
OXICLOUD_ENABLE_MUSIC=true
OXICLOUD_EXPOSE_SYSTEM_USERS=true
OXICLOUD_WOPI_ENABLED=false
OXICLOUD_NEXTCLOUD_ENABLED=true
OXICLOUD_ENABLE_ADMIN_INTERNAL_ENDPOINTS=true
RUST_LOG="warn,audit=info,oxicloud::infrastructure::services::oidc_service=info,oxicloud::application::services::auth_application_service=info"
OXICLOUD_RATE_LIMIT_REFRESH_MAX=3600
OXICLOUD_RATE_LIMIT_LOGIN_MAX=3600
OXICLOUD_RATE_LIMIT_REGISTER_MAX=3600
OXICLOUD_TRUST_PROXY_CIDR=0.0.0.0/0
# Mock SMTP — kept wired even though magic-link login is disabled under the
# OIDC master rule, so the invite/mail transport doesn't 503 unconfigured.
OXICLOUD_SMTP_MOCK=true
OXICLOUD_SMTP_HOST=localhost
OXICLOUD_SMTP_PORT=25
OXICLOUD_SMTP_FROM='OxiCloud Tests <test@oxicloud.local>'
OXICLOUD_SMTP_TLS=none
OXICLOUD_ALLOW_EXTERNAL_USERS=true
# ── OIDC client wired at the fake-idp sidecar (SSO-only) ───────────────────
# tests/oidc/fake_idp/server.js (panva/node-oidc-provider) publishes the
# issuer at the root URL; discovery is at /.well-known/openid-configuration
# under it. Update the `clients[0].client_id` field there in tandem if you
# rename the client.
OXICLOUD_OIDC_ENABLED=true
OXICLOUD_OIDC_ISSUER_URL=http://localhost:1081
OXICLOUD_OIDC_CLIENT_ID=oxicloud-test
OXICLOUD_OIDC_CLIENT_SECRET=test-client-secret-not-used-in-prod
# The IdP redirects back to this exact URL after auto-approving; must
# match the OxiCloud server's actual host + port.
OXICLOUD_OIDC_REDIRECT_URI=http://localhost:8090/api/auth/oidc/callback
OXICLOUD_OIDC_SCOPES="openid profile email"
# Frontend redirect target after a successful callback. The backend
# appends `/login?oidc_code=…` to this base, so the value here is the
# SPA origin only.
OXICLOUD_OIDC_FRONTEND_URL=http://localhost:8090
OXICLOUD_OIDC_AUTO_PROVISION=true
OXICLOUD_OIDC_PROVIDER_NAME=MockSSO-Only
# Group-to-role mapping — same fake-idp claim shape as server-with-oidc.env.
OXICLOUD_OIDC_ADMIN_GROUPS=admin-users
# The single flag that makes OIDC the ONLY login method: is_password_login_allowed()
# is exactly `!disable_password_login` (auth_application_service.rs). Magic-link
# is already hard-disabled whenever OIDC is enabled, regardless of AUTH_METHODS.
OXICLOUD_OIDC_DISABLE_PASSWORD_LOGIN=true
OXICLOUD_REQUIRE_VERIFIED_EMAIL=false
+6 -1
View File
@@ -67,7 +67,12 @@ const configuration = {
{
client_id: 'oxicloud-test',
client_secret: 'test-client-secret-not-used-in-prod',
redirect_uris: ['http://localhost:8087/api/auth/oidc/callback'],
// 8087: automated tests/oidc/oidc.hurl suite. 8090: human-run
// tests/oidc/run-manual-sso-only.sh (SSO-only auto-redirect check).
redirect_uris: [
'http://localhost:8087/api/auth/oidc/callback',
'http://localhost:8090/api/auth/oidc/callback',
],
grant_types: ['authorization_code'],
response_types: ['code'],
token_endpoint_auth_method: 'client_secret_post',
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env bash
# MANUAL, human-run SSO-only auto-redirect check. NOT part of `just
# api-test` / CI — there is no automated assertion here, this launches a
# real server + real fake IdP and waits for a human to open a browser and
# eyeball the behavior.
#
# What it proves that the automated suites can't:
# * tests/oidc/oidc.hurl drives the OIDC flow via curl against
# tests/common/server-with-oidc.env, which keeps password login
# enabled — the frontend's login-page auto-redirect guard
# (frontend/src/routes/login/+page.svelte) never fires there.
# * The Vitest coverage for that guard (frontend/src/routes/login/
# page.test.ts) mocks getOidcProviders() and stubs
# window.location.replace — it proves the logic is right, not that a
# real browser actually navigates away when the backend is genuinely
# OIDC-only.
#
# This script starts OxiCloud with tests/common/server-with-oidc-only.env
# (OIDC is the ONLY login method) against the same fake IdP used by the
# automated suite, then blocks until you Ctrl-C.
#
# Ports (deliberately distinct from tests/oidc/run.sh's 8087 / 1080, so
# this can run alongside `just api-test` or a local `cargo run` dev
# server): OxiCloud on 8090, fake IdP on 1081.
#
# Prerequisites: docker, cargo, node >= 20, npm.
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
COMMON="$REPO_ROOT/tests/common"
OIDC_DIR="$REPO_ROOT/tests/oidc"
FAKE_IDP_DIR="$OIDC_DIR/fake_idp"
SERVER_PORT=8090
IDP_PORT=1081
base_url="http://localhost:$SERVER_PORT"
oidc_issuer="http://localhost:$IDP_PORT"
# ── Helpers ────────────────────────────────────────────────────────────────
log() { echo "[oidc-manual] $*"; }
die() { echo "[oidc-manual] ERROR: $*" >&2; exit 1; }
wait_for_http() {
local url="$1" timeout="${2:-60}"
local deadline=$(( $(date +%s) + timeout ))
until curl -sf "$url" >/dev/null 2>&1; do
[[ $(date +%s) -ge $deadline ]] && die "Timeout waiting for $url"
sleep 0.5
done
}
# ── Fake-IdP process management (mirrors tests/oidc/run.sh) ────────────────
kill_fake_idp() {
pkill -f "tests/oidc/fake_idp/server.js" 2>/dev/null || true
pkill -f "node.*server.js" 2>/dev/null || true
if command -v lsof >/dev/null 2>&1; then
local pids
pids=$(lsof -ti :"$IDP_PORT" 2>/dev/null || true)
if [[ -n "$pids" ]]; then
# shellcheck disable=SC2086
kill -9 $pids 2>/dev/null || true
fi
fi
}
# ── Teardown (always runs on exit) ─────────────────────────────────────────
SERVER_PID=""
cleanup() {
if [[ -n "$SERVER_PID" ]]; then
log "Stopping OxiCloud server (pid $SERVER_PID)..."
kill "$SERVER_PID" 2>/dev/null || true
wait "$SERVER_PID" 2>/dev/null || true
fi
log "Stopping fake-idp..."
kill_fake_idp
bash "$COMMON/stop-db.sh" || true
}
trap cleanup EXIT
# ── 1. Postgres ────────────────────────────────────────────────────────────
bash "$COMMON/spawn-db.sh"
# ── 2. Fake IdP (Node) ─────────────────────────────────────────────────────
log "Installing fake-idp dependencies..."
if [[ -f "$FAKE_IDP_DIR/package-lock.json" ]]; then
(cd "$FAKE_IDP_DIR" && npm ci --silent --no-audit --no-fund)
else
(cd "$FAKE_IDP_DIR" && npm install --silent --no-audit --no-fund)
fi
log "Sweeping any orphan fake-idp processes from prior runs..."
kill_fake_idp
sleep 0.3
log "Starting fake-idp on port $IDP_PORT..."
FAKE_IDP_ISSUER="$oidc_issuer" FAKE_IDP_PORT="$IDP_PORT" \
node "$FAKE_IDP_DIR/server.js" > /tmp/fake-idp-manual.log 2>&1 &
log "Waiting for fake-idp discovery endpoint..."
wait_for_http "$oidc_issuer/.well-known/openid-configuration" 30
log "fake-idp is ready (logs: /tmp/fake-idp-manual.log)"
# ── 3. Load shared server env (SSO-only) ────────────────────────────────────
set -a
# shellcheck source=../common/server-with-oidc-only.env
source "$COMMON/server-with-oidc-only.env"
OXICLOUD_SERVER_PORT=$SERVER_PORT
OXICLOUD_STORAGE_PATH="$REPO_ROOT/tests/oidc-manual/storage"
set +a
# shellcheck source=../common/wipe-storage.sh
source "$COMMON/wipe-storage.sh"
wipe_storage "$OXICLOUD_STORAGE_PATH"
# ── 3.5. Ensure the SPA is built (static-dist/) ────────────────────────────
# The auto-redirect only fires against the production SPA bundle; without
# it `resolve_static_path` falls back to OXICLOUD_STATIC_PATH=./static,
# which doesn't have it. The frontend is a pure CSR SPA (prerender=false in
# +layout.ts) — there is only ONE shell file, static-dist/index.html, that
# every route (including /login) falls back to. Check for that, not a
# per-route file (one never gets emitted; checking for it would force a
# full rebuild on every single invocation).
DIST_DIR="$REPO_ROOT/static-dist"
if [[ ! -f "$DIST_DIR/index.html" ]]; then
log "Building SvelteKit SPA (static-dist/index.html missing)..."
(cd "$REPO_ROOT/frontend" \
&& npm ci --silent --no-audit --no-fund \
&& npm run build) || die "Frontend build failed; static-dist/ is required"
fi
# ── 4. Start OxiCloud server with OIDC-only config ──────────────────────────
BUILD_TARGET="${BUILD_TARGET:-debug}"
OXICLOUD_BIN="$REPO_ROOT/target/$BUILD_TARGET/oxicloud"
if [[ ! -x "$OXICLOUD_BIN" ]]; then
log "Building OxiCloud server ($BUILD_TARGET)..."
case "$BUILD_TARGET" in
debug) (cd "$REPO_ROOT" && cargo build 2>&1 | tail -n 20) || die "cargo build failed" ;;
release) (cd "$REPO_ROOT" && cargo build --release 2>&1 | tail -n 20) || die "cargo build --release failed" ;;
*) die "Unsupported BUILD_TARGET='$BUILD_TARGET' (expected 'debug' or 'release')" ;;
esac
fi
log "Starting OxiCloud server with OIDC-only config on port $SERVER_PORT..."
"$OXICLOUD_BIN" --config "$COMMON/server-with-oidc-only.env" &
SERVER_PID=$!
log "Waiting for server at $base_url..."
wait_for_http "$base_url/ready" 120
log "Server is ready."
# ── 5. Hand off to the human ────────────────────────────────────────────────
cat <<EOF
==========================================================
SSO-ONLY MANUAL TEST — server ready at $base_url
==========================================================
Open $base_url/login in a browser.
Expected: the page redirects immediately to the fake IdP
($oidc_issuer/...) with no login form flash. The fake IdP
auto-approves — you should land back on
$base_url/login?oidc_code=... and then on the authenticated app.
Edge cases to also eyeball:
* $base_url/login?error=access_denied
-> must NOT redirect (loop guard); shows the login form.
* First run / no admin yet (already handled above by wiping
storage) -> shows the setup wizard, not a redirect, until
you complete it once via the IdP.
Press Ctrl-C to stop the server and tear down.
==========================================================
EOF
wait "$SERVER_PID"