"use client"; import { useEffect, useState, useCallback } from "react"; import { useRouter } from "next/navigation"; import { api } from "@/lib/api"; import type { SearchResult } from "@/lib/types"; const TYPE_LABELS: Record = { destination: "目的地", blog: "博客", visa: "签证", faq: "FAQ", }; export default function GlobalSearch() { const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const [results, setResults] = useState([]); const [loading, setLoading] = useState(false); const [activeIdx, setActiveIdx] = useState(0); const router = useRouter(); useEffect(() => { const onKey = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key === "k") { e.preventDefault(); setOpen((o) => !o); } if (e.key === "Escape") setOpen(false); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, []); const doSearch = useCallback(async (q: string) => { if (!q.trim()) { setResults([]); return; } setLoading(true); try { const data = await api.search(q); setResults(data); setActiveIdx(0); } catch { setResults([]); } finally { setLoading(false); } }, []); useEffect(() => { const timer = setTimeout(() => doSearch(query), 250); return () => clearTimeout(timer); }, [query, doSearch]); const navigate = (url: string) => { setOpen(false); setQuery(""); if (url.startsWith("/#")) { router.push("/"); setTimeout(() => { document.querySelector(url.replace("/", ""))?.scrollIntoView({ behavior: "smooth" }); }, 300); } else { router.push(url); } }; const onKeyDown = (e: React.KeyboardEvent) => { if (e.key === "ArrowDown") { e.preventDefault(); setActiveIdx((i) => Math.min(i + 1, results.length - 1)); } if (e.key === "ArrowUp") { e.preventDefault(); setActiveIdx((i) => Math.max(i - 1, 0)); } if (e.key === "Enter" && results[activeIdx]) navigate(results[activeIdx].url); }; return ( <> {open && (
setOpen(false)}>
e.stopPropagation()}>
setQuery(e.target.value)} onKeyDown={onKeyDown} />
{loading &&

搜索中...

} {!loading && query && results.length === 0 && (

😢 没有找到「{query}」相关结果

)} {!loading && results.map((r, i) => ( ))} {!query && (

💡 试试搜索:清迈、签证、税务

⌨️ ↑↓ 选择 · Enter 跳转 · Esc 关闭

)}
)} ); }