refactor(search): adapt UI to use ResourceList
This commit is contained in:
@@ -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/client', () => ({ apiFetch: vi.fn(), apiJson: vi.fn() }));
|
||||||
vi.mock('$lib/api/csrf', () => ({ getCsrfHeaders: () => ({}) }));
|
vi.mock('$lib/api/csrf', () => ({ getCsrfHeaders: () => ({}) }));
|
||||||
import { apiFetch, apiJson } from '$lib/api/client';
|
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 f = apiFetch as unknown as ReturnType<typeof vi.fn>;
|
||||||
const j = apiJson as unknown as ReturnType<typeof vi.fn>;
|
const j = apiJson as unknown as ReturnType<typeof vi.fn>;
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
f.mockResolvedValue({ ok: true, status: 200, json: async () => ({}) });
|
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 () => {
|
it('builds search requests including filters', async () => {
|
||||||
await searchFiles('q', {
|
await searchResources('q', {
|
||||||
recursive: true,
|
recursive: true,
|
||||||
fileTypes: ['mp3', 'wav'],
|
fileTypes: ['mp3', 'wav'],
|
||||||
minSize: 1,
|
minSize: 1,
|
||||||
@@ -19,7 +19,22 @@ it('builds search requests including filters', async () => {
|
|||||||
sortBy: 'date'
|
sortBy: 'date'
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
expect(j).toHaveBeenCalledWith(expect.stringContaining('type=mp3%2Cwav'), expect.anything());
|
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 searchSuggest('q').catch(() => {});
|
||||||
await clearSearchCache().catch(() => {});
|
await clearSearchCache().catch(() => {});
|
||||||
expect(f.mock.calls.length + j.mock.calls.length).toBeGreaterThan(1);
|
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');
|
||||||
|
});
|
||||||
|
|||||||
@@ -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 { 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 {
|
export interface SearchOptions {
|
||||||
folderId?: string;
|
folderId?: string;
|
||||||
@@ -16,14 +16,31 @@ export interface SearchOptions {
|
|||||||
modifiedAfter?: number;
|
modifiedAfter?: number;
|
||||||
/** Unix-seconds upper bound on modified time. */
|
/** Unix-seconds upper bound on modified time. */
|
||||||
modifiedBefore?: number;
|
modifiedBefore?: number;
|
||||||
|
/** Page size (1–200 server-side; default 50). */
|
||||||
limit?: number;
|
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;
|
sortBy?: SortBy;
|
||||||
|
/** Restrict to files, folders, or both (default). */
|
||||||
|
resourceTypes?: ItemType[];
|
||||||
/** Abort the request when a newer search supersedes it. */
|
/** Abort the request when a newer search supersedes it. */
|
||||||
signal?: AbortSignal;
|
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();
|
const params = new URLSearchParams();
|
||||||
params.append('query', query);
|
params.append('query', query);
|
||||||
if (opts.folderId) params.append('folder_id', opts.folderId);
|
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.createdBefore != null) params.append('created_before', String(opts.createdBefore));
|
||||||
if (opts.modifiedAfter != null) params.append('modified_after', String(opts.modifiedAfter));
|
if (opts.modifiedAfter != null) params.append('modified_after', String(opts.modifiedAfter));
|
||||||
if (opts.modifiedBefore != null) params.append('modified_before', String(opts.modifiedBefore));
|
if (opts.modifiedBefore != null) params.append('modified_before', String(opts.modifiedBefore));
|
||||||
params.append('limit', String(opts.limit ?? 100));
|
if (opts.resourceTypes?.length) params.append('resource_types', opts.resourceTypes.join(','));
|
||||||
params.append('offset', String(opts.offset ?? 0));
|
if (opts.limit != null) params.append('limit', String(opts.limit));
|
||||||
params.append('sort_by', opts.sortBy ?? 'relevance');
|
if (opts.cursor) params.append('cursor', opts.cursor);
|
||||||
return apiJson<SearchResults>(`/api/search?${params.toString()}`, {
|
if (opts.sortBy) params.append('order_by', opts.sortBy);
|
||||||
|
return apiJson<SearchResourcesResponse>(`/api/search?${params.toString()}`, {
|
||||||
credentials: 'same-origin',
|
credentials: 'same-origin',
|
||||||
signal: opts.signal
|
signal: opts.signal
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -257,31 +257,43 @@ export type SortBy =
|
|||||||
| 'size'
|
| 'size'
|
||||||
| 'size_desc';
|
| 'size_desc';
|
||||||
|
|
||||||
export interface SearchCriteria {
|
/**
|
||||||
sort_by: SortBy;
|
* Per-item search metadata inline on every hit in the normalized
|
||||||
recursive: boolean;
|
* `/api/search` envelope. Mirrors backend `SearchMeta` — see
|
||||||
limit: number;
|
* `application/dtos/search_dto.rs`.
|
||||||
offset: number;
|
*/
|
||||||
name_contains?: string;
|
export interface SearchMeta {
|
||||||
file_types?: string[];
|
/** Relevance in [0, 1]; the higher the better. */
|
||||||
folder_id?: string;
|
score: number;
|
||||||
min_size?: number;
|
/** Optional HTML-safe excerpt when the match fired via content index. */
|
||||||
max_size?: number;
|
snippet?: string;
|
||||||
created_before?: number;
|
/** Where the match fired. */
|
||||||
created_after?: number;
|
via?: 'name' | 'content' | 'path';
|
||||||
modified_before?: number;
|
|
||||||
modified_after?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SearchResults {
|
/**
|
||||||
files: FileItem[];
|
* Single hit in the `/api/search` envelope. `resource_type` disambiguates
|
||||||
folders: FolderItem[];
|
* `resource`'s union so the shared `ResourceList` component can render it
|
||||||
total_count: number | null;
|
* exactly like a folders/favorites/recent/trash row.
|
||||||
limit: number;
|
*/
|
||||||
offset: number;
|
export interface SearchResourceItem {
|
||||||
has_more: boolean;
|
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;
|
query_time_ms: number;
|
||||||
sort_by: string;
|
total?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type DriveKind = 'personal' | 'shared';
|
export type DriveKind = 'personal' | 'shared';
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import { logout } from '$lib/api/endpoints/auth';
|
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 { fileInlineUrl, deleteFile } from '$lib/api/endpoints/files';
|
||||||
import { deleteFolder } from '$lib/api/endpoints/folders';
|
import { deleteFolder } from '$lib/api/endpoints/folders';
|
||||||
import { addFavorite } from '$lib/api/endpoints/favorites';
|
import { addFavorite } from '$lib/api/endpoints/favorites';
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
import { i18n, LANGUAGES, setLocale, t, type Locale } from '$lib/i18n/index.svelte';
|
import { i18n, LANGUAGES, setLocale, t, type Locale } from '$lib/i18n/index.svelte';
|
||||||
import { apiFetch } from '$lib/api/client';
|
import { apiFetch } from '$lib/api/client';
|
||||||
import { dialogs } from '$lib/stores/dialogs.svelte';
|
import { dialogs } from '$lib/stores/dialogs.svelte';
|
||||||
|
import { files as filesStore } from '$lib/stores/files.svelte';
|
||||||
import { preferences } from '$lib/stores/preferences.svelte';
|
import { preferences } from '$lib/stores/preferences.svelte';
|
||||||
import { session } from '$lib/stores/session.svelte';
|
import { session } from '$lib/stores/session.svelte';
|
||||||
import { theme, type Theme } from '$lib/stores/theme.svelte';
|
import { theme, type Theme } from '$lib/stores/theme.svelte';
|
||||||
@@ -255,11 +256,22 @@
|
|||||||
|
|
||||||
function goToResults() {
|
function goToResults() {
|
||||||
const q = searchQuery.trim();
|
const q = searchQuery.trim();
|
||||||
if (q) {
|
if (!q) return;
|
||||||
suggestOpen = false;
|
suggestOpen = false;
|
||||||
searchActive = false;
|
searchActive = false;
|
||||||
goto(resolve(`/search?q=${encodeURIComponent(q)}`));
|
// 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) {
|
function onSearch(e: SubmitEvent) {
|
||||||
@@ -285,12 +297,20 @@
|
|||||||
suggestInflight = ctl;
|
suggestInflight = ctl;
|
||||||
suggestBusy = true;
|
suggestBusy = true;
|
||||||
try {
|
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
|
if (seq !== suggestSeq) return; // superseded while awaiting
|
||||||
suggestions = [
|
// The wire is ordered — folders first, then files — but slice
|
||||||
...r.folders.slice(0, 3).map((item) => ({ kind: 'folder' as const, item })),
|
// per kind explicitly so the header preview stays a folder-heavy
|
||||||
...r.files.slice(0, 6).map((item) => ({ kind: 'file' as const, item }))
|
// 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;
|
suggestOpen = suggestions.length > 0;
|
||||||
} catch {
|
} catch {
|
||||||
if (seq !== suggestSeq || ctl.signal.aborted) return;
|
if (seq !== suggestSeq || ctl.signal.aborted) return;
|
||||||
|
|||||||
@@ -9,7 +9,9 @@ const { goto, pageState } = vi.hoisted(() => ({
|
|||||||
vi.mock('$app/navigation', () => ({ goto }));
|
vi.mock('$app/navigation', () => ({ goto }));
|
||||||
vi.mock('$app/state', () => ({ page: pageState }));
|
vi.mock('$app/state', () => ({ page: pageState }));
|
||||||
vi.mock('$lib/api/endpoints/auth', () => ({ logout: vi.fn() }));
|
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/api/endpoints/files', () => ({ fileInlineUrl: () => '/in' }));
|
||||||
|
|
||||||
import { logout } from '$lib/api/endpoints/auth';
|
import { logout } from '$lib/api/endpoints/auth';
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { logout } from '$lib/api/endpoints/auth';
|
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 { fileInlineUrl } from '$lib/api/endpoints/files';
|
||||||
import Icon from '$lib/icons/Icon.svelte';
|
import Icon from '$lib/icons/Icon.svelte';
|
||||||
import { t } from '$lib/i18n/index.svelte';
|
import { t } from '$lib/i18n/index.svelte';
|
||||||
@@ -193,24 +193,33 @@
|
|||||||
}
|
}
|
||||||
searchTimer = setTimeout(async () => {
|
searchTimer = setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
const r = await searchFiles(q, { recursive: true, limit: 5 });
|
const r = await searchResources(q, { recursive: true, limit: 8 });
|
||||||
const folders: Command[] = r.folders.slice(0, 3).map((f) => ({
|
// Wire items are ordered folders-first-then-files, but demux
|
||||||
id: `fld-${f.id}`,
|
// explicitly so the palette keeps the two-section layout even
|
||||||
label: f.name,
|
// when file hits dominate the result set.
|
||||||
icon: 'folder',
|
const folders: Command[] = r.items
|
||||||
hint: t('files.folder', 'Folder'),
|
.filter((it) => it.resource_type === 'folder')
|
||||||
run: nav(`/files/${f.id}`)
|
.slice(0, 3)
|
||||||
}));
|
.map((it) => ({
|
||||||
const files: Command[] = r.files.slice(0, 5).map((f) => ({
|
id: `fld-${it.resource.id}`,
|
||||||
id: `fil-${f.id}`,
|
label: it.resource.name,
|
||||||
label: f.name,
|
icon: 'folder',
|
||||||
icon: 'file',
|
hint: t('files.folder', 'Folder'),
|
||||||
hint: t('files.file', 'File'),
|
run: nav(`/files/${it.resource.id}`)
|
||||||
run: () => {
|
}));
|
||||||
close();
|
const files: Command[] = r.items
|
||||||
window.open(fileInlineUrl(f.id), '_blank', 'noopener');
|
.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];
|
fileMatches = [...folders, ...files];
|
||||||
} catch {
|
} catch {
|
||||||
fileMatches = [];
|
fileMatches = [];
|
||||||
|
|||||||
@@ -4,11 +4,13 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
|
|||||||
const { goto } = vi.hoisted(() => ({ goto: vi.fn() }));
|
const { goto } = vi.hoisted(() => ({ goto: vi.fn() }));
|
||||||
vi.mock('$app/navigation', () => ({ goto }));
|
vi.mock('$app/navigation', () => ({ goto }));
|
||||||
vi.mock('$lib/api/endpoints/auth', () => ({ logout: vi.fn() }));
|
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/api/endpoints/files', () => ({ fileInlineUrl: () => '/in' }));
|
||||||
vi.mock('$lib/stores/dialogs.svelte', () => ({ confirmDialog: vi.fn() }));
|
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 { session } from '$lib/stores/session.svelte';
|
||||||
import CommandPalette from './CommandPalette.svelte';
|
import CommandPalette from './CommandPalette.svelte';
|
||||||
|
|
||||||
@@ -42,6 +44,6 @@ it('searches files as the query is typed', async () => {
|
|||||||
await openPalette();
|
await openPalette();
|
||||||
const input = await screen.findByTestId('command-palette-input');
|
const input = await screen.findByTestId('command-palette-input');
|
||||||
await fireEvent.input(input, { target: { value: 'report' } });
|
await fireEvent.input(input, { target: { value: 'report' } });
|
||||||
await waitFor(() => expect(searchFiles).toHaveBeenCalled());
|
await waitFor(() => expect(searchResources).toHaveBeenCalled());
|
||||||
expect(m(searchFiles).mock.calls[0][0]).toBe('report');
|
expect(m(searchResources).mock.calls[0][0]).toBe('report');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -197,13 +197,33 @@
|
|||||||
|
|
||||||
.list-header-checkbox input[type="checkbox"],
|
.list-header-checkbox input[type="checkbox"],
|
||||||
.file-item .checkbox-cell input[type="checkbox"] {
|
.file-item .checkbox-cell input[type="checkbox"] {
|
||||||
width: 17px;
|
/* Bumped from 17px to 20px so the row-selection checkbox reads at
|
||||||
height: 17px;
|
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;
|
cursor: pointer;
|
||||||
accent-color: var(--color-accent);
|
accent-color: var(--color-accent);
|
||||||
border-radius: var(--radius-sm);
|
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 {
|
.list-header.selection-mode {
|
||||||
grid-template-columns: 36px 1fr;
|
grid-template-columns: 36px 1fr;
|
||||||
background-color: var(--color-multiselect-bg);
|
background-color: var(--color-multiselect-bg);
|
||||||
@@ -496,7 +516,26 @@
|
|||||||
|
|
||||||
.files-list-view .file-item .action-cell button:not(.btn-action):hover {
|
.files-list-view .file-item .action-cell button:not(.btn-action):hover {
|
||||||
background: var(--color-border-subtle);
|
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
|
/* Fav-star + shared-button share the same visibility rule: hidden on
|
||||||
@@ -668,8 +707,11 @@
|
|||||||
position: absolute;
|
position: absolute;
|
||||||
top: calc(var(--space-3) + 8px);
|
top: calc(var(--space-3) + 8px);
|
||||||
left: calc(var(--space-3) + 8px);
|
left: calc(var(--space-3) + 8px);
|
||||||
width: 26px;
|
/* 30x30 matches the action-cell chip pills (`.file-actions`, star,
|
||||||
height: 26px;
|
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);
|
border-radius: var(--radius-md);
|
||||||
background: var(--color-scrim-control);
|
background: var(--color-scrim-control);
|
||||||
backdrop-filter: blur(6px);
|
backdrop-filter: blur(6px);
|
||||||
@@ -699,8 +741,10 @@
|
|||||||
.files-grid-view .file-item .checkbox-cell input[type="checkbox"] {
|
.files-grid-view .file-item .checkbox-cell input[type="checkbox"] {
|
||||||
appearance: none;
|
appearance: none;
|
||||||
-webkit-appearance: none;
|
-webkit-appearance: none;
|
||||||
width: 18px;
|
/* Custom-drawn glyph sized proportionally to the 30x30 chip pill —
|
||||||
height: 18px;
|
bumped from 18x18 to match the list-view checkbox's 20x20. */
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
border: 2px solid var(--color-border-medium);
|
border: 2px solid var(--color-border-medium);
|
||||||
border-radius: var(--radius-sm);
|
border-radius: var(--radius-sm);
|
||||||
@@ -713,6 +757,17 @@
|
|||||||
border-color var(--motion-fast) var(--ease-standard);
|
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 {
|
.files-grid-view .file-item .checkbox-cell input[type="checkbox"]::after {
|
||||||
content: "";
|
content: "";
|
||||||
width: 5px;
|
width: 5px;
|
||||||
@@ -783,9 +838,11 @@
|
|||||||
markup still has shared, favorite, itemActions, kebab in that
|
markup still has shared, favorite, itemActions, kebab in that
|
||||||
sequence so list-view's inline right-aligned flow is unchanged. */
|
sequence so list-view's inline right-aligned flow is unchanged. */
|
||||||
.files-grid-view .file-item .action-cell:has(.shared-button, .favorite-star) {
|
.files-grid-view .file-item .action-cell:has(.shared-button, .favorite-star) {
|
||||||
/* Start right after the checkbox column (26px chip + inline gap)
|
/* Start right after the checkbox column (30px chip + inline gap)
|
||||||
so the left group aligns visually with the checkbox row. */
|
so the left group aligns visually with the checkbox row. Kept in
|
||||||
left: calc(var(--space-3) + 8px + 26px + var(--space-2));
|
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);
|
right: calc(var(--space-3) + 8px);
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -875,7 +932,23 @@
|
|||||||
opacity: 1;
|
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);
|
color: var(--color-accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -884,13 +957,20 @@
|
|||||||
border: 2px dashed var(--color-warning-border);
|
border: 2px dashed var(--color-warning-border);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Favorite star + shared button — visual overrides only. Position,
|
/* Favorite star + shared button — resting/active state colors only.
|
||||||
hover-reveal, chip geometry all come from the shared corner-cluster
|
HOVER color for both lives in the unified `.action-cell button:hover
|
||||||
rule on `.files-grid-view .file-item .action-cell`. What's left
|
→ --color-accent` rule above; the per-state palette here only fires
|
||||||
here is just the per-state colour: subtle at rest, saturated when
|
when the button is NOT hovered. Convention (Ed 2026-07-26):
|
||||||
the item's flag is set. `.active` on either button also bumps the
|
• hover → orange (accent) — every row action
|
||||||
parent cluster's opacity (via `:has()` above) so an unhovered card
|
• star.active (not hover) → gold
|
||||||
still shows its favorited/shared state. */
|
• 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.favorite-star,
|
||||||
.files-grid-view .file-item button.shared-button {
|
.files-grid-view .file-item button.shared-button {
|
||||||
color: var(--color-text-subtle);
|
color: var(--color-text-subtle);
|
||||||
@@ -898,19 +978,10 @@
|
|||||||
line-height: var(--leading-none);
|
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 {
|
.files-grid-view .file-item button.favorite-star.active {
|
||||||
color: var(--color-star-text-hover);
|
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 {
|
.files-grid-view .file-item button.shared-button.active {
|
||||||
color: var(--color-badge-blue-text);
|
color: var(--color-badge-blue-text);
|
||||||
}
|
}
|
||||||
@@ -1274,7 +1345,16 @@
|
|||||||
|
|
||||||
.btn-action:hover {
|
.btn-action:hover {
|
||||||
background: var(--color-border-subtle);
|
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.
|
/* Opt-in modifier: hide the button until the row is hovered / focused.
|
||||||
|
|||||||
@@ -24,7 +24,7 @@
|
|||||||
type Playlist,
|
type Playlist,
|
||||||
type PlaylistItem
|
type PlaylistItem
|
||||||
} from '$lib/api/endpoints/music';
|
} 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 type { FileItem } from '$lib/api/types';
|
||||||
import Icon from '$lib/icons/Icon.svelte';
|
import Icon from '$lib/icons/Icon.svelte';
|
||||||
import { confirmDialog, promptDialog } from '$lib/stores/dialogs.svelte';
|
import { confirmDialog, promptDialog } from '$lib/stores/dialogs.svelte';
|
||||||
@@ -450,17 +450,25 @@
|
|||||||
async function runAddSearch(query = '') {
|
async function runAddSearch(query = '') {
|
||||||
addSearching = true;
|
addSearching = true;
|
||||||
try {
|
try {
|
||||||
const res = await searchFiles(query.trim(), {
|
const res = await searchResources(query.trim(), {
|
||||||
recursive: true,
|
recursive: true,
|
||||||
fileTypes: AUDIO_TYPES,
|
fileTypes: AUDIO_TYPES,
|
||||||
|
resourceTypes: ['file'],
|
||||||
limit: 200
|
limit: 200
|
||||||
});
|
});
|
||||||
// Belt-and-braces: keep only audio mime types.
|
// Belt-and-braces: keep only audio mime types. The envelope
|
||||||
addResults = res.files.filter(
|
// items are `{resource_type, resource}` — resourceTypes:['file']
|
||||||
(f) =>
|
// already restricts to files, but re-narrow here so the
|
||||||
(f.mime_type ?? '').startsWith('audio/') ||
|
// downstream `FileItem[]` cast is honest even if the wire
|
||||||
AUDIO_TYPES.some((e) => f.name.toLowerCase().endsWith(`.${e}`))
|
// 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) {
|
} catch (e) {
|
||||||
errorToast(e);
|
errorToast(e);
|
||||||
addResults = [];
|
addResults = [];
|
||||||
|
|||||||
@@ -1,32 +1,110 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import EmptyState from '$lib/components/EmptyState.svelte';
|
import EmptyState from '$lib/components/EmptyState.svelte';
|
||||||
import VirtualList from '$lib/components/VirtualList.svelte';
|
import ResourceList, { isFile, type ContextAction } from '$lib/components/ResourceList.svelte';
|
||||||
import { errorMessage } from '$lib/utils/errors';
|
import { errorMessage, errorToast } from '$lib/utils/errors';
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import { searchFiles } from '$lib/api/endpoints/search';
|
import { searchResources } from '$lib/api/endpoints/search';
|
||||||
import { fileInlineUrl } from '$lib/api/endpoints/files';
|
import { fileDownloadUrl, renameFile, deleteFile } from '$lib/api/endpoints/files';
|
||||||
import type { FileItem, FolderItem, SearchResults, SortBy } from '$lib/api/types';
|
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 Icon from '$lib/icons/Icon.svelte';
|
||||||
import { t } from '$lib/i18n/index.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 { files as filesStore } from '$lib/stores/files.svelte';
|
||||||
import { ui } from '$lib/stores/ui.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') ?? '');
|
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 loading = $state(false);
|
||||||
let error = $state<string | null>(null);
|
let error = $state<string | null>(null);
|
||||||
let sortBy = $state<SortBy>('relevance');
|
let sortBy = $state<SortBy>('relevance');
|
||||||
// Scope: search everywhere, or within the folder last open in the files view.
|
// Derived from the URL — URL is the single source of truth so refresh,
|
||||||
// Default to the current folder when one is set (and we're not in the trash
|
// bookmarks and shared links all restore the same scope. Rules:
|
||||||
// section), mirroring the legacy searchView behaviour.
|
// `?scope=all` → 'all' (explicit "Everywhere" toggle;
|
||||||
let scope = $state<'all' | 'folder'>(
|
// `in=` may still be present as
|
||||||
filesStore.currentFolder && filesStore.section !== 'trash' ? 'folder' : 'all'
|
// 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
|
// Filters
|
||||||
type TypeKey = 'all' | 'image' | 'video' | 'document' | 'audio' | 'archive';
|
type TypeKey = 'all' | 'image' | 'video' | 'document' | 'audio' | 'archive';
|
||||||
@@ -129,17 +207,43 @@
|
|||||||
// full recursive backend search; without the token a SLOW earlier response
|
// full recursive backend search; without the token a SLOW earlier response
|
||||||
// could resolve after (and clobber) a newer one, and the superseded server
|
// 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
|
// 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 runSeq = 0;
|
||||||
let inflight: AbortController | null = null;
|
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) {
|
async function run(q: string) {
|
||||||
const seq = ++runSeq;
|
const seq = ++runSeq;
|
||||||
inflight?.abort();
|
inflight?.abort();
|
||||||
inflight = null;
|
inflight = null;
|
||||||
if (!q) {
|
if (!q) {
|
||||||
results = null;
|
raw = [];
|
||||||
|
cursor = undefined;
|
||||||
|
queryTimeMs = null;
|
||||||
|
total = undefined;
|
||||||
loading = false;
|
loading = false;
|
||||||
|
error = null;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const ctl = new AbortController();
|
const ctl = new AbortController();
|
||||||
@@ -147,22 +251,12 @@
|
|||||||
loading = true;
|
loading = true;
|
||||||
error = null;
|
error = null;
|
||||||
try {
|
try {
|
||||||
// Trash section searches are always global — there is no folder to scope to.
|
const fresh = await searchResources(q, { ...currentQueryParams(), signal: ctl.signal });
|
||||||
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
|
|
||||||
});
|
|
||||||
if (seq !== runSeq) return; // superseded while awaiting
|
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) {
|
} catch (e) {
|
||||||
// An aborted request is not an error — a newer run owns the UI.
|
// An aborted request is not an error — a newer run owns the UI.
|
||||||
if (seq !== runSeq || ctl.signal.aborted) return;
|
if (seq !== runSeq || ctl.signal.aborted) return;
|
||||||
@@ -172,27 +266,220 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function openFolder(folder: FolderItem) {
|
async function loadMore() {
|
||||||
goto(resolve(`/files/${folder.id}`));
|
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) {
|
// Feed ResourceList the raw resource objects — that's the shared
|
||||||
window.open(fileInlineUrl(file.id), '_blank', 'noopener');
|
// `{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
|
// Files carry `folder_id`, folders carry `parent_id`; both are nullable
|
||||||
// windowed list (only the visible rows hit the DOM, even for 100s of hits).
|
// at drive roots. Null → no meaningful parent to open. Mirrors the
|
||||||
type SearchEntry = { kind: 'folder'; folder: FolderItem } | { kind: 'file'; file: FileItem };
|
// same helper in /favorites and /recent.
|
||||||
const entries = $derived<SearchEntry[]>(
|
function parentFolderId(item: FileItem | FolderItem): string | null {
|
||||||
results
|
return isFile(item) ? item.folder_id : item.parent_id;
|
||||||
? [
|
}
|
||||||
...results.folders.map((folder) => ({ kind: 'folder' as const, folder })),
|
|
||||||
...results.files.map((file) => ({ kind: 'file' as const, file }))
|
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(() => {
|
$effect(() => {
|
||||||
// re-run when query, sort, scope, or any filter changes
|
// 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
|
* browser's default handler navigates to the dropped file — the tab
|
||||||
* REPLACES the app with the file itself, which is data-loss-esque
|
* REPLACES the app with the file itself, which is data-loss-esque
|
||||||
* (user loses their in-progress search + any unsaved UI state).
|
* (user loses their in-progress search + any unsaved UI state).
|
||||||
* The `ResourceList`-based views (`/photos`, `/shared`, `/trash`, …)
|
* ResourceList already fires a "wrong drop zone" toast via its
|
||||||
* already fire a "wrong drop zone" toast via their `.rl-root`
|
* `.rl-root` wrapper when `enableSystemDrop` is false, but that
|
||||||
* wrapper when `enableSystemDrop` is false — this handler brings
|
* covers only the list area — this handler covers the whole
|
||||||
* `/search` to the same contract, and covers the whole viewport
|
* viewport (sticky header, empty-state screen, gaps around the
|
||||||
* (not just a list surface) so drops on the sticky header /
|
* list). Same toast copy + "Go to Files" action as ResourceList
|
||||||
* result-card margins are caught too. Same toast copy + "Go to
|
* for a consistent recovery UX.
|
||||||
* Files" action as `ResourceList` for a consistent recovery UX.
|
|
||||||
*/
|
*/
|
||||||
function onWindowDragOver(e: DragEvent) {
|
function onWindowDragOver(e: DragEvent) {
|
||||||
if (!e.dataTransfer?.types?.includes('Files')) return;
|
if (!e.dataTransfer?.types?.includes('Files')) return;
|
||||||
@@ -258,38 +544,69 @@
|
|||||||
|
|
||||||
<svelte:window ondragover={onWindowDragOver} ondrop={onWindowDrop} />
|
<svelte:window ondragover={onWindowDragOver} ondrop={onWindowDrop} />
|
||||||
|
|
||||||
<div class="page-sticky-header search-head">
|
{#if !query}
|
||||||
<h1 class="page-title">
|
<EmptyState title={t('search.prompt', 'Type a query in the search bar above.')} />
|
||||||
{#if query}{t('search.results_for', { q: query }, 'Results for “{{q}}”')}{:else}{t(
|
{:else}
|
||||||
'search.title',
|
<ResourceList
|
||||||
'Search'
|
title={resultsTitle}
|
||||||
)}{/if}
|
{items}
|
||||||
{#if results?.query_time_ms != null}
|
{loading}
|
||||||
<span class="search-time">({results.query_time_ms} ms)</span>
|
{error}
|
||||||
{/if}
|
emptyIcon="search"
|
||||||
</h1>
|
emptyText={t('search.no_results', 'No results found for this search')}
|
||||||
{#if query}
|
hasMore={!!cursor}
|
||||||
<div class="search-controls">
|
onloadmore={loadMore}
|
||||||
{#if filesStore.currentFolder}
|
showPath
|
||||||
<div class="seg" role="group" aria-label={t('search.scope', 'Scope')}>
|
showViewToggle
|
||||||
<button
|
onopen={open}
|
||||||
class="seg__btn"
|
onfavorite={toggleFavorite}
|
||||||
class:active={scope === 'all'}
|
onshared={openShareDialog}
|
||||||
data-testid="search-scope-all-btn"
|
{contextActions}
|
||||||
onclick={() => (scope = 'all')}
|
menuPrepare={async (item) => {
|
||||||
>
|
// Lazy folder-access probe — fires only when the user opens
|
||||||
{t('search.everywhere', 'Everywhere')}
|
// the context menu on a row, not proactively for every row on
|
||||||
</button>
|
// load. Cached in the LRU (see `folderAccess.ts`) so
|
||||||
<button
|
// subsequent right-clicks on the same folder are instant.
|
||||||
class="seg__btn"
|
// Mirrors /favorites + /recent so the "Open parent folder"
|
||||||
class:active={scope === 'folder'}
|
// entry lands enabled/disabled without a "flash of enabled"
|
||||||
data-testid="search-scope-folder-btn"
|
// on first right-click.
|
||||||
onclick={() => (scope = 'folder')}
|
const pid = parentFolderId(item);
|
||||||
>
|
if (pid) await probeFolderAccess(pid);
|
||||||
{t('search.this_folder', 'This folder')}
|
}}
|
||||||
</button>
|
>
|
||||||
</div>
|
{#snippet actions()}
|
||||||
{/if}
|
<!--
|
||||||
|
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
|
<select
|
||||||
class="sort-select"
|
class="sort-select"
|
||||||
bind:value={typeFilter}
|
bind:value={typeFilter}
|
||||||
@@ -332,99 +649,68 @@
|
|||||||
{t('search.clear_filters', 'Clear filters')}
|
{t('search.clear_filters', 'Clear filters')}
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
{/snippet}
|
||||||
{/if}
|
{#snippet itemActions(item)}
|
||||||
</div>
|
<!--
|
||||||
|
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}
|
{#if fileViewer.component}
|
||||||
<div class="search-loading">
|
{@const FileViewer = fileViewer.component}
|
||||||
<Icon name="spinner" class="search-loading__spinner" />
|
<FileViewer bind:open={viewerOpen} file={viewerFile} />
|
||||||
<h2 class="search-loading__text">
|
{/if}
|
||||||
{t('search.searching_for', { q: query }, 'Searching for “{{q}}”…')}
|
{#if moveDialog.component}
|
||||||
</h2>
|
{@const MoveDialog = moveDialog.component}
|
||||||
</div>
|
<MoveDialog
|
||||||
{:else if error}
|
bind:open={moveOpen}
|
||||||
<EmptyState title={error} error />
|
item={moveTarget}
|
||||||
{:else if !query}
|
onmoved={() => {
|
||||||
<EmptyState title={t('search.prompt', 'Type a query in the search bar above.')} />
|
// A move can shift the row out of the current scope (`?in=<uuid>`)
|
||||||
{:else if isEmpty}
|
// or into it, and the SQL name-match count may change. Reload
|
||||||
<EmptyState icon="search" title={t('search.no_results', 'No results found for this search')} />
|
// page 1 rather than trying to patch state in place — search
|
||||||
{:else if results}
|
// state is already reactive on query/scope so a fresh `run()`
|
||||||
<div class="files-container">
|
// is cheap and correct.
|
||||||
<div class="files-list-view" style="--files-list-columns: minmax(200px, 2fr) 1fr 110px 140px">
|
void run(query);
|
||||||
<div class="list-header">
|
}}
|
||||||
<div>{t('files.col_name', 'Name')}</div>
|
/>
|
||||||
<div>{t('files.col_path', 'Path')}</div>
|
{/if}
|
||||||
<div>{t('files.col_size', 'Size')}</div>
|
{#if shareDialog.component}
|
||||||
<div>{t('files.col_modified', 'Modified')}</div>
|
{@const ShareDialog = shareDialog.component}
|
||||||
</div>
|
<ShareDialog bind:open={shareOpen} item={shareTarget} />
|
||||||
|
|
||||||
<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}
|
{/if}
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.search-head {
|
/* Filter cluster lives inside ResourceList's action-bar snippet now,
|
||||||
display: flex;
|
but the actual DOM is scoped to THIS component's <style> block —
|
||||||
align-items: center;
|
Svelte's scoped selectors still apply because these are declared
|
||||||
justify-content: space-between;
|
with the elements they style below.
|
||||||
gap: var(--space-3);
|
|
||||||
flex-wrap: wrap;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-controls {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--space-2);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
Every color/border here uses tokens; no raw values (Stylelint gate). */
|
||||||
.sort-select {
|
.sort-select {
|
||||||
padding: var(--space-2) var(--space-2-5);
|
padding: var(--space-2) var(--space-2-5);
|
||||||
border: 1px solid var(--color-border);
|
border: 1px solid var(--color-border);
|
||||||
@@ -453,10 +739,9 @@
|
|||||||
color: var(--color-on-accent);
|
color: var(--color-on-accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.search-time {
|
.seg__btn:disabled {
|
||||||
font-size: var(--text-sm);
|
opacity: 0.5;
|
||||||
font-weight: var(--weight-normal);
|
cursor: not-allowed;
|
||||||
color: var(--color-text-muted);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.clear-filters {
|
.clear-filters {
|
||||||
@@ -474,25 +759,4 @@
|
|||||||
.clear-filters:hover {
|
.clear-filters:hover {
|
||||||
background: var(--color-bg-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>
|
</style>
|
||||||
|
|||||||
@@ -7,10 +7,10 @@ const { goto, pageState } = vi.hoisted(() => ({
|
|||||||
}));
|
}));
|
||||||
vi.mock('$app/navigation', () => ({ goto }));
|
vi.mock('$app/navigation', () => ({ goto }));
|
||||||
vi.mock('$app/state', () => ({ page: pageState }));
|
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' }));
|
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';
|
import SearchPage from './+page.svelte';
|
||||||
|
|
||||||
const m = (fn: unknown) => fn as ReturnType<typeof vi.fn>;
|
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(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
pageState.url = new URL('http://localhost/search?q=report');
|
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 () => {
|
it('runs a search from the q query parameter on mount', async () => {
|
||||||
render(SearchPage);
|
render(SearchPage);
|
||||||
await waitFor(() => expect(searchFiles).toHaveBeenCalled());
|
await waitFor(() => expect(searchResources).toHaveBeenCalled());
|
||||||
expect(m(searchFiles).mock.calls[0][0]).toBe('report');
|
expect(m(searchResources).mock.calls[0][0]).toBe('report');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('does not search when there is no query', async () => {
|
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);
|
render(SearchPage);
|
||||||
// Give the reactive effect a tick to (not) fire.
|
// Give the reactive effect a tick to (not) fire.
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
expect(searchFiles).not.toHaveBeenCalled();
|
expect(searchResources).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('surfaces a search error', async () => {
|
it('surfaces a search error', async () => {
|
||||||
m(searchFiles).mockRejectedValue(new Error('search boom'));
|
m(searchResources).mockRejectedValue(new Error('search boom'));
|
||||||
render(SearchPage);
|
render(SearchPage);
|
||||||
await waitFor(() => expect(searchFiles).toHaveBeenCalled());
|
await waitFor(() => expect(searchResources).toHaveBeenCalled());
|
||||||
await waitFor(() => expect(screen.getByText('search boom')).toBeTruthy());
|
await waitFor(() => expect(screen.getByText('search boom')).toBeTruthy());
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user