Files
Kaname/src/app/(app)/library-view.tsx
T
Claude 7239ba2692 Library: load import folder files on demand, memoize search
The library page passed every importable folder's full file list (up to 5,000
entries each, from the worker's scan) into a client component, though it is
only used after clicking Import. With three such folders that was 84% of a
1.3 MB page, re-sent on every refresh after a job finished.

- listLocalFolders() returns path, commit and counts only; the Import button
  fetches one folder's files from GET /api/local-folders?path=…
- addModel() checks that an import folder exists without loading its files.
- LibraryView builds each model's search text once and memoizes the visible
  rows and facet counts; the facet sort uses one Intl.Collator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
2026-11-01 20:49:18 +00:00

316 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon, SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useMemo, useState } from "react";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { LocalTime } from "@/components/local-time";
import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { NativeSelect } from "@/components/ui/native-select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useLive } from "@/hooks/use-live";
import type { ModelStatus } from "@/lib/db/schema";
import { formatBytes, shortSha } from "@/lib/format";
import type { JobSnapshot } from "@/lib/jobs";
import type { LibraryRow } from "@/lib/library";
import {
EMPTY_FILTERS,
type Facet,
FACETS,
facetCounts,
type Filters,
matchesFilters,
matchesQuery,
queryTerms,
type SearchableModel,
searchText,
} from "@/lib/search";
import { FacetFilter } from "./facet-filter";
const OPEN = ["queued", "downloading", "verifying"];
const PAGE_SIZES = [10, 25, 50, 100];
const FACET_LABEL: Record<Facet, string> = {
author: "Author",
family: "Family",
quant: "Quant",
tag: "Tag",
status: "Status",
};
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
function toSearchable(r: LibraryRow): SearchableModel {
const m: SearchableModel = {
repoId: r.repoId,
author: r.author,
families: r.families,
baseModels: r.baseModels,
architecture: r.architecture,
quants: r.quants,
tags: r.tags.map((t) => t.name),
hubTags: r.hubTags,
pipelineTag: r.pipelineTag,
license: r.license,
status: r.status,
hubStatus:
r.hubState && r.hubState !== "available"
? HUB_STATE_LABEL[r.hubState].label
: r.updateAvailable
? "update available"
: null,
};
return { ...m, text: searchText(m) };
}
/** Search + facet filters (kept in the URL) over the library table. */
export function LibraryView({ rows }: { rows: LibraryRow[] }) {
const router = useRouter();
const pathname = usePathname();
const params = useSearchParams();
const [query, setQuery] = useState(() => params.get("q") ?? "");
const [page, setPage] = useState(0);
const [pageSize, setPageSize] = useState(25);
const [filters, setFilters] = useState<Filters>(() => {
const f = { ...EMPTY_FILTERS };
for (const facet of FACETS) f[facet] = params.getAll(facet);
return f;
});
function sync(nextQuery: string, nextFilters: Filters) {
const p = new URLSearchParams();
if (nextQuery) p.set("q", nextQuery);
for (const facet of FACETS) for (const v of nextFilters[facet]) p.append(facet, v);
const qs = p.toString();
router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
}
// A new search or filter starts on the first page.
const updateQuery = (q: string) => {
setQuery(q);
setPage(0);
sync(q, filters);
};
const updateFilter = (facet: Facet, values: string[]) => {
const next = { ...filters, [facet]: values };
setFilters(next);
setPage(0);
sync(query, next);
};
const clearAll = () => {
setQuery("");
setFilters(EMPTY_FILTERS);
setPage(0);
sync("", EMPTY_FILTERS);
};
// Search text and counts are computed once per change of rows, query or filters, not on every
// render (live job progress re-renders this table while downloads run).
const searchable = useMemo(() => rows.map(toSearchable), [rows]);
const tagColors = useMemo(() => new Map(rows.flatMap((r) => r.tags.map((t) => [t.name, t.color] as const))), [rows]);
const terms = useMemo(() => queryTerms(query), [query]);
const visible = useMemo(
() => rows.filter((_, i) => matchesQuery(searchable[i], terms) && matchesFilters(searchable[i], filters)),
[rows, searchable, terms, filters],
);
const facetOptions = useMemo(
() => Object.fromEntries(FACETS.map((facet) => [facet, facetCounts(searchable, facet, terms, filters)])) as Record<Facet, [string, number][]>,
[searchable, terms, filters],
);
const anyActive = query.trim() !== "" || FACETS.some((f) => filters[f].length > 0);
const pages = Math.max(1, Math.ceil(visible.length / pageSize));
const current = Math.min(page, pages - 1);
const shown = visible.slice(current * pageSize, (current + 1) * pageSize);
const { snapshot } = useLive();
const openJobs = new Map<string, JobSnapshot>();
for (const j of snapshot?.jobs ?? []) {
if (OPEN.includes(j.state) && !openJobs.has(j.modelId)) openJobs.set(j.modelId, j);
}
return (
// Glass: the painting from the hero shows through, blurred.
<Card className="relative z-10 gap-0 overflow-hidden bg-card/55 py-0 backdrop-blur-md">
{/* Toolbar: title, search and filters, part of the table. */}
<div className="flex flex-col gap-3 border-b px-4 py-3">
<div className="flex flex-wrap items-center gap-2">
<h2 className="mr-1 text-base font-semibold">Models</h2>
<span className="rounded-md bg-muted px-1.5 text-xs text-muted-foreground tabular-nums">
{anyActive ? `${visible.length} of ${rows.length}` : rows.length}
</span>
</div>
<div className="flex flex-wrap items-center gap-2">
{/* Same height and border as the filter pills. */}
<div className="relative w-full sm:w-64">
<SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
value={query}
onChange={(e) => updateQuery(e.target.value)}
placeholder="Search models…"
className="h-8 bg-transparent pl-8 text-sm"
aria-label="Search models"
/>
</div>
{FACETS.map((facet) => (
<FacetFilter
key={facet}
label={FACET_LABEL[facet]}
values={facetOptions[facet]}
selected={filters[facet]}
onChange={(v) => updateFilter(facet, v)}
format={facet === "status" ? statusLabel : undefined}
marker={facet === "tag" ? (v) => <TagDot name={v} color={tagColors.get(v)} /> : undefined}
/>
))}
{anyActive && (
<Button variant="ghost" size="sm" className="h-8" onClick={clearAll}>
Reset
<XIcon />
</Button>
)}
</div>
</div>
{visible.length === 0 ? (
<div className="flex flex-col items-center gap-1 px-4 py-12 text-center">
<p className="text-sm font-medium">No matching models</p>
<p className="text-sm text-muted-foreground">Try a different search or remove a filter.</p>
</div>
) : (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead className="pl-4">Model</TableHead>
<TableHead>Selection</TableHead>
<TableHead className="text-right">Size</TableHead>
<TableHead className="hidden lg:table-cell">Pinned</TableHead>
<TableHead className="hidden md:table-cell">Downloaded</TableHead>
<TableHead className="w-56 pr-4">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{shown.map((r) => {
const job = openJobs.get(r.id);
const base = r.baseModels[0];
return (
<TableRow key={r.id}>
<TableCell className="pl-4 whitespace-normal">
<Link href={`/${r.repoId}`} className="hover:underline">
<span className="text-muted-foreground">{r.author}/</span>
<span className="font-medium">{r.repoId.slice(r.author.length + 1)}</span>
</Link>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.tags.map((t) => (
<button
key={t.id}
type="button"
onClick={() => !filters.tag.includes(t.name) && updateFilter("tag", [...filters.tag, t.name])}
>
<TagBadge name={t.name} color={t.color} />
</button>
))}
</div>
</TableCell>
<TableCell>
{r.quants.length > 0 ? (
<span className="flex flex-wrap gap-1">
{r.quants.map((q) => (
<span key={q} className="rounded-md border px-1.5 font-mono text-[11px] leading-5">
{q}
</span>
))}
</span>
) : (
<span className="text-sm text-muted-foreground">
{r.fileCount} file{r.fileCount === 1 ? "" : "s"}
</span>
)}
</TableCell>
<TableCell className="text-right tabular-nums">{formatBytes(r.totalBytes)}</TableCell>
<TableCell className="hidden lg:table-cell">
<code className="font-mono text-xs text-muted-foreground" title={r.pinnedSha}>
{r.trackedRevision}@{shortSha(r.pinnedSha)}
</code>
</TableCell>
<TableCell className="hidden text-sm text-muted-foreground md:table-cell">
<LocalTime value={r.downloadedAt} />
</TableCell>
<TableCell className="pr-4">
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
</Link>
) : (
<span className="flex flex-wrap gap-1">
<ModelStatusBadge status={r.status} />
<HubStateBadge state={r.hubState} />
{r.updateAvailable && (r.hubState === "available" || !r.hubState) && (
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium whitespace-nowrap text-sky-700 dark:text-sky-300">
update available
</span>
)}
</span>
)}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
<div className="flex flex-wrap items-center justify-between gap-3 border-t px-4 py-2.5 text-sm">
<span className="text-muted-foreground tabular-nums">
{current * pageSize + 1}–{Math.min(visible.length, (current + 1) * pageSize)} of {visible.length}
</span>
<div className="flex items-center gap-3">
<label className="flex items-center gap-2 text-muted-foreground">
<span className="hidden sm:inline">Rows per page</span>
<NativeSelect
value={pageSize}
onChange={(e) => {
setPageSize(Number(e.target.value));
setPage(0);
}}
className="h-8 w-20"
aria-label="Rows per page"
>
{PAGE_SIZES.map((n) => (
<option key={n} value={n}>
{n}
</option>
))}
</NativeSelect>
</label>
<span className="text-muted-foreground tabular-nums">
Page {current + 1} of {pages}
</span>
<div className="flex items-center gap-1">
<Button variant="outline" size="icon-sm" onClick={() => setPage(0)} disabled={current === 0} aria-label="First page">
<ChevronsLeftIcon />
</Button>
<Button variant="outline" size="icon-sm" onClick={() => setPage(current - 1)} disabled={current === 0} aria-label="Previous page">
<ChevronLeftIcon />
</Button>
<Button variant="outline" size="icon-sm" onClick={() => setPage(current + 1)} disabled={current >= pages - 1} aria-label="Next page">
<ChevronRightIcon />
</Button>
<Button variant="outline" size="icon-sm" onClick={() => setPage(pages - 1)} disabled={current >= pages - 1} aria-label="Last page">
<ChevronsRightIcon />
</Button>
</div>
</div>
</div>
</>
)}
</Card>
);
}