-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.ts
100 lines (88 loc) · 2.4 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { useNavData, useSiteData } from 'dumi';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useLocaleDocRoutes } from '../utils';
// @ts-ignore
import workerCode from '-!../../../../compiled/_internal/searchWorker.min?dumi-raw';
export interface IHighlightText {
highlighted?: boolean;
text: string;
}
export interface ISearchNavResult {
title?: string;
priority: number;
hints: {
type: 'page' | 'title' | 'demo' | 'content';
link: string;
priority: number;
pageTitle: string;
highlightTitleTexts: IHighlightText[];
highlightTexts: IHighlightText[];
}[];
}
export type ISearchResult = ISearchNavResult[];
let worker: Worker;
// for ssr
if (typeof window !== 'undefined') {
// use blob to avoid generate entry(chunk) for worker
worker = new Worker(
URL.createObjectURL(
new Blob([workerCode], { type: 'application/javascript' }),
),
);
}
export const useSiteSearch = () => {
const debounceTimer = useRef<number>();
const routes = useLocaleDocRoutes();
const { demos } = useSiteData();
const [loading, setLoading] = useState(false);
const [keywords, setKeywords] = useState('');
const navData = useNavData();
const [result, setResult] = useState<ISearchResult>([]);
const setter = useCallback((val: string) => {
setLoading(true);
setKeywords(val);
}, []);
useEffect(() => {
worker.onmessage = (e) => {
setResult(e.data);
setLoading(false);
};
}, []);
useEffect(() => {
// omit demo component for postmessage
const demoData = Object.entries(demos).reduce<
Record<string, Partial<typeof demos[0]>>
>(
(acc, [key, { asset, routeId }]) => ({
...acc,
[key]: { asset, routeId },
}),
{},
);
worker.postMessage({
action: 'generate-metadata',
args: {
routes: JSON.parse(JSON.stringify(routes)),
nav: navData,
demos: demoData,
},
});
}, [routes, demos, navData]);
useEffect(() => {
const str = keywords.trim();
if (str) {
clearTimeout(debounceTimer.current);
debounceTimer.current = window.setTimeout(() => {
worker.postMessage({
action: 'get-search-result',
args: {
keywords: str,
},
});
}, 200);
} else {
setResult([]);
}
}, [keywords]);
return { keywords, setKeywords: setter, result, loading };
};