refactor(search): adapt UI to use ResourceList
This commit is contained in:
@@ -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 = [];
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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());
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user