@docusaurus/theme-common 2.0.0-beta.12faed89d → 2.0.0-beta.13

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 (89) hide show
  1. package/copyUntypedFiles.js +20 -0
  2. package/lib/.tsbuildinfo +1 -1
  3. package/lib/{utils/useCollapsible.d.ts → components/Collapsible/index.d.ts} +9 -3
  4. package/lib/{utils/useCollapsible.js → components/Collapsible/index.js} +36 -14
  5. package/lib/components/Details/index.d.ts +12 -0
  6. package/lib/components/Details/index.js +64 -0
  7. package/lib/components/Details/styles.module.css +58 -0
  8. package/lib/index.d.ts +19 -5
  9. package/lib/index.js +14 -3
  10. package/lib/utils/ThemeClassNames.d.ts +36 -12
  11. package/lib/utils/ThemeClassNames.js +36 -3
  12. package/lib/utils/announcementBarUtils.d.ts +3 -3
  13. package/lib/utils/announcementBarUtils.js +14 -18
  14. package/lib/utils/codeBlockUtils.d.ts +10 -0
  15. package/lib/utils/codeBlockUtils.js +119 -0
  16. package/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.d.ts +2 -2
  17. package/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.js +2 -2
  18. package/lib/utils/docsPreferredVersion/DocsPreferredVersionStorage.js +1 -3
  19. package/lib/utils/docsPreferredVersion/useDocsPreferredVersion.d.ts +11 -3
  20. package/lib/utils/docsPreferredVersion/useDocsPreferredVersion.js +1 -2
  21. package/lib/utils/docsUtils.d.ts +20 -0
  22. package/lib/utils/docsUtils.js +106 -0
  23. package/lib/utils/generalUtils.d.ts +6 -0
  24. package/lib/utils/generalUtils.js +2 -2
  25. package/lib/utils/historyUtils.d.ts +11 -0
  26. package/lib/utils/historyUtils.js +39 -0
  27. package/lib/utils/jsUtils.d.ts +19 -0
  28. package/lib/utils/jsUtils.js +25 -0
  29. package/lib/utils/mobileSecondaryMenu.d.ts +2 -2
  30. package/lib/utils/mobileSecondaryMenu.js +3 -4
  31. package/lib/utils/pathUtils.js +1 -3
  32. package/lib/utils/reactUtils.d.ts +9 -0
  33. package/lib/utils/reactUtils.js +26 -0
  34. package/lib/utils/regexpUtils.d.ts +10 -0
  35. package/lib/utils/regexpUtils.js +16 -0
  36. package/lib/utils/scrollUtils.d.ts +52 -0
  37. package/lib/utils/scrollUtils.js +135 -0
  38. package/lib/utils/storageUtils.d.ts +4 -0
  39. package/lib/utils/storageUtils.js +29 -3
  40. package/lib/utils/tagsUtils.d.ts +18 -0
  41. package/lib/utils/tagsUtils.js +33 -0
  42. package/lib/utils/tocUtils.d.ts +15 -0
  43. package/lib/utils/tocUtils.js +34 -0
  44. package/lib/utils/useContextualSearchFilters.d.ts +11 -0
  45. package/lib/utils/useContextualSearchFilters.js +36 -0
  46. package/{src/utils/docsUtils.ts → lib/utils/useLocalPathname.d.ts} +1 -5
  47. package/lib/utils/useLocalPathname.js +16 -0
  48. package/lib/utils/useLocationChange.js +9 -11
  49. package/lib/utils/usePluralForm.js +1 -3
  50. package/lib/utils/usePrevious.js +3 -2
  51. package/lib/utils/useTOCHighlight.d.ts +14 -0
  52. package/lib/utils/useTOCHighlight.js +124 -0
  53. package/lib/utils/useThemeConfig.d.ts +20 -3
  54. package/package.json +18 -12
  55. package/src/{utils/useCollapsible.tsx → components/Collapsible/index.tsx} +70 -25
  56. package/src/components/Details/index.tsx +94 -0
  57. package/src/components/Details/styles.module.css +58 -0
  58. package/src/index.ts +54 -4
  59. package/src/types.d.ts +0 -2
  60. package/src/utils/ThemeClassNames.ts +42 -4
  61. package/src/utils/__tests__/codeBlockUtils.test.ts +2 -2
  62. package/src/utils/__tests__/docsUtils.test.tsx +331 -0
  63. package/src/utils/__tests__/jsUtils.test.ts +33 -0
  64. package/src/utils/__tests__/tagUtils.test.ts +66 -0
  65. package/src/utils/__tests__/tocUtils.test.ts +197 -0
  66. package/src/utils/announcementBarUtils.tsx +20 -15
  67. package/src/utils/codeBlockUtils.ts +151 -0
  68. package/src/utils/docsPreferredVersion/DocsPreferredVersionProvider.tsx +7 -6
  69. package/src/utils/docsPreferredVersion/DocsPreferredVersionStorage.ts +2 -3
  70. package/src/utils/docsPreferredVersion/useDocsPreferredVersion.ts +14 -14
  71. package/src/utils/docsUtils.tsx +185 -0
  72. package/src/utils/generalUtils.ts +3 -2
  73. package/src/utils/historyUtils.ts +50 -0
  74. package/src/utils/jsUtils.ts +33 -0
  75. package/src/utils/mobileSecondaryMenu.tsx +9 -6
  76. package/src/utils/pathUtils.ts +2 -3
  77. package/src/utils/reactUtils.tsx +34 -0
  78. package/src/utils/regexpUtils.ts +23 -0
  79. package/src/utils/scrollUtils.tsx +237 -0
  80. package/src/utils/storageUtils.ts +27 -4
  81. package/src/utils/tagsUtils.ts +48 -0
  82. package/src/utils/tocUtils.ts +55 -0
  83. package/src/utils/useContextualSearchFilters.ts +50 -0
  84. package/src/utils/useLocalPathname.ts +20 -0
  85. package/src/utils/useLocationChange.ts +10 -12
  86. package/src/utils/usePluralForm.ts +2 -3
  87. package/src/utils/usePrevious.ts +3 -2
  88. package/src/utils/useTOCHighlight.ts +179 -0
  89. package/src/utils/useThemeConfig.ts +19 -3
@@ -0,0 +1,185 @@
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, {createContext, ReactNode, useContext} from 'react';
9
+ import {useAllDocsData} from '@theme/hooks/useDocs';
10
+ import {
11
+ PropSidebar,
12
+ PropSidebarItem,
13
+ PropSidebarItemCategory,
14
+ PropVersionDoc,
15
+ PropVersionMetadata,
16
+ } from '@docusaurus/plugin-content-docs';
17
+ import {isSamePath} from './pathUtils';
18
+ import {useLocation} from '@docusaurus/router';
19
+
20
+ // TODO not ideal, see also "useDocs"
21
+ export const isDocsPluginEnabled: boolean = !!useAllDocsData;
22
+
23
+ // Using a Symbol because null is a valid context value (a doc can have no sidebar)
24
+ // Inspired by https://github.com/jamiebuilds/unstated-next/blob/master/src/unstated-next.tsx
25
+ const EmptyContextValue: unique symbol = Symbol('EmptyContext');
26
+
27
+ const DocsVersionContext = createContext<
28
+ PropVersionMetadata | typeof EmptyContextValue
29
+ >(EmptyContextValue);
30
+
31
+ export function DocsVersionProvider({
32
+ children,
33
+ version,
34
+ }: {
35
+ children: ReactNode;
36
+ version: PropVersionMetadata | typeof EmptyContextValue;
37
+ }): JSX.Element {
38
+ return (
39
+ <DocsVersionContext.Provider value={version}>
40
+ {children}
41
+ </DocsVersionContext.Provider>
42
+ );
43
+ }
44
+
45
+ export function useDocsVersion(): PropVersionMetadata {
46
+ const version = useContext(DocsVersionContext);
47
+ if (version === EmptyContextValue) {
48
+ throw new Error('This hook requires usage of <DocsVersionProvider>');
49
+ }
50
+ return version;
51
+ }
52
+
53
+ export function useDocById(id: string): PropVersionDoc;
54
+ export function useDocById(id: string | undefined): PropVersionDoc | undefined;
55
+ export function useDocById(id: string | undefined): PropVersionDoc | undefined {
56
+ const version = useDocsVersion();
57
+ if (!id) {
58
+ return undefined;
59
+ }
60
+ const doc = version.docs[id];
61
+ if (!doc) {
62
+ throw new Error(`no version doc found by id=${id}`);
63
+ }
64
+ return doc;
65
+ }
66
+
67
+ const DocsSidebarContext = createContext<
68
+ PropSidebar | null | typeof EmptyContextValue
69
+ >(EmptyContextValue);
70
+
71
+ export function DocsSidebarProvider({
72
+ children,
73
+ sidebar,
74
+ }: {
75
+ children: ReactNode;
76
+ sidebar: PropSidebar | null;
77
+ }): JSX.Element {
78
+ return (
79
+ <DocsSidebarContext.Provider value={sidebar}>
80
+ {children}
81
+ </DocsSidebarContext.Provider>
82
+ );
83
+ }
84
+
85
+ export function useDocsSidebar(): PropSidebar | null {
86
+ const sidebar = useContext(DocsSidebarContext);
87
+ if (sidebar === EmptyContextValue) {
88
+ throw new Error('This hook requires usage of <DocsSidebarProvider>');
89
+ }
90
+ return sidebar;
91
+ }
92
+
93
+ // Use the components props and the sidebar in context
94
+ // to get back the related sidebar category that we want to render
95
+ export function findSidebarCategory(
96
+ sidebar: PropSidebar,
97
+ predicate: (category: PropSidebarItemCategory) => boolean,
98
+ ): PropSidebarItemCategory | undefined {
99
+ // eslint-disable-next-line no-restricted-syntax
100
+ for (const item of sidebar) {
101
+ if (item.type === 'category') {
102
+ if (predicate(item)) {
103
+ return item;
104
+ } else {
105
+ const subItem = findSidebarCategory(item.items, predicate);
106
+ if (subItem) {
107
+ return subItem;
108
+ }
109
+ }
110
+ }
111
+ }
112
+ return undefined;
113
+ }
114
+
115
+ // If a category card has no link => link to the first subItem having a link
116
+ export function findFirstCategoryLink(
117
+ item: PropSidebarItemCategory,
118
+ ): string | undefined {
119
+ if (item.href) {
120
+ return item.href;
121
+ }
122
+
123
+ // eslint-disable-next-line no-restricted-syntax
124
+ for (const subItem of item.items) {
125
+ if (subItem.type === 'link') {
126
+ return subItem.href;
127
+ }
128
+ if (subItem.type === 'category') {
129
+ const categoryLink = findFirstCategoryLink(subItem);
130
+ if (categoryLink) {
131
+ return categoryLink;
132
+ }
133
+ } else {
134
+ throw new Error(
135
+ `Unexpected category item type for ${JSON.stringify(subItem)}`,
136
+ );
137
+ }
138
+ }
139
+ return undefined;
140
+ }
141
+
142
+ export function useCurrentSidebarCategory(): PropSidebarItemCategory {
143
+ const {pathname} = useLocation();
144
+ const sidebar = useDocsSidebar();
145
+ if (!sidebar) {
146
+ throw new Error('Unexpected: cant find current sidebar in context');
147
+ }
148
+ const category = findSidebarCategory(sidebar, (item) =>
149
+ isSamePath(item.href, pathname),
150
+ );
151
+ if (!category) {
152
+ throw new Error(
153
+ `Unexpected: sidebar category could not be found for pathname='${pathname}'.
154
+ Hook useCurrentSidebarCategory() should only be used on Category pages`,
155
+ );
156
+ }
157
+ return category;
158
+ }
159
+
160
+ function containsActiveSidebarItem(
161
+ items: PropSidebarItem[],
162
+ activePath: string,
163
+ ): boolean {
164
+ return items.some((subItem) => isActiveSidebarItem(subItem, activePath));
165
+ }
166
+
167
+ export function isActiveSidebarItem(
168
+ item: PropSidebarItem,
169
+ activePath: string,
170
+ ): boolean {
171
+ const isActive = (testedPath: string | undefined) =>
172
+ typeof testedPath !== 'undefined' && isSamePath(testedPath, activePath);
173
+
174
+ if (item.type === 'link') {
175
+ return isActive(item.href);
176
+ }
177
+
178
+ if (item.type === 'category') {
179
+ return (
180
+ isActive(item.href) || containsActiveSidebarItem(item.items, activePath)
181
+ );
182
+ }
183
+
184
+ return false;
185
+ }
@@ -4,11 +4,12 @@
4
4
  * This source code is licensed under the MIT license found in the
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
+
7
8
  import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
8
9
 
9
10
  export const useTitleFormatter = (title?: string | undefined): string => {
10
- const {siteConfig = {}} = useDocusaurusContext();
11
- const {title: siteTitle, titleDelimiter = '|'} = siteConfig;
11
+ const {siteConfig} = useDocusaurusContext();
12
+ const {title: siteTitle, titleDelimiter} = siteConfig;
12
13
  return title && title.trim().length
13
14
  ? `${title.trim()} ${titleDelimiter} ${siteTitle}`
14
15
  : siteTitle;
@@ -0,0 +1,50 @@
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 {useEffect, useRef} from 'react';
9
+ import {useHistory} from '@docusaurus/router';
10
+ import type {Location, Action} from '@docusaurus/history';
11
+
12
+ type HistoryBlockHandler = (location: Location, action: Action) => void | false;
13
+
14
+ /*
15
+ Permits to register a handler that will be called on history actions (pop,push,replace)
16
+ If the handler returns false, the navigation transition will be blocked/cancelled
17
+ */
18
+ export function useHistoryActionHandler(handler: HistoryBlockHandler): void {
19
+ const {block} = useHistory();
20
+
21
+ // Avoid stale closure issues without triggering useless re-renders
22
+ const lastHandlerRef = useRef(handler);
23
+ useEffect(() => {
24
+ lastHandlerRef.current = handler;
25
+ }, [handler]);
26
+
27
+ useEffect(
28
+ () =>
29
+ // See https://github.com/remix-run/history/blob/main/docs/blocking-transitions.md
30
+ block((location, action) => lastHandlerRef.current(location, action)),
31
+ [block, lastHandlerRef],
32
+ );
33
+ }
34
+
35
+ /*
36
+ Permits to register a handler that will be called on history pop navigation (backward/forward)
37
+ If the handler returns false, the backward/forward transition will be blocked
38
+
39
+ Unfortunately there's no good way to detect the "direction" (backward/forward) of the POP event.
40
+ */
41
+ export function useHistoryPopHandler(handler: HistoryBlockHandler): void {
42
+ useHistoryActionHandler((location, action) => {
43
+ if (action === 'POP') {
44
+ // Eventually block navigation if handler returns false
45
+ return handler(location, action);
46
+ }
47
+ // Don't block other navigation actions
48
+ return undefined;
49
+ });
50
+ }
@@ -0,0 +1,33 @@
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
+ // A replacement of lodash in client code
9
+
10
+ /**
11
+ * Gets the duplicate values in an array.
12
+ * @param arr The array.
13
+ * @param comparator Compares two values and returns `true` if they are equal (duplicated).
14
+ * @returns Value of the elements `v` that have a preceding element `u` where `comparator(u, v) === true`. Values within the returned array are not guaranteed to be unique.
15
+ */
16
+ export function duplicates<T>(
17
+ arr: readonly T[],
18
+ comparator: (a: T, b: T) => boolean = (a, b) => a === b,
19
+ ): T[] {
20
+ return arr.filter(
21
+ (v, vIndex) => arr.findIndex((u) => comparator(u, v)) !== vIndex,
22
+ );
23
+ }
24
+
25
+ /**
26
+ * Remove duplicate array items (similar to _.uniq)
27
+ * @param arr The array.
28
+ * @returns An array with duplicate elements removed by reference comparison.
29
+ */
30
+ export function uniq<T>(arr: T[]): T[] {
31
+ // Note: had problems with [...new Set()]: https://github.com/facebook/docusaurus/issues/4972#issuecomment-863895061
32
+ return Array.from(new Set(arr));
33
+ }
@@ -29,7 +29,7 @@ type ExtraProps = {
29
29
  toggleSidebar: () => void;
30
30
  };
31
31
 
32
- export type MobileSecondaryMenuComponent<Props extends unknown> = ComponentType<
32
+ export type MobileSecondaryMenuComponent<Props> = ComponentType<
33
33
  Props & ExtraProps
34
34
  >;
35
35
 
@@ -46,7 +46,11 @@ type ContextValue = ReturnType<typeof useContextValue>;
46
46
 
47
47
  const Context = createContext<ContextValue | null>(null);
48
48
 
49
- export function MobileSecondaryMenuProvider({children}: {children: ReactNode}) {
49
+ export function MobileSecondaryMenuProvider({
50
+ children,
51
+ }: {
52
+ children: ReactNode;
53
+ }): JSX.Element {
50
54
  return (
51
55
  <Context.Provider value={useContextValue()}>{children}</Context.Provider>
52
56
  );
@@ -79,13 +83,14 @@ function useShallowMemoizedObject<O extends Record<string, unknown>>(obj: O) {
79
83
  return useMemo(
80
84
  () => obj,
81
85
  // Is this safe?
86
+ // eslint-disable-next-line react-hooks/exhaustive-deps
82
87
  [...Object.keys(obj), ...Object.values(obj)],
83
88
  );
84
89
  }
85
90
 
86
91
  // Fill the secondary menu placeholder with some real content
87
92
  export function MobileSecondaryMenuFiller<
88
- Props extends Record<string, unknown>
93
+ Props extends Record<string, unknown>,
89
94
  >({
90
95
  component,
91
96
  props,
@@ -103,9 +108,7 @@ export function MobileSecondaryMenuFiller<
103
108
  setState({component, props: memoizedProps});
104
109
  }, [setState, component, memoizedProps]);
105
110
 
106
- useEffect(() => {
107
- return () => setState(null);
108
- }, [setState]);
111
+ useEffect(() => () => setState(null), [setState]);
109
112
 
110
113
  return null;
111
114
  }
@@ -10,8 +10,7 @@ export const isSamePath = (
10
10
  path1: string | undefined,
11
11
  path2: string | undefined,
12
12
  ): boolean => {
13
- const normalize = (pathname: string | undefined) => {
14
- return !pathname || pathname?.endsWith('/') ? pathname : `${pathname}/`;
15
- };
13
+ const normalize = (pathname: string | undefined) =>
14
+ !pathname || pathname?.endsWith('/') ? pathname : `${pathname}/`;
16
15
  return normalize(path1) === normalize(path2);
17
16
  };
@@ -0,0 +1,34 @@
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, useEffect, useLayoutEffect, useRef} from 'react';
9
+
10
+ // This hook is like useLayoutEffect, but without the SSR warning
11
+ // It seems hacky but it's used in many React libs (Redux, Formik...)
12
+ // Also mentioned here: https://github.com/facebook/react/issues/16956
13
+ // It is useful when you need to update a ref as soon as possible after a React render (before useEffect)
14
+ export const useIsomorphicLayoutEffect =
15
+ typeof window !== 'undefined' ? useLayoutEffect : useEffect;
16
+
17
+ // Permits to transform an unstable callback (like an arrow function provided as props)
18
+ // to a "stable" callback that is safe to use in a useEffect dependency array
19
+ // Useful to avoid React stale closure problems + avoid useless effect re-executions
20
+ //
21
+ // Workaround until the React team recommends a good solution, see https://github.com/facebook/react/issues/16956
22
+ // This generally works has some potential drawbacks, such as https://github.com/facebook/react/issues/16956#issuecomment-536636418
23
+ export function useDynamicCallback<T extends (...args: never[]) => unknown>(
24
+ callback: T,
25
+ ): T {
26
+ const ref = useRef<T>(callback);
27
+
28
+ useIsomorphicLayoutEffect(() => {
29
+ ref.current = callback;
30
+ }, [callback]);
31
+
32
+ // @ts-expect-error: TODO, not sure how to fix this TS error
33
+ return useCallback<T>((...args) => ref.current(...args), []);
34
+ }
@@ -0,0 +1,23 @@
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
+ * Utility to convert an optional string into a Regex case sensitive and global
10
+ */
11
+ export function isRegexpStringMatch(
12
+ regexAsString?: string,
13
+ valueToTest?: string,
14
+ ): boolean {
15
+ if (
16
+ typeof regexAsString === 'undefined' ||
17
+ typeof valueToTest === 'undefined'
18
+ ) {
19
+ return false;
20
+ }
21
+
22
+ return new RegExp(regexAsString, 'gi').test(valueToTest);
23
+ }
@@ -0,0 +1,237 @@
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
+ createContext,
10
+ ReactNode,
11
+ useCallback,
12
+ useContext,
13
+ useEffect,
14
+ useLayoutEffect,
15
+ useMemo,
16
+ useRef,
17
+ } from 'react';
18
+ import {useDynamicCallback} from './reactUtils';
19
+ import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
20
+
21
+ /**
22
+ * We need a way to update the scroll position while ignoring scroll events
23
+ * without affecting Navbar/BackToTop visibility
24
+ *
25
+ * This API permits to temporarily disable/ignore scroll events
26
+ * Motivated by https://github.com/facebook/docusaurus/pull/5618
27
+ */
28
+ type ScrollController = {
29
+ /**
30
+ * A boolean ref tracking whether scroll events are enabled
31
+ */
32
+ scrollEventsEnabledRef: React.MutableRefObject<boolean>;
33
+ /**
34
+ * Enables scroll events in `useScrollPosition`
35
+ */
36
+ enableScrollEvents: () => void;
37
+ /**
38
+ * Disables scroll events in `useScrollPosition`
39
+ */
40
+ disableScrollEvents: () => void;
41
+ };
42
+
43
+ function useScrollControllerContextValue(): ScrollController {
44
+ const scrollEventsEnabledRef = useRef(true);
45
+
46
+ return useMemo(
47
+ () => ({
48
+ scrollEventsEnabledRef,
49
+ enableScrollEvents: () => {
50
+ scrollEventsEnabledRef.current = true;
51
+ },
52
+ disableScrollEvents: () => {
53
+ scrollEventsEnabledRef.current = false;
54
+ },
55
+ }),
56
+ [],
57
+ );
58
+ }
59
+
60
+ const ScrollMonitorContext = createContext<ScrollController | undefined>(
61
+ undefined,
62
+ );
63
+
64
+ export function ScrollControllerProvider({
65
+ children,
66
+ }: {
67
+ children: ReactNode;
68
+ }): JSX.Element {
69
+ return (
70
+ <ScrollMonitorContext.Provider value={useScrollControllerContextValue()}>
71
+ {children}
72
+ </ScrollMonitorContext.Provider>
73
+ );
74
+ }
75
+
76
+ export function useScrollController(): ScrollController {
77
+ const context = useContext(ScrollMonitorContext);
78
+ if (context == null) {
79
+ throw new Error(
80
+ '"useScrollController" is used but no context provider was found in the React tree.',
81
+ );
82
+ }
83
+ return context;
84
+ }
85
+
86
+ const getScrollPosition = (): ScrollPosition | null =>
87
+ ExecutionEnvironment.canUseDOM
88
+ ? {
89
+ scrollX: window.pageXOffset,
90
+ scrollY: window.pageYOffset,
91
+ }
92
+ : null;
93
+
94
+ type ScrollPosition = {scrollX: number; scrollY: number};
95
+
96
+ export function useScrollPosition(
97
+ effect: (
98
+ position: ScrollPosition,
99
+ lastPosition: ScrollPosition | null,
100
+ ) => void,
101
+ deps: unknown[] = [],
102
+ ): void {
103
+ const {scrollEventsEnabledRef} = useScrollController();
104
+ const lastPositionRef = useRef<ScrollPosition | null>(getScrollPosition());
105
+
106
+ const dynamicEffect = useDynamicCallback(effect);
107
+
108
+ useEffect(() => {
109
+ const handleScroll = () => {
110
+ if (!scrollEventsEnabledRef.current) {
111
+ return;
112
+ }
113
+ const currentPosition = getScrollPosition()!;
114
+
115
+ if (dynamicEffect) {
116
+ dynamicEffect(currentPosition, lastPositionRef.current);
117
+ }
118
+
119
+ lastPositionRef.current = currentPosition;
120
+ };
121
+
122
+ const opts: AddEventListenerOptions & EventListenerOptions = {
123
+ passive: true,
124
+ };
125
+
126
+ handleScroll();
127
+ window.addEventListener('scroll', handleScroll, opts);
128
+
129
+ return () => window.removeEventListener('scroll', handleScroll, opts);
130
+ }, [
131
+ dynamicEffect,
132
+ scrollEventsEnabledRef,
133
+ // eslint-disable-next-line react-hooks/exhaustive-deps
134
+ ...deps,
135
+ ]);
136
+ }
137
+
138
+ type UseScrollPositionSaver = {
139
+ /**
140
+ * Measure the top of an element, and store the details
141
+ */
142
+ save: (elem: HTMLElement) => void;
143
+ /**
144
+ * Restore the page position to keep the stored element's position from
145
+ * the top of the viewport, and remove the stored details
146
+ */
147
+ restore: () => {restored: boolean};
148
+ };
149
+
150
+ function useScrollPositionSaver(): UseScrollPositionSaver {
151
+ const lastElementRef = useRef<{elem: HTMLElement | null; top: number}>({
152
+ elem: null,
153
+ top: 0,
154
+ });
155
+
156
+ const save = useCallback((elem: HTMLElement) => {
157
+ lastElementRef.current = {
158
+ elem,
159
+ top: elem.getBoundingClientRect().top,
160
+ };
161
+ }, []);
162
+
163
+ const restore = useCallback(() => {
164
+ const {
165
+ current: {elem, top},
166
+ } = lastElementRef;
167
+ if (!elem) {
168
+ return {restored: false};
169
+ }
170
+ const newTop = elem.getBoundingClientRect().top;
171
+ const heightDiff = newTop - top;
172
+ if (heightDiff) {
173
+ window.scrollBy({left: 0, top: heightDiff});
174
+ }
175
+ lastElementRef.current = {elem: null, top: 0};
176
+
177
+ return {restored: heightDiff !== 0};
178
+ }, []);
179
+
180
+ return useMemo(() => ({save, restore}), [restore, save]);
181
+ }
182
+
183
+ type UseScrollPositionBlockerReturn = {
184
+ blockElementScrollPositionUntilNextRender: (el: HTMLElement) => void;
185
+ };
186
+
187
+ /**
188
+ * This hook permits to "block" the scroll position of a dom element
189
+ * The idea is that we should be able to update DOM content above this element
190
+ * but the screen position of this element should not change
191
+ *
192
+ * Feature motivated by the Tabs groups:
193
+ * clicking on a tab may affect tabs of the same group upper in the tree
194
+ * Yet to avoid a bad UX, the clicked tab must remain under the user mouse!
195
+ * See GIF here: https://github.com/facebook/docusaurus/pull/5618
196
+ */
197
+ export function useScrollPositionBlocker(): UseScrollPositionBlockerReturn {
198
+ const scrollController = useScrollController();
199
+ const scrollPositionSaver = useScrollPositionSaver();
200
+
201
+ const nextLayoutEffectCallbackRef = useRef<(() => void) | undefined>(
202
+ undefined,
203
+ );
204
+
205
+ const blockElementScrollPositionUntilNextRender = useCallback(
206
+ (el: HTMLElement) => {
207
+ scrollPositionSaver.save(el);
208
+ scrollController.disableScrollEvents();
209
+ nextLayoutEffectCallbackRef.current = () => {
210
+ const {restored} = scrollPositionSaver.restore();
211
+ nextLayoutEffectCallbackRef.current = undefined;
212
+
213
+ // Restoring the former scroll position will trigger a scroll event
214
+ // We need to wait for next scroll event to happen
215
+ // before enabling again the scrollController events
216
+ if (restored) {
217
+ const handleScrollRestoreEvent = () => {
218
+ scrollController.enableScrollEvents();
219
+ window.removeEventListener('scroll', handleScrollRestoreEvent);
220
+ };
221
+ window.addEventListener('scroll', handleScrollRestoreEvent);
222
+ } else {
223
+ scrollController.enableScrollEvents();
224
+ }
225
+ };
226
+ },
227
+ [scrollController, scrollPositionSaver],
228
+ );
229
+
230
+ useLayoutEffect(() => {
231
+ nextLayoutEffectCallbackRef.current?.();
232
+ });
233
+
234
+ return {
235
+ blockElementScrollPositionUntilNextRender,
236
+ };
237
+ }
@@ -27,7 +27,7 @@ function getBrowserStorage(
27
27
  try {
28
28
  return window[storageType];
29
29
  } catch (e) {
30
- logOnceBrowserStorageNotAvailableWarning(e);
30
+ logOnceBrowserStorageNotAvailableWarning(e as Error);
31
31
  return null;
32
32
  }
33
33
  }
@@ -79,6 +79,10 @@ Please only call storage APIs in effects and event handlers.`);
79
79
 
80
80
  /**
81
81
  * Creates an object for accessing a particular key in localStorage.
82
+ * The API is fail-safe, and usage of browser storage should be considered unreliable
83
+ * Local storage might simply be unavailable (iframe + browser security) or operations might fail individually
84
+ * Please assume that using this API can be a NO-OP
85
+ * See also https://github.com/facebook/docusaurus/issues/6036
82
86
  */
83
87
  export const createStorageSlot = (
84
88
  key: string,
@@ -92,9 +96,28 @@ export const createStorageSlot = (
92
96
  return NoopStorageSlot;
93
97
  }
94
98
  return {
95
- get: () => browserStorage.getItem(key),
96
- set: (value) => browserStorage.setItem(key, value),
97
- del: () => browserStorage.removeItem(key),
99
+ get: () => {
100
+ try {
101
+ return browserStorage.getItem(key);
102
+ } catch (e) {
103
+ console.error(`Docusaurus storage error, can't get key=${key}`, e);
104
+ return null;
105
+ }
106
+ },
107
+ set: (value) => {
108
+ try {
109
+ browserStorage.setItem(key, value);
110
+ } catch (e) {
111
+ console.error(`Docusaurus storage error, can't set ${key}=${value}`, e);
112
+ }
113
+ },
114
+ del: () => {
115
+ try {
116
+ browserStorage.removeItem(key);
117
+ } catch (e) {
118
+ console.error(`Docusaurus storage error, can't delete key=${key}`, e);
119
+ }
120
+ },
98
121
  };
99
122
  };
100
123