@rspress/core 2.0.21 → 2.0.23

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/bin/rspress.js +3 -1
  2. package/dist/{2711~0.js → a~0.js} +90 -70
  3. package/dist/{8472~0.js → b~0.js} +19 -14
  4. package/dist/cli/index.js +12 -13
  5. package/dist/config/loadConfigFile.d.ts +3 -4
  6. package/dist/config/loadConfigFile.js +13 -17
  7. package/dist/{7748~0.js → d~0.js} +0 -2
  8. package/dist/eject-theme/components/Llms/LlmsHint.test.tsx +8 -0
  9. package/dist/eject-theme/components/Llms/LlmsHint.tsx +11 -3
  10. package/dist/eject-theme/components/Nav/NavMenu.scss +4 -0
  11. package/dist/eject-theme/components/Nav/NavMenu.tsx +20 -13
  12. package/dist/eject-theme/components/Nav/index.tsx +30 -4
  13. package/dist/eject-theme/components/NavHamburger/index.tsx +11 -3
  14. package/dist/eject-theme/components/NavList/context.ts +3 -0
  15. package/dist/eject-theme/components/NavList/index.tsx +24 -0
  16. package/dist/eject-theme/components/NavScreen/NavScreenMenu.test.tsx +59 -0
  17. package/dist/eject-theme/components/NavScreen/NavScreenMenu.tsx +43 -2
  18. package/dist/eject-theme/components/NavScreen/index.scss +0 -6
  19. package/dist/eject-theme/components/NavScreen/index.tsx +20 -3
  20. package/dist/eject-theme/components/ReadPercent/useReadPercent.ts +1 -1
  21. package/dist/eject-theme/components/Search/SearchButton.scss +1 -0
  22. package/dist/eject-theme/components/Search/SearchPanel.scss +51 -12
  23. package/dist/eject-theme/components/Search/SearchPanel.tsx +62 -216
  24. package/dist/eject-theme/components/Search/logic/providers/LocalProvider.ts +39 -17
  25. package/dist/eject-theme/components/Search/useSearchPanel.ts +217 -0
  26. package/dist/eject-theme/components/SocialLinks/SocialLink.tsx +2 -2
  27. package/dist/eject-theme/components/SourceCode/index.tsx +1 -1
  28. package/dist/eject-theme/components/Steps/index.scss +1 -1
  29. package/dist/eject-theme/components/SwitchAppearance/getClipPath.test.ts +15 -0
  30. package/dist/eject-theme/components/SwitchAppearance/getClipPath.ts +26 -0
  31. package/dist/eject-theme/components/SwitchAppearance/index.tsx +22 -26
  32. package/dist/eject-theme/components/Tabs/index.tsx +14 -14
  33. package/dist/index.js +1 -1
  34. package/dist/node/PluginDriver.d.ts +1 -1
  35. package/dist/node/PluginDriver.js +5 -9
  36. package/dist/node/auto-nav-sidebar/index.js +1 -1
  37. package/dist/node/auto-nav-sidebar/locales.js +1 -1
  38. package/dist/node/auto-nav-sidebar/normalize.js +6 -6
  39. package/dist/node/auto-nav-sidebar/utils.js +1 -1
  40. package/dist/node/auto-nav-sidebar/walk.js +1 -1
  41. package/dist/node/build.d.ts +3 -2
  42. package/dist/node/build.js +9 -3
  43. package/dist/node/constants.js +1 -1
  44. package/dist/node/dev.d.ts +4 -4
  45. package/dist/node/dev.js +8 -6
  46. package/dist/node/eject.js +5 -5
  47. package/dist/node/initRsbuild.d.ts +2 -3
  48. package/dist/node/initRsbuild.js +9 -7
  49. package/dist/node/last-updated/index.js +2 -2
  50. package/dist/node/logger/hint.js +4 -4
  51. package/dist/node/mdx/options.js +1 -1
  52. package/dist/node/mdx/processor.js +3 -3
  53. package/dist/node/mdx/rehypePlugins/codeMeta.js +1 -1
  54. package/dist/node/mdx/rehypePlugins/headerAnchor.js +1 -1
  55. package/dist/node/mdx/rehypePlugins/shiki.js +1 -1
  56. package/dist/node/mdx/remarkPlugins/builtin.js +1 -1
  57. package/dist/node/mdx/remarkPlugins/containerSyntax.js +6 -5
  58. package/dist/node/mdx/remarkPlugins/fileCodeBlock.js +5 -5
  59. package/dist/node/mdx/remarkPlugins/image.js +5 -5
  60. package/dist/node/mdx/remarkPlugins/link.js +5 -5
  61. package/dist/node/mdx/remarkPlugins/toc.js +1 -1
  62. package/dist/node/medium-zoom/index.js +1 -1
  63. package/dist/node/route/RoutePage.js +6 -4
  64. package/dist/node/route/RouteService.js +3 -3
  65. package/dist/node/route/extractPageData.js +20 -7
  66. package/dist/node/route/normalizeRoutePath.js +1 -1
  67. package/dist/node/runtimeModule/i18n.js +5 -5
  68. package/dist/node/runtimeModule/pageData/createPageData.js +1 -1
  69. package/dist/node/runtimeModule/pageData/rsbuildPlugin.js +1 -1
  70. package/dist/node/runtimeModule/searchHooks.js +1 -1
  71. package/dist/node/runtimeModule/siteData/createSiteData.js +1 -1
  72. package/dist/node/runtimeModule/siteData/normalizeThemeConfig.js +1 -1
  73. package/dist/node/runtimeModule/siteData/rsbuildPlugin.js +1 -1
  74. package/dist/node/serve.d.ts +3 -3
  75. package/dist/node/serve.js +10 -4
  76. package/dist/node/ssg/alternateLinks.js +1 -1
  77. package/dist/node/ssg/htmlFile.js +1 -1
  78. package/dist/node/ssg/renderHtmlTemplate.js +4 -3
  79. package/dist/node/ssg/renderPage.js +5 -5
  80. package/dist/node/ssg/renderPageWorker.js +2 -2
  81. package/dist/node/ssg/renderPages.js +6 -6
  82. package/dist/node/ssg/rsbuildPluginSSG.js +1 -1
  83. package/dist/node/ssg/ssgEnv.js +1 -1
  84. package/dist/node/ssg-md/llms/emitLlmsTxt.js +1 -1
  85. package/dist/node/ssg-md/llms/llmsTxt.js +1 -1
  86. package/dist/node/ssg-md/remarkSplitMdx.js +1 -1
  87. package/dist/node/ssg-md/renderPage.js +5 -5
  88. package/dist/node/ssg-md/renderPages.js +6 -6
  89. package/dist/node/ssg-md/rsbuildPluginSSGMD.js +1 -1
  90. package/dist/node/utils/checkLanguageParity.js +5 -7
  91. package/dist/node/utils/createHash.js +1 -1
  92. package/dist/node/utils/error.js +4 -4
  93. package/dist/node/utils/flattenMdxContent.js +2 -2
  94. package/dist/node/utils/fs.js +1 -1
  95. package/dist/node/utils/getPageKey.js +1 -1
  96. package/dist/node/utils/index.d.ts +1 -1
  97. package/dist/node/utils/reactAlias.js +5 -5
  98. package/dist/node/utils/slash.d.ts +1 -0
  99. package/dist/node/utils/slash.js +4 -0
  100. package/dist/{864~0.js → n~0.js} +42 -41
  101. package/dist/rslib-runtime~0.js +27 -35
  102. package/dist/runtime/App.js +3 -2
  103. package/dist/runtime/hooks/createExternalStore.d.ts +4 -0
  104. package/dist/runtime/hooks/createExternalStore.js +20 -0
  105. package/dist/runtime/hooks/useGlobalComponents.d.ts +1 -0
  106. package/dist/runtime/hooks/useGlobalComponents.js +10 -0
  107. package/dist/runtime/hooks/useI18n.js +5 -3
  108. package/dist/runtime/hooks/useI18nText.d.ts +1 -0
  109. package/dist/runtime/hooks/useI18nText.js +10 -0
  110. package/dist/runtime/hooks/usePages.d.ts +2 -0
  111. package/dist/runtime/hooks/usePages.js +12 -3
  112. package/dist/runtime/hooks/useSearchHooks.d.ts +8 -0
  113. package/dist/runtime/hooks/useSearchHooks.js +14 -0
  114. package/dist/runtime/hooks/useSite.d.ts +1 -0
  115. package/dist/runtime/hooks/useSite.js +9 -2
  116. package/dist/runtime/index.d.ts +3 -1
  117. package/dist/runtime/index.js +5 -1
  118. package/dist/runtime/initPageData.js +10 -10
  119. package/dist/runtime/route.js +5 -5
  120. package/dist/runtime/utils.js +6 -6
  121. package/dist/theme/components/Link/useLinkNavigate.js +1 -1
  122. package/dist/theme/components/Llms/LlmsHint.js +23 -6
  123. package/dist/theme/components/Nav/NavMenu.css +4 -0
  124. package/dist/theme/components/Nav/NavMenu.d.ts +4 -2
  125. package/dist/theme/components/Nav/NavMenu.js +17 -9
  126. package/dist/theme/components/Nav/index.d.ts +7 -1
  127. package/dist/theme/components/Nav/index.js +13 -4
  128. package/dist/theme/components/NavHamburger/index.d.ts +2 -1
  129. package/dist/theme/components/NavHamburger/index.js +8 -2
  130. package/dist/theme/components/NavList/context.d.ts +1 -0
  131. package/dist/theme/components/NavList/context.js +3 -0
  132. package/dist/theme/components/NavList/index.d.ts +6 -0
  133. package/dist/theme/components/NavList/index.js +17 -0
  134. package/dist/theme/components/NavScreen/NavScreenMenu.d.ts +3 -2
  135. package/dist/theme/components/NavScreen/NavScreenMenu.js +42 -6
  136. package/dist/theme/components/NavScreen/index.css +0 -10
  137. package/dist/theme/components/NavScreen/index.d.ts +2 -1
  138. package/dist/theme/components/NavScreen/index.js +11 -3
  139. package/dist/theme/components/PackageManagerTabs/index.js +2 -2
  140. package/dist/theme/components/ReadPercent/useReadPercent.js +1 -0
  141. package/dist/theme/components/Search/SearchButton.css +1 -0
  142. package/dist/theme/components/Search/SearchPanel.css +47 -9
  143. package/dist/theme/components/Search/SearchPanel.js +104 -210
  144. package/dist/theme/components/Search/logic/providers/LocalProvider.d.ts +1 -0
  145. package/dist/theme/components/Search/logic/providers/LocalProvider.js +24 -14
  146. package/dist/theme/components/Search/logic/search.js +1 -1
  147. package/dist/theme/components/Search/useSearchPanel.d.ts +23 -0
  148. package/dist/theme/components/Search/useSearchPanel.js +155 -0
  149. package/dist/theme/components/SocialLinks/SocialLink.js +2 -2
  150. package/dist/theme/components/SourceCode/index.js +1 -1
  151. package/dist/theme/components/Steps/index.css +3 -3
  152. package/dist/theme/components/SwitchAppearance/getClipPath.d.ts +8 -0
  153. package/dist/theme/components/SwitchAppearance/getClipPath.js +13 -0
  154. package/dist/theme/components/SwitchAppearance/index.js +9 -7
  155. package/dist/theme/components/Tabs/index.js +4 -4
  156. package/dist/theme/components/Tag/index.js +2 -2
  157. package/dist/theme/index.d.ts +1 -0
  158. package/dist/theme/index.js +1 -0
  159. package/dist/theme/layout/DocLayout/index.js +2 -2
  160. package/dist/theme/layout/Layout/index.js +12 -4
  161. package/dist/theme/logic/useFullTextSearch.js +6 -1
  162. package/dist/theme/logic/utils.d.ts +0 -2
  163. package/dist/theme/logic/utils.js +56 -6
  164. package/dist/theme/styles/vars/shiki-vars.css +1 -1
  165. package/dist/tinypool~0.js +5 -3
  166. package/dist/{4538~0.js → t~0.js} +2 -2
  167. package/package.json +15 -16
  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, useSearchHooks } 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
- import * as userSearchHooks from 'virtual-search-hooks';
15
- import { PageSearcher } from './logic/search';
12
+
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,30 @@ 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();
102
+ const userSearchHooks = useSearchHooks();
133
103
  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
104
 
180
- const searcher = createSearcher();
181
-
182
- setInitStatus('initing');
183
- await searcher.init();
184
- setInitStatus('inited');
105
+ const {
106
+ currentRenderType,
107
+ currentSuggestions,
108
+ currentSuggestionIndex,
109
+ clearQuery,
110
+ handleQueryInput,
111
+ initStatus,
112
+ isSearching,
113
+ query,
114
+ resultTabIndex,
115
+ searchError,
116
+ searchIndexURL,
117
+ searchResult,
118
+ searchEnabled,
119
+ setCurrentSuggestionIndex,
120
+ setResultTabIndex,
121
+ } = useSearchPanel({ focused, searchInputRef });
185
122
 
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
- }
123
+ if (!searchEnabled) {
124
+ return null;
192
125
  }
193
126
 
194
127
  const clearSearchState = () => {
@@ -250,6 +183,7 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
250
183
  return;
251
184
  }
252
185
  if (
186
+ focused &&
253
187
  currentSuggestionIndex >= 0 &&
254
188
  currentRenderType === RenderType.Default
255
189
  ) {
@@ -258,8 +192,10 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
258
192
  normalizeSuggestions(currentSuggestions).values(),
259
193
  ).flat();
260
194
  const suggestion = flatSuggestions[currentSuggestionIndex];
261
- navigate(suggestion.link);
262
- clearSearchState();
195
+ if (suggestion) {
196
+ navigate(suggestion.link);
197
+ clearSearchState();
198
+ }
263
199
  }
264
200
  break;
265
201
  case KEY_CODE.ESC:
@@ -282,114 +218,13 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
282
218
  currentSuggestionIndex,
283
219
  ]);
284
220
 
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) => {
221
+ const renderSearchResult = (result: MatchResult) => {
384
222
  if (result.length === 1) {
385
223
  const currentSearchResult = result[0]
386
224
  .result as DefaultMatchResult['result'];
387
- if (currentSearchResult.length === 0 && !isSearching) {
388
- return <NoSearchResult query={query} />;
389
- }
390
225
  return (
391
226
  <div ref={searchResultTabRef}>
392
- {renderSearchResultItem(currentSearchResult, query, isSearching)}
227
+ {renderSearchResultItem(currentSearchResult)}
393
228
  </div>
394
229
  );
395
230
  }
@@ -409,9 +244,9 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
409
244
  {result.map(item => (
410
245
  <Tab key={item.group} label={item.group}>
411
246
  {item.renderType === RenderType.Default &&
412
- renderSearchResultItem(item.result, query, isSearching)}
247
+ renderSearchResultItem(item.result)}
413
248
  {item.renderType === RenderType.Custom &&
414
- userSearchHooks[renderKey](item.result)}
249
+ userSearchHooks[renderKey]?.(item.result)}
415
250
  </Tab>
416
251
  ))}
417
252
  </Tabs>
@@ -420,21 +255,10 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
420
255
 
421
256
  const renderSearchResultItem = (
422
257
  suggestionList: DefaultMatchResult['result'],
423
- query: string,
424
- isSearching: boolean,
425
258
  ) => {
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
259
+ // Wait for the current search before showing the no-results message.
436
260
  if (suggestionList.length === 0 && initStatus === 'inited') {
437
- return <NoSearchResult query={query} />;
261
+ return isSearching ? null : <NoSearchResult query={query} />;
438
262
  }
439
263
 
440
264
  const normalizedSuggestions = normalizeSuggestions(suggestionList);
@@ -490,6 +314,11 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
490
314
 
491
315
  return (
492
316
  <>
317
+ {searchIndexURL && (
318
+ <Head>
319
+ <link rel="prefetch" href={searchIndexURL} />
320
+ </Head>
321
+ )}
493
322
  {focused &&
494
323
  createPortal(
495
324
  <div
@@ -508,7 +337,14 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
508
337
  <div className="rp-search-panel__header">
509
338
  <div className="rp-search-panel__input-form">
510
339
  <label>
511
- <SvgWrapper icon={IconSearch} />
340
+ <SvgWrapper
341
+ icon={IconSearch}
342
+ className={`rp-search-panel__search-icon${
343
+ initStatus === 'initing' || isSearching
344
+ ? ' rp-search-panel__search-icon--loading'
345
+ : ''
346
+ }`}
347
+ />
512
348
  </label>
513
349
  <input
514
350
  className="rp-search-panel__input"
@@ -518,7 +354,10 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
518
354
  autoComplete="off"
519
355
  autoFocus
520
356
  inputMode="search"
521
- onChange={e => handleQueryChange(e.target.value)}
357
+ onChange={e => {
358
+ const value = e.target.value;
359
+ handleQueryInput(value);
360
+ }}
522
361
  />
523
362
  <label>
524
363
  <SvgWrapper
@@ -531,7 +370,7 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
531
370
  clearSearchState();
532
371
  } else {
533
372
  searchInputRef.current.value = '';
534
- setQuery('');
373
+ clearQuery();
535
374
  }
536
375
  }
537
376
  }}
@@ -549,12 +388,19 @@ export function SearchPanel({ focused, setFocused }: SearchPanelProps) {
549
388
  </h2>
550
389
  </div>
551
390
 
552
- {query && initStatus === 'inited' ? (
391
+ {(query || initStatus === 'error') &&
392
+ (initStatus === 'inited' || initStatus === 'error') ? (
553
393
  <div
554
394
  className="rp-search-panel__results rp-scrollbar"
555
395
  ref={searchResultRef}
556
396
  >
557
- {renderSearchResult(searchResult, isSearching)}
397
+ {initStatus === 'error' ? (
398
+ <div className="rp-search-panel__error">
399
+ Error: {searchError}
400
+ </div>
401
+ ) : (
402
+ renderSearchResult(searchResult)
403
+ )}
558
404
  </div>
559
405
  ) : null}
560
406
  </div>
@@ -15,7 +15,7 @@ import {
15
15
  type DocumentValue,
16
16
  type EnrichedDocumentSearchResults,
17
17
  } from 'flexsearch';
18
- import { searchIndexHash } from 'virtual-page-data';
18
+ import { searchIndexHash } from '@rspress/core/runtime';
19
19
  import { LOCAL_INDEX, type Provider, type SearchQuery } from '../Provider';
20
20
  import type { SearchOptions } from '../types';
21
21
  import { normalizeTextCase } from '../util';
@@ -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) {