@docusaurus/theme-common 2.0.0-beta.2 → 2.0.0-beta.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 (272) hide show
  1. package/lib/components/Collapsible/index.d.ts +64 -0
  2. package/lib/components/Collapsible/index.d.ts.map +1 -0
  3. package/lib/components/Collapsible/index.js +150 -0
  4. package/lib/components/Collapsible/index.js.map +1 -0
  5. package/lib/components/Details/index.d.ts +17 -0
  6. package/lib/components/Details/index.d.ts.map +1 -0
  7. package/lib/components/Details/index.js +76 -0
  8. package/lib/components/Details/index.js.map +1 -0
  9. package/lib/components/Details/styles.module.css +62 -0
  10. package/lib/contexts/announcementBar.d.ts +22 -0
  11. package/lib/contexts/announcementBar.d.ts.map +1 -0
  12. package/lib/{utils/announcementBarUtils.js → contexts/announcementBar.js} +30 -31
  13. package/lib/contexts/announcementBar.js.map +1 -0
  14. package/lib/contexts/blogPost.d.ts +33 -0
  15. package/lib/contexts/blogPost.d.ts.map +1 -0
  16. package/lib/contexts/blogPost.js +46 -0
  17. package/lib/contexts/blogPost.js.map +1 -0
  18. package/lib/contexts/colorMode.d.ts +27 -0
  19. package/lib/contexts/colorMode.d.ts.map +1 -0
  20. package/lib/contexts/colorMode.js +132 -0
  21. package/lib/contexts/colorMode.js.map +1 -0
  22. package/lib/contexts/doc.d.ts +30 -0
  23. package/lib/contexts/doc.d.ts.map +1 -0
  24. package/lib/contexts/doc.js +48 -0
  25. package/lib/contexts/doc.js.map +1 -0
  26. package/lib/contexts/docSidebarItemsExpandedState.d.ts +31 -0
  27. package/lib/contexts/docSidebarItemsExpandedState.d.ts.map +1 -0
  28. package/lib/contexts/docSidebarItemsExpandedState.js +28 -0
  29. package/lib/contexts/docSidebarItemsExpandedState.js.map +1 -0
  30. package/lib/contexts/docsPreferredVersion.d.ts +30 -0
  31. package/lib/contexts/docsPreferredVersion.d.ts.map +1 -0
  32. package/lib/contexts/docsPreferredVersion.js +130 -0
  33. package/lib/contexts/docsPreferredVersion.js.map +1 -0
  34. package/lib/contexts/docsSidebar.d.ts +26 -0
  35. package/lib/contexts/docsSidebar.d.ts.map +1 -0
  36. package/lib/contexts/docsSidebar.js +30 -0
  37. package/lib/contexts/docsSidebar.js.map +1 -0
  38. package/lib/contexts/docsVersion.d.ts +20 -0
  39. package/lib/contexts/docsVersion.d.ts.map +1 -0
  40. package/lib/contexts/docsVersion.js +26 -0
  41. package/lib/contexts/docsVersion.js.map +1 -0
  42. package/lib/contexts/navbarMobileSidebar.d.ts +31 -0
  43. package/lib/contexts/navbarMobileSidebar.d.ts.map +1 -0
  44. package/lib/contexts/navbarMobileSidebar.js +56 -0
  45. package/lib/contexts/navbarMobileSidebar.js.map +1 -0
  46. package/lib/contexts/navbarSecondaryMenu/content.d.ts +37 -0
  47. package/lib/contexts/navbarSecondaryMenu/content.d.ts.map +1 -0
  48. package/lib/contexts/navbarSecondaryMenu/content.js +50 -0
  49. package/lib/contexts/navbarSecondaryMenu/content.js.map +1 -0
  50. package/lib/contexts/navbarSecondaryMenu/display.d.ts +24 -0
  51. package/lib/contexts/navbarSecondaryMenu/display.d.ts.map +1 -0
  52. package/lib/contexts/navbarSecondaryMenu/display.js +62 -0
  53. package/lib/contexts/navbarSecondaryMenu/display.js.map +1 -0
  54. package/lib/contexts/tabGroupChoice.d.ts +21 -0
  55. package/lib/contexts/tabGroupChoice.d.ts.map +1 -0
  56. package/lib/contexts/tabGroupChoice.js +49 -0
  57. package/lib/contexts/tabGroupChoice.js.map +1 -0
  58. package/lib/{utils/usePrevious.d.ts → hooks/styles.css} +4 -1
  59. package/lib/hooks/useBackToTopButton.d.ts +27 -0
  60. package/lib/hooks/useBackToTopButton.d.ts.map +1 -0
  61. package/lib/hooks/useBackToTopButton.js +50 -0
  62. package/lib/hooks/useBackToTopButton.js.map +1 -0
  63. package/lib/hooks/useCodeWordWrap.d.ts +14 -0
  64. package/lib/hooks/useCodeWordWrap.d.ts.map +1 -0
  65. package/lib/hooks/useCodeWordWrap.js +67 -0
  66. package/lib/hooks/useCodeWordWrap.js.map +1 -0
  67. package/lib/hooks/useHideableNavbar.d.ts +17 -0
  68. package/lib/hooks/useHideableNavbar.d.ts.map +1 -0
  69. package/lib/hooks/useHideableNavbar.js +60 -0
  70. package/lib/hooks/useHideableNavbar.js.map +1 -0
  71. package/lib/hooks/useKeyboardNavigation.d.ts +20 -0
  72. package/lib/hooks/useKeyboardNavigation.d.ts.map +1 -0
  73. package/lib/hooks/useKeyboardNavigation.js +39 -0
  74. package/lib/hooks/useKeyboardNavigation.js.map +1 -0
  75. package/lib/hooks/useLockBodyScroll.d.ts +12 -0
  76. package/lib/hooks/useLockBodyScroll.d.ts.map +1 -0
  77. package/lib/hooks/useLockBodyScroll.js +20 -0
  78. package/lib/hooks/useLockBodyScroll.js.map +1 -0
  79. package/lib/hooks/useMutationObserver.d.ts +4 -0
  80. package/lib/hooks/useMutationObserver.d.ts.map +1 -0
  81. package/lib/hooks/useMutationObserver.js +29 -0
  82. package/lib/hooks/useMutationObserver.js.map +1 -0
  83. package/lib/hooks/usePrismTheme.d.ts +13 -0
  84. package/lib/hooks/usePrismTheme.d.ts.map +1 -0
  85. package/lib/hooks/usePrismTheme.js +21 -0
  86. package/lib/hooks/usePrismTheme.js.map +1 -0
  87. package/lib/hooks/useSearchPage.d.ts +25 -0
  88. package/lib/hooks/useSearchPage.d.ts.map +1 -0
  89. package/lib/hooks/useSearchPage.js +43 -0
  90. package/lib/hooks/useSearchPage.js.map +1 -0
  91. package/lib/hooks/useSkipToContent.d.ts +25 -0
  92. package/lib/hooks/useSkipToContent.d.ts.map +1 -0
  93. package/lib/hooks/useSkipToContent.js +35 -0
  94. package/lib/hooks/useSkipToContent.js.map +1 -0
  95. package/lib/hooks/useTOCHighlight.d.ts +25 -0
  96. package/lib/hooks/useTOCHighlight.d.ts.map +1 -0
  97. package/lib/hooks/useTOCHighlight.js +130 -0
  98. package/lib/hooks/useTOCHighlight.js.map +1 -0
  99. package/lib/hooks/useWindowSize.d.ts +28 -0
  100. package/lib/hooks/useWindowSize.d.ts.map +1 -0
  101. package/lib/hooks/useWindowSize.js +59 -0
  102. package/lib/hooks/useWindowSize.js.map +1 -0
  103. package/lib/index.d.ts +16 -13
  104. package/lib/index.d.ts.map +1 -0
  105. package/lib/index.js +23 -12
  106. package/lib/index.js.map +1 -0
  107. package/lib/internal.d.ts +41 -0
  108. package/lib/internal.d.ts.map +1 -0
  109. package/lib/internal.js +52 -0
  110. package/lib/internal.js.map +1 -0
  111. package/lib/utils/ThemeClassNames.d.ts +49 -12
  112. package/lib/utils/ThemeClassNames.d.ts.map +1 -0
  113. package/lib/utils/ThemeClassNames.js +47 -4
  114. package/lib/utils/ThemeClassNames.js.map +1 -0
  115. package/lib/utils/codeBlockUtils.d.ts +63 -0
  116. package/lib/utils/codeBlockUtils.d.ts.map +1 -0
  117. package/lib/utils/codeBlockUtils.js +159 -3
  118. package/lib/utils/codeBlockUtils.js.map +1 -0
  119. package/lib/utils/docsUtils.d.ts +91 -0
  120. package/lib/utils/docsUtils.d.ts.map +1 -0
  121. package/lib/utils/docsUtils.js +217 -1
  122. package/lib/utils/docsUtils.js.map +1 -0
  123. package/lib/utils/footerUtils.d.ts +13 -0
  124. package/lib/utils/footerUtils.d.ts.map +1 -0
  125. package/lib/utils/footerUtils.js +14 -0
  126. package/lib/utils/footerUtils.js.map +1 -0
  127. package/lib/utils/generalUtils.d.ts +11 -1
  128. package/lib/utils/generalUtils.d.ts.map +1 -0
  129. package/lib/utils/generalUtils.js +9 -5
  130. package/lib/utils/generalUtils.js.map +1 -0
  131. package/lib/utils/historyUtils.d.ts +17 -0
  132. package/lib/utils/historyUtils.d.ts.map +1 -0
  133. package/lib/utils/historyUtils.js +38 -0
  134. package/lib/utils/historyUtils.js.map +1 -0
  135. package/lib/utils/jsUtils.d.ts +23 -0
  136. package/lib/utils/jsUtils.d.ts.map +1 -0
  137. package/lib/utils/jsUtils.js +29 -0
  138. package/lib/utils/jsUtils.js.map +1 -0
  139. package/lib/utils/metadataUtils.d.ts +38 -0
  140. package/lib/utils/metadataUtils.d.ts.map +1 -0
  141. package/lib/utils/metadataUtils.js +70 -0
  142. package/lib/utils/metadataUtils.js.map +1 -0
  143. package/lib/utils/navbarUtils.d.ts +21 -0
  144. package/lib/utils/navbarUtils.d.ts.map +1 -0
  145. package/lib/utils/navbarUtils.js +36 -0
  146. package/lib/utils/navbarUtils.js.map +1 -0
  147. package/lib/utils/reactUtils.d.ts +69 -0
  148. package/lib/utils/reactUtils.d.ts.map +1 -0
  149. package/lib/utils/reactUtils.js +98 -0
  150. package/lib/utils/reactUtils.js.map +1 -0
  151. package/lib/utils/regexpUtils.d.ts +12 -0
  152. package/lib/utils/regexpUtils.d.ts.map +1 -0
  153. package/lib/utils/regexpUtils.js +18 -0
  154. package/lib/utils/regexpUtils.js.map +1 -0
  155. package/lib/utils/routesUtils.d.ts +26 -0
  156. package/lib/utils/routesUtils.d.ts.map +1 -0
  157. package/lib/utils/routesUtils.js +54 -0
  158. package/lib/utils/routesUtils.js.map +1 -0
  159. package/lib/utils/scrollUtils.d.ts +83 -0
  160. package/lib/utils/scrollUtils.d.ts.map +1 -0
  161. package/lib/utils/scrollUtils.js +200 -0
  162. package/lib/utils/scrollUtils.js.map +1 -0
  163. package/lib/utils/searchUtils.d.ts +13 -0
  164. package/lib/utils/searchUtils.d.ts.map +1 -0
  165. package/lib/utils/searchUtils.js +37 -0
  166. package/lib/utils/searchUtils.js.map +1 -0
  167. package/lib/utils/storageUtils.d.ts +15 -7
  168. package/lib/utils/storageUtils.d.ts.map +1 -0
  169. package/lib/utils/storageUtils.js +55 -22
  170. package/lib/utils/storageUtils.js.map +1 -0
  171. package/lib/utils/tagsUtils.d.ts +18 -0
  172. package/lib/utils/tagsUtils.d.ts.map +1 -0
  173. package/lib/utils/tagsUtils.js +36 -0
  174. package/lib/utils/tagsUtils.js.map +1 -0
  175. package/lib/utils/tocUtils.d.ts +36 -0
  176. package/lib/utils/tocUtils.d.ts.map +1 -0
  177. package/lib/utils/tocUtils.js +84 -0
  178. package/lib/utils/tocUtils.js.map +1 -0
  179. package/lib/utils/useAlternatePageUtils.d.ts +21 -1
  180. package/lib/utils/useAlternatePageUtils.d.ts.map +1 -0
  181. package/lib/utils/useAlternatePageUtils.js +9 -4
  182. package/lib/utils/useAlternatePageUtils.js.map +1 -0
  183. package/lib/utils/useLocalPathname.d.ts +13 -0
  184. package/lib/utils/useLocalPathname.d.ts.map +1 -0
  185. package/lib/utils/useLocalPathname.js +19 -0
  186. package/lib/utils/useLocalPathname.js.map +1 -0
  187. package/lib/utils/useLocationChange.d.ts +9 -6
  188. package/lib/utils/useLocationChange.d.ts.map +1 -0
  189. package/lib/utils/useLocationChange.js +17 -11
  190. package/lib/utils/useLocationChange.js.map +1 -0
  191. package/lib/utils/usePluralForm.d.ts +12 -0
  192. package/lib/utils/usePluralForm.d.ts.map +1 -0
  193. package/lib/utils/usePluralForm.js +36 -37
  194. package/lib/utils/usePluralForm.js.map +1 -0
  195. package/lib/utils/useThemeConfig.d.ts +56 -28
  196. package/lib/utils/useThemeConfig.d.ts.map +1 -0
  197. package/lib/utils/useThemeConfig.js +4 -0
  198. package/lib/utils/useThemeConfig.js.map +1 -0
  199. package/package.json +35 -13
  200. package/src/components/Collapsible/index.tsx +263 -0
  201. package/src/components/Details/index.tsx +109 -0
  202. package/src/components/Details/styles.module.css +62 -0
  203. package/src/{utils/announcementBarUtils.tsx → contexts/announcementBar.tsx} +43 -39
  204. package/src/contexts/blogPost.tsx +80 -0
  205. package/src/contexts/colorMode.tsx +198 -0
  206. package/src/contexts/doc.tsx +71 -0
  207. package/src/contexts/docSidebarItemsExpandedState.tsx +55 -0
  208. package/src/contexts/docsPreferredVersion.tsx +251 -0
  209. package/src/contexts/docsSidebar.tsx +50 -0
  210. package/src/contexts/docsVersion.tsx +36 -0
  211. package/src/contexts/navbarMobileSidebar.tsx +99 -0
  212. package/src/contexts/navbarSecondaryMenu/content.tsx +100 -0
  213. package/src/contexts/navbarSecondaryMenu/display.tsx +102 -0
  214. package/src/contexts/tabGroupChoice.tsx +85 -0
  215. package/{lib/utils/pathUtils.d.ts → src/hooks/styles.css} +4 -1
  216. package/src/hooks/useBackToTopButton.ts +73 -0
  217. package/src/hooks/useCodeWordWrap.ts +105 -0
  218. package/src/hooks/useHideableNavbar.ts +75 -0
  219. package/src/hooks/useKeyboardNavigation.ts +45 -0
  220. package/src/hooks/useLockBodyScroll.ts +21 -0
  221. package/src/hooks/useMutationObserver.ts +38 -0
  222. package/src/hooks/usePrismTheme.ts +24 -0
  223. package/src/hooks/useSearchPage.ts +79 -0
  224. package/src/hooks/useSkipToContent.ts +58 -0
  225. package/src/hooks/useTOCHighlight.ts +189 -0
  226. package/src/hooks/useWindowSize.ts +72 -0
  227. package/src/index.ts +53 -28
  228. package/src/internal.ts +122 -0
  229. package/src/types.d.ts +0 -2
  230. package/src/utils/ThemeClassNames.ts +54 -5
  231. package/src/utils/codeBlockUtils.ts +241 -2
  232. package/src/utils/docsUtils.tsx +334 -0
  233. package/src/utils/footerUtils.ts +18 -0
  234. package/src/utils/generalUtils.ts +9 -5
  235. package/src/utils/historyUtils.ts +45 -0
  236. package/src/utils/jsUtils.ts +36 -0
  237. package/src/utils/metadataUtils.tsx +115 -0
  238. package/src/utils/navbarUtils.tsx +45 -0
  239. package/src/utils/reactUtils.tsx +129 -0
  240. package/src/utils/regexpUtils.ts +24 -0
  241. package/src/utils/routesUtils.ts +75 -0
  242. package/src/utils/scrollUtils.tsx +304 -0
  243. package/src/utils/searchUtils.ts +51 -0
  244. package/src/utils/storageUtils.ts +56 -23
  245. package/src/utils/tagsUtils.ts +50 -0
  246. package/src/utils/tocUtils.ts +119 -0
  247. package/src/utils/useAlternatePageUtils.ts +19 -6
  248. package/src/utils/useLocalPathname.ts +22 -0
  249. package/src/utils/useLocationChange.ts +24 -20
  250. package/src/utils/usePluralForm.ts +50 -38
  251. package/src/utils/useThemeConfig.ts +55 -30
  252. package/lib/.tsbuildinfo +0 -1
  253. package/lib/utils/announcementBarInlineJavaScript.d.ts +0 -0
  254. package/lib/utils/announcementBarInlineJavaScript.js +0 -1
  255. package/lib/utils/announcementBarUtils.d.ts +0 -17
  256. package/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.d.ts +0 -21
  257. package/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.js +0 -94
  258. package/lib/utils/docsPreferredVersion/DocsPreferredVersionStorage.d.ts +0 -13
  259. package/lib/utils/docsPreferredVersion/DocsPreferredVersionStorage.js +0 -20
  260. package/lib/utils/docsPreferredVersion/useDocsPreferredVersion.d.ts +0 -5
  261. package/lib/utils/docsPreferredVersion/useDocsPreferredVersion.js +0 -41
  262. package/lib/utils/pathUtils.js +0 -13
  263. package/lib/utils/usePrevious.js +0 -14
  264. package/src/utils/__tests__/codeBlockUtils.test.ts +0 -54
  265. package/src/utils/__tests__/pathUtils.test.ts +0 -32
  266. package/src/utils/docsPreferredVersion/DocsPreferredVersionProvider.tsx +0 -165
  267. package/src/utils/docsPreferredVersion/DocsPreferredVersionStorage.ts +0 -34
  268. package/src/utils/docsPreferredVersion/useDocsPreferredVersion.ts +0 -66
  269. package/src/utils/docsUtils.ts +0 -11
  270. package/src/utils/pathUtils.ts +0 -17
  271. package/src/utils/usePrevious.ts +0 -18
  272. package/tsconfig.json +0 -10
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import React, {
9
+ useCallback,
10
+ useEffect,
11
+ useLayoutEffect,
12
+ useMemo,
13
+ useRef,
14
+ type ComponentType,
15
+ type ReactNode,
16
+ } from 'react';
17
+ import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
18
+
19
+ /**
20
+ * This hook is like `useLayoutEffect`, but without the SSR warning.
21
+ * It seems hacky but it's used in many React libs (Redux, Formik...).
22
+ * Also mentioned here: https://github.com/facebook/react/issues/16956
23
+ *
24
+ * It is useful when you need to update a ref as soon as possible after a React
25
+ * render (before `useEffect`).
26
+ */
27
+ export const useIsomorphicLayoutEffect = ExecutionEnvironment.canUseDOM
28
+ ? useLayoutEffect
29
+ : useEffect;
30
+
31
+ /**
32
+ * Temporary userland implementation until an official hook is implemented
33
+ * See RFC: https://github.com/reactjs/rfcs/pull/220
34
+ *
35
+ * Permits to transform an unstable callback (like an arrow function provided as
36
+ * props) to a "stable" callback that is safe to use in a `useEffect` dependency
37
+ * array. Useful to avoid React stale closure problems + avoid useless effect
38
+ * re-executions.
39
+ *
40
+ * This generally works but has some potential drawbacks, such as
41
+ * https://github.com/facebook/react/issues/16956#issuecomment-536636418
42
+ */
43
+ export function useEvent<T extends (...args: never[]) => unknown>(
44
+ callback: T,
45
+ ): T {
46
+ const ref = useRef<T>(callback);
47
+
48
+ useIsomorphicLayoutEffect(() => {
49
+ ref.current = callback;
50
+ }, [callback]);
51
+
52
+ // @ts-expect-error: TS is right that this callback may be a supertype of T,
53
+ // but good enough for our use
54
+ return useCallback<T>((...args) => ref.current(...args), []);
55
+ }
56
+
57
+ /**
58
+ * Gets `value` from the last render.
59
+ */
60
+ export function usePrevious<T>(value: T): T | undefined {
61
+ const ref = useRef<T>();
62
+
63
+ useIsomorphicLayoutEffect(() => {
64
+ ref.current = value;
65
+ });
66
+
67
+ return ref.current;
68
+ }
69
+
70
+ /**
71
+ * This error is thrown when a context is consumed outside its provider. Allows
72
+ * reusing a generic error message format and reduces bundle size. The hook's
73
+ * name will be extracted from its stack, so only the provider's name is needed.
74
+ */
75
+ export class ReactContextError extends Error {
76
+ constructor(providerName: string, additionalInfo?: string) {
77
+ super();
78
+ this.name = 'ReactContextError';
79
+ this.message = `Hook ${
80
+ this.stack?.split('\n')[1]?.match(/at (?:\w+\.)?(?<name>\w+)/)?.groups!
81
+ .name ?? ''
82
+ } is called outside the <${providerName}>. ${additionalInfo ?? ''}`;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Shallow-memoize an object. This means the returned object will be the same as
88
+ * the previous render if the property keys and values did not change. This
89
+ * works for simple cases: when property values are primitives or stable
90
+ * objects.
91
+ *
92
+ * @param obj
93
+ */
94
+ export function useShallowMemoObject<O extends object>(obj: O): O {
95
+ const deps = Object.entries(obj);
96
+ // Sort by keys to make it order-insensitive
97
+ deps.sort((a, b) => a[0].localeCompare(b[0]));
98
+ // eslint-disable-next-line react-hooks/exhaustive-deps
99
+ return useMemo(() => obj, deps.flat());
100
+ }
101
+
102
+ type SimpleProvider = ComponentType<{children: ReactNode}>;
103
+
104
+ /**
105
+ * Creates a single React provider from an array of existing providers
106
+ * assuming providers only take "children" as props.
107
+ *
108
+ * Prevents the annoying React element nesting
109
+ * Example here: https://getfrontend.tips/compose-multiple-react-providers/
110
+ *
111
+ * The order matters:
112
+ * - The first provider is at the top of the tree.
113
+ * - The last provider is the most nested one
114
+ *
115
+ * @param providers array of providers to compose
116
+ */
117
+ export function composeProviders(providers: SimpleProvider[]): SimpleProvider {
118
+ // Creates a single React component: it's cheaper to compose JSX elements
119
+ return ({children}) => (
120
+ <>
121
+ {providers.reduceRight(
122
+ (element, CurrentProvider) => (
123
+ <CurrentProvider>{element}</CurrentProvider>
124
+ ),
125
+ children,
126
+ )}
127
+ </>
128
+ );
129
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ /**
9
+ * Matches a string regex (as provided from the config) against a target in a
10
+ * null-safe fashion, case insensitive and global.
11
+ */
12
+ export function isRegexpStringMatch(
13
+ regexAsString?: string,
14
+ valueToTest?: string,
15
+ ): boolean {
16
+ if (
17
+ typeof regexAsString === 'undefined' ||
18
+ typeof valueToTest === 'undefined'
19
+ ) {
20
+ return false;
21
+ }
22
+
23
+ return new RegExp(regexAsString, 'gi').test(valueToTest);
24
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import {useMemo} from 'react';
9
+ import generatedRoutes from '@generated/routes';
10
+ import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
11
+ import type {RouteConfig} from 'react-router-config';
12
+
13
+ /**
14
+ * Compare the 2 paths, case insensitive and ignoring trailing slash
15
+ */
16
+ export function isSamePath(
17
+ path1: string | undefined,
18
+ path2: string | undefined,
19
+ ): boolean {
20
+ const normalize = (pathname: string | undefined) =>
21
+ (!pathname || pathname.endsWith('/')
22
+ ? pathname
23
+ : `${pathname}/`
24
+ )?.toLowerCase();
25
+ return normalize(path1) === normalize(path2);
26
+ }
27
+
28
+ /**
29
+ * Note that sites don't always have a homepage in practice, so we can't assume
30
+ * that linking to '/' is always safe.
31
+ * @see https://github.com/facebook/docusaurus/pull/6517#issuecomment-1048709116
32
+ */
33
+ export function findHomePageRoute({
34
+ baseUrl,
35
+ routes: initialRoutes,
36
+ }: {
37
+ routes: RouteConfig[];
38
+ baseUrl: string;
39
+ }): RouteConfig | undefined {
40
+ function isHomePageRoute(route: RouteConfig): boolean {
41
+ return route.path === baseUrl && route.exact === true;
42
+ }
43
+
44
+ function isHomeParentRoute(route: RouteConfig): boolean {
45
+ return route.path === baseUrl && !route.exact;
46
+ }
47
+
48
+ function doFindHomePageRoute(routes: RouteConfig[]): RouteConfig | undefined {
49
+ if (routes.length === 0) {
50
+ return undefined;
51
+ }
52
+ const homePage = routes.find(isHomePageRoute);
53
+ if (homePage) {
54
+ return homePage;
55
+ }
56
+ const indexSubRoutes = routes
57
+ .filter(isHomeParentRoute)
58
+ .flatMap((route) => route.routes ?? []);
59
+ return doFindHomePageRoute(indexSubRoutes);
60
+ }
61
+
62
+ return doFindHomePageRoute(initialRoutes);
63
+ }
64
+
65
+ /**
66
+ * Fetches the route that points to "/". Use this instead of the naive "/",
67
+ * because the homepage may not exist.
68
+ */
69
+ export function useHomePageRoute(): RouteConfig | undefined {
70
+ const {baseUrl} = useDocusaurusContext().siteConfig;
71
+ return useMemo(
72
+ () => findHomePageRoute({routes: generatedRoutes, baseUrl}),
73
+ [baseUrl],
74
+ );
75
+ }
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+
8
+ import React, {
9
+ useCallback,
10
+ useContext,
11
+ useEffect,
12
+ useLayoutEffect,
13
+ useMemo,
14
+ useRef,
15
+ type ReactNode,
16
+ } from 'react';
17
+ import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
18
+ import useIsBrowser from '@docusaurus/useIsBrowser';
19
+ import {useEvent, ReactContextError} from './reactUtils';
20
+
21
+ type ScrollController = {
22
+ /** A boolean ref tracking whether scroll events are enabled. */
23
+ scrollEventsEnabledRef: React.MutableRefObject<boolean>;
24
+ /** Enable scroll events in `useScrollPosition`. */
25
+ enableScrollEvents: () => void;
26
+ /** Disable scroll events in `useScrollPosition`. */
27
+ disableScrollEvents: () => void;
28
+ };
29
+
30
+ function useScrollControllerContextValue(): ScrollController {
31
+ const scrollEventsEnabledRef = useRef(true);
32
+
33
+ return useMemo(
34
+ () => ({
35
+ scrollEventsEnabledRef,
36
+ enableScrollEvents: () => {
37
+ scrollEventsEnabledRef.current = true;
38
+ },
39
+ disableScrollEvents: () => {
40
+ scrollEventsEnabledRef.current = false;
41
+ },
42
+ }),
43
+ [],
44
+ );
45
+ }
46
+
47
+ const ScrollMonitorContext = React.createContext<ScrollController | undefined>(
48
+ undefined,
49
+ );
50
+
51
+ export function ScrollControllerProvider({
52
+ children,
53
+ }: {
54
+ children: ReactNode;
55
+ }): JSX.Element {
56
+ const value = useScrollControllerContextValue();
57
+ return (
58
+ <ScrollMonitorContext.Provider value={value}>
59
+ {children}
60
+ </ScrollMonitorContext.Provider>
61
+ );
62
+ }
63
+
64
+ /**
65
+ * We need a way to update the scroll position while ignoring scroll events
66
+ * so as not to toggle Navbar/BackToTop visibility.
67
+ *
68
+ * This API permits to temporarily disable/ignore scroll events. Motivated by
69
+ * https://github.com/facebook/docusaurus/pull/5618
70
+ */
71
+ export function useScrollController(): ScrollController {
72
+ const context = useContext(ScrollMonitorContext);
73
+ if (context == null) {
74
+ throw new ReactContextError('ScrollControllerProvider');
75
+ }
76
+ return context;
77
+ }
78
+
79
+ type ScrollPosition = {scrollX: number; scrollY: number};
80
+
81
+ const getScrollPosition = (): ScrollPosition | null =>
82
+ ExecutionEnvironment.canUseDOM
83
+ ? {
84
+ scrollX: window.pageXOffset,
85
+ scrollY: window.pageYOffset,
86
+ }
87
+ : null;
88
+
89
+ /**
90
+ * This hook fires an effect when the scroll position changes. The effect will
91
+ * be provided with the before/after scroll positions. Note that the effect may
92
+ * not be always run: if scrolling is disabled through `useScrollController`, it
93
+ * will be a no-op.
94
+ *
95
+ * @see {@link useScrollController}
96
+ */
97
+ export function useScrollPosition(
98
+ effect: (
99
+ position: ScrollPosition,
100
+ lastPosition: ScrollPosition | null,
101
+ ) => void,
102
+ deps: unknown[] = [],
103
+ ): void {
104
+ const {scrollEventsEnabledRef} = useScrollController();
105
+ const lastPositionRef = useRef<ScrollPosition | null>(getScrollPosition());
106
+
107
+ const dynamicEffect = useEvent(effect);
108
+
109
+ useEffect(() => {
110
+ const handleScroll = () => {
111
+ if (!scrollEventsEnabledRef.current) {
112
+ return;
113
+ }
114
+ const currentPosition = getScrollPosition()!;
115
+ dynamicEffect(currentPosition, lastPositionRef.current);
116
+ lastPositionRef.current = currentPosition;
117
+ };
118
+
119
+ const opts: AddEventListenerOptions & EventListenerOptions = {
120
+ passive: true,
121
+ };
122
+
123
+ handleScroll();
124
+ window.addEventListener('scroll', handleScroll, opts);
125
+
126
+ return () => window.removeEventListener('scroll', handleScroll, opts);
127
+ // eslint-disable-next-line react-hooks/exhaustive-deps
128
+ }, [dynamicEffect, scrollEventsEnabledRef, ...deps]);
129
+ }
130
+
131
+ type UseScrollPositionSaver = {
132
+ /** Measure the top of an element, and store the details. */
133
+ save: (elem: HTMLElement) => void;
134
+ /**
135
+ * Restore the page position to keep the stored element's position from
136
+ * the top of the viewport, and remove the stored details.
137
+ */
138
+ restore: () => {restored: boolean};
139
+ };
140
+
141
+ function useScrollPositionSaver(): UseScrollPositionSaver {
142
+ const lastElementRef = useRef<{elem: HTMLElement | null; top: number}>({
143
+ elem: null,
144
+ top: 0,
145
+ });
146
+
147
+ const save = useCallback((elem: HTMLElement) => {
148
+ lastElementRef.current = {
149
+ elem,
150
+ top: elem.getBoundingClientRect().top,
151
+ };
152
+ }, []);
153
+
154
+ const restore = useCallback(() => {
155
+ const {
156
+ current: {elem, top},
157
+ } = lastElementRef;
158
+ if (!elem) {
159
+ return {restored: false};
160
+ }
161
+ const newTop = elem.getBoundingClientRect().top;
162
+ const heightDiff = newTop - top;
163
+ if (heightDiff) {
164
+ window.scrollBy({left: 0, top: heightDiff});
165
+ }
166
+ lastElementRef.current = {elem: null, top: 0};
167
+
168
+ return {restored: heightDiff !== 0};
169
+ }, []);
170
+
171
+ return useMemo(() => ({save, restore}), [restore, save]);
172
+ }
173
+
174
+ /**
175
+ * This hook permits to "block" the scroll position of a DOM element.
176
+ * The idea is that we should be able to update DOM content above this element
177
+ * but the screen position of this element should not change.
178
+ *
179
+ * Feature motivated by the Tabs groups: clicking on a tab may affect tabs of
180
+ * the same group upper in the tree, yet to avoid a bad UX, the clicked tab must
181
+ * remain under the user mouse.
182
+ *
183
+ * @see https://github.com/facebook/docusaurus/pull/5618
184
+ */
185
+ export function useScrollPositionBlocker(): {
186
+ /**
187
+ * Takes an element, and keeps its screen position no matter what's getting
188
+ * rendered above it, until the next render.
189
+ */
190
+ blockElementScrollPositionUntilNextRender: (el: HTMLElement) => void;
191
+ } {
192
+ const scrollController = useScrollController();
193
+ const scrollPositionSaver = useScrollPositionSaver();
194
+
195
+ const nextLayoutEffectCallbackRef = useRef<(() => void) | undefined>(
196
+ undefined,
197
+ );
198
+
199
+ const blockElementScrollPositionUntilNextRender = useCallback(
200
+ (el: HTMLElement) => {
201
+ scrollPositionSaver.save(el);
202
+ scrollController.disableScrollEvents();
203
+ nextLayoutEffectCallbackRef.current = () => {
204
+ const {restored} = scrollPositionSaver.restore();
205
+ nextLayoutEffectCallbackRef.current = undefined;
206
+
207
+ // Restoring the former scroll position will trigger a scroll event. We
208
+ // need to wait for next scroll event to happen before enabling the
209
+ // scrollController events again.
210
+ if (restored) {
211
+ const handleScrollRestoreEvent = () => {
212
+ scrollController.enableScrollEvents();
213
+ window.removeEventListener('scroll', handleScrollRestoreEvent);
214
+ };
215
+ window.addEventListener('scroll', handleScrollRestoreEvent);
216
+ } else {
217
+ scrollController.enableScrollEvents();
218
+ }
219
+ };
220
+ },
221
+ [scrollController, scrollPositionSaver],
222
+ );
223
+
224
+ useLayoutEffect(() => {
225
+ nextLayoutEffectCallbackRef.current?.();
226
+ });
227
+
228
+ return {
229
+ blockElementScrollPositionUntilNextRender,
230
+ };
231
+ }
232
+
233
+ type CancelScrollTop = () => void;
234
+
235
+ function smoothScrollNative(top: number): CancelScrollTop {
236
+ window.scrollTo({top, behavior: 'smooth'});
237
+ return () => {
238
+ // Nothing to cancel, it's natively cancelled if user tries to scroll down
239
+ };
240
+ }
241
+
242
+ function smoothScrollPolyfill(top: number): CancelScrollTop {
243
+ let raf: number | null = null;
244
+ const isUpScroll = document.documentElement.scrollTop > top;
245
+ function rafRecursion() {
246
+ const currentScroll = document.documentElement.scrollTop;
247
+ if (
248
+ (isUpScroll && currentScroll > top) ||
249
+ (!isUpScroll && currentScroll < top)
250
+ ) {
251
+ raf = requestAnimationFrame(rafRecursion);
252
+ window.scrollTo(0, Math.floor((currentScroll - top) * 0.85) + top);
253
+ }
254
+ }
255
+ rafRecursion();
256
+
257
+ // Break the recursion. Prevents the user from "fighting" against that
258
+ // recursion producing a weird UX
259
+ return () => raf && cancelAnimationFrame(raf);
260
+ }
261
+
262
+ /**
263
+ * A "smart polyfill" of `window.scrollTo({ top, behavior: "smooth" })`.
264
+ * This currently always uses a polyfilled implementation unless
265
+ * `scroll-behavior: smooth` has been set in CSS, because native support
266
+ * detection for scroll behavior seems unreliable.
267
+ *
268
+ * This hook does not do anything by itself: it returns a start and a stop
269
+ * handle. You can execute either handle at any time.
270
+ */
271
+ export function useSmoothScrollTo(): {
272
+ /**
273
+ * Start the scroll.
274
+ *
275
+ * @param top The final scroll top position.
276
+ */
277
+ startScroll: (top: number) => void;
278
+ /**
279
+ * A cancel function, because the non-native smooth scroll-top
280
+ * implementation must be interrupted if user scrolls down. If there's no
281
+ * existing animation or the scroll is using native behavior, this is a no-op.
282
+ */
283
+ cancelScroll: CancelScrollTop;
284
+ } {
285
+ const cancelRef = useRef<CancelScrollTop | null>(null);
286
+ const isBrowser = useIsBrowser();
287
+ // Not all have support for smooth scrolling (particularly Safari mobile iOS)
288
+ // TODO proper detection is currently unreliable!
289
+ // see https://github.com/wessberg/scroll-behavior-polyfill/issues/16
290
+ // For now, we only use native scroll behavior if smooth is already set,
291
+ // because otherwise the polyfill produces a weird UX when both CSS and JS try
292
+ // to scroll a page, and they cancel each other.
293
+ const supportsNativeSmoothScrolling =
294
+ isBrowser &&
295
+ getComputedStyle(document.documentElement).scrollBehavior === 'smooth';
296
+ return {
297
+ startScroll: (top: number) => {
298
+ cancelRef.current = supportsNativeSmoothScrolling
299
+ ? smoothScrollNative(top)
300
+ : smoothScrollPolyfill(top);
301
+ },
302
+ cancelScroll: () => cancelRef.current?.(),
303
+ };
304
+ }
@@ -5,11 +5,62 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
+ import {
9
+ useAllDocsData,
10
+ useActivePluginAndVersion,
11
+ } from '@docusaurus/plugin-content-docs/client';
12
+ import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
13
+ import {useDocsPreferredVersionByPluginId} from '../contexts/docsPreferredVersion';
14
+
8
15
  export const DEFAULT_SEARCH_TAG = 'default';
9
16
 
17
+ /** The search tag to append as each doc's metadata. */
10
18
  export function docVersionSearchTag(
11
19
  pluginId: string,
12
20
  versionName: string,
13
21
  ): string {
14
22
  return `docs-${pluginId}-${versionName}`;
15
23
  }
24
+
25
+ /**
26
+ * Gets the relevant context information for contextual search.
27
+ *
28
+ * The value is generic and not coupled to Algolia/DocSearch, since we may want
29
+ * to support multiple search engines, or allowing users to use their own search
30
+ * engine solution.
31
+ */
32
+ export function useContextualSearchFilters(): {locale: string; tags: string[]} {
33
+ const {i18n} = useDocusaurusContext();
34
+ const allDocsData = useAllDocsData();
35
+ const activePluginAndVersion = useActivePluginAndVersion();
36
+ const docsPreferredVersionByPluginId = useDocsPreferredVersionByPluginId();
37
+
38
+ // This can't use more specialized hooks because we are mapping over all
39
+ // plugin instances.
40
+ function getDocPluginTags(pluginId: string) {
41
+ const activeVersion =
42
+ activePluginAndVersion?.activePlugin.pluginId === pluginId
43
+ ? activePluginAndVersion.activeVersion
44
+ : undefined;
45
+
46
+ const preferredVersion = docsPreferredVersionByPluginId[pluginId];
47
+
48
+ const latestVersion = allDocsData[pluginId]!.versions.find(
49
+ (v) => v.isLast,
50
+ )!;
51
+
52
+ const version = activeVersion ?? preferredVersion ?? latestVersion;
53
+
54
+ return docVersionSearchTag(pluginId, version.name);
55
+ }
56
+
57
+ const tags = [
58
+ DEFAULT_SEARCH_TAG,
59
+ ...Object.keys(allDocsData).map(getDocPluginTags),
60
+ ];
61
+
62
+ return {
63
+ locale: i18n.currentLocale,
64
+ tags,
65
+ };
66
+ }