refactor(search): adapt UI to use ResourceList

This commit is contained in:
Edouard Vanbelle
2026-07-26 16:38:49 +02:00
parent c22741bc7f
commit c946cf4333
11 changed files with 739 additions and 309 deletions
+18 -3
View File
@@ -2,16 +2,16 @@ import { it, expect, vi, beforeEach } from 'vitest';
vi.mock('$lib/api/client', () => ({ apiFetch: vi.fn(), apiJson: vi.fn() }));
vi.mock('$lib/api/csrf', () => ({ getCsrfHeaders: () => ({}) }));
import { apiFetch, apiJson } from '$lib/api/client';
import { searchFiles, searchSuggest, clearSearchCache } from './search';
import { searchResources, searchSuggest, clearSearchCache } from './search';
const f = apiFetch as unknown as ReturnType<typeof vi.fn>;
const j = apiJson as unknown as ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
f.mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });
j.mockResolvedValue({ files: [], folders: [] });
j.mockResolvedValue({ items: [], query_time_ms: 0 });
});
it('builds search requests including filters', async () => {
await searchFiles('q', {
await searchResources('q', {
recursive: true,
fileTypes: ['mp3', 'wav'],
minSize: 1,
@@ -19,7 +19,22 @@ it('builds search requests including filters', async () => {
sortBy: 'date'
}).catch(() => {});
expect(j).toHaveBeenCalledWith(expect.stringContaining('type=mp3%2Cwav'), expect.anything());
// Sort dimension is sent on the wire as `order_by`, matching the
// backend's `SearchResourcesQuery` (post-normalization).
expect(j).toHaveBeenCalledWith(expect.stringContaining('order_by=date'), expect.anything());
await searchSuggest('q').catch(() => {});
await clearSearchCache().catch(() => {});
expect(f.mock.calls.length + j.mock.calls.length).toBeGreaterThan(1);
});
it('forwards cursor pagination and resource-type filter', async () => {
await searchResources('q', {
cursor: 'abc',
resourceTypes: ['file'],
limit: 25
}).catch(() => {});
const call = j.mock.calls.at(-1)?.[0] as string;
expect(call).toContain('cursor=abc');
expect(call).toContain('resource_types=file');
expect(call).toContain('limit=25');
});
+26 -8
View File
@@ -1,6 +1,6 @@
/** Search endpoint — ported from features/files/search.js. */
// Search endpoint — hits the normalized `/*/resources` envelope shape.
import { apiFetch, apiJson } from '$lib/api/client';
import type { SearchResults, SortBy } from '$lib/api/types';
import type { ItemType, SearchResourcesResponse, SortBy } from '$lib/api/types';
export interface SearchOptions {
folderId?: string;
@@ -16,14 +16,31 @@ export interface SearchOptions {
modifiedAfter?: number;
/** Unix-seconds upper bound on modified time. */
modifiedBefore?: number;
/** Page size (1–200 server-side; default 50). */
limit?: number;
offset?: number;
/**
* Cursor from a previous response's `next_cursor`. Absent → first page.
* The wire uses cursor pagination now; the old `offset` param is gone.
*/
cursor?: string;
/** Sort dimension; maps to backend `order_by`. */
sortBy?: SortBy;
/** Restrict to files, folders, or both (default). */
resourceTypes?: ItemType[];
/** Abort the request when a newer search supersedes it. */
signal?: AbortSignal;
}
export function searchFiles(query: string, opts: SearchOptions = {}): Promise<SearchResults> {
/**
* Cursor-paginated search. Returns the shared envelope
* `{ items[], next_cursor?, query_time_ms, total? }` — same shape as
* favorites / recent / trash / folder listings so `ResourceList`
* consumes the items without a demux step.
*/
export function searchResources(
query: string,
opts: SearchOptions = {}
): Promise<SearchResourcesResponse> {
const params = new URLSearchParams();
params.append('query', query);
if (opts.folderId) params.append('folder_id', opts.folderId);
@@ -37,10 +54,11 @@ export function searchFiles(query: string, opts: SearchOptions = {}): Promise<Se
if (opts.createdBefore != null) params.append('created_before', String(opts.createdBefore));
if (opts.modifiedAfter != null) params.append('modified_after', String(opts.modifiedAfter));
if (opts.modifiedBefore != null) params.append('modified_before', String(opts.modifiedBefore));
params.append('limit', String(opts.limit ?? 100));
params.append('offset', String(opts.offset ?? 0));
params.append('sort_by', opts.sortBy ?? 'relevance');
return apiJson<SearchResults>(`/api/search?${params.toString()}`, {
if (opts.resourceTypes?.length) params.append('resource_types', opts.resourceTypes.join(','));
if (opts.limit != null) params.append('limit', String(opts.limit));
if (opts.cursor) params.append('cursor', opts.cursor);
if (opts.sortBy) params.append('order_by', opts.sortBy);
return apiJson<SearchResourcesResponse>(`/api/search?${params.toString()}`, {
credentials: 'same-origin',
signal: opts.signal
});
+34 -22
View File
@@ -257,31 +257,43 @@ export type SortBy =
| 'size'
| 'size_desc';
export interface SearchCriteria {
sort_by: SortBy;
recursive: boolean;
limit: number;
offset: number;
name_contains?: string;
file_types?: string[];
folder_id?: string;
min_size?: number;
max_size?: number;
created_before?: number;
created_after?: number;
modified_before?: number;
modified_after?: number;
/**
* Per-item search metadata inline on every hit in the normalized
* `/api/search` envelope. Mirrors backend `SearchMeta` — see
* `application/dtos/search_dto.rs`.
*/
export interface SearchMeta {
/** Relevance in [0, 1]; the higher the better. */
score: number;
/** Optional HTML-safe excerpt when the match fired via content index. */
snippet?: string;
/** Where the match fired. */
via?: 'name' | 'content' | 'path';
}
export interface SearchResults {
files: FileItem[];
folders: FolderItem[];
total_count: number | null;
limit: number;
offset: number;
has_more: boolean;
/**
* Single hit in the `/api/search` envelope. `resource_type` disambiguates
* `resource`'s union so the shared `ResourceList` component can render it
* exactly like a folders/favorites/recent/trash row.
*/
export interface SearchResourceItem {
resource_type: ItemType;
resource: FileItem | FolderItem;
meta: SearchMeta;
}
/**
* Wire response of `GET /api/search`. Same envelope shape as the other
* "resources" listing endpoints (`items[]` + optional `next_cursor`),
* plus two search-specific top-level fields: `query_time_ms` (health
* signal for admins, "Found N in Xms" for users) and `total` (approximate,
* caller-visible; never leaks a count for rows the caller can't see).
*/
export interface SearchResourcesResponse {
items: SearchResourceItem[];
next_cursor?: string;
query_time_ms: number;
sort_by: string;
total?: number;
}
export type DriveKind = 'personal' | 'shared';
+30 -10
View File
@@ -4,7 +4,7 @@
import { resolve } from '$app/paths';
import { page } from '$app/state';
import { logout } from '$lib/api/endpoints/auth';
import { searchFiles } from '$lib/api/endpoints/search';
import { searchResources } from '$lib/api/endpoints/search';
import { fileInlineUrl, deleteFile } from '$lib/api/endpoints/files';
import { deleteFolder } from '$lib/api/endpoints/folders';
import { addFavorite } from '$lib/api/endpoints/favorites';
@@ -17,6 +17,7 @@
import { i18n, LANGUAGES, setLocale, t, type Locale } from '$lib/i18n/index.svelte';
import { apiFetch } from '$lib/api/client';
import { dialogs } from '$lib/stores/dialogs.svelte';
import { files as filesStore } from '$lib/stores/files.svelte';
import { preferences } from '$lib/stores/preferences.svelte';
import { session } from '$lib/stores/session.svelte';
import { theme, type Theme } from '$lib/stores/theme.svelte';
@@ -255,11 +256,22 @@
function goToResults() {
const q = searchQuery.trim();
if (q) {
suggestOpen = false;
searchActive = false;
goto(resolve(`/search?q=${encodeURIComponent(q)}`));
if (!q) return;
suggestOpen = false;
searchActive = false;
// Carry the currently-open folder into the search URL as `?in=<uuid>`
// so a hard refresh, a shared link, or a bookmark all restore the
// "This folder" scope. Trash section is always global — skip. See
// `/search/+page.svelte` for the receiver side.
//
// Built by hand instead of via `URLSearchParams` because the Svelte
// lint (svelte/prefer-svelte-reactivity) flags the mutable stdlib
// variant; the two params here don't need reactivity anyway.
const parts = [`q=${encodeURIComponent(q)}`];
if (filesStore.currentFolder && filesStore.section !== 'trash') {
parts.push(`in=${encodeURIComponent(filesStore.currentFolder)}`);
}
goto(resolve(`/search?${parts.join('&')}`));
}
function onSearch(e: SubmitEvent) {
@@ -285,12 +297,20 @@
suggestInflight = ctl;
suggestBusy = true;
try {
const r = await searchFiles(q, { recursive: true, limit: 6, signal: ctl.signal });
const r = await searchResources(q, { recursive: true, limit: 9, signal: ctl.signal });
if (seq !== suggestSeq) return; // superseded while awaiting
suggestions = [
...r.folders.slice(0, 3).map((item) => ({ kind: 'folder' as const, item })),
...r.files.slice(0, 6).map((item) => ({ kind: 'file' as const, item }))
];
// The wire is ordered — folders first, then files — but slice
// per kind explicitly so the header preview stays a folder-heavy
// list even when files dominate the result set.
const folders = r.items
.filter((it) => it.resource_type === 'folder')
.slice(0, 3)
.map((it) => ({ kind: 'folder' as const, item: it.resource as FolderItem }));
const files = r.items
.filter((it) => it.resource_type === 'file')
.slice(0, 6)
.map((it) => ({ kind: 'file' as const, item: it.resource as FileItem }));
suggestions = [...folders, ...files];
suggestOpen = suggestions.length > 0;
} catch {
if (seq !== suggestSeq || ctl.signal.aborted) return;
+3 -1
View File
@@ -9,7 +9,9 @@ const { goto, pageState } = vi.hoisted(() => ({
vi.mock('$app/navigation', () => ({ goto }));
vi.mock('$app/state', () => ({ page: pageState }));
vi.mock('$lib/api/endpoints/auth', () => ({ logout: vi.fn() }));
vi.mock('$lib/api/endpoints/search', () => ({ searchFiles: vi.fn(async () => ({ items: [] })) }));
vi.mock('$lib/api/endpoints/search', () => ({
searchResources: vi.fn(async () => ({ items: [], query_time_ms: 0 }))
}));
vi.mock('$lib/api/endpoints/files', () => ({ fileInlineUrl: () => '/in' }));
import { logout } from '$lib/api/endpoints/auth';
@@ -2,7 +2,7 @@
import { goto } from '$app/navigation';
import { resolve } from '$app/paths';
import { logout } from '$lib/api/endpoints/auth';
import { searchFiles } from '$lib/api/endpoints/search';
import { searchResources } from '$lib/api/endpoints/search';
import { fileInlineUrl } from '$lib/api/endpoints/files';
import Icon from '$lib/icons/Icon.svelte';
import { t } from '$lib/i18n/index.svelte';
@@ -193,24 +193,33 @@
}
searchTimer = setTimeout(async () => {
try {
const r = await searchFiles(q, { recursive: true, limit: 5 });
const folders: Command[] = r.folders.slice(0, 3).map((f) => ({
id: `fld-${f.id}`,
label: f.name,
icon: 'folder',
hint: t('files.folder', 'Folder'),
run: nav(`/files/${f.id}`)
}));
const files: Command[] = r.files.slice(0, 5).map((f) => ({
id: `fil-${f.id}`,
label: f.name,
icon: 'file',
hint: t('files.file', 'File'),
run: () => {
close();
window.open(fileInlineUrl(f.id), '_blank', 'noopener');
}
}));
const r = await searchResources(q, { recursive: true, limit: 8 });
// Wire items are ordered folders-first-then-files, but demux
// explicitly so the palette keeps the two-section layout even
// when file hits dominate the result set.
const folders: Command[] = r.items
.filter((it) => it.resource_type === 'folder')
.slice(0, 3)
.map((it) => ({
id: `fld-${it.resource.id}`,
label: it.resource.name,
icon: 'folder',
hint: t('files.folder', 'Folder'),
run: nav(`/files/${it.resource.id}`)
}));
const files: Command[] = r.items
.filter((it) => it.resource_type === 'file')
.slice(0, 5)
.map((it) => ({
id: `fil-${it.resource.id}`,
label: it.resource.name,
icon: 'file',
hint: t('files.file', 'File'),
run: () => {
close();
window.open(fileInlineUrl(it.resource.id), '_blank', 'noopener');
}
}));
fileMatches = [...folders, ...files];
} catch {
fileMatches = [];
@@ -4,11 +4,13 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
const { goto } = vi.hoisted(() => ({ goto: vi.fn() }));
vi.mock('$app/navigation', () => ({ goto }));
vi.mock('$lib/api/endpoints/auth', () => ({ logout: vi.fn() }));
vi.mock('$lib/api/endpoints/search', () => ({ searchFiles: vi.fn(async () => ({ items: [] })) }));
vi.mock('$lib/api/endpoints/search', () => ({
searchResources: vi.fn(async () => ({ items: [], query_time_ms: 0 }))
}));
vi.mock('$lib/api/endpoints/files', () => ({ fileInlineUrl: () => '/in' }));
vi.mock('$lib/stores/dialogs.svelte', () => ({ confirmDialog: vi.fn() }));
import { searchFiles } from '$lib/api/endpoints/search';
import { searchResources } from '$lib/api/endpoints/search';
import { session } from '$lib/stores/session.svelte';
import CommandPalette from './CommandPalette.svelte';
@@ -42,6 +44,6 @@ it('searches files as the query is typed', async () => {
await openPalette();
const input = await screen.findByTestId('command-palette-input');
await fireEvent.input(input, { target: { value: 'report' } });
await waitFor(() => expect(searchFiles).toHaveBeenCalled());
expect(m(searchFiles).mock.calls[0][0]).toBe('report');
await waitFor(() => expect(searchResources).toHaveBeenCalled());
expect(m(searchResources).mock.calls[0][0]).toBe('report');
});
+108 -28
View File
@@ -197,13 +197,33 @@
.list-header-checkbox input[type="checkbox"],
.file-item .checkbox-cell input[type="checkbox"] {
width: 17px;
height: 17px;
/* Bumped from 17px to 20px so the row-selection checkbox reads at
a similar visual weight to the 28x28 action buttons that sit at
the other end of the row (Ed's 2026-07-26 UX note). 20px is the
upper end of the browser-native checkbox range — beyond that
platforms start rendering an oversized-and-blurry glyph. */
width: 20px;
height: 20px;
cursor: pointer;
accent-color: var(--color-accent);
border-radius: var(--radius-sm);
}
/* Orange outline on hover for the row-selection checkbox (Ed's UX ask
2026-07-26). `outline` (not `border`) because native checkboxes in
list view honor `accent-color` but their border rendering is
platform-inconsistent — `outline` is drawn OUTSIDE the box and
doesn't reflow the layout. Grid view uses a custom-drawn checkbox
(see `.files-grid-view … input[type="checkbox"]` below) which
accepts real border styling; its hover override lives with that
block and beats this via specificity. Matches the "everything
hovers to accent" convention shared with row-action buttons. */
.list-header-checkbox input[type="checkbox"]:hover,
.file-item .checkbox-cell input[type="checkbox"]:hover {
outline: 2px solid var(--color-accent);
outline-offset: 1px;
}
.list-header.selection-mode {
grid-template-columns: 36px 1fr;
background-color: var(--color-multiselect-bg);
@@ -496,7 +516,26 @@
.files-list-view .file-item .action-cell button:not(.btn-action):hover {
background: var(--color-border-subtle);
color: var(--color-text-dark);
/* Accent-orange hover — matches the grid view's `.file-actions:hover`
and the shared `.btn-action:hover` rule. Semantic overrides on
`.favorite-star:hover` / `.shared-button:hover` (gold / blue) take
precedence via more-specific selectors below. */
color: var(--color-accent);
}
/* List-view resting/active state colors for favorite (gold) and shared
(blue). Hover is intentionally NOT overridden here — the generic
`.action-cell button:not(.btn-action):hover → --color-accent` rule
above owns the orange hover for every button (kebab / favorite /
shared) per Ed's 2026-07-26 spec. This block only paints the
at-rest state on `.active` rows so the star / shared chip stays
discoverable on a quiet row. */
.files-list-view .file-item .action-cell button.favorite-star.active {
color: var(--color-star-text-hover);
}
.files-list-view .file-item .action-cell button.shared-button.active {
color: var(--color-badge-blue-text);
}
/* Fav-star + shared-button share the same visibility rule: hidden on
@@ -668,8 +707,11 @@
position: absolute;
top: calc(var(--space-3) + 8px);
left: calc(var(--space-3) + 8px);
width: 26px;
height: 26px;
/* 30x30 matches the action-cell chip pills (`.file-actions`, star,
shared, `.btn-action`) so the checkbox and the corner-cluster
buttons read as siblings of one visual size (Ed 2026-07-26). */
width: 30px;
height: 30px;
border-radius: var(--radius-md);
background: var(--color-scrim-control);
backdrop-filter: blur(6px);
@@ -699,8 +741,10 @@
.files-grid-view .file-item .checkbox-cell input[type="checkbox"] {
appearance: none;
-webkit-appearance: none;
width: 18px;
height: 18px;
/* Custom-drawn glyph sized proportionally to the 30x30 chip pill —
bumped from 18x18 to match the list-view checkbox's 20x20. */
width: 20px;
height: 20px;
margin: 0;
border: 2px solid var(--color-border-medium);
border-radius: var(--radius-sm);
@@ -713,6 +757,17 @@
border-color var(--motion-fast) var(--ease-standard);
}
/* Grid view uses a custom-drawn checkbox (`appearance: none`) so we can
swap the real border color on hover — cleaner than the list-view
`outline` trick, and no double-ring on this variant. Specificity
(0,4,1 + 0,0,1) beats the shared `input[type="checkbox"]:hover`
outline rule above so the grid-view chip doesn't get both a border
AND an outline. */
.files-grid-view .file-item .checkbox-cell input[type="checkbox"]:hover {
border-color: var(--color-accent);
outline: none;
}
.files-grid-view .file-item .checkbox-cell input[type="checkbox"]::after {
content: "";
width: 5px;
@@ -783,9 +838,11 @@
markup still has shared, favorite, itemActions, kebab in that
sequence so list-view's inline right-aligned flow is unchanged. */
.files-grid-view .file-item .action-cell:has(.shared-button, .favorite-star) {
/* Start right after the checkbox column (26px chip + inline gap)
so the left group aligns visually with the checkbox row. */
left: calc(var(--space-3) + 8px + 26px + var(--space-2));
/* Start right after the checkbox column (30px chip + inline gap)
so the left group aligns visually with the checkbox row. Kept in
sync with `.checkbox-cell` width above — the two share this
constant. */
left: calc(var(--space-3) + 8px + 30px + var(--space-2));
right: calc(var(--space-3) + 8px);
display: flex;
align-items: center;
@@ -875,7 +932,23 @@
opacity: 1;
}
.files-grid-view .file-item .action-cell .file-actions:hover {
/* Unified row-action hover: every button in the grid-view corner cluster
(kebab, star, shared, btn-action*) turns accent-orange on hover.
Semantic states are conveyed by the `.active` class, not by hover
color, so favorite = gold when starred, shared = blue when shared,
both regardless of pointer position (see `.active` rules below).
Ed's 2026-07-26 UX call: "orange for mouse over on all buttons;
blue only for active shared."
Selector specificity (0,4,1 + 0,0,1 = high) beats the chip-visual
base rule at ~line 852 (`.files-grid-view .file-item .action-cell
.btn-action { color: var(--color-text) }`, 0,4,0), which is why the
simpler `.btn-action:hover` didn't take effect inside the corner
cluster. */
.files-grid-view .file-item .action-cell .file-actions:hover,
.files-grid-view .file-item .action-cell .btn-action:hover,
.files-grid-view .file-item .action-cell .favorite-star:hover,
.files-grid-view .file-item .action-cell .shared-button:hover {
color: var(--color-accent);
}
@@ -884,13 +957,20 @@
border: 2px dashed var(--color-warning-border);
}
/* Favorite star + shared button — visual overrides only. Position,
hover-reveal, chip geometry all come from the shared corner-cluster
rule on `.files-grid-view .file-item .action-cell`. What's left
here is just the per-state colour: subtle at rest, saturated when
the item's flag is set. `.active` on either button also bumps the
parent cluster's opacity (via `:has()` above) so an unhovered card
still shows its favorited/shared state. */
/* Favorite star + shared button — resting/active state colors only.
HOVER color for both lives in the unified `.action-cell button:hover
→ --color-accent` rule above; the per-state palette here only fires
when the button is NOT hovered. Convention (Ed 2026-07-26):
• hover → orange (accent) — every row action
• star.active (not hover) → gold
• shared.active (not hover) → blue
`.active` retains its color even on hover for `favorite-star` (star
users expect gold-on-gold on the currently-starred item; losing the
glyph mid-click reads as broken) but yields to orange for `shared`
per Ed's explicit "blue only for active shared" — pointer-over on
an already-shared row should still communicate "you're about to
toggle something." */
.files-grid-view .file-item button.favorite-star,
.files-grid-view .file-item button.shared-button {
color: var(--color-text-subtle);
@@ -898,19 +978,10 @@
line-height: var(--leading-none);
}
.files-grid-view .file-item button.favorite-star:hover {
color: var(--color-star-text);
}
.files-grid-view .file-item button.favorite-star.active {
color: var(--color-star-text-hover);
}
.files-grid-view .file-item button.favorite-star.active:hover {
color: var(--color-star-active);
}
.files-grid-view .file-item button.shared-button:hover,
.files-grid-view .file-item button.shared-button.active {
color: var(--color-badge-blue-text);
}
@@ -1274,7 +1345,16 @@
.btn-action:hover {
background: var(--color-border-subtle);
color: var(--color-text-dark);
/* Accent (orange) hover matches `.file-actions` (kebab) and the
favorite / shared button semantics — the pre-refactor grey-only
tint left `/recent`'s broom, `/trash`'s restore and `/search`'s
"open parent" reading as inert on hover next to the accented
kebab. Ed's 2026-07-26 UX ask: "all row buttons should change
color on hover, not just kebab and favorite." Section-specific
variants (`.btn-action--delete` in trash, `--on` in ShareDialog)
still win via more-specific selectors so red / etc. semantics
are preserved. */
color: var(--color-accent);
}
/* Opt-in modifier: hide the button until the row is hovered / focused.
+16 -8
View File
@@ -24,7 +24,7 @@
type Playlist,
type PlaylistItem
} from '$lib/api/endpoints/music';
import { searchFiles } from '$lib/api/endpoints/search';
import { searchResources } from '$lib/api/endpoints/search';
import type { FileItem } from '$lib/api/types';
import Icon from '$lib/icons/Icon.svelte';
import { confirmDialog, promptDialog } from '$lib/stores/dialogs.svelte';
@@ -450,17 +450,25 @@
async function runAddSearch(query = '') {
addSearching = true;
try {
const res = await searchFiles(query.trim(), {
const res = await searchResources(query.trim(), {
recursive: true,
fileTypes: AUDIO_TYPES,
resourceTypes: ['file'],
limit: 200
});
// Belt-and-braces: keep only audio mime types.
addResults = res.files.filter(
(f) =>
(f.mime_type ?? '').startsWith('audio/') ||
AUDIO_TYPES.some((e) => f.name.toLowerCase().endsWith(`.${e}`))
);
// Belt-and-braces: keep only audio mime types. The envelope
// items are `{resource_type, resource}` — resourceTypes:['file']
// already restricts to files, but re-narrow here so the
// downstream `FileItem[]` cast is honest even if the wire
// ordering ever surfaces a folder.
addResults = res.items
.filter((it) => it.resource_type === 'file')
.map((it) => it.resource as FileItem)
.filter(
(f) =>
(f.mime_type ?? '').startsWith('audio/') ||
AUDIO_TYPES.some((e) => f.name.toLowerCase().endsWith(`.${e}`))
);
} catch (e) {
errorToast(e);
addResults = [];
+462 -198
View File
@@ -1,32 +1,110 @@
<script lang="ts">
import EmptyState from '$lib/components/EmptyState.svelte';
import VirtualList from '$lib/components/VirtualList.svelte';
import { errorMessage } from '$lib/utils/errors';
import ResourceList, { isFile, type ContextAction } from '$lib/components/ResourceList.svelte';
import { errorMessage, errorToast } from '$lib/utils/errors';
import { goto } from '$app/navigation';
import { resolve } from '$app/paths';
import { page } from '$app/state';
import { searchFiles } from '$lib/api/endpoints/search';
import { fileInlineUrl } from '$lib/api/endpoints/files';
import type { FileItem, FolderItem, SearchResults, SortBy } from '$lib/api/types';
import { searchResources } from '$lib/api/endpoints/search';
import { fileDownloadUrl, renameFile, deleteFile } from '$lib/api/endpoints/files';
import { renameFolder, deleteFolder } from '$lib/api/endpoints/folders';
import { addFavorite, removeFavorite } from '$lib/api/endpoints/favorites';
import type { FileItem, FolderItem, SearchResourceItem, SortBy } from '$lib/api/types';
import { lazyComponent } from '$lib/composables/lazyComponent.svelte';
import { folderAccessCached, probeFolderAccess } from '$lib/utils/folderAccess';
import Icon from '$lib/icons/Icon.svelte';
import { t } from '$lib/i18n/index.svelte';
import { confirmDialog, promptDialog } from '$lib/stores/dialogs.svelte';
import { files as filesStore } from '$lib/stores/files.svelte';
import { ui } from '$lib/stores/ui.svelte';
import { formatBytes } from '$lib/utils/format';
import { formatDate, iconNameFromClass, fileIconKindClass } from '$lib/utils/display';
const query = $derived(page.url.searchParams.get('q') ?? '');
let results = $state<SearchResults | null>(null);
// Folder scope encoded in the URL as `?in=<uuid>` so refresh survives —
// pre-refactor the scope lived only in `filesStore.currentFolder`, which
// resets to null on a hard reload. Ed hit this 2026-07-26: refresh
// silently switched to "Everywhere" and disabled "This folder".
// `AppShell` also encodes this param when the user searches from a
// specific `/files/<uuid>`, so the round-trip is symmetric.
//
// `?in=` is *sticky* — it stays in the URL even after the user picks
// "Everywhere" — so they can toggle back to "This folder" without
// losing the reference. The active-scope flip is signalled separately
// by `?scope=all` (absent = default to folder when `in` is present).
const scopeFolderId = $derived(page.url.searchParams.get('in') ?? null);
const scopeOverride = $derived(page.url.searchParams.get('scope'));
// A concrete folder for the scope: prefer the URL param (durable across
// refresh), fall back to whatever folder the Files view has open in
// this session (the pre-URL-param behaviour).
const effectiveFolder = $derived(scopeFolderId ?? filesStore.currentFolder ?? null);
// Rendered as `<h1 class="page-title">` inside ResourceList. Bakes the
// query time / result count into the title string because ResourceList
// doesn't (yet) expose a subtitle slot, and lifting the "Xms" affordance
// into the title is small enough not to warrant one. The bare "Search"
// label is the empty-query fallback for the browser-tab title path
// (`<svelte:head>`); when there IS a query, ResourceList never mounts
// with this string — the `else` branch below owns the render.
const resultsTitle = $derived.by(() => {
const base = query
? t('search.results_for', { q: query }, 'Results for “{{q}}”')
: t('search.title', 'Search');
if (queryTimeMs == null) return base;
const suffix =
total != null
? t('search.found_n_in_ms', { n: total, ms: queryTimeMs }, '{{n}} results in {{ms}} ms')
: `${queryTimeMs} ms`;
return `${base} · ${suffix}`;
});
// Accumulated pages of results. Cursor pagination — a filter/sort/query
// change resets to page 1, infinite scroll appends via `loadMore()`.
let raw = $state<SearchResourceItem[]>([]);
let cursor = $state<string | undefined>(undefined);
let queryTimeMs = $state<number | null>(null);
let total = $state<number | undefined>(undefined);
let loading = $state(false);
let error = $state<string | null>(null);
let sortBy = $state<SortBy>('relevance');
// Scope: search everywhere, or within the folder last open in the files view.
// Default to the current folder when one is set (and we're not in the trash
// section), mirroring the legacy searchView behaviour.
let scope = $state<'all' | 'folder'>(
filesStore.currentFolder && filesStore.section !== 'trash' ? 'folder' : 'all'
// Derived from the URL — URL is the single source of truth so refresh,
// bookmarks and shared links all restore the same scope. Rules:
// `?scope=all` → 'all' (explicit "Everywhere" toggle;
// `in=` may still be present as
// a sticky fallback for the
// "This folder" button)
// `?in=<uuid>` (no override) → 'folder'
// neither → 'all'
const scope = $derived<'all' | 'folder'>(
scopeOverride === 'all' ? 'all' : effectiveFolder && scopeFolderId ? 'folder' : 'all'
);
function setScope(next: 'all' | 'folder') {
// Build the query string by hand — Svelte's lint flags mutating a
// stdlib `URLSearchParams`, and we don't need reactivity here.
//
// Key point (Ed's 2026-07-26 UX ask): the `in=` param is preserved
// even when switching to "Everywhere" so "This folder" stays
// clickable and remembers WHICH folder. The active-scope flip
// rides on `scope=all` instead.
const parts: string[] = [];
if (query) parts.push(`q=${encodeURIComponent(query)}`);
// Sticky `in=`: keep whatever's already in the URL, or seed it
// from filesStore when the user first pins "This folder" from a
// fresh /search visit.
const stickyFolder = scopeFolderId ?? (next === 'folder' ? filesStore.currentFolder : null);
if (stickyFolder) {
parts.push(`in=${encodeURIComponent(stickyFolder)}`);
}
if (next === 'all' && stickyFolder) {
// Only meaningful when there's a folder to override — otherwise
// the URL is "everywhere by default" and the flag would be noise.
parts.push('scope=all');
}
const target = resolve(parts.length ? `/search?${parts.join('&')}` : '/search');
// `replaceState: true` keeps the browser back-button meaningful —
// scope changes are UI state, not navigation. `keepFocus: true`
// keeps focus on whatever button the user just clicked.
void goto(target, { replaceState: true, keepFocus: true, noScroll: true });
}
// Filters
type TypeKey = 'all' | 'image' | 'video' | 'document' | 'audio' | 'archive';
@@ -129,17 +207,43 @@
// full recursive backend search; without the token a SLOW earlier response
// could resolve after (and clobber) a newer one, and the superseded server
// work ran to completion. The seq token keeps only the latest result; the
// AbortController cancels the superseded request outright.
// AbortController cancels the superseded request outright. The same token
// invalidates any in-flight `loadMore()` when the query/filter changes so
// its rows never append to a fresh result set.
let runSeq = 0;
let inflight: AbortController | null = null;
function currentQueryParams() {
// Trash section searches are always global — there is no folder to
// scope to. Otherwise the folder comes from the URL (`?in=<uuid>`)
// via `scopeFolderId`, which survives a hard refresh and shared
// links unlike `filesStore.currentFolder` (session-only, resets on
// reload).
const folderId =
scope === 'folder' && filesStore.section !== 'trash'
? (effectiveFolder ?? undefined)
: undefined;
return {
recursive: true,
sortBy,
folderId,
fileTypes: typeFilter === 'all' ? undefined : TYPE_EXT[typeFilter],
...sizeBounds(sizeFilter),
modifiedAfter: dateBound(dateFilter)
};
}
async function run(q: string) {
const seq = ++runSeq;
inflight?.abort();
inflight = null;
if (!q) {
results = null;
raw = [];
cursor = undefined;
queryTimeMs = null;
total = undefined;
loading = false;
error = null;
return;
}
const ctl = new AbortController();
@@ -147,22 +251,12 @@
loading = true;
error = null;
try {
// Trash section searches are always global — there is no folder to scope to.
const folderId =
scope === 'folder' && filesStore.section !== 'trash'
? (filesStore.currentFolder ?? undefined)
: undefined;
const fresh = await searchFiles(q, {
recursive: true,
sortBy,
folderId,
fileTypes: typeFilter === 'all' ? undefined : TYPE_EXT[typeFilter],
...sizeBounds(sizeFilter),
modifiedAfter: dateBound(dateFilter),
signal: ctl.signal
});
const fresh = await searchResources(q, { ...currentQueryParams(), signal: ctl.signal });
if (seq !== runSeq) return; // superseded while awaiting
results = fresh;
raw = fresh.items;
cursor = fresh.next_cursor;
queryTimeMs = fresh.query_time_ms;
total = fresh.total;
} catch (e) {
// An aborted request is not an error — a newer run owns the UI.
if (seq !== runSeq || ctl.signal.aborted) return;
@@ -172,27 +266,220 @@
}
}
function openFolder(folder: FolderItem) {
goto(resolve(`/files/${folder.id}`));
async function loadMore() {
if (!cursor || loading) return;
// Snapshot the current seq — if a filter/sort/query change bumps
// `runSeq` while we're awaiting, we drop this page on the floor
// (its rows belong to a stale filter set).
const seq = runSeq;
const ctl = new AbortController();
// Don't overwrite `inflight` — that belongs to `run()` and lets a
// query change abort a page-1 fetch. A concurrent loadMore is
// harmless: at most one appends because of the seq guard.
loading = true;
try {
const nextPage = await searchResources(query, {
...currentQueryParams(),
cursor,
signal: ctl.signal
});
if (seq !== runSeq) return;
raw = [...raw, ...nextPage.items];
cursor = nextPage.next_cursor;
// total/query_time refresh — the server recomputes both per page.
total = nextPage.total ?? total;
} catch (e) {
if (seq !== runSeq || ctl.signal.aborted) return;
error = errorMessage(e);
} finally {
if (seq === runSeq) loading = false;
}
}
function openFile(file: FileItem) {
window.open(fileInlineUrl(file.id), '_blank', 'noopener');
// Feed ResourceList the raw resource objects — that's the shared
// `{FileItem | FolderItem}[]` shape every other /*/resources page
// uses. Search-specific meta (score/snippet/via) is not surfaced
// today; a follow-up commit will extend ResourceList with an
// optional per-row meta slot for the snippet + a "matched: content"
// chip. Score isn't worth surfacing to end users.
const items = $derived(raw.map((it) => it.resource as FileItem | FolderItem));
// ── Per-row actions ──────────────────────────────────────────────────
// Match the shape of `/favorites` + `/recent`: files open inline in
// the shared FileViewer (was new-tab pre-refactor — a discontinuity
// with the rest of the app), folders navigate. Share + move + delete
// all reuse the same lazy dialogs.
let viewerOpen = $state(false);
let viewerFile = $state<FileItem | null>(null);
let moveOpen = $state(false);
let moveTarget = $state<{ id: string; name: string; kind: 'file' | 'folder' } | null>(null);
let shareOpen = $state(false);
let shareTarget = $state<{ id: string; name: string; kind: 'file' | 'folder' } | null>(null);
const fileViewer = lazyComponent(() => import('$lib/components/FileViewer.svelte'));
const moveDialog = lazyComponent(() => import('$lib/components/MoveDialog.svelte'));
const shareDialog = lazyComponent(() => import('$lib/components/ShareDialog.svelte'));
$effect(() => {
if (viewerOpen) void fileViewer.load();
if (moveOpen) void moveDialog.load();
if (shareOpen) void shareDialog.load();
});
function kindOf(item: FileItem | FolderItem): 'file' | 'folder' {
return isFile(item) ? 'file' : 'folder';
}
const isEmpty = $derived(!!results && results.files.length === 0 && results.folders.length === 0);
function open(item: FileItem | FolderItem) {
if (!isFile(item)) {
goto(resolve(`/files/${item.id}`));
return;
}
viewerFile = item;
viewerOpen = true;
}
// Flatten folders + files into one list so the results render through a single
// windowed list (only the visible rows hit the DOM, even for 100s of hits).
type SearchEntry = { kind: 'folder'; folder: FolderItem } | { kind: 'file'; file: FileItem };
const entries = $derived<SearchEntry[]>(
results
? [
...results.folders.map((folder) => ({ kind: 'folder' as const, folder })),
...results.files.map((file) => ({ kind: 'file' as const, file }))
]
: []
);
// Files carry `folder_id`, folders carry `parent_id`; both are nullable
// at drive roots. Null → no meaningful parent to open. Mirrors the
// same helper in /favorites and /recent.
function parentFolderId(item: FileItem | FolderItem): string | null {
return isFile(item) ? item.folder_id : item.parent_id;
}
async function toggleFavorite(item: FileItem | FolderItem) {
const kind = kindOf(item);
try {
if (item.is_favorite) {
await removeFavorite(kind, item.id);
} else {
await addFavorite(kind, item.id);
}
// Optimistic in-place update — a full reload would jump the
// user out of their scroll position on an infinite-scroll
// page. Mutating the raw envelope entry updates the derived
// `items` array and ResourceList's star widget flips.
const idx = raw.findIndex((it) => it.resource.id === item.id);
if (idx !== -1) {
raw[idx] = {
...raw[idx],
resource: { ...raw[idx].resource, is_favorite: !item.is_favorite }
};
}
} catch (e) {
errorToast(e);
}
}
function openShareDialog(item: FileItem | FolderItem) {
shareTarget = { id: item.id, name: item.name, kind: kindOf(item) };
shareOpen = true;
}
function openMoveDialog(item: FileItem | FolderItem) {
moveTarget = { id: item.id, name: item.name, kind: kindOf(item) };
moveOpen = true;
}
function downloadItem(item: FileItem | FolderItem) {
if (!isFile(item)) return;
const a = document.createElement('a');
a.href = fileDownloadUrl(item.id);
a.download = item.name;
document.body.appendChild(a);
a.click();
a.remove();
}
async function rename(item: FileItem | FolderItem) {
const name = await promptDialog({
title: t('common.rename', 'Rename'),
defaultValue: item.name,
confirmText: t('common.rename', 'Rename')
});
if (!name || name === item.name) return;
try {
if (isFile(item)) await renameFile(item.id, name);
else await renameFolder(item.id, name);
// Update the row in place so the user keeps their scroll
// position instead of jumping back to page 1.
const idx = raw.findIndex((it) => it.resource.id === item.id);
if (idx !== -1) {
raw[idx] = { ...raw[idx], resource: { ...raw[idx].resource, name } };
}
} catch (e) {
errorToast(e);
}
}
async function remove(item: FileItem | FolderItem) {
const ok = await confirmDialog({
title: t('common.delete', 'Delete'),
message: t('files.confirm_delete', { name: item.name }, 'Delete "{{name}}"?'),
confirmText: t('common.delete', 'Delete'),
danger: true
});
if (!ok) return;
try {
if (isFile(item)) await deleteFile(item.id);
else await deleteFolder(item.id);
raw = raw.filter((it) => it.resource.id !== item.id);
} catch (e) {
errorToast(e);
}
}
function openParent(item: FileItem | FolderItem) {
const pid = parentFolderId(item);
if (pid) goto(resolve(`/files/${pid}`));
}
// Canonical context-menu order — matches `/favorites` and `/files`
// (Open parent, Download, Share, Move, Rename, Delete) so users
// don't have to relearn the menu when switching sections.
const contextActions: ContextAction[] = [
{
key: 'open_parent',
label: t('files.open_parent', 'Open parent folder'),
icon: 'folder-open',
// Hidden only when there is literally no parent (drive-root
// folders where `parent_id === null`). Otherwise stay visible
// and disable when the caller lacks Read on the parent — a
// grey entry reads as "you can't do this here" rather than
// "the option is missing." `folderAccessCached` returns
// true/false/undefined; disable only on explicit `false`.
visible: (item) => parentFolderId(item) !== null,
disabled: (item) => {
const pid = parentFolderId(item);
return pid === null || folderAccessCached(pid) === false;
},
run: openParent
},
{
key: 'download',
label: t('common.download', 'Download'),
icon: 'download',
visible: isFile,
run: downloadItem
},
{
key: 'share',
label: t('files.share', 'Share'),
icon: 'share-alt',
run: openShareDialog
},
{
key: 'move',
label: t('files.move', 'Move'),
icon: 'arrows-alt',
run: openMoveDialog
},
{ key: 'rename', label: t('common.rename', 'Rename'), icon: 'pen', run: rename },
{
key: 'delete',
label: t('common.delete', 'Delete'),
icon: 'trash',
danger: true,
run: remove
}
];
$effect(() => {
// re-run when query, sort, scope, or any filter changes
@@ -211,13 +498,12 @@
* browser's default handler navigates to the dropped file — the tab
* REPLACES the app with the file itself, which is data-loss-esque
* (user loses their in-progress search + any unsaved UI state).
* The `ResourceList`-based views (`/photos`, `/shared`, `/trash`, …)
* already fire a "wrong drop zone" toast via their `.rl-root`
* wrapper when `enableSystemDrop` is false — this handler brings
* `/search` to the same contract, and covers the whole viewport
* (not just a list surface) so drops on the sticky header /
* result-card margins are caught too. Same toast copy + "Go to
* Files" action as `ResourceList` for a consistent recovery UX.
* ResourceList already fires a "wrong drop zone" toast via its
* `.rl-root` wrapper when `enableSystemDrop` is false, but that
* covers only the list area — this handler covers the whole
* viewport (sticky header, empty-state screen, gaps around the
* list). Same toast copy + "Go to Files" action as ResourceList
* for a consistent recovery UX.
*/
function onWindowDragOver(e: DragEvent) {
if (!e.dataTransfer?.types?.includes('Files')) return;
@@ -258,38 +544,69 @@
<svelte:window ondragover={onWindowDragOver} ondrop={onWindowDrop} />
<div class="page-sticky-header search-head">
<h1 class="page-title">
{#if query}{t('search.results_for', { q: query }, 'Results for “{{q}}”')}{:else}{t(
'search.title',
'Search'
)}{/if}
{#if results?.query_time_ms != null}
<span class="search-time">({results.query_time_ms} ms)</span>
{/if}
</h1>
{#if query}
<div class="search-controls">
{#if filesStore.currentFolder}
<div class="seg" role="group" aria-label={t('search.scope', 'Scope')}>
<button
class="seg__btn"
class:active={scope === 'all'}
data-testid="search-scope-all-btn"
onclick={() => (scope = 'all')}
>
{t('search.everywhere', 'Everywhere')}
</button>
<button
class="seg__btn"
class:active={scope === 'folder'}
data-testid="search-scope-folder-btn"
onclick={() => (scope = 'folder')}
>
{t('search.this_folder', 'This folder')}
</button>
</div>
{/if}
{#if !query}
<EmptyState title={t('search.prompt', 'Type a query in the search bar above.')} />
{:else}
<ResourceList
title={resultsTitle}
{items}
{loading}
{error}
emptyIcon="search"
emptyText={t('search.no_results', 'No results found for this search')}
hasMore={!!cursor}
onloadmore={loadMore}
showPath
showViewToggle
onopen={open}
onfavorite={toggleFavorite}
onshared={openShareDialog}
{contextActions}
menuPrepare={async (item) => {
// Lazy folder-access probe — fires only when the user opens
// the context menu on a row, not proactively for every row on
// load. Cached in the LRU (see `folderAccess.ts`) so
// subsequent right-clicks on the same folder are instant.
// Mirrors /favorites + /recent so the "Open parent folder"
// entry lands enabled/disabled without a "flash of enabled"
// on first right-click.
const pid = parentFolderId(item);
if (pid) await probeFolderAccess(pid);
}}
>
{#snippet actions()}
<!--
Scope segment is always visible so the affordance is
discoverable even from a cold `/search?q=…` load; when
there's no `filesStore.currentFolder` (user typed the URL
directly, or search bar navigation didn't carry a folder),
"This folder" disables — clicking it wouldn't have a
folder to scope to. Pre-refactor the whole segment was
hidden in that case, which read as "the option was
removed" (2026-07-26 UX feedback).
-->
<div class="seg" role="group" aria-label={t('search.scope', 'Scope')}>
<button
class="seg__btn"
class:active={scope === 'all'}
data-testid="search-scope-all-btn"
onclick={() => setScope('all')}
>
{t('search.everywhere', 'Everywhere')}
</button>
<button
class="seg__btn"
class:active={scope === 'folder'}
data-testid="search-scope-folder-btn"
disabled={!effectiveFolder}
title={effectiveFolder
? undefined
: t('search.this_folder_disabled', 'Open a folder in Files to scope search to it')}
onclick={() => setScope('folder')}
>
{t('search.this_folder', 'This folder')}
</button>
</div>
<select
class="sort-select"
bind:value={typeFilter}
@@ -332,99 +649,68 @@
{t('search.clear_filters', 'Clear filters')}
</button>
{/if}
</div>
{/if}
</div>
{/snippet}
{#snippet itemActions(item)}
<!--
Per-row "Open parent folder" quick-action — search results
are context-poor by nature (the path column shows WHERE the
match is, but jumping there takes an extra right-click on
every other section). Surface it as a direct button so a
single click navigates. Same `.btn-action` treatment as
trash's Restore / Delete and recent's broom, so the row's
action-cell keeps the visual rhythm shared across sections.
Hidden when there's no meaningful parent (drive-root
folders where `parent_id === null`).
-->
{#if parentFolderId(item) !== null}
<button
class="btn-action btn-action--hover"
data-testid={`search-open-parent-btn-${item.id}`}
title={t('files.open_parent', 'Open parent folder')}
aria-label={t('files.open_parent', 'Open parent folder')}
onclick={(e) => {
e.stopPropagation();
openParent(item);
}}
>
<Icon name="folder-open" />
</button>
{/if}
{/snippet}
</ResourceList>
{/if}
{#if loading}
<div class="search-loading">
<Icon name="spinner" class="search-loading__spinner" />
<h2 class="search-loading__text">
{t('search.searching_for', { q: query }, 'Searching for “{{q}}”…')}
</h2>
</div>
{:else if error}
<EmptyState title={error} error />
{:else if !query}
<EmptyState title={t('search.prompt', 'Type a query in the search bar above.')} />
{:else if isEmpty}
<EmptyState icon="search" title={t('search.no_results', 'No results found for this search')} />
{:else if results}
<div class="files-container">
<div class="files-list-view" style="--files-list-columns: minmax(200px, 2fr) 1fr 110px 140px">
<div class="list-header">
<div>{t('files.col_name', 'Name')}</div>
<div>{t('files.col_path', 'Path')}</div>
<div>{t('files.col_size', 'Size')}</div>
<div>{t('files.col_modified', 'Modified')}</div>
</div>
<VirtualList
items={entries}
rowHeight={56}
key={(e) => (e.kind === 'folder' ? e.folder.id : e.file.id)}
>
{#snippet row(e)}
{#if e.kind === 'folder'}
<div
class="file-item"
role="button"
tabindex="0"
aria-label={e.folder.name}
data-testid={e.folder.name}
onclick={() => openFolder(e.folder)}
onkeydown={(ev) => ev.key === 'Enter' && openFolder(e.folder)}
>
<div class="name-cell">
<span class="file-icon file-icon--folder"><Icon name="folder" /></span>
<span>{e.folder.name}</span>
</div>
<div class="path-cell">{e.folder.path}</div>
<div class="size-cell">—</div>
<div class="date-cell">{formatDate(e.folder.modified_at)}</div>
</div>
{:else}
<div
class="file-item"
role="button"
tabindex="0"
aria-label={e.file.name}
data-testid={e.file.name}
onclick={() => openFile(e.file)}
onkeydown={(ev) => ev.key === 'Enter' && openFile(e.file)}
>
<div class="name-cell">
<span class="file-icon {fileIconKindClass(iconNameFromClass(e.file.icon_class))}"
><Icon name={iconNameFromClass(e.file.icon_class)} /></span
>
<span>{e.file.name}</span>
</div>
<div class="path-cell">{e.file.path}</div>
<div class="size-cell">{e.file.size != null ? formatBytes(e.file.size) : ''}</div>
<div class="date-cell">{formatDate(e.file.modified_at)}</div>
</div>
{/if}
{/snippet}
</VirtualList>
</div>
</div>
{#if fileViewer.component}
{@const FileViewer = fileViewer.component}
<FileViewer bind:open={viewerOpen} file={viewerFile} />
{/if}
{#if moveDialog.component}
{@const MoveDialog = moveDialog.component}
<MoveDialog
bind:open={moveOpen}
item={moveTarget}
onmoved={() => {
// A move can shift the row out of the current scope (`?in=<uuid>`)
// or into it, and the SQL name-match count may change. Reload
// page 1 rather than trying to patch state in place — search
// state is already reactive on query/scope so a fresh `run()`
// is cheap and correct.
void run(query);
}}
/>
{/if}
{#if shareDialog.component}
{@const ShareDialog = shareDialog.component}
<ShareDialog bind:open={shareOpen} item={shareTarget} />
{/if}
<style>
.search-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
flex-wrap: wrap;
}
.search-controls {
display: flex;
align-items: center;
gap: var(--space-2);
}
/* Filter cluster lives inside ResourceList's action-bar snippet now,
but the actual DOM is scoped to THIS component's <style> block —
Svelte's scoped selectors still apply because these are declared
with the elements they style below.
Every color/border here uses tokens; no raw values (Stylelint gate). */
.sort-select {
padding: var(--space-2) var(--space-2-5);
border: 1px solid var(--color-border);
@@ -453,10 +739,9 @@
color: var(--color-on-accent);
}
.search-time {
font-size: var(--text-sm);
font-weight: var(--weight-normal);
color: var(--color-text-muted);
.seg__btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.clear-filters {
@@ -474,25 +759,4 @@
.clear-filters:hover {
background: var(--color-bg-hover);
}
.search-loading {
display: flex;
align-items: center;
gap: var(--space-3);
padding: var(--space-4) 0;
color: var(--color-text-muted);
}
.search-loading :global(.search-loading__spinner) {
font-size: var(--text-xl);
color: var(--color-accent);
animation: spin var(--spin-duration) linear infinite;
}
.search-loading__text {
margin: 0;
font-size: var(--text-lg);
font-weight: var(--weight-medium);
color: var(--color-text);
}
</style>
+8 -8
View File
@@ -7,10 +7,10 @@ const { goto, pageState } = vi.hoisted(() => ({
}));
vi.mock('$app/navigation', () => ({ goto }));
vi.mock('$app/state', () => ({ page: pageState }));
vi.mock('$lib/api/endpoints/search', () => ({ searchFiles: vi.fn() }));
vi.mock('$lib/api/endpoints/search', () => ({ searchResources: vi.fn() }));
vi.mock('$lib/api/endpoints/files', () => ({ fileInlineUrl: () => '/in' }));
import { searchFiles } from '$lib/api/endpoints/search';
import { searchResources } from '$lib/api/endpoints/search';
import SearchPage from './+page.svelte';
const m = (fn: unknown) => fn as ReturnType<typeof vi.fn>;
@@ -18,13 +18,13 @@ const m = (fn: unknown) => fn as ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
pageState.url = new URL('http://localhost/search?q=report');
m(searchFiles).mockResolvedValue({ files: [], folders: [], total: 0 });
m(searchResources).mockResolvedValue({ items: [], query_time_ms: 0, total: 0 });
});
it('runs a search from the q query parameter on mount', async () => {
render(SearchPage);
await waitFor(() => expect(searchFiles).toHaveBeenCalled());
expect(m(searchFiles).mock.calls[0][0]).toBe('report');
await waitFor(() => expect(searchResources).toHaveBeenCalled());
expect(m(searchResources).mock.calls[0][0]).toBe('report');
});
it('does not search when there is no query', async () => {
@@ -32,12 +32,12 @@ it('does not search when there is no query', async () => {
render(SearchPage);
// Give the reactive effect a tick to (not) fire.
await Promise.resolve();
expect(searchFiles).not.toHaveBeenCalled();
expect(searchResources).not.toHaveBeenCalled();
});
it('surfaces a search error', async () => {
m(searchFiles).mockRejectedValue(new Error('search boom'));
m(searchResources).mockRejectedValue(new Error('search boom'));
render(SearchPage);
await waitFor(() => expect(searchFiles).toHaveBeenCalled());
await waitFor(() => expect(searchResources).toHaveBeenCalled());
await waitFor(() => expect(screen.getByText('search boom')).toBeTruthy());
});