返回 CodeWhale
docs-search.tsx
根目录 / web / components / docs-search.tsx
1 "use client";
2
3 import { useState, useMemo, useRef, useCallback, useEffect } from "react";
4 import Link from "next/link";
5 import { usePathname } from "next/navigation";
6 import { normalizeDocSearchText, searchDocSections, type DocSearchSection } from "@/lib/doc-search-match";
7 import {
8 DOC_CATEGORY_LABELS,
9 DOC_TOPICS,
10 docTopicHref,
11 docTopicIsExternal,
12 type DocTopic,
13 } from "@/lib/docs-map";
14 import { DOC_TASKS, docTaskHaystack, type DocTask } from "@/lib/docs-tasks";
15 import { fill, getDocsShell, getFeatures, pickText } from "@/lib/i18n/dictionaries";
16 import { FEATURE_CATALOGUE } from "@/lib/features";
17 import { Status } from "./status-badge";
18 import { readBoundedBody } from "@/lib/bounded-body";
19 import { recordFunnel } from "./usage-counting";
20 import { docTopicHaystack, highlightSpan } from "@/lib/search-utils";
21 import { isSlashShortcut, type ShortcutKeyEvent } from "@/lib/slash-shortcut";
22 import { EmptyState } from "./surface-state";
23
24 /* ------------------------------------------------------------------ */
25 /* Helpers */
26 /* ------------------------------------------------------------------ */
27
28 function topicSources(topic: DocTopic): string[] {
29 return Array.isArray(topic.repoSource) ? topic.repoSource : [topic.repoSource];
30 }
31
32 function highlight(text: string, query: string): React.ReactNode {
33 // Index arithmetic lives in search-utils: lowercasing can change a
34 // string's length, so `text` cannot be sliced with indices taken from
35 // its lowercased copy.
36 const span = highlightSpan(text, query);
37 if (!span) return text;
38 return (
39 <>
40 {span.before}
41 <mark className="search-highlight">{span.match}</mark>
42 {span.after}
43 </>
44 );
45 }
46
47 /* ------------------------------------------------------------------ */
48 /* Rows */
49 /* ------------------------------------------------------------------ */
50
51 function TaskRow({ task, locale, query, onSelect }: { task: DocTask; locale: string; query: string; onSelect?: () => void }) {
52 return (
53 <Link href={`/${locale}${task.href}`} className="docs-topic-row docs-task-row" onClick={onSelect}>
54 <div className="docs-topic-main">
55 <div className="docs-topic-title">{highlight(pickText(task.label, locale), query)}</div>
56 <p>{highlight(pickText(task.description, locale), query)}</p>
57 </div>
58 <span className="docs-topic-arrow" aria-hidden="true">→</span>
59 </Link>
60 );
61 }
62
63 function TopicRow({
64 topic,
65 locale,
66 query,
67 webGuideTag,
68 sourceDocTag,
69 sourceDetails,
70 onSelect,
71 }: {
72 topic: DocTopic;
73 locale: string;
74 query: string;
75 webGuideTag: string;
76 sourceDocTag: string;
77 sourceDetails: string;
78 onSelect?: () => void;
79 }) {
80 const href = docTopicHref(topic, locale);
81 const isExternal = docTopicIsExternal(topic);
82 const sources = topicSources(topic);
83
84 // The row is a link; its provenance (the repository files the entry is
85 // written from) sits beside it behind a disclosure, so it is there for
86 // maintainers without crowding the index.
87 return (
88 <div className="docs-topic-item">
89 <Link
90 href={href}
91 target={isExternal ? "_blank" : undefined}
92 rel={isExternal ? "noreferrer" : undefined}
93 className="docs-topic-row"
94 onClick={onSelect}
95 >
96 <div className="docs-topic-main">
97 <div className="docs-topic-title">
98 {highlight(pickText(topic.label, locale), query)}
99 <span>{isExternal ? sourceDocTag : webGuideTag}</span>
100 </div>
101 <p>{highlight(pickText(topic.description, locale), query)}</p>
102 </div>
103 <span className="docs-topic-arrow" aria-hidden="true">{isExternal ? "↗" : "→"}</span>
104 </Link>
105 <details className="docs-topic-details">
106 <summary>{sourceDetails}</summary>
107 <p className="docs-topic-source">
108 {sources.map((s, i) => (
109 <span key={s}>
110 {i > 0 && ", "}
111 <code>{highlight(s, query)}</code>
112 </span>
113 ))}
114 </p>
115 </details>
116 </div>
117 );
118 }
119
120 /* ------------------------------------------------------------------ */
121 /* Main component */
122 /* ------------------------------------------------------------------ */
123
124 /**
125 * The docs search combines rendered article sections, tasks and topics.
126 * Topic and task metadata match both English and Chinese; article sections
127 * follow the active dictionary. Every string is dictionary-driven.
128 */
129 export function isDocsSearchShortcut(e: ShortcutKeyEvent & { shiftKey?: boolean }): boolean {
130 if (isSlashShortcut(e)) return true;
131 if (e.defaultPrevented || e.altKey || e.shiftKey || e.isComposing) return false;
132 return (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k";
133 }
134
135 function isSearchSection(value: unknown): value is DocSearchSection {
136 if (!value || typeof value !== "object" || Array.isArray(value)) return false;
137 const row = value as Record<string, unknown>;
138 if (Object.keys(row).some((key) => !["href", "pageTitle", "title", "text", "lang"].includes(key))) return false;
139 return typeof row.href === "string" && /^\/(?:docs|install|models|plugins|constitution)(?:[\/#]|$)/.test(row.href)
140 && typeof row.pageTitle === "string" && typeof row.title === "string" && typeof row.text === "string"
141 && (row.lang === undefined || (typeof row.lang === "string" && row.lang.length <= 35));
142 }
143
144 export function DocsSearch({ locale, compact = false }: { locale: string; compact?: boolean }) {
145 const t = getDocsShell(locale);
146 const [query, setQuery] = useState("");
147 const inputRef = useRef<HTMLInputElement>(null);
148
149 const topicHaystacks = useMemo(() => DOC_TOPICS.map(docTopicHaystack), []);
150 const taskHaystacks = useMemo(() => DOC_TASKS.map(docTaskHaystack), []);
151
152 const [loaded, setLoaded] = useState<{ locale: string; sections: DocSearchSection[] } | null>(null);
153 const [loadingLocale, setLoadingLocale] = useState<string | null>(null);
154 const [errorLocale, setErrorLocale] = useState<string | null>(null);
155 const request = useRef<{ locale: string; controller: AbortController } | null>(null);
156 const ready = loaded?.locale === locale;
157 const sections = useMemo(() => loaded?.locale === locale ? loaded.sections : [], [loaded, locale]);
158 const loadSections = useCallback(async () => {
159 if (loaded?.locale === locale || request.current?.locale === locale) return;
160 request.current?.controller.abort();
161 const controller = new AbortController();
162 request.current = { locale, controller };
163 setLoadingLocale(locale);
164 setErrorLocale(null);
165 const timeout = setTimeout(() => {
166 if (!controller.signal.aborted) {
167 setErrorLocale(locale);
168 controller.abort();
169 }
170 }, 8000);
171 try {
172 const response = await fetch(`/api/docs/search/${encodeURIComponent(locale)}`, {
173 credentials: "omit", referrerPolicy: "no-referrer",
174 signal: controller.signal,
175 });
176 if (!response.ok) throw new Error("unavailable");
177 const bytes = await readBoundedBody(response, 2 * 1024 * 1024);
178 const payload: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
179 const entries = payload && typeof payload === "object" ? (payload as { sections?: unknown }).sections : null;
180 if (!Array.isArray(entries) || entries.length === 0 || entries.length > 10000 || !entries.every(isSearchSection)) throw new Error("invalid index");
181 if (!controller.signal.aborted) setLoaded({ locale, sections: entries });
182 } catch {
183 if (!controller.signal.aborted) setErrorLocale(locale);
184 } finally {
185 clearTimeout(timeout);
186 if (request.current?.controller === controller) { request.current = null; setLoadingLocale(null); }
187 }
188 }, [locale, loaded]);
189 useEffect(() => () => request.current?.controller.abort(), []);
190 const sectionMatches = useMemo(() => searchDocSections(sections, query), [sections, query]);
191 const q = normalizeDocSearchText(query);
192 const filteredTasks = useMemo(
193 () => (q ? DOC_TASKS.filter((_, i) => taskHaystacks[i].includes(q)) : DOC_TASKS),
194 [q, taskHaystacks],
195 );
196 const filteredTopics = useMemo(
197 () => (q ? DOC_TOPICS.filter((_, i) => topicHaystacks[i].includes(q)) : DOC_TOPICS),
198 [q, topicHaystacks],
199 );
200 const filteredFeatures = useMemo(() => q ? FEATURE_CATALOGUE.features.filter((feature) =>
201 normalizeDocSearchText([feature.id, feature.name, feature.summary, feature.flag, feature.docs, ...Object.entries(feature.surfaces).flat()].filter(Boolean).join(" ")).includes(q)
202 ) : [], [q]);
203
204 // Group filtered topics by category (preserve DOC_TOPICS order).
205 const grouped = useMemo(() => {
206 const map = new Map<DocTopic["category"], DocTopic[]>();
207 for (const topic of filteredTopics) {
208 const group = map.get(topic.category) ?? [];
209 group.push(topic);
210 map.set(topic.category, group);
211 }
212 return map;
213 }, [filteredTopics]);
214
215 const handleKeyDown = useCallback((e: KeyboardEvent) => {
216 if (isDocsSearchShortcut(e)) {
217 e.preventDefault();
218 inputRef.current?.focus();
219 inputRef.current?.select();
220 }
221 }, []);
222
223 useEffect(() => {
224 window.addEventListener("keydown", handleKeyDown);
225 return () => window.removeEventListener("keydown", handleKeyDown);
226 }, [handleKeyDown]);
227
228 const total = DOC_TOPICS.length + DOC_TASKS.length + FEATURE_CATALOGUE.features.length + sections.length;
229 const matched = filteredTopics.length + filteredTasks.length + filteredFeatures.length + sectionMatches.length;
230 const hasQuery = q.length > 0;
231 const measuredQuery = useRef<string | null>(null);
232 const measureSearch = useCallback(() => {
233 if (!q || !ready) return;
234 const key = `${locale}:${q}`;
235 if (measuredQuery.current === key) return;
236 measuredQuery.current = key;
237 recordFunnel("docs_search");
238 if (matched === 0) recordFunnel("docs_search_empty");
239 }, [q, matched, ready, locale]);
240 useEffect(() => {
241 if (!q) { measuredQuery.current = null; return; }
242 if (!ready) return;
243 const timer = setTimeout(measureSearch, 400);
244 return () => clearTimeout(timer);
245 }, [q, ready, measureSearch]);
246 const selectSearchResult = () => {
247 if (!q || !ready) return;
248 measureSearch();
249 recordFunnel("docs_search_result");
250 if (compact) setQuery("");
251 };
252 useEffect(() => { if (q) void loadSections(); }, [q, loadSections]);
253
254 return (
255 <div className="docs-index">
256 {/* Search bar */}
257 <div className="docs-search-block">
258 <label htmlFor="docs-search" className="docs-search-label">
259 {t.searchLabel}
260 </label>
261 <div className="relative">
262 <input
263 id="docs-search"
264 ref={inputRef}
265 type="text"
266 value={query}
267 onChange={(e) => setQuery(e.target.value)}
268 onFocus={() => void loadSections()}
269 onKeyDown={(e) => {
270 if (e.key !== "Escape") return;
271 e.preventDefault();
272 if (query.length > 0) {
273 setQuery("");
274 } else {
275 e.currentTarget.blur();
276 }
277 }}
278 aria-keyshortcuts="/ Control+k Meta+k"
279 placeholder={t.searchPlaceholder}
280 className="search-input docs-search-input w-full"
281 aria-label={t.searchLabel}
282 autoComplete="off"
283 />
284 {hasQuery ? (
285 <button
286 type="button"
287 onClick={() => setQuery("")}
288 className="docs-search-clear"
289 aria-label={t.searchClear}
290 >
291 ✕
292 </button>
293 ) : (
294 <span className="docs-search-shortcut" aria-hidden="true">
295 <kbd>Ctrl+K</kbd>
296 <kbd>/</kbd>
297 </span>
298 )}
299 </div>
300 {hasQuery && ready && (
301 <div className="docs-search-count" aria-live="polite">
302 {matched > 0
303 ? fill(t.searchMatches, { matched, total, query: query.trim() })
304 : fill(t.searchNoMatches, { query: query.trim() })}
305 </div>
306 )}
307 </div>
308
309 {loadingLocale === locale && <p role="status">{t.searchLoading}</p>}
310 {errorLocale === locale && <div role="status"><p>{t.searchUnavailable}</p><button type="button" className="btn btn-secondary" onClick={() => void loadSections()}>{t.searchRetry}</button></div>}
311 {(!compact || hasQuery) && (!hasQuery || ready) && (matched > 0 ? (
312 <div className="docs-result-groups">
313 {sectionMatches.length > 0 && <section className="docs-result-group">
314 <div className="docs-result-heading"><h2>{t.searchLabel}</h2><span>{sectionMatches.length}</span></div>
315 <div className="docs-topic-list">{sectionMatches.map((section) => (
316 <Link key={section.href} href={`/${locale}${section.href}`} className="docs-topic-row" onClick={selectSearchResult}>
317 <div className="docs-topic-main">
318 <div className="docs-topic-title">{highlight(`${section.pageTitle} · ${section.title}`, query)}</div>
319 <p lang={section.lang}>{highlight(section.excerpt, query)}</p>
320 </div>
321 <span className="docs-topic-arrow" aria-hidden="true">→</span>
322 </Link>
323 ))}</div>
324 </section>}
325 {filteredFeatures.length > 0 && <section className="docs-result-group">
326 <div className="docs-result-heading"><h2>{getFeatures(locale).title}</h2><span>{filteredFeatures.length}</span></div>
327 <div className="docs-topic-list">{filteredFeatures.map((feature) => <Link key={feature.id} href={`/${locale}/features#${feature.id}`} className="docs-topic-row" onClick={selectSearchResult}>
328 <div className="docs-topic-main" lang="en" dir="ltr"><div className="docs-topic-title">{highlight(feature.name, query)}</div><p>{highlight(feature.summary, query)}</p></div>
329 <Status tone={feature.status === "stable" ? "ready" : "attention"}>{getFeatures(locale)[feature.status]}</Status>
330 </Link>)}</div>
331 </section>}
332 {/* Tasks — "I am trying to…" */}
333 {filteredTasks.length > 0 && (
334 <section id="tasks" className="docs-result-group docs-task-group">
335 <div className="docs-result-heading">
336 <h2>{t.tasksHeading}</h2>
337 <span>{filteredTasks.length}</span>
338 </div>
339 {!hasQuery && <p className="docs-result-lead">{t.tasksLead}</p>}
340 <div className="docs-topic-list">
341 {filteredTasks.map((task) => (
342 <TaskRow key={task.id} task={task} locale={locale} query={query} onSelect={hasQuery ? selectSearchResult : undefined} />
343 ))}
344 </div>
345 </section>
346 )}
347
348 {/* Topics by category */}
349 {grouped.size > 0 && (
350 <div className="docs-result-topics">
351 {!hasQuery && (
352 <div className="docs-result-heading docs-result-heading-topics">
353 <h2>{t.topicsHeading}</h2>
354 <span>{filteredTopics.length}</span>
355 </div>
356 )}
357 {[...grouped.entries()].map(([category, topics]) => (
358 <section key={category} id={category} className="docs-result-group">
359 <div className="docs-result-heading">
360 <h3>{pickText(DOC_CATEGORY_LABELS[category], locale)}</h3>
361 <span>{topics.length}</span>
362 </div>
363 <div className="docs-topic-list">
364 {topics.map((topic) => (
365 <TopicRow
366 key={topic.id}
367 topic={topic}
368 locale={locale}
369 query={query}
370 webGuideTag={t.webGuideTag}
371 sourceDocTag={t.sourceDocTag}
372 sourceDetails={t.sourceDetails}
373 onSelect={hasQuery ? selectSearchResult : undefined}
374 />
375 ))}
376 </div>
377 </section>
378 ))}
379 </div>
380 )}
381 </div>
382 ) : (
383 <EmptyState
384 locale={locale}
385 title={t.emptyTitle}
386 body={t.emptyBody}
387 action={
388 <a
389 href="https://github.com/codewhale-hq/CodeWhale/tree/main/docs"
390 target="_blank"
391 rel="noreferrer"
392 className="portal-button portal-button-secondary"
393 >
394 {t.emptyCta}
395 </a>
396 }
397 />
398 ))}
399
400 {/* Registry note (only when not searching) */}
401 {!hasQuery && !compact && (
402 <section className="docs-source-note">
403 <p>{t.indexNote}</p>
404 </section>
405 )}
406 </div>
407 );
408 }
409
410 export function DocsArticleSearch({ locale }: { locale: string }) {
411 const pathname = usePathname();
412 if (pathname.replace(/\/+$/, "") === `/${locale}/docs`) return null;
413 return <div className="mb-8"><DocsSearch locale={locale} compact /></div>;
414 }
415
415 lines Plain Text