@rspress/core 2.0.20 → 2.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/dist/cli/index.js +12 -13
  2. package/dist/config/loadConfigFile.d.ts +3 -4
  3. package/dist/config/loadConfigFile.js +13 -17
  4. package/dist/{7748~0.js → d~0.js} +0 -2
  5. package/dist/eject-theme/components/Banner/index.tsx +50 -9
  6. package/dist/eject-theme/components/Callout/index.scss +6 -1
  7. package/dist/eject-theme/components/CodeBlock/index.scss +2 -0
  8. package/dist/eject-theme/components/DocContent/doc.scss +2 -2
  9. package/dist/eject-theme/components/Link/getHref.test.ts +33 -0
  10. package/dist/eject-theme/components/Link/getHref.ts +60 -0
  11. package/dist/eject-theme/components/Link/index.tsx +7 -6
  12. package/dist/eject-theme/components/Link/useLinkNavigate.ts +6 -51
  13. package/dist/eject-theme/components/Llms/LlmsHint.test.tsx +8 -0
  14. package/dist/eject-theme/components/Llms/LlmsHint.tsx +11 -3
  15. package/dist/eject-theme/components/Nav/NavMenu.scss +19 -3
  16. package/dist/eject-theme/components/Nav/NavMenu.tsx +20 -13
  17. package/dist/eject-theme/components/Nav/index.scss +3 -1
  18. package/dist/eject-theme/components/Nav/index.tsx +30 -4
  19. package/dist/eject-theme/components/NavHamburger/index.tsx +11 -3
  20. package/dist/eject-theme/components/NavList/context.ts +3 -0
  21. package/dist/eject-theme/components/NavList/index.tsx +24 -0
  22. package/dist/eject-theme/components/NavScreen/NavScreenMenu.test.tsx +59 -0
  23. package/dist/eject-theme/components/NavScreen/NavScreenMenu.tsx +43 -2
  24. package/dist/eject-theme/components/NavScreen/index.scss +0 -6
  25. package/dist/eject-theme/components/NavScreen/index.tsx +20 -3
  26. package/dist/eject-theme/components/Prompt/index.scss +2 -1
  27. package/dist/eject-theme/components/ReadPercent/useReadPercent.ts +1 -1
  28. package/dist/eject-theme/components/Search/SearchButton.scss +1 -0
  29. package/dist/eject-theme/components/Search/SearchPanel.scss +51 -12
  30. package/dist/eject-theme/components/Search/SearchPanel.tsx +54 -212
  31. package/dist/eject-theme/components/Search/logic/providers/LocalProvider.ts +38 -16
  32. package/dist/eject-theme/components/Search/useSearchPanel.ts +216 -0
  33. package/dist/eject-theme/components/Steps/index.scss +1 -1
  34. package/dist/eject-theme/components/SwitchAppearance/getClipPath.test.ts +15 -0
  35. package/dist/eject-theme/components/SwitchAppearance/getClipPath.ts +26 -0
  36. package/dist/eject-theme/components/SwitchAppearance/global.scss +18 -0
  37. package/dist/eject-theme/components/SwitchAppearance/index.tsx +26 -35
  38. package/dist/eject-theme/components/Tabs/index.tsx +14 -14
  39. package/dist/index.js +1 -1
  40. package/dist/node/PluginDriver.d.ts +1 -1
  41. package/dist/node/PluginDriver.js +5 -9
  42. package/dist/node/auto-nav-sidebar/index.js +1 -1
  43. package/dist/node/auto-nav-sidebar/locales.js +1 -1
  44. package/dist/node/auto-nav-sidebar/normalize.js +6 -6
  45. package/dist/node/auto-nav-sidebar/utils.js +1 -1
  46. package/dist/node/auto-nav-sidebar/walk.js +1 -1
  47. package/dist/node/build.d.ts +3 -2
  48. package/dist/node/build.js +9 -3
  49. package/dist/node/constants.js +1 -1
  50. package/dist/node/dev.d.ts +4 -4
  51. package/dist/node/dev.js +8 -6
  52. package/dist/node/eject.js +5 -5
  53. package/dist/node/initRsbuild.d.ts +2 -3
  54. package/dist/node/initRsbuild.js +9 -7
  55. package/dist/node/last-updated/index.js +2 -2
  56. package/dist/node/logger/hint.js +4 -4
  57. package/dist/node/mdx/options.js +1 -1
  58. package/dist/node/mdx/processor.js +3 -3
  59. package/dist/node/mdx/rehypePlugins/codeMeta.js +1 -1
  60. package/dist/node/mdx/rehypePlugins/headerAnchor.js +1 -1
  61. package/dist/node/mdx/rehypePlugins/shiki.js +1 -1
  62. package/dist/node/mdx/remarkPlugins/builtin.js +1 -1
  63. package/dist/node/mdx/remarkPlugins/containerSyntax.js +6 -5
  64. package/dist/node/mdx/remarkPlugins/fileCodeBlock.js +5 -5
  65. package/dist/node/mdx/remarkPlugins/image.js +5 -5
  66. package/dist/node/mdx/remarkPlugins/link.js +5 -5
  67. package/dist/node/mdx/remarkPlugins/toc.js +1 -1
  68. package/dist/node/medium-zoom/index.js +1 -1
  69. package/dist/node/route/RoutePage.js +6 -4
  70. package/dist/node/route/RouteService.js +3 -3
  71. package/dist/node/route/extractPageData.js +20 -7
  72. package/dist/node/route/normalizeRoutePath.js +1 -1
  73. package/dist/node/runtimeModule/i18n.js +5 -5
  74. package/dist/node/runtimeModule/pageData/createPageData.js +1 -1
  75. package/dist/node/runtimeModule/pageData/rsbuildPlugin.js +1 -1
  76. package/dist/node/runtimeModule/searchHooks.js +1 -1
  77. package/dist/node/runtimeModule/siteData/createSiteData.js +1 -1
  78. package/dist/node/runtimeModule/siteData/normalizeThemeConfig.js +1 -1
  79. package/dist/node/runtimeModule/siteData/rsbuildPlugin.js +1 -1
  80. package/dist/node/serve.d.ts +3 -3
  81. package/dist/node/serve.js +10 -4
  82. package/dist/node/ssg/alternateLinks.js +1 -1
  83. package/dist/node/ssg/htmlFile.js +1 -1
  84. package/dist/node/ssg/renderHtmlTemplate.js +1 -1
  85. package/dist/node/ssg/renderPage.js +5 -5
  86. package/dist/node/ssg/renderPageWorker.js +2 -2
  87. package/dist/node/ssg/renderPages.js +6 -6
  88. package/dist/node/ssg/rsbuildPluginSSG.js +1 -1
  89. package/dist/node/ssg/ssgEnv.js +1 -1
  90. package/dist/node/ssg-md/llms/emitLlmsTxt.js +1 -1
  91. package/dist/node/ssg-md/llms/llmsTxt.js +1 -1
  92. package/dist/node/ssg-md/remarkSplitMdx.js +1 -1
  93. package/dist/node/ssg-md/renderPage.js +5 -5
  94. package/dist/node/ssg-md/renderPages.js +6 -6
  95. package/dist/node/ssg-md/rsbuildPluginSSGMD.js +1 -1
  96. package/dist/node/utils/checkLanguageParity.js +5 -7
  97. package/dist/node/utils/createHash.js +1 -1
  98. package/dist/node/utils/error.js +4 -4
  99. package/dist/node/utils/flattenMdxContent.js +2 -2
  100. package/dist/node/utils/fs.js +1 -1
  101. package/dist/node/utils/getPageKey.js +1 -1
  102. package/dist/node/utils/index.d.ts +1 -1
  103. package/dist/node/utils/reactAlias.js +5 -5
  104. package/dist/node/utils/slash.d.ts +1 -0
  105. package/dist/node/utils/slash.js +4 -0
  106. package/dist/{864~0.js → n~0.js} +41 -41
  107. package/dist/{2711~0.js → o~0.js} +90 -56
  108. package/dist/rslib-runtime~0.js +27 -35
  109. package/dist/theme/components/Banner/index.js +53 -9
  110. package/dist/theme/components/Callout/index.css +6 -1
  111. package/dist/theme/components/CodeBlock/index.css +2 -0
  112. package/dist/theme/components/DocContent/doc.css +2 -2
  113. package/dist/theme/components/Link/getHref.d.ts +8 -0
  114. package/dist/theme/components/Link/getHref.js +33 -0
  115. package/dist/theme/components/Link/index.js +7 -6
  116. package/dist/theme/components/Link/useLinkNavigate.d.ts +0 -7
  117. package/dist/theme/components/Link/useLinkNavigate.js +8 -32
  118. package/dist/theme/components/Llms/LlmsHint.js +23 -6
  119. package/dist/theme/components/Nav/NavMenu.css +18 -6
  120. package/dist/theme/components/Nav/NavMenu.d.ts +4 -2
  121. package/dist/theme/components/Nav/NavMenu.js +17 -9
  122. package/dist/theme/components/Nav/index.css +3 -1
  123. package/dist/theme/components/Nav/index.d.ts +7 -1
  124. package/dist/theme/components/Nav/index.js +13 -4
  125. package/dist/theme/components/NavHamburger/index.d.ts +2 -1
  126. package/dist/theme/components/NavHamburger/index.js +8 -2
  127. package/dist/theme/components/NavList/context.d.ts +1 -0
  128. package/dist/theme/components/NavList/context.js +3 -0
  129. package/dist/theme/components/NavList/index.d.ts +6 -0
  130. package/dist/theme/components/NavList/index.js +17 -0
  131. package/dist/theme/components/NavScreen/NavScreenMenu.d.ts +3 -2
  132. package/dist/theme/components/NavScreen/NavScreenMenu.js +42 -6
  133. package/dist/theme/components/NavScreen/index.css +0 -10
  134. package/dist/theme/components/NavScreen/index.d.ts +2 -1
  135. package/dist/theme/components/NavScreen/index.js +11 -3
  136. package/dist/theme/components/PackageManagerTabs/index.js +2 -2
  137. package/dist/theme/components/Prompt/index.css +2 -1
  138. package/dist/theme/components/ReadPercent/useReadPercent.js +1 -0
  139. package/dist/theme/components/Search/SearchButton.css +1 -0
  140. package/dist/theme/components/Search/SearchPanel.css +47 -9
  141. package/dist/theme/components/Search/SearchPanel.js +97 -205
  142. package/dist/theme/components/Search/logic/providers/LocalProvider.d.ts +1 -0
  143. package/dist/theme/components/Search/logic/providers/LocalProvider.js +23 -13
  144. package/dist/theme/components/Search/logic/search.js +1 -1
  145. package/dist/theme/components/Search/useSearchPanel.d.ts +23 -0
  146. package/dist/theme/components/Search/useSearchPanel.js +155 -0
  147. package/dist/theme/components/Steps/index.css +3 -3
  148. package/dist/theme/components/SwitchAppearance/getClipPath.d.ts +8 -0
  149. package/dist/theme/components/SwitchAppearance/getClipPath.js +13 -0
  150. package/dist/theme/components/SwitchAppearance/global.css +12 -0
  151. package/dist/theme/components/SwitchAppearance/index.js +11 -15
  152. package/dist/theme/components/Tabs/index.js +4 -4
  153. package/dist/theme/components/Tag/index.js +2 -2
  154. package/dist/theme/index.d.ts +1 -0
  155. package/dist/theme/index.js +1 -0
  156. package/dist/theme/layout/DocLayout/index.js +2 -2
  157. package/dist/theme/layout/Layout/index.js +12 -4
  158. package/dist/theme/logic/applyThemeToDOM.d.ts +2 -0
  159. package/dist/theme/logic/applyThemeToDOM.js +17 -0
  160. package/dist/theme/logic/useFullTextSearch.js +6 -1
  161. package/dist/theme/logic/useThemeState.d.ts +1 -2
  162. package/dist/theme/logic/useThemeState.js +1 -7
  163. package/dist/theme/styles/vars/shiki-vars.css +1 -1
  164. package/dist/tinypool~0.js +5 -3
  165. package/dist/{4538~0.js → t~0.js} +2 -2
  166. package/dist/{8472~0.js → v~0.js} +1 -1
  167. package/package.json +11 -12
  168. package/dist/eject-theme/components/NavScreen/NavScreenMenuOthers.tsx +0 -29
  169. package/dist/node/utils/normalizePath.d.ts +0 -3
  170. package/dist/node/utils/normalizePath.js +0 -10
  171. package/dist/theme/components/NavScreen/NavScreenMenuOthers.d.ts +0 -2
  172. package/dist/theme/components/NavScreen/NavScreenMenuOthers.js +0 -30
  173. package/dist/theme/logic/useHandler.d.ts +0 -6
  174. package/dist/theme/logic/useHandler.js +0 -7
  175. /package/dist/{9857~0.js → 4~0.js} +0 -0
  176. /package/dist/{8016~0.js → i~0.js} +0 -0
  177. /package/dist/{5357~0.js → r~0.js} +0 -0
  178. /package/dist/{102~0.js → t2~0.js} +0 -0
  179. /package/dist/{9940~0.js → tx~0.js} +0 -0
@@ -1,29 +1,25 @@
1
- import { useI18n, usePageData } from '@rspress/core/runtime';
1
+ import { Head, useI18n } from '@rspress/core/runtime';
2
2
  import {
3
3
  IconClose,
4
- IconLoading,
5
4
  IconSearch,
6
5
  SvgWrapper,
7
6
  Tab,
8
7
  Tabs,
9
8
  useLinkNavigate,
10
9
  } from '@rspress/core/theme';
11
- import { debounce } from '@rspress/shared/lodash-es';
12
- import { useCallback, useEffect, useRef, useState } from 'react';
10
+ import { useEffect, useRef, useState } from 'react';
13
11
  import { createPortal } from 'react-dom';
14
12
  import * as userSearchHooks from 'virtual-search-hooks';
15
- import { PageSearcher } from './logic/search';
16
13
  import type {
17
- CustomMatchResult,
18
14
  DefaultMatchResult,
19
15
  DefaultMatchResultItem,
20
16
  MatchResult,
21
- PageSearcherConfig,
22
17
  } from './logic/types';
23
18
  import { RenderType } from './logic/types';
24
19
  import { NoSearchResult } from './NoSearchResult';
25
20
  import './SearchPanel.scss';
26
21
  import { SuggestItem } from './SuggestItem';
22
+ import { useSearchPanel } from './useSearchPanel';
27
23
 
28
24
  const KEY_CODE = {
29
25
  ARROW_UP: 'ArrowUp',
@@ -38,19 +34,6 @@ export interface SearchPanelProps {
38
34
  setFocused: (focused: boolean) => void;
39
35
  }
40
36
 
41
- const useDebounce = <T extends (...args: any[]) => any>(cb: T) => {
42
- const cbRef = useRef(cb);
43
- cbRef.current = cb;
44
- const debounced = useCallback(
45
- debounce(
46
- ((...args: Parameters<T>): ReturnType<T> => cbRef.current(...args)) as T,
47
- 150,
48
- ),
49
- [],
50
- );
51
- return debounced;
52
- };
53
-
54
37
  const normalizeSuggestions = (
55
38
  suggestions: DefaultMatchResult['result'],
56
39
  ): Map<string, DefaultMatchResultItem[]> => {
@@ -68,17 +51,7 @@ const normalizeSuggestions = (
68
51
  };
69
52
 
70
53
  export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
71
- const [query, setQuery] = useState('');
72
- const [searchResult, setSearchResult] = useState<MatchResult>([]);
73
54
  const searchInputRef = useRef<HTMLInputElement | null>(null);
74
- const [isSearching, setIsSearching] = useState(false);
75
- const [resultTabIndex, setResultTabIndex] = useState(0);
76
- const [currentSuggestionIndex, setCurrentSuggestionIndex] = useState(0);
77
- const pageSearcherRef = useRef<PageSearcher | null>(null);
78
- const pageSearcherConfigRef = useRef<PageSearcherConfig | null>(null);
79
- const [initStatus, setInitStatus] = useState<
80
- 'initial' | 'initing' | 'inited'
81
- >('initial');
82
55
  const searchResultRef = useRef<HTMLDivElement>(null);
83
56
  const searchResultTabRef = useRef<HTMLDivElement>(null);
84
57
  const mousePositionRef = useRef<{
@@ -125,70 +98,29 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
125
98
  }
126
99
  }
127
100
  };
128
- const {
129
- siteData,
130
- page: { lang, version },
131
- } = usePageData();
132
101
  const t = useI18n();
133
102
  const navigate = useLinkNavigate();
134
- const { search, title: siteTitle } = siteData;
135
- const versionedSearch =
136
- typeof search !== 'boolean' && (search?.versioned ?? true);
137
- const DEFAULT_RESULT = [
138
- { group: siteTitle, result: [], renderType: RenderType.Default },
139
- ];
140
- const currentSuggestions =
141
- (searchResult[resultTabIndex]?.result as DefaultMatchResultItem[]) ?? [];
142
- const currentRenderType =
143
- searchResult[resultTabIndex]?.renderType ?? RenderType.Default;
144
-
145
- if (search === false) {
146
- return null;
147
- }
148
-
149
- /**
150
- * Create page searcher instance.
151
- */
152
- const createSearcher = () => {
153
- if (pageSearcherRef.current) {
154
- return pageSearcherRef.current;
155
- }
156
-
157
- const pageSearcherConfig = {
158
- currentLang: lang,
159
- currentVersion: version,
160
- };
161
- const pageSearcher = new PageSearcher({
162
- indexName: siteTitle,
163
- ...search,
164
- ...pageSearcherConfig,
165
- });
166
- pageSearcherRef.current = pageSearcher;
167
- pageSearcherConfigRef.current = pageSearcherConfig;
168
-
169
- return pageSearcherRef.current;
170
- };
171
-
172
- /**
173
- * Call `searcher.init` to initialize the search index
174
- */
175
- async function initSearch() {
176
- if (initStatus !== 'initial') {
177
- return;
178
- }
179
103
 
180
- const searcher = createSearcher();
181
-
182
- setInitStatus('initing');
183
- await searcher.init();
184
- setInitStatus('inited');
104
+ const {
105
+ currentRenderType,
106
+ currentSuggestions,
107
+ currentSuggestionIndex,
108
+ clearQuery,
109
+ handleQueryInput,
110
+ initStatus,
111
+ isSearching,
112
+ query,
113
+ resultTabIndex,
114
+ searchError,
115
+ searchIndexURL,
116
+ searchResult,
117
+ searchEnabled,
118
+ setCurrentSuggestionIndex,
119
+ setResultTabIndex,
120
+ } = useSearchPanel({ focused, searchInputRef });
185
121
 
186
- const query = searchInputRef.current?.value;
187
- if (query) {
188
- const matched = await searcher.match(query);
189
- setSearchResult(matched || DEFAULT_RESULT);
190
- setIsSearching(false);
191
- }
122
+ if (!searchEnabled) {
123
+ return null;
192
124
  }
193
125
 
194
126
  const clearSearchState = () => {
@@ -282,114 +214,13 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
282
214
  currentSuggestionIndex,
283
215
  ]);
284
216
 
285
- useEffect(() => {
286
- if (focused) {
287
- setSearchResult(DEFAULT_RESULT);
288
- initSearch();
289
- } else {
290
- setQuery('');
291
- }
292
- }, [focused]);
293
-
294
- // Prefetch the search index when the page is idle
295
- useEffect(() => {
296
- let idleCallbackID: number | undefined;
297
- if ('requestIdleCallback' in window && !pageSearcherRef.current) {
298
- idleCallbackID = window.requestIdleCallback(() => {
299
- const searcher = createSearcher();
300
- searcher.fetchSearchIndex();
301
- });
302
- }
303
- return () => {
304
- if (idleCallbackID !== undefined && 'cancelIdleCallback' in window) {
305
- window.cancelIdleCallback(idleCallbackID);
306
- }
307
- };
308
- }, []);
309
-
310
- // init pageSearcher again when lang or version changed
311
- useEffect(() => {
312
- const { currentLang, currentVersion } = pageSearcherConfigRef.current ?? {};
313
- const isLangChanged = lang !== currentLang;
314
- const isVersionChanged = versionedSearch && version !== currentVersion;
315
-
316
- if (isLangChanged || isVersionChanged) {
317
- // reset status first
318
- setInitStatus('initial');
319
- pageSearcherRef.current = null;
320
- const searcher = createSearcher();
321
- searcher.fetchSearchIndex();
322
- }
323
- }, [lang, version, versionedSearch]);
324
-
325
- const handleQueryChangedImpl = async (value: string) => {
326
- let newQuery = value;
327
- setQuery(newQuery);
328
- if (newQuery) {
329
- const searchResult: MatchResult = [];
330
-
331
- if ('beforeSearch' in userSearchHooks) {
332
- const key = 'beforeSearch' as const;
333
- const transformedQuery = await userSearchHooks[key](newQuery);
334
- if (transformedQuery) {
335
- newQuery = transformedQuery;
336
- }
337
- }
338
-
339
- const defaultSearchResult =
340
- await pageSearcherRef.current?.match(newQuery);
341
-
342
- if (defaultSearchResult) {
343
- searchResult.push(...defaultSearchResult);
344
- }
345
-
346
- if ('onSearch' in userSearchHooks) {
347
- const key = 'onSearch' as const;
348
- const customSearchResult = await userSearchHooks[key](
349
- newQuery,
350
- searchResult as DefaultMatchResult[],
351
- );
352
- if (customSearchResult) {
353
- searchResult.push(
354
- ...customSearchResult.map(
355
- item =>
356
- ({
357
- renderType: RenderType.Custom,
358
- ...item,
359
- }) as CustomMatchResult,
360
- ),
361
- );
362
- }
363
- }
364
-
365
- if ('afterSearch' in userSearchHooks) {
366
- const key = 'afterSearch' as const;
367
- await userSearchHooks[key](newQuery, searchResult);
368
- }
369
-
370
- // only setSearchResult when query is current query value
371
- const currQuery = searchInputRef.current?.value;
372
- if (currQuery === newQuery) {
373
- // Reset current suggestion index to 0 when search query changes
374
- setCurrentSuggestionIndex(0);
375
- setSearchResult(searchResult || DEFAULT_RESULT);
376
- setIsSearching(false);
377
- }
378
- }
379
- };
380
-
381
- const handleQueryChange = useDebounce(handleQueryChangedImpl);
382
-
383
- const renderSearchResult = (result: MatchResult, isSearching: boolean) => {
217
+ const renderSearchResult = (result: MatchResult) => {
384
218
  if (result.length === 1) {
385
219
  const currentSearchResult = result[0]
386
220
  .result as DefaultMatchResult['result'];
387
- if (currentSearchResult.length === 0 && !isSearching) {
388
- return <NoSearchResult query={query} />;
389
- }
390
221
  return (
391
222
  <div ref={searchResultTabRef}>
392
- {renderSearchResultItem(currentSearchResult, query, isSearching)}
223
+ {renderSearchResultItem(currentSearchResult)}
393
224
  </div>
394
225
  );
395
226
  }
@@ -409,7 +240,7 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
409
240
  {result.map(item => (
410
241
  <Tab key={item.group} label={item.group}>
411
242
  {item.renderType === RenderType.Default &&
412
- renderSearchResultItem(item.result, query, isSearching)}
243
+ renderSearchResultItem(item.result)}
413
244
  {item.renderType === RenderType.Custom &&
414
245
  userSearchHooks[renderKey](item.result)}
415
246
  </Tab>
@@ -420,21 +251,10 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
420
251
 
421
252
  const renderSearchResultItem = (
422
253
  suggestionList: DefaultMatchResult['result'],
423
- query: string,
424
- isSearching: boolean,
425
254
  ) => {
426
- // if isSearching, show loading svg
427
- if (isSearching) {
428
- return (
429
- <div className="rp-search-panel__loading">
430
- <SvgWrapper icon={IconLoading} />
431
- </div>
432
- );
433
- }
434
-
435
- // if no result, show the no result tip
255
+ // Wait for the current search before showing the no-results message.
436
256
  if (suggestionList.length === 0 && initStatus === 'inited') {
437
- return <NoSearchResult query={query} />;
257
+ return isSearching ? null : <NoSearchResult query={query} />;
438
258
  }
439
259
 
440
260
  const normalizedSuggestions = normalizeSuggestions(suggestionList);
@@ -490,6 +310,11 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
490
310
 
491
311
  return (
492
312
  <>
313
+ {searchIndexURL && (
314
+ <Head>
315
+ <link rel="prefetch" href={searchIndexURL} />
316
+ </Head>
317
+ )}
493
318
  {focused &&
494
319
  createPortal(
495
320
  <div
@@ -508,7 +333,14 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
508
333
  <div className="rp-search-panel__header">
509
334
  <div className="rp-search-panel__input-form">
510
335
  <label>
511
- <SvgWrapper icon={IconSearch} />
336
+ <SvgWrapper
337
+ icon={IconSearch}
338
+ className={`rp-search-panel__search-icon${
339
+ initStatus === 'initing' || isSearching
340
+ ? ' rp-search-panel__search-icon--loading'
341
+ : ''
342
+ }`}
343
+ />
512
344
  </label>
513
345
  <input
514
346
  className="rp-search-panel__input"
@@ -518,7 +350,10 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
518
350
  autoComplete="off"
519
351
  autoFocus
520
352
  inputMode="search"
521
- onChange={e => handleQueryChange(e.target.value)}
353
+ onChange={e => {
354
+ const value = e.target.value;
355
+ handleQueryInput(value);
356
+ }}
522
357
  />
523
358
  <label>
524
359
  <SvgWrapper
@@ -531,7 +366,7 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
531
366
  clearSearchState();
532
367
  } else {
533
368
  searchInputRef.current.value = '';
534
- setQuery('');
369
+ clearQuery();
535
370
  }
536
371
  }
537
372
  }}
@@ -549,12 +384,19 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
549
384
  </h2>
550
385
  </div>
551
386
 
552
- {query && initStatus === 'inited' ? (
387
+ {(query || initStatus === 'error') &&
388
+ (initStatus === 'inited' || initStatus === 'error') ? (
553
389
  <div
554
390
  className="rp-search-panel__results rp-scrollbar"
555
391
  ref={searchResultRef}
556
392
  >
557
- {renderSearchResult(searchResult, isSearching)}
393
+ {initStatus === 'error' ? (
394
+ <div className="rp-search-panel__error">
395
+ Error: {searchError}
396
+ </div>
397
+ ) : (
398
+ renderSearchResult(searchResult)
399
+ )}
558
400
  </div>
559
401
  ) : null}
560
402
  </div>
@@ -44,6 +44,23 @@ type FlexSearchDocumentWithType = Document<
44
44
  false
45
45
  >;
46
46
 
47
+ export function getSearchIndexURL(
48
+ lang: string,
49
+ version: string,
50
+ ): string | undefined {
51
+ const searchIndexGroupID = `${version ?? ''}###${lang ?? ''}`;
52
+ const searchIndexHashValue = searchIndexHash[searchIndexGroupID];
53
+
54
+ // for example, in page-type-home fixture, there is only home index.md, so no search index generated
55
+ if (!searchIndexHashValue) {
56
+ return undefined;
57
+ }
58
+
59
+ const searchIndexVersion = version ? `.${version.replace('.', '_')}` : '';
60
+ const searchIndexLang = lang ? `.${lang}` : '';
61
+ return `${removeTrailingSlash(__WEBPACK_PUBLIC_PATH__)}/static/${SEARCH_INDEX_NAME}${searchIndexVersion}${searchIndexLang}.${searchIndexHashValue}.json`;
62
+ }
63
+
47
64
  const cjkRegex =
48
65
  /[\u3131-\u314e|\u314f-\u3163|\uac00-\ud7a3]|[\u4E00-\u9FCC\u3400-\u4DB5\uFA0E\uFA0F\uFA11\uFA13\uFA14\uFA1F\uFA21\uFA23\uFA24\uFA27-\uFA29]|[\ud840-\ud868][\udc00-\udfff]|\ud869[\udc00-\uded6\udf00-\udfff]|[\ud86a-\ud86c][\udc00-\udfff]|\ud86d[\udc00-\udf34\udf40-\udfff]|\ud86e[\udc00-\udc1d]|[\u3041-\u3096]|[\u30A1-\u30FA]/giu;
49
66
  const cyrillicRegex = /[\u0400-\u04FF]/g;
@@ -70,22 +87,19 @@ export class LocalProvider implements Provider {
70
87
  #fetchPromise?: Promise<PageIndexInfo[]>;
71
88
 
72
89
  async #getPages(lang: string, version: string): Promise<PageIndexInfo[]> {
73
- const searchIndexGroupID = `${version ?? ''}###${lang ?? ''}`;
74
-
75
- // for example, in page-type-home fixture, there is only home index.md, so no search index generated
76
- if (!searchIndexHash[searchIndexGroupID]) {
90
+ const searchIndexURL = getSearchIndexURL(lang, version);
91
+ if (!searchIndexURL) {
77
92
  return [];
78
93
  }
79
94
 
80
- const searchIndexVersion = version ? `.${version.replace('.', '_')}` : '';
81
- const searchIndexLang = lang ? `.${lang}` : '';
82
- const searchIndexURL = `${removeTrailingSlash(__WEBPACK_PUBLIC_PATH__)}/static/${SEARCH_INDEX_NAME}${searchIndexVersion}${searchIndexLang}.${searchIndexHash[searchIndexGroupID]}.json`;
83
-
84
- const handleError = (result: unknown) => {
95
+ const handleError = (result: unknown): never => {
85
96
  console.error(
86
97
  'Failed to fetch search index, please reload the page and try again.',
87
98
  );
88
99
  console.error(result);
100
+ throw result instanceof Error
101
+ ? result
102
+ : new Error('Failed to fetch search index');
89
103
  };
90
104
 
91
105
  try {
@@ -93,11 +107,10 @@ export class LocalProvider implements Provider {
93
107
  if (result.ok) {
94
108
  return result.json();
95
109
  }
96
- handleError(result);
110
+ throw result;
97
111
  } catch (error) {
98
- handleError(error);
112
+ return handleError(error);
99
113
  }
100
- return [];
101
114
  }
102
115
 
103
116
  async fetchSearchIndex(options: SearchOptions) {
@@ -144,7 +157,12 @@ export class LocalProvider implements Provider {
144
157
  };
145
158
  // Init Search Indexes
146
159
  // English Index
147
- this.#index = new Document(createOptions);
160
+ this.#index = new Document({
161
+ ...createOptions,
162
+ // Limit token length for performance: https://github.com/web-infra-dev/rspress/pull/3682
163
+ // cspell:ignore maxlength
164
+ encoder: { maxlength: 64 },
165
+ });
148
166
  // CJK: Chinese, Japanese, Korean
149
167
  this.#cjkIndex = new Document({
150
168
  ...createOptions,
@@ -160,14 +178,18 @@ export class LocalProvider implements Provider {
160
178
  str.flatMap(s => tokenize(s, cyrillicRegex)),
161
179
  },
162
180
  });
181
+ const pending: Promise<unknown>[] = [];
163
182
  for (const item of pagesForSearch) {
164
183
  // Add search index async to avoid blocking the main thread
165
184
  // Type assertion: PageIndexForFlexSearch is compatible with FlexSearchCompatibleData at runtime
166
185
  const flexSearchItem = item as unknown as FlexSearchCompatibleData;
167
- this.#index!.addAsync(item.routePath, flexSearchItem);
168
- this.#cjkIndex!.addAsync(item.routePath, flexSearchItem);
169
- this.#cyrillicIndex!.addAsync(item.routePath, flexSearchItem);
186
+ pending.push(
187
+ this.#index!.addAsync(item.routePath, flexSearchItem),
188
+ this.#cjkIndex!.addAsync(item.routePath, flexSearchItem),
189
+ this.#cyrillicIndex!.addAsync(item.routePath, flexSearchItem),
190
+ );
170
191
  }
192
+ await Promise.all(pending);
171
193
  }
172
194
 
173
195
  async search(query: SearchQuery) {
@@ -0,0 +1,216 @@
1
+ import { usePageData } from '@rspress/core/runtime';
2
+ import type { LocalSearchOptions } from '@rspress/core';
3
+ import { debounce } from '@rspress/shared/lodash-es';
4
+ import {
5
+ useCallback,
6
+ useEffect,
7
+ useRef,
8
+ useState,
9
+ type RefObject,
10
+ } from 'react';
11
+ import * as userSearchHooks from 'virtual-search-hooks';
12
+ import { getSearchIndexURL } from './logic/providers/LocalProvider';
13
+ import { PageSearcher } from './logic/search';
14
+ import type {
15
+ CustomMatchResult,
16
+ DefaultMatchResult,
17
+ MatchResult,
18
+ PageSearcherConfig,
19
+ } from './logic/types';
20
+ import { RenderType } from './logic/types';
21
+
22
+ const useDebounce = <T extends (...args: any[]) => any>(cb: T) => {
23
+ const cbRef = useRef(cb);
24
+ cbRef.current = cb;
25
+ return useCallback(
26
+ debounce(
27
+ ((...args: Parameters<T>): ReturnType<T> => cbRef.current(...args)) as T,
28
+ 150,
29
+ ),
30
+ [],
31
+ );
32
+ };
33
+
34
+ export function useSearchPanel({
35
+ focused,
36
+ searchInputRef,
37
+ }: {
38
+ focused: boolean;
39
+ searchInputRef: RefObject<HTMLInputElement | null>;
40
+ }) {
41
+ const {
42
+ siteData,
43
+ page: { lang, version },
44
+ } = usePageData();
45
+ const { search, title: siteTitle } = siteData;
46
+ const [query, setQuery] = useState('');
47
+ const [searchResult, setSearchResult] = useState<MatchResult>([]);
48
+ const [isSearching, setIsSearching] = useState(false);
49
+ const [resultTabIndex, setResultTabIndex] = useState(0);
50
+ const [currentSuggestionIndex, setCurrentSuggestionIndex] = useState(0);
51
+ const [initStatus, setInitStatus] = useState<
52
+ 'initial' | 'initing' | 'inited' | 'error'
53
+ >('initial');
54
+ const [searchError, setSearchError] = useState<string>();
55
+ const pageSearcherRef = useRef<PageSearcher | null>(null);
56
+ const pageSearcherConfigRef = useRef<PageSearcherConfig | null>(null);
57
+ const searchEnabled = search !== false;
58
+ const searchOptions: LocalSearchOptions = search === false ? {} : search;
59
+ const versionedSearch = searchEnabled && (search?.versioned ?? true);
60
+ const searchIndexURL = searchEnabled
61
+ ? getSearchIndexURL(lang, versionedSearch ? version : '')
62
+ : undefined;
63
+ const DEFAULT_RESULT = [
64
+ { group: siteTitle, result: [], renderType: RenderType.Default },
65
+ ];
66
+
67
+ const createSearcher = () => {
68
+ if (pageSearcherRef.current) {
69
+ return pageSearcherRef.current;
70
+ }
71
+ const pageSearcherConfig = { currentLang: lang, currentVersion: version };
72
+ const pageSearcher = new PageSearcher({
73
+ indexName: siteTitle,
74
+ ...searchOptions,
75
+ ...pageSearcherConfig,
76
+ });
77
+ pageSearcherRef.current = pageSearcher;
78
+ pageSearcherConfigRef.current = pageSearcherConfig;
79
+ return pageSearcher;
80
+ };
81
+
82
+ const initSearch = async () => {
83
+ if (initStatus !== 'initial') {
84
+ return;
85
+ }
86
+ const searcher = createSearcher();
87
+ setSearchError(undefined);
88
+ setInitStatus('initing');
89
+ try {
90
+ await searcher.init();
91
+ } catch (error) {
92
+ if (pageSearcherRef.current !== searcher) {
93
+ return;
94
+ }
95
+ setSearchError(error instanceof Error ? error.message : String(error));
96
+ setInitStatus('error');
97
+ setIsSearching(false);
98
+ return;
99
+ }
100
+ if (pageSearcherRef.current !== searcher) {
101
+ return;
102
+ }
103
+ setInitStatus('inited');
104
+ const currentQuery = searchInputRef.current?.value;
105
+ if (currentQuery) {
106
+ const matched = await searcher.match(currentQuery);
107
+ if (
108
+ pageSearcherRef.current !== searcher ||
109
+ searchInputRef.current?.value !== currentQuery
110
+ ) {
111
+ return;
112
+ }
113
+ setSearchResult(matched || DEFAULT_RESULT);
114
+ setIsSearching(false);
115
+ }
116
+ };
117
+
118
+ useEffect(() => {
119
+ if (!searchEnabled) {
120
+ return;
121
+ }
122
+ if (focused) {
123
+ setSearchResult(DEFAULT_RESULT);
124
+ initSearch();
125
+ } else {
126
+ setQuery('');
127
+ }
128
+ }, [focused, searchEnabled]);
129
+
130
+ useEffect(() => {
131
+ if (!searchEnabled) {
132
+ return;
133
+ }
134
+ const { currentLang, currentVersion } = pageSearcherConfigRef.current ?? {};
135
+ const isLangChanged = lang !== currentLang;
136
+ const isVersionChanged = versionedSearch && version !== currentVersion;
137
+ if (isLangChanged || isVersionChanged) {
138
+ setInitStatus('initial');
139
+ setSearchError(undefined);
140
+ setIsSearching(false);
141
+ pageSearcherRef.current = null;
142
+ createSearcher()
143
+ .fetchSearchIndex()
144
+ .catch(() => {});
145
+ }
146
+ }, [lang, version, versionedSearch, searchEnabled]);
147
+
148
+ const handleQueryChangedImpl = async (value: string) => {
149
+ let newQuery = value;
150
+ setQuery(newQuery);
151
+ if (!newQuery) {
152
+ setIsSearching(false);
153
+ return;
154
+ }
155
+ const result: MatchResult = [];
156
+ if ('beforeSearch' in userSearchHooks) {
157
+ const transformedQuery = await userSearchHooks.beforeSearch(newQuery);
158
+ if (transformedQuery) newQuery = transformedQuery;
159
+ }
160
+ const defaultSearchResult = await pageSearcherRef.current?.match(newQuery);
161
+ if (defaultSearchResult) result.push(...defaultSearchResult);
162
+ if ('onSearch' in userSearchHooks) {
163
+ const customSearchResult = await userSearchHooks.onSearch(
164
+ newQuery,
165
+ result as DefaultMatchResult[],
166
+ );
167
+ if (customSearchResult) {
168
+ result.push(
169
+ ...customSearchResult.map(
170
+ item =>
171
+ ({ renderType: RenderType.Custom, ...item }) as CustomMatchResult,
172
+ ),
173
+ );
174
+ }
175
+ }
176
+ if ('afterSearch' in userSearchHooks) {
177
+ await userSearchHooks.afterSearch(newQuery, result);
178
+ }
179
+ if (searchInputRef.current?.value === newQuery) {
180
+ setCurrentSuggestionIndex(0);
181
+ setSearchResult(result || DEFAULT_RESULT);
182
+ setIsSearching(false);
183
+ }
184
+ };
185
+
186
+ const handleQueryChange = useDebounce(handleQueryChangedImpl);
187
+ const handleQueryInput = (value: string) => {
188
+ setIsSearching(Boolean(value));
189
+ handleQueryChange(value);
190
+ };
191
+ const clearQuery = () => {
192
+ setQuery('');
193
+ setIsSearching(false);
194
+ };
195
+
196
+ return {
197
+ searchEnabled,
198
+ clearQuery,
199
+ currentRenderType:
200
+ searchResult[resultTabIndex]?.renderType ?? RenderType.Default,
201
+ currentSuggestions:
202
+ (searchResult[resultTabIndex]?.result as DefaultMatchResult['result']) ??
203
+ [],
204
+ handleQueryInput,
205
+ initStatus,
206
+ isSearching,
207
+ resultTabIndex,
208
+ searchError,
209
+ searchIndexURL,
210
+ searchResult,
211
+ query,
212
+ currentSuggestionIndex,
213
+ setCurrentSuggestionIndex,
214
+ setResultTabIndex,
215
+ };
216
+ }
@@ -11,7 +11,7 @@
11
11
  padding-left: var(--rp-steps-gap);
12
12
  counter-reset: step;
13
13
 
14
- h3 {
14
+ > :is(h2, h3, h4, h5, h6) {
15
15
  counter-increment: step;
16
16
  margin-top: 0;
17
17
  position: relative;