@azerion/bunosaurus-theme-common 0.0.0-stage → 4.0.0

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 (261) hide show
  1. package/README.md +2 -2
  2. package/lib/components/Collapsible/index.d.ts +59 -0
  3. package/lib/components/Collapsible/index.d.ts.map +1 -0
  4. package/lib/components/Collapsible/index.js +145 -0
  5. package/lib/components/Collapsible/index.js.map +1 -0
  6. package/lib/components/Details/index.d.ts +20 -0
  7. package/lib/components/Details/index.d.ts.map +1 -0
  8. package/lib/components/Details/index.js +86 -0
  9. package/lib/components/Details/index.js.map +1 -0
  10. package/lib/components/Details/styles.module.css +66 -0
  11. package/lib/components/ThemedComponent/index.d.ts +31 -0
  12. package/lib/components/ThemedComponent/index.d.ts.map +1 -0
  13. package/lib/components/ThemedComponent/index.js +47 -0
  14. package/lib/components/ThemedComponent/index.js.map +1 -0
  15. package/lib/components/ThemedComponent/styles.module.css +26 -0
  16. package/lib/contexts/announcementBar.d.ts +21 -0
  17. package/lib/contexts/announcementBar.d.ts.map +1 -0
  18. package/lib/contexts/announcementBar.js +72 -0
  19. package/lib/contexts/announcementBar.js.map +1 -0
  20. package/lib/contexts/colorMode.d.ts +23 -0
  21. package/lib/contexts/colorMode.d.ts.map +1 -0
  22. package/lib/contexts/colorMode.js +163 -0
  23. package/lib/contexts/colorMode.js.map +1 -0
  24. package/lib/contexts/navbarMobileSidebar.d.ts +31 -0
  25. package/lib/contexts/navbarMobileSidebar.d.ts.map +1 -0
  26. package/lib/contexts/navbarMobileSidebar.js +65 -0
  27. package/lib/contexts/navbarMobileSidebar.js.map +1 -0
  28. package/lib/contexts/navbarSecondaryMenu/content.d.ts +37 -0
  29. package/lib/contexts/navbarSecondaryMenu/content.d.ts.map +1 -0
  30. package/lib/contexts/navbarSecondaryMenu/content.js +50 -0
  31. package/lib/contexts/navbarSecondaryMenu/content.js.map +1 -0
  32. package/lib/contexts/navbarSecondaryMenu/display.d.ts +24 -0
  33. package/lib/contexts/navbarSecondaryMenu/display.d.ts.map +1 -0
  34. package/lib/contexts/navbarSecondaryMenu/display.js +62 -0
  35. package/lib/contexts/navbarSecondaryMenu/display.js.map +1 -0
  36. package/lib/hooks/useBackToTopButton.d.ts +27 -0
  37. package/lib/hooks/useBackToTopButton.d.ts.map +1 -0
  38. package/lib/hooks/useBackToTopButton.js +50 -0
  39. package/lib/hooks/useBackToTopButton.js.map +1 -0
  40. package/lib/hooks/useCodeWordWrap.d.ts +15 -0
  41. package/lib/hooks/useCodeWordWrap.d.ts.map +1 -0
  42. package/lib/hooks/useCodeWordWrap.js +67 -0
  43. package/lib/hooks/useCodeWordWrap.js.map +1 -0
  44. package/lib/hooks/useHideableNavbar.d.ts +17 -0
  45. package/lib/hooks/useHideableNavbar.d.ts.map +1 -0
  46. package/lib/hooks/useHideableNavbar.js +65 -0
  47. package/lib/hooks/useHideableNavbar.js.map +1 -0
  48. package/lib/hooks/useLockBodyScroll.d.ts +12 -0
  49. package/lib/hooks/useLockBodyScroll.d.ts.map +1 -0
  50. package/lib/hooks/useLockBodyScroll.js +20 -0
  51. package/lib/hooks/useLockBodyScroll.js.map +1 -0
  52. package/lib/hooks/useMutationObserver.d.ts +4 -0
  53. package/lib/hooks/useMutationObserver.d.ts.map +1 -0
  54. package/lib/hooks/useMutationObserver.js +29 -0
  55. package/lib/hooks/useMutationObserver.js.map +1 -0
  56. package/lib/hooks/usePrismTheme.d.ts +13 -0
  57. package/lib/hooks/usePrismTheme.d.ts.map +1 -0
  58. package/lib/hooks/usePrismTheme.js +21 -0
  59. package/lib/hooks/usePrismTheme.js.map +1 -0
  60. package/lib/hooks/useTOCHighlight.d.ts +25 -0
  61. package/lib/hooks/useTOCHighlight.d.ts.map +1 -0
  62. package/lib/hooks/useTOCHighlight.js +130 -0
  63. package/lib/hooks/useTOCHighlight.js.map +1 -0
  64. package/lib/hooks/useWindowSize.d.ts +27 -0
  65. package/lib/hooks/useWindowSize.d.ts.map +1 -0
  66. package/lib/hooks/useWindowSize.js +49 -0
  67. package/lib/hooks/useWindowSize.js.map +1 -0
  68. package/lib/index.d.ts +30 -0
  69. package/lib/index.d.ts.map +1 -0
  70. package/lib/index.js +37 -0
  71. package/lib/index.js.map +1 -0
  72. package/lib/internal.d.ts +35 -0
  73. package/lib/internal.d.ts.map +1 -0
  74. package/lib/internal.js +45 -0
  75. package/lib/internal.js.map +1 -0
  76. package/lib/translations/blogTranslations.d.ts +20 -0
  77. package/lib/translations/blogTranslations.d.ts.map +1 -0
  78. package/lib/translations/blogTranslations.js +52 -0
  79. package/lib/translations/blogTranslations.js.map +1 -0
  80. package/lib/translations/contentVisibilityTranslations.d.ts +12 -0
  81. package/lib/translations/contentVisibilityTranslations.d.ts.map +1 -0
  82. package/lib/translations/contentVisibilityTranslations.js +30 -0
  83. package/lib/translations/contentVisibilityTranslations.js.map +1 -0
  84. package/lib/translations/docsTranslations.d.ts +8 -0
  85. package/lib/translations/docsTranslations.d.ts.map +1 -0
  86. package/lib/translations/docsTranslations.js +17 -0
  87. package/lib/translations/docsTranslations.js.map +1 -0
  88. package/lib/utils/IntlUtils.d.ts +2 -0
  89. package/lib/utils/IntlUtils.d.ts.map +1 -0
  90. package/lib/utils/IntlUtils.js +20 -0
  91. package/lib/utils/IntlUtils.js.map +1 -0
  92. package/lib/utils/ThemeClassNames.d.ts +99 -0
  93. package/lib/utils/ThemeClassNames.d.ts.map +1 -0
  94. package/lib/utils/ThemeClassNames.js +107 -0
  95. package/lib/utils/ThemeClassNames.js.map +1 -0
  96. package/lib/utils/accessibilityUtils.d.ts +8 -0
  97. package/lib/utils/accessibilityUtils.d.ts.map +1 -0
  98. package/lib/utils/accessibilityUtils.js +10 -0
  99. package/lib/utils/accessibilityUtils.js.map +1 -0
  100. package/lib/utils/admonitionUtils.d.ts +12 -0
  101. package/lib/utils/admonitionUtils.d.ts.map +1 -0
  102. package/lib/utils/admonitionUtils.js +32 -0
  103. package/lib/utils/admonitionUtils.js.map +1 -0
  104. package/lib/utils/anchorUtils.d.ts +16 -0
  105. package/lib/utils/anchorUtils.d.ts.map +1 -0
  106. package/lib/utils/anchorUtils.js +26 -0
  107. package/lib/utils/anchorUtils.js.map +1 -0
  108. package/lib/utils/anchorUtils.module.css +14 -0
  109. package/lib/utils/codeBlockUtils.d.ts +101 -0
  110. package/lib/utils/codeBlockUtils.d.ts.map +1 -0
  111. package/lib/utils/codeBlockUtils.js +310 -0
  112. package/lib/utils/codeBlockUtils.js.map +1 -0
  113. package/lib/utils/emojiUtils.d.ts +20 -0
  114. package/lib/utils/emojiUtils.d.ts.map +1 -0
  115. package/lib/utils/emojiUtils.js +32 -0
  116. package/lib/utils/emojiUtils.js.map +1 -0
  117. package/lib/utils/errorBoundaryUtils.d.ts +31 -0
  118. package/lib/utils/errorBoundaryUtils.d.ts.map +1 -0
  119. package/lib/utils/errorBoundaryUtils.js +48 -0
  120. package/lib/utils/errorBoundaryUtils.js.map +1 -0
  121. package/lib/utils/errorBoundaryUtils.module.css +16 -0
  122. package/lib/utils/footerUtils.d.ts +13 -0
  123. package/lib/utils/footerUtils.d.ts.map +1 -0
  124. package/lib/utils/footerUtils.js +14 -0
  125. package/lib/utils/footerUtils.js.map +1 -0
  126. package/lib/utils/historyUtils.d.ts +39 -0
  127. package/lib/utils/historyUtils.d.ts.map +1 -0
  128. package/lib/utils/historyUtils.js +148 -0
  129. package/lib/utils/historyUtils.js.map +1 -0
  130. package/lib/utils/jsUtils.d.ts +24 -0
  131. package/lib/utils/jsUtils.d.ts.map +1 -0
  132. package/lib/utils/jsUtils.js +43 -0
  133. package/lib/utils/jsUtils.js.map +1 -0
  134. package/lib/utils/metadataUtils.d.ts +38 -0
  135. package/lib/utils/metadataUtils.d.ts.map +1 -0
  136. package/lib/utils/metadataUtils.js +87 -0
  137. package/lib/utils/metadataUtils.js.map +1 -0
  138. package/lib/utils/navbarUtils.d.ts +21 -0
  139. package/lib/utils/navbarUtils.d.ts.map +1 -0
  140. package/lib/utils/navbarUtils.js +35 -0
  141. package/lib/utils/navbarUtils.js.map +1 -0
  142. package/lib/utils/reactUtils.d.ts +60 -0
  143. package/lib/utils/reactUtils.d.ts.map +1 -0
  144. package/lib/utils/reactUtils.js +91 -0
  145. package/lib/utils/reactUtils.js.map +1 -0
  146. package/lib/utils/regexpUtils.d.ts +12 -0
  147. package/lib/utils/regexpUtils.d.ts.map +1 -0
  148. package/lib/utils/regexpUtils.js +18 -0
  149. package/lib/utils/regexpUtils.js.map +1 -0
  150. package/lib/utils/routesUtils.d.ts +26 -0
  151. package/lib/utils/routesUtils.d.ts.map +1 -0
  152. package/lib/utils/routesUtils.js +54 -0
  153. package/lib/utils/routesUtils.js.map +1 -0
  154. package/lib/utils/scrollUtils.d.ts +83 -0
  155. package/lib/utils/scrollUtils.d.ts.map +1 -0
  156. package/lib/utils/scrollUtils.js +201 -0
  157. package/lib/utils/scrollUtils.js.map +1 -0
  158. package/lib/utils/searchUtils.d.ts +8 -0
  159. package/lib/utils/searchUtils.d.ts.map +1 -0
  160. package/lib/utils/searchUtils.js +8 -0
  161. package/lib/utils/searchUtils.js.map +1 -0
  162. package/lib/utils/skipToContentUtils.d.ts +20 -0
  163. package/lib/utils/skipToContentUtils.d.ts.map +1 -0
  164. package/lib/utils/skipToContentUtils.js +75 -0
  165. package/lib/utils/skipToContentUtils.js.map +1 -0
  166. package/lib/utils/storageUtils.d.ts +36 -0
  167. package/lib/utils/storageUtils.d.ts.map +1 -0
  168. package/lib/utils/storageUtils.js +193 -0
  169. package/lib/utils/storageUtils.js.map +1 -0
  170. package/lib/utils/tabsUtils.d.ts +55 -0
  171. package/lib/utils/tabsUtils.d.ts.map +1 -0
  172. package/lib/utils/tabsUtils.js +179 -0
  173. package/lib/utils/tabsUtils.js.map +1 -0
  174. package/lib/utils/tagsUtils.d.ts +20 -0
  175. package/lib/utils/tagsUtils.d.ts.map +1 -0
  176. package/lib/utils/tagsUtils.js +41 -0
  177. package/lib/utils/tagsUtils.js.map +1 -0
  178. package/lib/utils/titleFormatterUtils.d.ts +59 -0
  179. package/lib/utils/titleFormatterUtils.d.ts.map +1 -0
  180. package/lib/utils/titleFormatterUtils.js +49 -0
  181. package/lib/utils/titleFormatterUtils.js.map +1 -0
  182. package/lib/utils/tocUtils.d.ts +36 -0
  183. package/lib/utils/tocUtils.d.ts.map +1 -0
  184. package/lib/utils/tocUtils.js +84 -0
  185. package/lib/utils/tocUtils.js.map +1 -0
  186. package/lib/utils/useAlternatePageUtils.d.ts +32 -0
  187. package/lib/utils/useAlternatePageUtils.d.ts.map +1 -0
  188. package/lib/utils/useAlternatePageUtils.js +42 -0
  189. package/lib/utils/useAlternatePageUtils.js.map +1 -0
  190. package/lib/utils/useLocalPathname.d.ts +13 -0
  191. package/lib/utils/useLocalPathname.d.ts.map +1 -0
  192. package/lib/utils/useLocalPathname.js +19 -0
  193. package/lib/utils/useLocalPathname.js.map +1 -0
  194. package/lib/utils/useLocationChange.d.ts +17 -0
  195. package/lib/utils/useLocationChange.d.ts.map +1 -0
  196. package/lib/utils/useLocationChange.js +31 -0
  197. package/lib/utils/useLocationChange.js.map +1 -0
  198. package/lib/utils/usePluralForm.d.ts +21 -0
  199. package/lib/utils/usePluralForm.d.ts.map +1 -0
  200. package/lib/utils/usePluralForm.js +93 -0
  201. package/lib/utils/usePluralForm.js.map +1 -0
  202. package/lib/utils/useThemeConfig.d.ts +120 -0
  203. package/lib/utils/useThemeConfig.d.ts.map +1 -0
  204. package/lib/utils/useThemeConfig.js +14 -0
  205. package/lib/utils/useThemeConfig.js.map +1 -0
  206. package/package.json +58 -4
  207. package/src/components/Collapsible/index.tsx +250 -0
  208. package/src/components/Details/index.tsx +130 -0
  209. package/src/components/Details/styles.module.css +66 -0
  210. package/src/components/ThemedComponent/index.tsx +75 -0
  211. package/src/components/ThemedComponent/styles.module.css +26 -0
  212. package/src/contexts/announcementBar.tsx +117 -0
  213. package/src/contexts/colorMode.tsx +257 -0
  214. package/src/contexts/navbarMobileSidebar.tsx +119 -0
  215. package/src/contexts/navbarSecondaryMenu/content.tsx +100 -0
  216. package/src/contexts/navbarSecondaryMenu/display.tsx +102 -0
  217. package/src/hooks/useBackToTopButton.ts +73 -0
  218. package/src/hooks/useCodeWordWrap.ts +107 -0
  219. package/src/hooks/useHideableNavbar.ts +81 -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/useTOCHighlight.ts +189 -0
  224. package/src/hooks/useWindowSize.ts +67 -0
  225. package/src/index.ts +112 -0
  226. package/src/internal.ts +107 -0
  227. package/src/translations/blogTranslations.tsx +89 -0
  228. package/src/translations/contentVisibilityTranslations.tsx +51 -0
  229. package/src/translations/docsTranslations.tsx +28 -0
  230. package/src/types.d.ts +8 -0
  231. package/src/utils/IntlUtils.ts +27 -0
  232. package/src/utils/ThemeClassNames.ts +119 -0
  233. package/src/utils/accessibilityUtils.ts +10 -0
  234. package/src/utils/admonitionUtils.tsx +44 -0
  235. package/src/utils/anchorUtils.module.css +14 -0
  236. package/src/utils/anchorUtils.ts +31 -0
  237. package/src/utils/codeBlockUtils.tsx +494 -0
  238. package/src/utils/emojiUtils.ts +40 -0
  239. package/src/utils/errorBoundaryUtils.module.css +16 -0
  240. package/src/utils/errorBoundaryUtils.tsx +71 -0
  241. package/src/utils/footerUtils.ts +18 -0
  242. package/src/utils/historyUtils.ts +199 -0
  243. package/src/utils/jsUtils.ts +54 -0
  244. package/src/utils/metadataUtils.tsx +145 -0
  245. package/src/utils/navbarUtils.tsx +45 -0
  246. package/src/utils/reactUtils.tsx +120 -0
  247. package/src/utils/regexpUtils.ts +24 -0
  248. package/src/utils/routesUtils.ts +75 -0
  249. package/src/utils/scrollUtils.tsx +303 -0
  250. package/src/utils/searchUtils.ts +8 -0
  251. package/src/utils/skipToContentUtils.tsx +108 -0
  252. package/src/utils/storageUtils.ts +260 -0
  253. package/src/utils/tabsUtils.tsx +307 -0
  254. package/src/utils/tagsUtils.tsx +61 -0
  255. package/src/utils/titleFormatterUtils.tsx +120 -0
  256. package/src/utils/tocUtils.ts +119 -0
  257. package/src/utils/useAlternatePageUtils.ts +80 -0
  258. package/src/utils/useLocalPathname.ts +22 -0
  259. package/src/utils/useLocationChange.ts +41 -0
  260. package/src/utils/usePluralForm.ts +131 -0
  261. package/src/utils/useThemeConfig.ts +147 -0
@@ -0,0 +1,303 @@
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.RefObject<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
+ }): ReactNode {
56
+ const value = useScrollControllerContextValue();
57
+ return <ScrollMonitorContext value={value}>{children}</ScrollMonitorContext>;
58
+ }
59
+
60
+ /**
61
+ * We need a way to update the scroll position while ignoring scroll events
62
+ * so as not to toggle Navbar/BackToTop visibility.
63
+ *
64
+ * This API permits to temporarily disable/ignore scroll events. Motivated by
65
+ * https://github.com/facebook/docusaurus/pull/5618
66
+ */
67
+ export function useScrollController(): ScrollController {
68
+ const context = useContext(ScrollMonitorContext);
69
+ if (context == null) {
70
+ throw new ReactContextError('ScrollControllerProvider');
71
+ }
72
+ return context;
73
+ }
74
+
75
+ type ScrollPosition = {scrollX: number; scrollY: number};
76
+
77
+ const getScrollPosition = (): ScrollPosition | null =>
78
+ ExecutionEnvironment.canUseDOM
79
+ ? {
80
+ scrollX: window.pageXOffset,
81
+ scrollY: window.pageYOffset,
82
+ }
83
+ : null;
84
+
85
+ /**
86
+ * This hook fires an effect when the scroll position changes. The effect will
87
+ * be provided with the before/after scroll positions. Note that the effect may
88
+ * not be always run: if scrolling is disabled through `useScrollController`, it
89
+ * will be a no-op.
90
+ *
91
+ * @see {@link useScrollController}
92
+ */
93
+ export function useScrollPosition(
94
+ effect: (
95
+ position: ScrollPosition,
96
+ lastPosition: ScrollPosition | null,
97
+ ) => void,
98
+ deps: unknown[] = [],
99
+ ): void {
100
+ const {scrollEventsEnabledRef} = useScrollController();
101
+ const lastPositionRef = useRef<ScrollPosition | null>(getScrollPosition());
102
+
103
+ const dynamicEffect = useEvent(effect);
104
+
105
+ useEffect(() => {
106
+ const handleScroll = () => {
107
+ if (!scrollEventsEnabledRef.current) {
108
+ return;
109
+ }
110
+ const currentPosition = getScrollPosition()!;
111
+ dynamicEffect(currentPosition, lastPositionRef.current);
112
+ lastPositionRef.current = currentPosition;
113
+ };
114
+
115
+ const opts: AddEventListenerOptions & EventListenerOptions = {
116
+ passive: true,
117
+ };
118
+
119
+ handleScroll();
120
+ window.addEventListener('scroll', handleScroll, opts);
121
+
122
+ return () => window.removeEventListener('scroll', handleScroll, opts);
123
+ // eslint-disable-next-line react-hooks/exhaustive-deps
124
+ }, [dynamicEffect, scrollEventsEnabledRef, ...deps]);
125
+ }
126
+
127
+ type UseScrollPositionSaver = {
128
+ /** Measure the top of an element, and store the details. */
129
+ save: (elem: HTMLElement) => void;
130
+ /**
131
+ * Restore the page position to keep the stored element's position from
132
+ * the top of the viewport, and remove the stored details.
133
+ */
134
+ restore: () => {restored: boolean};
135
+ };
136
+
137
+ function useScrollPositionSaver(): UseScrollPositionSaver {
138
+ const lastElementRef = useRef<{elem: HTMLElement | null; top: number}>({
139
+ elem: null,
140
+ top: 0,
141
+ });
142
+
143
+ const save = useCallback((elem: HTMLElement) => {
144
+ lastElementRef.current = {
145
+ elem,
146
+ top: elem.getBoundingClientRect().top,
147
+ };
148
+ }, []);
149
+
150
+ const restore = useCallback(() => {
151
+ const {
152
+ current: {elem, top},
153
+ } = lastElementRef;
154
+ if (!elem) {
155
+ return {restored: false};
156
+ }
157
+ const newTop = elem.getBoundingClientRect().top;
158
+ const heightDiff = newTop - top;
159
+ if (heightDiff) {
160
+ window.scrollBy({left: 0, top: heightDiff});
161
+ }
162
+ lastElementRef.current = {elem: null, top: 0};
163
+
164
+ return {restored: heightDiff !== 0};
165
+ }, []);
166
+
167
+ return useMemo(() => ({save, restore}), [restore, save]);
168
+ }
169
+
170
+ /**
171
+ * This hook permits to "block" the scroll position of a DOM element.
172
+ * The idea is that we should be able to update DOM content above this element
173
+ * but the screen position of this element should not change.
174
+ *
175
+ * Feature motivated by the Tabs groups: clicking on a tab may affect tabs of
176
+ * the same group upper in the tree, yet to avoid a bad UX, the clicked tab must
177
+ * remain under the user mouse.
178
+ *
179
+ * @see https://github.com/facebook/docusaurus/pull/5618
180
+ */
181
+ export function useScrollPositionBlocker(): {
182
+ /**
183
+ * Takes an element, and keeps its screen position no matter what's getting
184
+ * rendered above it, until the next render.
185
+ */
186
+ blockElementScrollPositionUntilNextRender: (el: HTMLElement) => void;
187
+ } {
188
+ const scrollController = useScrollController();
189
+ const scrollPositionSaver = useScrollPositionSaver();
190
+
191
+ const nextLayoutEffectCallbackRef = useRef<(() => void) | undefined>(
192
+ undefined,
193
+ );
194
+
195
+ const blockElementScrollPositionUntilNextRender = useCallback(
196
+ (el: HTMLElement) => {
197
+ scrollPositionSaver.save(el);
198
+ scrollController.disableScrollEvents();
199
+ nextLayoutEffectCallbackRef.current = () => {
200
+ const {restored} = scrollPositionSaver.restore();
201
+ nextLayoutEffectCallbackRef.current = undefined;
202
+
203
+ // Restoring the former scroll position will trigger a scroll event. We
204
+ // need to wait for next scroll event to happen before enabling the
205
+ // scrollController events again.
206
+ if (restored) {
207
+ const handleScrollRestoreEvent = () => {
208
+ scrollController.enableScrollEvents();
209
+ window.removeEventListener('scroll', handleScrollRestoreEvent);
210
+ };
211
+ window.addEventListener('scroll', handleScrollRestoreEvent);
212
+ } else {
213
+ scrollController.enableScrollEvents();
214
+ }
215
+ };
216
+ },
217
+ [scrollController, scrollPositionSaver],
218
+ );
219
+
220
+ useLayoutEffect(() => {
221
+ // Queuing permits to restore scroll position after all useLayoutEffect
222
+ // have run, and yet preserve the sync nature of the scroll restoration
223
+ // See https://github.com/facebook/docusaurus/issues/8625
224
+ queueMicrotask(() => nextLayoutEffectCallbackRef.current?.());
225
+ });
226
+
227
+ return {
228
+ blockElementScrollPositionUntilNextRender,
229
+ };
230
+ }
231
+
232
+ type CancelScrollTop = () => void;
233
+
234
+ function smoothScrollNative(top: number): CancelScrollTop {
235
+ window.scrollTo({top, behavior: 'smooth'});
236
+ return () => {
237
+ // Nothing to cancel, it's natively cancelled if user tries to scroll down
238
+ };
239
+ }
240
+
241
+ function smoothScrollPolyfill(top: number): CancelScrollTop {
242
+ let raf: number | null = null;
243
+ const isUpScroll = document.documentElement.scrollTop > top;
244
+ function rafRecursion() {
245
+ const currentScroll = document.documentElement.scrollTop;
246
+ if (
247
+ (isUpScroll && currentScroll > top) ||
248
+ (!isUpScroll && currentScroll < top)
249
+ ) {
250
+ raf = requestAnimationFrame(rafRecursion);
251
+ window.scrollTo(0, Math.floor((currentScroll - top) * 0.85) + top);
252
+ }
253
+ }
254
+ rafRecursion();
255
+
256
+ // Break the recursion. Prevents the user from "fighting" against that
257
+ // recursion producing a weird UX
258
+ return () => raf && cancelAnimationFrame(raf);
259
+ }
260
+
261
+ /**
262
+ * A "smart polyfill" of `window.scrollTo({ top, behavior: "smooth" })`.
263
+ * This currently always uses a polyfilled implementation unless
264
+ * `scroll-behavior: smooth` has been set in CSS, because native support
265
+ * detection for scroll behavior seems unreliable.
266
+ *
267
+ * This hook does not do anything by itself: it returns a start and a stop
268
+ * handle. You can execute either handle at any time.
269
+ */
270
+ export function useSmoothScrollTo(): {
271
+ /**
272
+ * Start the scroll.
273
+ *
274
+ * @param top The final scroll top position.
275
+ */
276
+ startScroll: (top: number) => void;
277
+ /**
278
+ * A cancel function, because the non-native smooth scroll-top
279
+ * implementation must be interrupted if user scrolls down. If there's no
280
+ * existing animation or the scroll is using native behavior, this is a no-op.
281
+ */
282
+ cancelScroll: CancelScrollTop;
283
+ } {
284
+ const cancelRef = useRef<CancelScrollTop | null>(null);
285
+ const isBrowser = useIsBrowser();
286
+ // Not all have support for smooth scrolling (particularly Safari mobile iOS)
287
+ // TODO proper detection is currently unreliable!
288
+ // see https://github.com/wessberg/scroll-behavior-polyfill/issues/16
289
+ // For now, we only use native scroll behavior if smooth is already set,
290
+ // because otherwise the polyfill produces a weird UX when both CSS and JS try
291
+ // to scroll a page, and they cancel each other.
292
+ const supportsNativeSmoothScrolling =
293
+ isBrowser &&
294
+ getComputedStyle(document.documentElement).scrollBehavior === 'smooth';
295
+ return {
296
+ startScroll: (top: number) => {
297
+ cancelRef.current = supportsNativeSmoothScrolling
298
+ ? smoothScrollNative(top)
299
+ : smoothScrollPolyfill(top);
300
+ },
301
+ cancelScroll: () => cancelRef.current?.(),
302
+ };
303
+ }
@@ -0,0 +1,8 @@
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
+ export const DEFAULT_SEARCH_TAG = 'default';
@@ -0,0 +1,108 @@
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 type React from 'react';
9
+ import {useCallback, useRef, type ComponentProps, type ReactNode} from 'react';
10
+ import {useHistory} from '@docusaurus/router';
11
+ import {translate} from '@docusaurus/Translate';
12
+ import {useLocationChange} from './useLocationChange';
13
+
14
+ /**
15
+ * The id of the element that should become focused on a page
16
+ * that does not have a <main> html tag.
17
+ * Focusing the Docusaurus Layout children is a reasonable fallback.
18
+ *
19
+ * __ prefix allows search crawlers (Algolia/DocSearch) to ignore anchors
20
+ * https://github.com/facebook/docusaurus/issues/8883#issuecomment-1516328368
21
+ */
22
+ export const SkipToContentFallbackId = '__docusaurus_skipToContent_fallback';
23
+
24
+ /**
25
+ * Returns the skip to content element to focus when the link is clicked.
26
+ */
27
+ function getSkipToContentTarget(): HTMLElement | null {
28
+ return (
29
+ // Try to focus the <main> in priority
30
+ // Note: this will only work if JS is enabled
31
+ // See https://github.com/facebook/docusaurus/issues/6411#issuecomment-1284136069
32
+ document.querySelector('main:first-of-type') ??
33
+ // Then try to focus the fallback element (usually the Layout children)
34
+ document.getElementById(SkipToContentFallbackId)
35
+ );
36
+ }
37
+
38
+ function programmaticFocus(el: HTMLElement) {
39
+ el.setAttribute('tabindex', '-1');
40
+ el.focus();
41
+ el.removeAttribute('tabindex');
42
+ }
43
+
44
+ /** This hook wires the logic for a skip-to-content link. */
45
+ function useSkipToContent(): {
46
+ /**
47
+ * The ref to the container. On page transition, the container will be focused
48
+ * so that keyboard navigators can instantly interact with the link and jump
49
+ * to content.
50
+ */
51
+ containerRef: React.RefObject<HTMLDivElement | null>;
52
+ /**
53
+ * Callback fired when the skip to content link has been clicked.
54
+ * It will programmatically focus the main content.
55
+ */
56
+ onClick: (e: React.MouseEvent<HTMLAnchorElement>) => void;
57
+ } {
58
+ const containerRef = useRef<HTMLDivElement>(null);
59
+ const {action} = useHistory();
60
+
61
+ const onClick = useCallback((e: React.MouseEvent<HTMLAnchorElement>) => {
62
+ e.preventDefault();
63
+ const targetElement = getSkipToContentTarget();
64
+ if (targetElement) {
65
+ programmaticFocus(targetElement);
66
+ }
67
+ }, []);
68
+
69
+ // "Reset" focus when navigating.
70
+ // See https://github.com/facebook/docusaurus/pull/8204#issuecomment-1276547558
71
+ useLocationChange(({location}) => {
72
+ if (containerRef.current && !location.hash && action === 'PUSH') {
73
+ programmaticFocus(containerRef.current);
74
+ }
75
+ });
76
+
77
+ return {containerRef, onClick};
78
+ }
79
+
80
+ const DefaultSkipToContentLabel = translate({
81
+ id: 'theme.common.skipToMainContent',
82
+ description:
83
+ 'The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation',
84
+ message: 'Skip to main content',
85
+ });
86
+
87
+ type SkipToContentLinkProps = Omit<ComponentProps<'a'>, 'href' | 'onClick'>;
88
+
89
+ export function SkipToContentLink(props: SkipToContentLinkProps): ReactNode {
90
+ const linkLabel = props.children ?? DefaultSkipToContentLabel;
91
+ const {containerRef, onClick} = useSkipToContent();
92
+ return (
93
+ <div
94
+ ref={containerRef}
95
+ role="region"
96
+ aria-label={DefaultSkipToContentLabel}>
97
+ {/* eslint-disable-next-line @docusaurus/no-html-links */}
98
+ <a
99
+ {...props}
100
+ // Note this is a fallback href in case JS is disabled
101
+ // It has limitations, see https://github.com/facebook/docusaurus/issues/6411#issuecomment-1284136069
102
+ href={`#${SkipToContentFallbackId}`}
103
+ onClick={onClick}>
104
+ {linkLabel}
105
+ </a>
106
+ </div>
107
+ );
108
+ }
@@ -0,0 +1,260 @@
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 {useCallback, useState, useSyncExternalStore} from 'react';
9
+ import SiteStorage from '@generated/site-storage';
10
+
11
+ export type StorageType = (typeof SiteStorage)['type'] | 'none';
12
+
13
+ const DefaultStorageType: StorageType = SiteStorage.type;
14
+
15
+ function applyNamespace(storageKey: string): string {
16
+ return `${storageKey}${SiteStorage.namespace}`;
17
+ }
18
+
19
+ // window.addEventListener('storage') only works for different windows...
20
+ // so for current window we have to dispatch the event manually
21
+ // Now we can listen for both cross-window / current-window storage changes!
22
+ // see https://stackoverflow.com/a/71177640/82609
23
+ // see https://stackoverflow.com/questions/26974084/listen-for-changes-with-localstorage-on-the-same-window
24
+ function dispatchChangeEvent({
25
+ key,
26
+ oldValue,
27
+ newValue,
28
+ storage,
29
+ }: {
30
+ key: string;
31
+ oldValue: string | null;
32
+ newValue: string | null;
33
+ storage: Storage;
34
+ }) {
35
+ // If we set multiple times the same storage value, events should not be fired
36
+ // The native events behave this way, so our manual event dispatch should
37
+ // rather behave exactly the same. Not doing so might create infinite loops.
38
+ // See https://github.com/facebook/docusaurus/issues/8594
39
+ if (oldValue === newValue) {
40
+ return;
41
+ }
42
+ const event = document.createEvent('StorageEvent');
43
+ event.initStorageEvent(
44
+ 'storage',
45
+ false,
46
+ false,
47
+ key,
48
+ oldValue,
49
+ newValue,
50
+ window.location.href,
51
+ storage,
52
+ );
53
+ window.dispatchEvent(event);
54
+ }
55
+
56
+ /**
57
+ * Will return `null` if browser storage is unavailable (like running Docusaurus
58
+ * in an iframe). This should NOT be called in SSR.
59
+ *
60
+ * @see https://github.com/facebook/docusaurus/pull/4501
61
+ */
62
+ function getBrowserStorage(
63
+ storageType: StorageType = DefaultStorageType,
64
+ ): Storage | null {
65
+ if (typeof window === 'undefined') {
66
+ throw new Error(
67
+ 'Browser storage is not available on Node.js/Docusaurus SSR process.',
68
+ );
69
+ }
70
+ if (storageType === 'none') {
71
+ return null;
72
+ }
73
+ try {
74
+ return window[storageType];
75
+ } catch (err) {
76
+ logOnceBrowserStorageNotAvailableWarning(err as Error);
77
+ return null;
78
+ }
79
+ }
80
+
81
+ let hasLoggedBrowserStorageNotAvailableWarning = false;
82
+ /**
83
+ * Poor man's memoization to avoid logging multiple times the same warning.
84
+ * Sometimes, `localStorage`/`sessionStorage` is unavailable due to browser
85
+ * policies.
86
+ */
87
+ function logOnceBrowserStorageNotAvailableWarning(error: Error) {
88
+ if (!hasLoggedBrowserStorageNotAvailableWarning) {
89
+ console.warn(
90
+ `Docusaurus browser storage is not available.
91
+ Possible reasons: running Docusaurus in an iframe, in an incognito browser session, or using too strict browser privacy settings.`,
92
+ error,
93
+ );
94
+ hasLoggedBrowserStorageNotAvailableWarning = true;
95
+ }
96
+ }
97
+
98
+ // Convenient storage interface for a single storage key
99
+ export type StorageSlot = {
100
+ get: () => string | null;
101
+ set: (value: string) => void;
102
+ del: () => void;
103
+ listen: (onChange: (event: StorageEvent) => void) => () => void;
104
+ };
105
+
106
+ const NoopStorageSlot: StorageSlot = {
107
+ get: () => null,
108
+ set: () => {},
109
+ del: () => {},
110
+ listen: () => () => {},
111
+ };
112
+
113
+ // Fail-fast, as storage APIs should not be used during the SSR process
114
+ function createServerStorageSlot(key: string): StorageSlot {
115
+ function throwError(): never {
116
+ throw new Error(`Illegal storage API usage for storage key "${key}".
117
+ Docusaurus storage APIs are not supposed to be called on the server-rendering process.
118
+ Please only call storage APIs in effects and event handlers.`);
119
+ }
120
+
121
+ return {
122
+ get: throwError,
123
+ set: throwError,
124
+ del: throwError,
125
+ listen: throwError,
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Creates an interface to work on a particular key in the storage model.
131
+ * Note that this function only initializes the interface, but doesn't allocate
132
+ * anything by itself (i.e. no side-effects).
133
+ *
134
+ * The API is fail-safe, since usage of browser storage should be considered
135
+ * unreliable. Local storage might simply be unavailable (iframe + browser
136
+ * security) or operations might fail individually. Please assume that using
137
+ * this API can be a no-op. See also https://github.com/facebook/docusaurus/issues/6036
138
+ */
139
+ export function createStorageSlot(
140
+ keyInput: string,
141
+ options?: {persistence?: StorageType},
142
+ ): StorageSlot {
143
+ const key = applyNamespace(keyInput);
144
+ if (typeof window === 'undefined') {
145
+ return createServerStorageSlot(key);
146
+ }
147
+ const storage = getBrowserStorage(options?.persistence);
148
+ if (storage === null) {
149
+ return NoopStorageSlot;
150
+ }
151
+ return {
152
+ get: () => {
153
+ try {
154
+ return storage.getItem(key);
155
+ } catch (err) {
156
+ console.error(`Docusaurus storage error, can't get key=${key}`, err);
157
+ return null;
158
+ }
159
+ },
160
+ set: (newValue) => {
161
+ try {
162
+ const oldValue = storage.getItem(key);
163
+ storage.setItem(key, newValue);
164
+ dispatchChangeEvent({
165
+ key,
166
+ oldValue,
167
+ newValue,
168
+ storage,
169
+ });
170
+ } catch (err) {
171
+ console.error(
172
+ `Docusaurus storage error, can't set ${key}=${newValue}`,
173
+ err,
174
+ );
175
+ }
176
+ },
177
+ del: () => {
178
+ try {
179
+ const oldValue = storage.getItem(key);
180
+ storage.removeItem(key);
181
+ dispatchChangeEvent({key, oldValue, newValue: null, storage});
182
+ } catch (err) {
183
+ console.error(`Docusaurus storage error, can't delete key=${key}`, err);
184
+ }
185
+ },
186
+ listen: (onChange) => {
187
+ try {
188
+ const listener = (event: StorageEvent) => {
189
+ if (event.storageArea === storage && event.key === key) {
190
+ onChange(event);
191
+ }
192
+ };
193
+ window.addEventListener('storage', listener);
194
+ return () => window.removeEventListener('storage', listener);
195
+ } catch (err) {
196
+ console.error(
197
+ `Docusaurus storage error, can't listen for changes of key=${key}`,
198
+ err,
199
+ );
200
+ return () => {};
201
+ }
202
+ },
203
+ };
204
+ }
205
+
206
+ export function useStorageSlot(
207
+ key: string | null,
208
+ options?: {persistence?: StorageType},
209
+ ): [string | null, StorageSlot] {
210
+ // Not ideal but good enough: assumes storage slot config is constant
211
+ const [storageSlot] = useState(() => {
212
+ if (key === null) {
213
+ return NoopStorageSlot;
214
+ }
215
+ return createStorageSlot(key, options);
216
+ });
217
+
218
+ const listen: StorageSlot['listen'] = useCallback(
219
+ (onChange) => {
220
+ // Do not try to add a listener during SSR
221
+ if (typeof window === 'undefined') {
222
+ return () => {};
223
+ }
224
+ return storageSlot.listen(onChange);
225
+ },
226
+ [storageSlot],
227
+ );
228
+
229
+ const currentValue = useSyncExternalStore(
230
+ listen,
231
+ () => {
232
+ return storageSlot.get();
233
+ },
234
+ () => null,
235
+ );
236
+
237
+ return [currentValue, storageSlot];
238
+ }
239
+
240
+ /**
241
+ * Returns a list of all the keys currently stored in browser storage,
242
+ * or an empty list if browser storage can't be accessed.
243
+ */
244
+ export function listStorageKeys(
245
+ storageType: StorageType = DefaultStorageType,
246
+ ): string[] {
247
+ const browserStorage = getBrowserStorage(storageType);
248
+ if (!browserStorage) {
249
+ return [];
250
+ }
251
+
252
+ const keys: string[] = [];
253
+ for (let i = 0; i < browserStorage.length; i += 1) {
254
+ const key = browserStorage.key(i);
255
+ if (key !== null) {
256
+ keys.push(key);
257
+ }
258
+ }
259
+ return keys;
260
+ }