返回 CodeWhale
react-text.ts
根目录 / web / lib / react-text.ts
1 /**
2 * Flatten a React node tree to searchable / structured-data plain text.
3 * Shared by the FAQ search haystack and FAQPage JSON-LD.
4 */
5 export function extractText(node: React.ReactNode): string {
6 if (node == null || typeof node === "boolean") return "";
7 if (typeof node === "string") return node;
8 if (typeof node === "number") return String(node);
9 if (Array.isArray(node)) return node.map(extractText).join(" ");
10 if (typeof node === "object" && "props" in node) {
11 const props = (node as { props?: { children?: React.ReactNode } }).props;
12 return props ? extractText(props.children) : "";
13 }
14 return "";
15 }
16
17 /** Collapse JSX-extracted whitespace into a single structured-data string. */
18 export function flattenExtractedText(node: React.ReactNode): string {
19 return extractText(node).replace(/\s+/g, " ").trim();
20 }
21
21 lines TYPESCRIPT