Client bundles: no drizzle in the browser, lazy palette, one copy of the painting
- The enum arrays move from schema.ts to src/lib/db/enums.ts (no imports), which schema.ts re-exports. The endpoint form and benchmark start imported ENDPOINT_ENGINES/QUALITY_SECTIONS from the schema, which put drizzle-orm, every table definition and ulid (18 KB gzipped) on the endpoint pages. An ESLint rule now refuses value imports from the schema in client code. - The ⌘K palette dialog is its own chunk, loaded on first open and preloaded when you hover or focus Search or press ⌘/Ctrl. - The dot painting's brightness grid was copied into 10 page chunks (~10 KB gzipped each); it is now one async chunk, parsed once per tab. The canvas skips redraws when size, pixel ratio and theme are unchanged (the ResizeObserver's first callback drew everything a second time) and draws at most once per frame while resizing. First-load JS per route drops by 10-29 KB gzipped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EooZ9biu7kFNB4eDJrwQc5
This commit is contained in:
9 files changed
+458
-339
No files matched your search
@@ -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<string, string> = { 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<Index | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
const list = useRef<HTMLDivElement>(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<Item[]>(() => {
|
||||
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 (
|
||||
<Dialog.Root
|
||||
open={open}
|
||||
onOpenChange={(o) => {
|
||||
setOpen(o);
|
||||
if (!o) {
|
||||
setQuery("");
|
||||
setActive(0);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Backdrop className="fixed inset-0 z-50 bg-black/50 backdrop-blur-[2px] data-ending-style:opacity-0 data-starting-style:opacity-0" />
|
||||
<Dialog.Popup className="fixed top-[15vh] left-1/2 z-50 flex max-h-[70vh] w-[min(40rem,calc(100vw-2rem))] -translate-x-1/2 flex-col overflow-hidden rounded-2xl bg-popover/85 text-popover-foreground shadow-2xl ring-1 ring-foreground/10 backdrop-blur-xl outline-none data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0">
|
||||
<Dialog.Title className="sr-only">Search</Dialog.Title>
|
||||
<div className="flex items-center gap-2 border-b px-4">
|
||||
<SearchIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
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"
|
||||
/>
|
||||
<kbd className="rounded-full border px-2 text-[10px] leading-4 text-muted-foreground">Esc</kbd>
|
||||
</div>
|
||||
<div ref={list} className="min-h-0 flex-1 overflow-y-auto p-2" role="listbox">
|
||||
{flat.length === 0 ? (
|
||||
<p className="px-3 py-8 text-center text-sm text-muted-foreground">{index ? `Nothing matches "${query}".` : "Loading…"}</p>
|
||||
) : (
|
||||
groups.map(({ g, rows }) => (
|
||||
<div key={g} className="mb-1">
|
||||
<div className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g}</div>
|
||||
{rows.map((it) => {
|
||||
n++;
|
||||
const i = n;
|
||||
return (
|
||||
<button
|
||||
key={it.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === current}
|
||||
data-index={i}
|
||||
onMouseMove={() => setActive(i)}
|
||||
onClick={it.run}
|
||||
className={cn("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left text-sm", i === current && "bg-muted")}
|
||||
>
|
||||
<it.icon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate">{it.title}</span>
|
||||
{it.hint && <span className="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground">{it.hint}</span>}
|
||||
{i === current && <CornerDownLeftIcon className="size-3.5 shrink-0 text-muted-foreground" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Dialog.Popup>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
@@ -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<string, string> = { 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 ? <CommandPaletteDialog open={open} setOpen={setOpen} /> : 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<Index | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
const list = useRef<HTMLDivElement>(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<Item[]>(() => {
|
||||
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 (
|
||||
<Dialog.Root
|
||||
open={open}
|
||||
onOpenChange={(o) => {
|
||||
setOpen(o);
|
||||
if (!o) {
|
||||
setQuery("");
|
||||
setActive(0);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Dialog.Portal>
|
||||
<Dialog.Backdrop className="fixed inset-0 z-50 bg-black/50 backdrop-blur-[2px] data-ending-style:opacity-0 data-starting-style:opacity-0" />
|
||||
<Dialog.Popup className="fixed top-[15vh] left-1/2 z-50 flex max-h-[70vh] w-[min(40rem,calc(100vw-2rem))] -translate-x-1/2 flex-col overflow-hidden rounded-2xl bg-popover/85 text-popover-foreground shadow-2xl ring-1 ring-foreground/10 backdrop-blur-xl outline-none data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0">
|
||||
<Dialog.Title className="sr-only">Search</Dialog.Title>
|
||||
<div className="flex items-center gap-2 border-b px-4">
|
||||
<SearchIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
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"
|
||||
/>
|
||||
<kbd className="rounded-full border px-2 text-[10px] leading-4 text-muted-foreground">Esc</kbd>
|
||||
</div>
|
||||
<div ref={list} className="min-h-0 flex-1 overflow-y-auto p-2" role="listbox">
|
||||
{flat.length === 0 ? (
|
||||
<p className="px-3 py-8 text-center text-sm text-muted-foreground">{index ? `Nothing matches "${query}".` : "Loading…"}</p>
|
||||
) : (
|
||||
groups.map(({ g, rows }) => (
|
||||
<div key={g} className="mb-1">
|
||||
<div className="px-2 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g}</div>
|
||||
{rows.map((it) => {
|
||||
n++;
|
||||
const i = n;
|
||||
return (
|
||||
<button
|
||||
key={it.id}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={i === current}
|
||||
data-index={i}
|
||||
onMouseMove={() => setActive(i)}
|
||||
onClick={it.run}
|
||||
className={cn("flex w-full items-center gap-3 rounded-lg px-2.5 py-2 text-left text-sm", i === current && "bg-muted")}
|
||||
>
|
||||
<it.icon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate">{it.title}</span>
|
||||
{it.hint && <span className="max-w-[45%] shrink-0 truncate text-xs text-muted-foreground">{it.hint}</span>}
|
||||
{i === current && <CornerDownLeftIcon className="size-3.5 shrink-0 text-muted-foreground" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</Dialog.Popup>
|
||||
</Dialog.Portal>
|
||||
</Dialog.Root>
|
||||
);
|
||||
}
|
||||
|
||||
/** The menu button that opens the palette, showing its shortcut. */
|
||||
export function CommandPaletteButton({ className }: { className?: string }) {
|
||||
const mac = useSyncExternalStore(noSubscribe, isMac, () => false);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.dispatchEvent(new Event("kaname:command-palette"))}
|
||||
onClick={() => window.dispatchEvent(new Event(OPEN_EVENT))}
|
||||
onPointerEnter={preload}
|
||||
onFocus={preload}
|
||||
className={cn("flex h-8 items-center gap-2 rounded-lg px-2 text-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground", className)}
|
||||
aria-label="Search"
|
||||
>
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef } from "react";
|
||||
import { ADAM_DOTS, ADAM_H, ADAM_W } from "./adam-dots";
|
||||
|
||||
const SPACING = 6; // CSS px between dot centres
|
||||
const levels = Uint8Array.from(ADAM_DOTS, (c) => parseInt(c, 16));
|
||||
|
||||
type Grid = { w: number; h: number; levels: Uint8Array };
|
||||
|
||||
// The brightness grid (26 KB of text) is its own chunk, shared by every page and parsed once per
|
||||
// tab. Imported statically, it was copied into each page's chunk.
|
||||
let grid: Promise<Grid> | null = null;
|
||||
const loadGrid = () =>
|
||||
(grid ??= import("./adam-dots").then(({ ADAM_DOTS, ADAM_H, ADAM_W }) => ({
|
||||
w: ADAM_W,
|
||||
h: ADAM_H,
|
||||
levels: Uint8Array.from(ADAM_DOTS, (c) => parseInt(c, 16)),
|
||||
})));
|
||||
|
||||
/**
|
||||
* The Creation of Adam as a dot matrix. `view` is the horizontal slice of the painting (0–1) that
|
||||
@@ -30,30 +40,43 @@ export function DotPainting({
|
||||
useEffect(() => {
|
||||
const canvas = ref.current;
|
||||
if (!canvas) return;
|
||||
let data: Grid | null = null;
|
||||
let cancelled = false;
|
||||
let frame = 0;
|
||||
// What the canvas shows (size, pixel ratio, theme, color): a drawing takes tens of ms, so skip it
|
||||
// when nothing changed, e.g. for the ResizeObserver's first callback or another class on <html>.
|
||||
let drawn = "";
|
||||
const draw = () => {
|
||||
frame = 0;
|
||||
if (!data) return;
|
||||
const { width, height } = canvas.getBoundingClientRect();
|
||||
if (!width || !height) return;
|
||||
const dpr = window.devicePixelRatio || 1;
|
||||
const color = getComputedStyle(canvas).color;
|
||||
const dark = document.documentElement.classList.contains("dark");
|
||||
const key = `${width}x${height}@${dpr} ${dark} ${color}`;
|
||||
if (key === drawn) return;
|
||||
drawn = key;
|
||||
const { w, h, levels } = data;
|
||||
canvas.width = Math.round(width * dpr);
|
||||
canvas.height = Math.round(height * dpr);
|
||||
const g = canvas.getContext("2d")!;
|
||||
g.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
g.clearRect(0, 0, width, height);
|
||||
g.fillStyle = getComputedStyle(canvas).color;
|
||||
const dark = document.documentElement.classList.contains("dark");
|
||||
g.fillStyle = color;
|
||||
// CSS px per grid cell: `view` of the painting's width fills the box (at least covering it).
|
||||
const scale = Math.max(width / (view * ADAM_W), height / ADAM_H);
|
||||
const offX = ax * width - fx * ADAM_W * scale;
|
||||
const offY = ay * height - fy * ADAM_H * scale;
|
||||
const scale = Math.max(width / (view * w), height / h);
|
||||
const offX = ax * width - fx * w * scale;
|
||||
const offY = ay * height - fy * h * scale;
|
||||
const clampOff = (o: number, box: number, size: number) => Math.min(0, Math.max(box - size, o));
|
||||
const ox = clampOff(offX, width, ADAM_W * scale);
|
||||
const oy = clampOff(offY, height, ADAM_H * scale);
|
||||
const ox = clampOff(offX, width, w * scale);
|
||||
const oy = clampOff(offY, height, h * scale);
|
||||
const maxR = SPACING * 0.48;
|
||||
for (let y = SPACING / 2; y < height; y += SPACING) {
|
||||
const iy = Math.min(ADAM_H - 1, Math.max(0, Math.floor((y - oy) / scale)));
|
||||
const iy = Math.min(h - 1, Math.max(0, Math.floor((y - oy) / scale)));
|
||||
for (let x = SPACING / 2; x < width; x += SPACING) {
|
||||
const ix = Math.min(ADAM_W - 1, Math.max(0, Math.floor((x - ox) / scale)));
|
||||
const v = levels[iy * ADAM_W + ix] / 15;
|
||||
const ix = Math.min(w - 1, Math.max(0, Math.floor((x - ox) / scale)));
|
||||
const v = levels[iy * w + ix] / 15;
|
||||
const r = maxR * (dark ? v : 1 - v);
|
||||
if (r < 0.35) continue;
|
||||
g.beginPath();
|
||||
@@ -62,13 +85,23 @@ export function DotPainting({
|
||||
}
|
||||
}
|
||||
};
|
||||
draw();
|
||||
const resize = new ResizeObserver(draw);
|
||||
// While a window is resized, observations arrive every frame: draw at most once per frame.
|
||||
const schedule = () => {
|
||||
if (!frame) frame = requestAnimationFrame(draw);
|
||||
};
|
||||
void loadGrid().then((g) => {
|
||||
if (cancelled) return;
|
||||
data = g;
|
||||
draw();
|
||||
});
|
||||
const resize = new ResizeObserver(schedule);
|
||||
resize.observe(canvas);
|
||||
// next-themes switches the class on <html>.
|
||||
const theme = new MutationObserver(draw);
|
||||
const theme = new MutationObserver(schedule);
|
||||
theme.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
|
||||
return () => {
|
||||
cancelled = true;
|
||||
cancelAnimationFrame(frame);
|
||||
resize.disconnect();
|
||||
theme.disconnect();
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user