返回 CodeWhale
search-palette.tsx
根目录 / web / components / docs-preview / search-palette.tsx
1 "use client";
2
3 import Link from "next/link";
4 import { useEffect, useMemo, useRef, useState } from "react";
5 import { Icon } from "@/components/icon";
6 import { rankDocSections, type DocSearchSection } from "@/lib/doc-search-match";
7 import { highlightSpan } from "@/lib/search-utils";
8
9 interface Labels { search: string; placeholder: string; empty: string; none: string; failed: string; close: string }
10
11 function Marked({ text, query }: { text: string; query: string }) {
12 const span =
13 highlightSpan(text, query) ??
14 query
15 .trim()
16 .split(/\s+/)
17 .map((term) => highlightSpan(text, term))
18 .find((candidate) => candidate !== null) ??
19 null;
20 return span ? <>{span.before}<mark>{span.match}</mark>{span.after}</> : <>{text}</>;
21 }
22
23 export function DocsPreviewSearch({ locale, indexHref, labels }: { locale: string; indexHref: string; labels: Labels }) {
24 const dialog = useRef<HTMLDialogElement>(null);
25 const [query, setQuery] = useState("");
26 const [active, setActive] = useState(0);
27 const [sections, setSections] = useState<DocSearchSection[] | null>(null);
28 const [failed, setFailed] = useState(false);
29 const results = useMemo(() => (sections ? rankDocSections(sections, query) : []), [sections, query]);
30
31 const open = () => {
32 dialog.current?.showModal();
33 if (sections || failed) return;
34 fetch(indexHref)
35 .then((response) => (response.ok ? response.json() : Promise.reject(new Error(String(response.status)))))
36 .then((body: { sections: DocSearchSection[] }) => setSections(body.sections))
37 .catch(() => setFailed(true));
38 };
39
40 useEffect(() => {
41 const onKey = (event: KeyboardEvent) => {
42 if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
43 event.preventDefault();
44 if (dialog.current?.open) dialog.current.close();
45 else open();
46 }
47 };
48 window.addEventListener("keydown", onKey);
49 return () => window.removeEventListener("keydown", onKey);
50 });
51
52 const onInputKey = (event: React.KeyboardEvent<HTMLInputElement>) => {
53 if (event.key === "ArrowDown" || event.key === "ArrowUp") {
54 event.preventDefault();
55 setActive((current) => (results.length ? (current + (event.key === "ArrowDown" ? 1 : results.length - 1)) % results.length : 0));
56 } else if (event.key === "Enter" && results[active]) {
57 event.preventDefault();
58 dialog.current?.querySelector<HTMLAnchorElement>(`[data-result="${active}"]`)?.click();
59 }
60 };
61
62 const term = query.trim();
63
64 return (
65 <>
66 <button type="button" className="dp-search-trigger" onClick={open} aria-haspopup="dialog">
67 <Icon name="search" className="icon" />
68 <span>{labels.placeholder}</span>
69 <kbd aria-hidden="true">⌘K</kbd>
70 </button>
71 <dialog ref={dialog} className="dp-search" aria-label={labels.search} onClick={(event) => { if (event.target === dialog.current) dialog.current?.close(); }} onClose={() => { setQuery(""); setActive(0); }}>
72 <div className="dp-search-panel">
73 <div className="dp-search-field">
74 <Icon name="search" className="icon" />
75 <input
76 type="search"
77 autoFocus
78 value={query}
79 onChange={(event) => { setQuery(event.target.value); setActive(0); }}
80 onKeyDown={onInputKey}
81 placeholder={labels.placeholder}
82 aria-label={labels.search}
83 role="combobox"
84 aria-expanded={results.length > 0}
85 aria-controls="dp-search-results"
86 aria-activedescendant={results[active] ? `dp-search-result-${active}` : undefined}
87 />
88 <button type="button" className="btn btn-sm btn-ghost" onClick={() => dialog.current?.close()}>{labels.close}</button>
89 </div>
90 <ul id="dp-search-results" role="listbox" aria-label={labels.search} className="dp-search-results">
91 {results.map((result, index) => (
92 <li key={`${result.href}-${index}`} id={`dp-search-result-${index}`} role="option" aria-selected={index === active} lang={result.lang}>
93 <Link href={`/${locale}${result.href}`} data-result={index} onClick={() => dialog.current?.close()} onMouseMove={() => setActive(index)}>
94 <span className="dp-search-crumb">{result.pageTitle}</span>
95 <span className="dp-search-title"><Marked text={result.title} query={term} /></span>
96 <span className="dp-search-excerpt"><Marked text={result.excerpt} query={term} /></span>
97 </Link>
98 </li>
99 ))}
100 </ul>
101 <p className="dp-search-status" role="status">
102 {failed ? labels.failed : !term ? labels.empty : sections && !results.length ? labels.none.replace("{query}", term) : ""}
103 </p>
104 </div>
105 </dialog>
106 </>
107 );
108 }
109
109 lines Plain Text