diff --git a/CHANGELOG.md b/CHANGELOG.md index e943926..4115d00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ step 1 (Hugging Face downloader) is released as a minor version. - **Lighter benchmark lists**: the Benchmarks and Endpoints pages, a model's sidebar and the ⌘K search load only what they show (headline numbers, the quality score), not every run's full results; the list refreshed every 3 s during a run now sends a fraction of the data. +- **Less JavaScript per page** (10–29 KB gzipped less on every page): the dot painting's data is + loaded once and cached instead of being part of each page, the ⌘K search loads when you first + reach for it, and the endpoint pages no longer include database code. The painting is drawn once + per page view instead of twice, and at most once per frame while the window is resized. ## [0.16.0] - 2026-10-30 diff --git a/eslint.config.mjs b/eslint.config.mjs index 912c67d..89c3129 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -15,6 +15,27 @@ const eslintConfig = defineConfig([ // Bundled worker output "dist/**", ]), + // A value import from the schema in a client component puts drizzle-orm and every table + // definition into the browser bundle. Enums are in @/lib/db/enums; types are fine. Pages, layouts + // and route handlers run on the server only. + { + files: ["src/components/**/*.{ts,tsx}", "src/hooks/**/*.{ts,tsx}", "src/app/**/*.{ts,tsx}"], + ignores: ["src/app/**/page.tsx", "src/app/**/layout.tsx", "src/app/**/route.ts"], + rules: { + "@typescript-eslint/no-restricted-imports": [ + "error", + { + paths: [ + { + name: "@/lib/db/schema", + allowTypeImports: true, + message: "In client code this bundles drizzle-orm and every table. Import enums from @/lib/db/enums.", + }, + ], + }, + ], + }, + }, ]); export default eslintConfig; diff --git a/src/app/(app)/endpoints/[id]/benchmark-start.tsx b/src/app/(app)/endpoints/[id]/benchmark-start.tsx index 80f950e..32db811 100644 --- a/src/app/(app)/endpoints/[id]/benchmark-start.tsx +++ b/src/app/(app)/endpoints/[id]/benchmark-start.tsx @@ -9,7 +9,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { NativeSelect } from "@/components/ui/native-select"; -import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/schema"; +import { type BenchmarkPhase, QUALITY_SECTIONS, type QualitySection } from "@/lib/db/enums"; import { SECTION_HINT, SECTION_LABEL } from "@/lib/quality-view"; import { cn } from "@/lib/utils"; diff --git a/src/app/(app)/endpoints/endpoint-form.tsx b/src/app/(app)/endpoints/endpoint-form.tsx index d2e83bc..e56819a 100644 --- a/src/app/(app)/endpoints/endpoint-form.tsx +++ b/src/app/(app)/endpoints/endpoint-form.tsx @@ -10,7 +10,8 @@ import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { NativeSelect } from "@/components/ui/native-select"; import { ENGINE_LABEL } from "@/lib/benchmark-meta"; -import { ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe } from "@/lib/db/schema"; +import { ENDPOINT_ENGINES } from "@/lib/db/enums"; +import type { EndpointHardware, EndpointProbe } from "@/lib/db/schema"; import type { EndpointView } from "@/lib/endpoints"; type Field = { key: keyof EndpointHardware; label: string; placeholder?: string; kind?: "number" | "int"; hint?: string }; diff --git a/src/components/command-palette-dialog.tsx b/src/components/command-palette-dialog.tsx new file mode 100644 index 0000000..0240699 --- /dev/null +++ b/src/components/command-palette-dialog.tsx @@ -0,0 +1,227 @@ +"use client"; + +import { Dialog } from "@base-ui/react/dialog"; +import { + BoxIcon, + CornerDownLeftIcon, + DownloadIcon, + GaugeIcon, + LibraryIcon, + MonitorIcon, + MoonIcon, + PlusIcon, + ScanSearchIcon, + SearchIcon, + ServerIcon, + SunIcon, + TagIcon, + TagsIcon, +} from "lucide-react"; +import { useRouter } from "next/navigation"; +import { useTheme } from "next-themes"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { cn } from "@/lib/utils"; + +type Index = { + models: { id: string; repoId: string; quants: string[]; status: string; tags: string[] }[]; + endpoints: { id: string; name: string; model: string | null; engine: string | null }[]; + benchmarks: { id: string; label: string | null; kind: string; state: string; target: string; model: string; createdAt: number }[]; + tags: string[]; +}; + +type Item = { + id: string; + group: string; + title: string; + hint?: string; + icon: React.ComponentType<{ className?: string }>; + /** Extra words that match (not shown). */ + keywords?: string; + run: () => void; +}; + +const KIND_LABEL: Record = { run: "speed run", ab: "A/B", eval: "quality eval" }; + +/** Every whitespace-separated term must appear (case-insensitive); earlier and title matches rank higher. */ +function score(item: Item, terms: string[]): number { + if (terms.length === 0) return 1; + const title = item.title.toLowerCase(); + const all = `${title} ${item.hint ?? ""} ${item.keywords ?? ""} ${item.group}`.toLowerCase(); + let s = 0; + for (const t of terms) { + const i = all.indexOf(t); + if (i < 0) return 0; + s += title.startsWith(t) ? 4 : title.includes(t) ? 2 : 1; + } + return s; +} + +/** The palette itself: loaded on first use (see command-palette.tsx), then kept mounted. */ +export function CommandPaletteDialog({ open, setOpen }: { open: boolean; setOpen: (open: boolean) => void }) { + const router = useRouter(); + const { setTheme } = useTheme(); + const [query, setQuery] = useState(""); + const [index, setIndex] = useState(null); + const [active, setActive] = useState(0); + const list = useRef(null); + + // Fresh data every time it opens (the library changes while you use it). + useEffect(() => { + if (!open) return; + let stop = false; + void fetch("/api/search-index", { cache: "no-store" }) + .then((r) => (r.ok ? r.json() : null)) + .then((d: Index | null) => !stop && d && setIndex(d)); + return () => { + stop = true; + }; + }, [open]); + + const go = (href: string) => () => { + setOpen(false); + router.push(href); + }; + + const items = useMemo(() => { + const out: Item[] = [ + { id: "p:library", group: "Pages", title: "Library", icon: LibraryIcon, keywords: "models home", run: go("/") }, + { id: "p:endpoints", group: "Pages", title: "Endpoints", icon: ServerIcon, keywords: "servers", run: go("/endpoints") }, + { id: "p:benchmarks", group: "Pages", title: "Benchmarks", icon: GaugeIcon, keywords: "runs compare", run: go("/benchmarks") }, + { id: "a:add-model", group: "Actions", title: "Add model", icon: PlusIcon, keywords: "download new hugging face repo", run: go("/?add=1") }, + { id: "a:new-endpoint", group: "Actions", title: "Add endpoint", icon: PlusIcon, keywords: "new server", run: go("/endpoints/new") }, + { id: "a:scan", group: "Actions", title: "Scan the models folder", icon: ScanSearchIcon, keywords: "rescan import", run: go("/settings/downloads#scan") }, + { id: "a:theme-light", group: "Actions", title: "Light theme", icon: SunIcon, keywords: "appearance", run: () => (setTheme("light"), setOpen(false)) }, + { id: "a:theme-dark", group: "Actions", title: "Dark theme", icon: MoonIcon, keywords: "appearance", run: () => (setTheme("dark"), setOpen(false)) }, + { id: "a:theme-system", group: "Actions", title: "System theme", icon: MonitorIcon, keywords: "appearance", run: () => (setTheme("system"), setOpen(false)) }, + { id: "s:labels", group: "Settings", title: "File labels", icon: TagIcon, keywords: "colors roles", run: go("/settings/labels") }, + { id: "s:tags", group: "Settings", title: "Tags", icon: TagsIcon, keywords: "rename colors", run: go("/settings/tags") }, + { id: "s:speed", group: "Settings", title: "Download speed limit", icon: DownloadIcon, hint: "Downloads", keywords: "bandwidth mb/s", run: go("/settings/downloads") }, + { id: "s:recommended", group: "Settings", title: "Recommended files", icon: DownloadIcon, hint: "Downloads", keywords: "mmproj mtp template quant", run: go("/settings/downloads") }, + { id: "s:scan", group: "Settings", title: "Models folder scan schedule", icon: ScanSearchIcon, hint: "Downloads", keywords: "daily weekly monthly nas", run: go("/settings/downloads#scan") }, + ]; + for (const m of index?.models ?? []) { + out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) }); + } + for (const e of index?.endpoints ?? []) { + out.push({ id: `e:${e.id}`, group: "Endpoints", title: e.name, hint: [e.engine, e.model].filter(Boolean).join(" · "), icon: ServerIcon, run: go(`/endpoints/${e.id}`) }); + } + for (const b of index?.benchmarks ?? []) { + out.push({ + id: `b:${b.id}`, + group: "Benchmarks", + title: b.label ?? `${b.target} · ${b.model}`, + hint: `${KIND_LABEL[b.kind] ?? b.kind} · ${b.state} · ${new Date(b.createdAt).toLocaleDateString()}`, + icon: GaugeIcon, + keywords: `${b.target} ${b.model}`, + run: go(`/benchmarks/${b.id}`), + }); + } + for (const t of index?.tags ?? []) { + out.push({ id: `t:${t}`, group: "Tags", title: t, hint: "models with this tag", icon: TagIcon, run: go(`/?tag=${encodeURIComponent(t)}`) }); + } + return out; + // `go` only closes over router and setOpen (the shell's state setter), which are stable. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [index, setTheme]); + + const terms = query.toLowerCase().split(/\s+/).filter(Boolean); + const groups = useMemo(() => { + const scored = items.map((it) => ({ it, s: score(it, terms) })).filter((x) => x.s > 0); + const order = ["Pages", "Actions", "Models", "Endpoints", "Benchmarks", "Settings", "Tags"]; + // Without a query: pages, actions and settings, plus the newest few of the rest. + const per = terms.length ? 8 : 4; + return order + .map((g) => ({ g, rows: scored.filter((x) => x.it.group === g).sort((a, b) => b.s - a.s).slice(0, per).map((x) => x.it) })) + .filter((x) => x.rows.length && (terms.length || ["Pages", "Actions", "Models", "Benchmarks"].includes(x.g))); + // terms is derived from query + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [items, query]); + const flat = groups.flatMap((g) => g.rows); + const current = Math.min(active, Math.max(0, flat.length - 1)); + + useEffect(() => { + list.current?.querySelector(`[data-index="${current}"]`)?.scrollIntoView({ block: "nearest" }); + }, [current]); + + function onKeyDown(e: React.KeyboardEvent) { + if (e.key === "ArrowDown") { + e.preventDefault(); + setActive((current + 1) % Math.max(1, flat.length)); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + setActive((current - 1 + flat.length) % Math.max(1, flat.length)); + } else if (e.key === "Enter") { + e.preventDefault(); + flat[current]?.run(); + } + } + + let n = -1; + return ( + { + setOpen(o); + if (!o) { + setQuery(""); + setActive(0); + } + }} + > + + + + Search +
+ + { + setQuery(e.target.value); + setActive(0); + }} + onKeyDown={onKeyDown} + placeholder="Search models, endpoints, benchmarks, settings…" + className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" + aria-label="Search" + /> + Esc +
+
+ {flat.length === 0 ? ( +

{index ? `Nothing matches "${query}".` : "Loading…"}

+ ) : ( + groups.map(({ g, rows }) => ( +
+
{g}
+ {rows.map((it) => { + n++; + const i = n; + return ( + + ); + })} +
+ )) + )} +
+
+
+
+ ); +} diff --git a/src/components/command-palette.tsx b/src/components/command-palette.tsx index 57616be..b112d60 100644 --- a/src/components/command-palette.tsx +++ b/src/components/command-palette.tsx @@ -1,258 +1,61 @@ "use client"; -import { Dialog } from "@base-ui/react/dialog"; -import { - BoxIcon, - CornerDownLeftIcon, - DownloadIcon, - GaugeIcon, - LibraryIcon, - MonitorIcon, - MoonIcon, - PlusIcon, - ScanSearchIcon, - SearchIcon, - ServerIcon, - SunIcon, - TagIcon, - TagsIcon, -} from "lucide-react"; -import { useRouter } from "next/navigation"; -import { useTheme } from "next-themes"; -import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; +import { SearchIcon } from "lucide-react"; +import dynamic from "next/dynamic"; +import { useEffect, useState, useSyncExternalStore } from "react"; import { cn } from "@/lib/utils"; -type Index = { - models: { id: string; repoId: string; quants: string[]; status: string; tags: string[] }[]; - endpoints: { id: string; name: string; model: string | null; engine: string | null }[]; - benchmarks: { id: string; label: string | null; kind: string; state: string; target: string; model: string; createdAt: number }[]; - tags: string[]; -}; +// The dialog (base-ui Dialog, all items and icons) is its own chunk, kept out of every page's first +// load: most page views never open it. It starts loading when you reach for it (hovering or focusing +// the Search button, pressing ⌘ or Ctrl) and renders on the first open. +const loadDialog = () => import("./command-palette-dialog"); +const CommandPaletteDialog = dynamic(() => loadDialog().then((m) => m.CommandPaletteDialog), { ssr: false }); +const preload = () => void loadDialog(); -type Item = { - id: string; - group: string; - title: string; - hint?: string; - icon: React.ComponentType<{ className?: string }>; - /** Extra words that match (not shown). */ - keywords?: string; - run: () => void; -}; +const OPEN_EVENT = "kaname:command-palette"; -const KIND_LABEL: Record = { run: "speed run", ab: "A/B", eval: "quality eval" }; +/** ⌘K / Ctrl+K: jump to any model, endpoint, benchmark run, settings page or action. */ +export function CommandPalette() { + const [open, setOpen] = useState(false); + // Mounted from the first open on, so it keeps its state like before. + const [used, setUsed] = useState(false); -/** Every whitespace-separated term must appear (case-insensitive); earlier and title matches rank higher. */ -function score(item: Item, terms: string[]): number { - if (terms.length === 0) return 1; - const title = item.title.toLowerCase(); - const all = `${title} ${item.hint ?? ""} ${item.keywords ?? ""} ${item.group}`.toLowerCase(); - let s = 0; - for (const t of terms) { - const i = all.indexOf(t); - if (i < 0) return 0; - s += title.startsWith(t) ? 4 : title.includes(t) ? 2 : 1; - } - return s; + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Meta" || e.key === "Control") preload(); + if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { + e.preventDefault(); + setUsed(true); + setOpen((o) => !o); + } + }; + const onOpen = () => { + setUsed(true); + setOpen(true); + }; + window.addEventListener("keydown", onKey); + window.addEventListener(OPEN_EVENT, onOpen); + return () => { + window.removeEventListener("keydown", onKey); + window.removeEventListener(OPEN_EVENT, onOpen); + }; + }, []); + + return used ? : null; } const isMac = () => /mac|iphone|ipad/i.test(navigator.platform || navigator.userAgent); const noSubscribe = () => () => {}; -/** ⌘K / Ctrl+K: jump to any model, endpoint, benchmark run, settings page or action. */ -export function CommandPalette() { - const router = useRouter(); - const { setTheme } = useTheme(); - const [open, setOpen] = useState(false); - const [query, setQuery] = useState(""); - const [index, setIndex] = useState(null); - const [active, setActive] = useState(0); - const list = useRef(null); - - useEffect(() => { - const onKey = (e: KeyboardEvent) => { - if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { - e.preventDefault(); - setOpen((o) => !o); - } - }; - const onOpen = () => setOpen(true); - window.addEventListener("keydown", onKey); - window.addEventListener("kaname:command-palette", onOpen); - return () => { - window.removeEventListener("keydown", onKey); - window.removeEventListener("kaname:command-palette", onOpen); - }; - }, []); - - // Fresh data every time it opens (the library changes while you use it). - useEffect(() => { - if (!open) return; - let stop = false; - void fetch("/api/search-index", { cache: "no-store" }) - .then((r) => (r.ok ? r.json() : null)) - .then((d: Index | null) => !stop && d && setIndex(d)); - return () => { - stop = true; - }; - }, [open]); - - const go = (href: string) => () => { - setOpen(false); - router.push(href); - }; - - const items = useMemo(() => { - const out: Item[] = [ - { id: "p:library", group: "Pages", title: "Library", icon: LibraryIcon, keywords: "models home", run: go("/") }, - { id: "p:endpoints", group: "Pages", title: "Endpoints", icon: ServerIcon, keywords: "servers", run: go("/endpoints") }, - { id: "p:benchmarks", group: "Pages", title: "Benchmarks", icon: GaugeIcon, keywords: "runs compare", run: go("/benchmarks") }, - { id: "a:add-model", group: "Actions", title: "Add model", icon: PlusIcon, keywords: "download new hugging face repo", run: go("/?add=1") }, - { id: "a:new-endpoint", group: "Actions", title: "Add endpoint", icon: PlusIcon, keywords: "new server", run: go("/endpoints/new") }, - { id: "a:scan", group: "Actions", title: "Scan the models folder", icon: ScanSearchIcon, keywords: "rescan import", run: go("/settings/downloads#scan") }, - { id: "a:theme-light", group: "Actions", title: "Light theme", icon: SunIcon, keywords: "appearance", run: () => (setTheme("light"), setOpen(false)) }, - { id: "a:theme-dark", group: "Actions", title: "Dark theme", icon: MoonIcon, keywords: "appearance", run: () => (setTheme("dark"), setOpen(false)) }, - { id: "a:theme-system", group: "Actions", title: "System theme", icon: MonitorIcon, keywords: "appearance", run: () => (setTheme("system"), setOpen(false)) }, - { id: "s:labels", group: "Settings", title: "File labels", icon: TagIcon, keywords: "colors roles", run: go("/settings/labels") }, - { id: "s:tags", group: "Settings", title: "Tags", icon: TagsIcon, keywords: "rename colors", run: go("/settings/tags") }, - { id: "s:speed", group: "Settings", title: "Download speed limit", icon: DownloadIcon, hint: "Downloads", keywords: "bandwidth mb/s", run: go("/settings/downloads") }, - { id: "s:recommended", group: "Settings", title: "Recommended files", icon: DownloadIcon, hint: "Downloads", keywords: "mmproj mtp template quant", run: go("/settings/downloads") }, - { id: "s:scan", group: "Settings", title: "Models folder scan schedule", icon: ScanSearchIcon, hint: "Downloads", keywords: "daily weekly monthly nas", run: go("/settings/downloads#scan") }, - ]; - for (const m of index?.models ?? []) { - out.push({ id: `m:${m.id}`, group: "Models", title: m.repoId, hint: m.quants.join(", ") || m.status, icon: BoxIcon, keywords: `${m.status} ${m.tags.join(" ")}`, run: go(`/${m.repoId}`) }); - } - for (const e of index?.endpoints ?? []) { - out.push({ id: `e:${e.id}`, group: "Endpoints", title: e.name, hint: [e.engine, e.model].filter(Boolean).join(" · "), icon: ServerIcon, run: go(`/endpoints/${e.id}`) }); - } - for (const b of index?.benchmarks ?? []) { - out.push({ - id: `b:${b.id}`, - group: "Benchmarks", - title: b.label ?? `${b.target} · ${b.model}`, - hint: `${KIND_LABEL[b.kind] ?? b.kind} · ${b.state} · ${new Date(b.createdAt).toLocaleDateString()}`, - icon: GaugeIcon, - keywords: `${b.target} ${b.model}`, - run: go(`/benchmarks/${b.id}`), - }); - } - for (const t of index?.tags ?? []) { - out.push({ id: `t:${t}`, group: "Tags", title: t, hint: "models with this tag", icon: TagIcon, run: go(`/?tag=${encodeURIComponent(t)}`) }); - } - return out; - // `go` only closes over router and setOpen, which are stable. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [index, setTheme]); - - const terms = query.toLowerCase().split(/\s+/).filter(Boolean); - const groups = useMemo(() => { - const scored = items.map((it) => ({ it, s: score(it, terms) })).filter((x) => x.s > 0); - const order = ["Pages", "Actions", "Models", "Endpoints", "Benchmarks", "Settings", "Tags"]; - // Without a query: pages, actions and settings, plus the newest few of the rest. - const per = terms.length ? 8 : 4; - return order - .map((g) => ({ g, rows: scored.filter((x) => x.it.group === g).sort((a, b) => b.s - a.s).slice(0, per).map((x) => x.it) })) - .filter((x) => x.rows.length && (terms.length || ["Pages", "Actions", "Models", "Benchmarks"].includes(x.g))); - // terms is derived from query - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [items, query]); - const flat = groups.flatMap((g) => g.rows); - const current = Math.min(active, Math.max(0, flat.length - 1)); - - useEffect(() => { - list.current?.querySelector(`[data-index="${current}"]`)?.scrollIntoView({ block: "nearest" }); - }, [current]); - - function onKeyDown(e: React.KeyboardEvent) { - if (e.key === "ArrowDown") { - e.preventDefault(); - setActive((current + 1) % Math.max(1, flat.length)); - } else if (e.key === "ArrowUp") { - e.preventDefault(); - setActive((current - 1 + flat.length) % Math.max(1, flat.length)); - } else if (e.key === "Enter") { - e.preventDefault(); - flat[current]?.run(); - } - } - - let n = -1; - return ( - { - setOpen(o); - if (!o) { - setQuery(""); - setActive(0); - } - }} - > - - - - Search -
- - { - setQuery(e.target.value); - setActive(0); - }} - onKeyDown={onKeyDown} - placeholder="Search models, endpoints, benchmarks, settings…" - className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" - aria-label="Search" - /> - Esc -
-
- {flat.length === 0 ? ( -

{index ? `Nothing matches "${query}".` : "Loading…"}

- ) : ( - groups.map(({ g, rows }) => ( -
-
{g}
- {rows.map((it) => { - n++; - const i = n; - return ( - - ); - })} -
- )) - )} -
-
-
-
- ); -} - /** The menu button that opens the palette, showing its shortcut. */ export function CommandPaletteButton({ className }: { className?: string }) { const mac = useSyncExternalStore(noSubscribe, isMac, () => false); return (