返回 CodeWhale
doc-search-match.ts
根目录 / web / lib / doc-search-match.ts
1 import { highlightSpan } from "./search-utils";
2
3 export interface DocSearchSection {
4 href: string;
5 pageTitle: string;
6 title: string;
7 text: string;
8 lang?: string;
9 }
10
11 export function normalizeDocSearchText(text: string): string {
12 return text.trim().toLowerCase().replace(/\s+/g, " ");
13 }
14
15 export function searchDocSections(sections: readonly DocSearchSection[], query: string): (DocSearchSection & { excerpt: string })[] {
16 const normalized = normalizeDocSearchText(query);
17 if (!normalized) return [];
18 return sections.filter((section) => normalizeDocSearchText(`${section.pageTitle} ${section.title} ${section.text}`).includes(normalized)).map((section) => {
19 const text = section.text.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1").replace(/`/g, "").replace(/\s+/g, " ");
20 const span = highlightSpan(text, normalized);
21 const position = span ? span.before.length : 0;
22 const start = Math.max(0, position - 70);
23 const end = Math.min(text.length, start + 240);
24 return { ...section, excerpt: `${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}` };
25 });
26 }
27
28 export function rankDocSections(sections: readonly DocSearchSection[], query: string, limit = 12): (DocSearchSection & { excerpt: string })[] {
29 const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
30 if (!terms.length) return [];
31 return sections.flatMap((section) => {
32 const title = section.title.toLowerCase();
33 const page = section.pageTitle.toLowerCase();
34 const text = section.text.replace(/\s+/g, " ");
35 const body = text.toLowerCase();
36 let score = 0;
37 for (const term of terms) {
38 const hit = (title.includes(term) ? 8 : 0) + (page.includes(term) ? 3 : 0) + (body.includes(term) ? 1 : 0);
39 if (!hit) return [];
40 score += hit;
41 }
42 const span = terms.map((term) => highlightSpan(text, term)).find((candidate) => candidate !== null) ?? null;
43 const position = span ? span.before.length : 0;
44 const start = Math.max(0, position - 60);
45 const end = Math.min(text.length, start + 180);
46 return [{ ...section, score, excerpt: `${start ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}` }];
47 }).sort((a, b) => b.score - a.score).slice(0, limit);
48 }
49
49 lines TYPESCRIPT