import { type SearchAction, type SearchWork, tmdbImageUrl } from "@umt/contracts"; import { CornerDownLeft, Film, Globe, LoaderCircle, type LucideIcon, Search } from "lucide-react"; import { type ReactNode, useEffect, useId, useMemo, useRef, useState } from "react"; import { Link, useNavigate } from "react-router"; import { useSearch } from "~/api/search.ts"; import { settingsPath } from "~/components/console/nav.ts"; import { Dialog, DialogContent, DialogDescription, DialogTitle } from "~/components/ui/dialog.tsx"; import { errorMessage } from "~/lib/api.ts"; import { cn } from "~/lib/utils.ts"; import { SearchHistory, useSearchHistory } from "./search-history.tsx"; import { actionIcon, mediaKindLabel } from "./search-labels.ts"; import { isSearchShortcut, openSearchPalette, searchPagePath, setSearchPaletteOpen, useSearchPalette, } from "./search-store.ts"; import { inventoryBadge, workHref } from "./work-card.tsx"; // 命令面板(Ctrl/⌘+K):输入即查作品(本地 + TMDB 合并,带库内状态)/ 页面与操作;选中作品打开作品详情页。 // 面板里不订阅、不查站点;最后一项进搜索结果页。 function useDebounced(v: T, ms: number): T { const [d, setD] = useState(v); useEffect(() => { const t = setTimeout(() => setD(v), ms); return () => clearTimeout(t); }, [v, ms]); return d; } type Item = { key: string; group: string; icon: LucideIcon; /** TMDB 海报路径:有则以小海报代替图标(失败回退图标) */ posterPath?: string | null | undefined; title: ReactNode; meta?: ReactNode; /** 右侧动作提示 */ hint: string; run: () => void; }; /** 全局快捷键 Ctrl/⌘+K:切换面板(输入框里同样生效) */ export function useSearchHotkey() { useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.repeat || !isSearchShortcut(e)) return; e.preventDefault(); openSearchPalette(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, []); } export function CommandPalette() { useSearchHotkey(); const { open, initial } = useSearchPalette(); return ( 搜索 搜索作品和页面;选中作品打开详情 {open ? : null} ); } function PaletteBody({ initial }: { initial: string }) { const navigate = useNavigate(); const history = useSearchHistory(); const listId = useId(); const [q, setQ] = useState(initial); const term = useDebounced(q.trim(), 150); const media = useSearch(term, "media", 6); const actions = useSearch(term, "actions", 6); const [active, setActive] = useState(0); const listRef = useRef(null); const close = () => setSearchPaletteOpen(false); const go = (to: string) => { if (q.trim()) history.add(q); close(); navigate(to); }; const stale = q.trim() !== term; const works = term ? (media.data?.media?.works ?? []) : []; const tmdb = term ? media.data?.media?.tmdb : undefined; const acts = term ? (actions.data?.actions?.items ?? []) : []; // biome-ignore lint/correctness/useExhaustiveDependencies: 只随数据变化重建(go 每次渲染新建) const items = useMemo(() => { const out: Item[] = []; for (const w of works) out.push(workItem(w, () => go(workHref(w)))); for (const a of acts) out.push(actionItem(a, () => go(a.href))); if (term) out.push({ key: "releases", group: "搜索页", icon: Search, title: ( 查看「{term}」的全部结果 ), hint: "打开", run: () => go(searchPagePath(term)), }); return out; }, [works, acts, term]); // biome-ignore lint/correctness/useExhaustiveDependencies: 结果变化时高亮回到第一项 useEffect(() => setActive(0), [items.length, term]); useEffect(() => { listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" }); }, [active]); const onKeyDown = (e: React.KeyboardEvent) => { if (e.nativeEvent.isComposing) return; if (e.key === "ArrowDown") { e.preventDefault(); setActive((i) => (items.length ? (i + 1) % items.length : 0)); } else if (e.key === "ArrowUp") { e.preventDefault(); setActive((i) => (items.length ? (i - 1 + items.length) % items.length : 0)); } else if (e.key === "Enter") { e.preventDefault(); const it = items[active]; if (it && !stale) it.run(); else if (q.trim()) go(searchPagePath(q)); } }; const loading = !!term && (media.isFetching || actions.isFetching); const activeKey = items[active]?.key; let lastGroup = ""; return (
setQ(e.target.value)} onKeyDown={onKeyDown} placeholder="搜索作品、页面" role="combobox" aria-expanded={items.length > 0} aria-controls={listId} aria-activedescendant={activeKey ? `${listId}-${activeKey}` : undefined} aria-autocomplete="list" className="h-12 min-w-0 flex-1 bg-transparent text-body text-foreground outline-none placeholder:text-muted-foreground" /> {loading ? : null} Esc
{!term ? (
{ history.add(term); go(searchPagePath(term)); }} />

输入作品名、别名或页面名称。选中作品打开详情页。

) : ( <> {items.map((it, i) => { const head = it.group !== lastGroup ? it.group : null; lastGroup = it.group; return (
{head ? (

{head}

) : null} {/* biome-ignore lint/a11y/useKeyWithClickEvents: 键盘由输入框(combobox)的上下键与回车处理 */}
i !== active && setActive(i)} onClick={it.run} className={cn( "flex cursor-pointer items-center gap-3 rounded-xl px-3 py-2 transition-colors duration-micro", i === active ? "bg-foreground/[0.06]" : "", )} >
{it.title}
{it.meta ?
{it.meta}
: null}
{it.hint}
); })} {!stale && media.data && tmdb && !tmdb.configured ? (

TMDB 未配置,只搜本地作品。 去配置

) : null} {!stale && tmdb?.error ? (

TMDB 查询失败:{tmdb.error}

) : null} {media.isError || actions.isError ? (

{errorMessage(media.error ?? actions.error, "搜索失败")}

) : null} )}
↑↓ 选择 ↵ 打开
); } function workItem(w: SearchWork, run: () => void): Item { const inv = inventoryBadge(w.inventory); const parts = [ mediaKindLabel(w.kind), w.year ? String(w.year) : null, inv.label, w.inventory.subscribed ? "已订阅" : null, ]; return { key: `work-${w.key}`, group: "作品", icon: w.localEntityId ? Film : Globe, posterPath: w.posterPath, title: ( {w.title} {w.originalTitle && w.originalTitle !== w.title ? ( · {w.originalTitle} ) : null} ), meta: parts.filter(Boolean).join(" · "), hint: "详情", run, }; } function ItemIcon({ it }: { it: Item }) { const [failed, setFailed] = useState(false); const src = failed ? null : tmdbImageUrl(it.posterPath, "w92"); if (src) { return ( setFailed(true)} className="h-9 w-6 shrink-0 rounded-tight border border-border object-cover" /> ); } return ; } function actionItem(a: SearchAction, run: () => void): Item { return { key: `action-${a.id}`, group: "页面与操作", icon: actionIcon(a.kind), title: a.title, meta: a.group, hint: "前往", run, }; }