@docusaurus/theme-common 2.2.0 → 2.3.1

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 (39) hide show
  1. package/lib/hooks/useSearchPage.d.ts.map +1 -1
  2. package/lib/hooks/useSearchPage.js +4 -2
  3. package/lib/hooks/useSearchPage.js.map +1 -1
  4. package/lib/index.d.ts +1 -1
  5. package/lib/index.d.ts.map +1 -1
  6. package/lib/index.js +1 -1
  7. package/lib/index.js.map +1 -1
  8. package/lib/internal.d.ts +3 -2
  9. package/lib/internal.d.ts.map +1 -1
  10. package/lib/internal.js +2 -2
  11. package/lib/internal.js.map +1 -1
  12. package/lib/utils/historyUtils.d.ts +12 -1
  13. package/lib/utils/historyUtils.d.ts.map +1 -1
  14. package/lib/utils/historyUtils.js +23 -0
  15. package/lib/utils/historyUtils.js.map +1 -1
  16. package/lib/utils/scrollUtils.d.ts.map +1 -1
  17. package/lib/utils/scrollUtils.js +4 -1
  18. package/lib/utils/scrollUtils.js.map +1 -1
  19. package/lib/utils/storageUtils.d.ts +4 -0
  20. package/lib/utils/storageUtils.d.ts.map +1 -1
  21. package/lib/utils/storageUtils.js +77 -7
  22. package/lib/utils/storageUtils.js.map +1 -1
  23. package/lib/utils/tabsUtils.d.ts +46 -0
  24. package/lib/utils/tabsUtils.d.ts.map +1 -0
  25. package/lib/utils/tabsUtils.js +153 -0
  26. package/lib/utils/tabsUtils.js.map +1 -0
  27. package/package.json +11 -10
  28. package/src/hooks/useSearchPage.ts +10 -5
  29. package/src/index.ts +5 -1
  30. package/src/internal.ts +7 -5
  31. package/src/utils/historyUtils.ts +33 -1
  32. package/src/utils/scrollUtils.tsx +4 -1
  33. package/src/utils/storageUtils.ts +115 -7
  34. package/src/utils/tabsUtils.tsx +270 -0
  35. package/lib/contexts/tabGroupChoice.d.ts +0 -21
  36. package/lib/contexts/tabGroupChoice.d.ts.map +0 -1
  37. package/lib/contexts/tabGroupChoice.js +0 -49
  38. package/lib/contexts/tabGroupChoice.js.map +0 -1
  39. package/src/contexts/tabGroupChoice.tsx +0 -85
@@ -0,0 +1,270 @@
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
+ isValidElement,
10
+ useCallback,
11
+ useState,
12
+ useMemo,
13
+ type ReactNode,
14
+ type ReactElement,
15
+ useLayoutEffect,
16
+ } from 'react';
17
+ import {useHistory} from '@docusaurus/router';
18
+ import {useQueryStringValue} from '@docusaurus/theme-common/internal';
19
+ import {duplicates, useStorageSlot} from '../index';
20
+
21
+ /**
22
+ * TabValue is the "config" of a given Tab
23
+ * Provided through <Tabs> "values" prop or through the children <TabItem> props
24
+ */
25
+ export interface TabValue {
26
+ readonly value: string;
27
+ readonly label?: string;
28
+ readonly attributes?: {[key: string]: unknown};
29
+ readonly default?: boolean;
30
+ }
31
+
32
+ export interface TabsProps {
33
+ readonly lazy?: boolean;
34
+ readonly block?: boolean;
35
+ readonly children:
36
+ | readonly ReactElement<TabItemProps>[]
37
+ | ReactElement<TabItemProps>;
38
+ readonly defaultValue?: string | null;
39
+ readonly values?: readonly TabValue[];
40
+ readonly groupId?: string;
41
+ readonly className?: string;
42
+ readonly queryString?: string | boolean;
43
+ }
44
+
45
+ export interface TabItemProps {
46
+ readonly children: ReactNode;
47
+ readonly value: string;
48
+ readonly default?: boolean;
49
+ readonly label?: string;
50
+ readonly hidden?: boolean;
51
+ readonly className?: string;
52
+ readonly attributes?: {[key: string]: unknown};
53
+ }
54
+
55
+ // A very rough duck type, but good enough to guard against mistakes while
56
+ // allowing customization
57
+ function isTabItem(
58
+ comp: ReactElement<object>,
59
+ ): comp is ReactElement<TabItemProps> {
60
+ return 'value' in comp.props;
61
+ }
62
+
63
+ function ensureValidChildren(children: TabsProps['children']) {
64
+ return React.Children.map(children, (child) => {
65
+ if (isValidElement(child) && isTabItem(child)) {
66
+ return child;
67
+ }
68
+ // child.type.name will give non-sensical values in prod because of
69
+ // minification, but we assume it won't throw in prod.
70
+ throw new Error(
71
+ `Docusaurus error: Bad <Tabs> child <${
72
+ // @ts-expect-error: guarding against unexpected cases
73
+ typeof child.type === 'string' ? child.type : child.type.name
74
+ }>: all children of the <Tabs> component should be <TabItem>, and every <TabItem> should have a unique "value" prop.`,
75
+ );
76
+ });
77
+ }
78
+
79
+ function extractChildrenTabValues(children: TabsProps['children']): TabValue[] {
80
+ return ensureValidChildren(children).map(
81
+ ({props: {value, label, attributes, default: isDefault}}) => ({
82
+ value,
83
+ label,
84
+ attributes,
85
+ default: isDefault,
86
+ }),
87
+ );
88
+ }
89
+
90
+ function ensureNoDuplicateValue(values: readonly TabValue[]) {
91
+ const dup = duplicates(values, (a, b) => a.value === b.value);
92
+ if (dup.length > 0) {
93
+ throw new Error(
94
+ `Docusaurus error: Duplicate values "${dup
95
+ .map((a) => a.value)
96
+ .join(', ')}" found in <Tabs>. Every value needs to be unique.`,
97
+ );
98
+ }
99
+ }
100
+
101
+ function useTabValues(
102
+ props: Pick<TabsProps, 'values' | 'children'>,
103
+ ): readonly TabValue[] {
104
+ const {values: valuesProp, children} = props;
105
+ return useMemo(() => {
106
+ const values = valuesProp ?? extractChildrenTabValues(children);
107
+ ensureNoDuplicateValue(values);
108
+ return values;
109
+ }, [valuesProp, children]);
110
+ }
111
+
112
+ function isValidValue({
113
+ value,
114
+ tabValues,
115
+ }: {
116
+ value: string | null | undefined;
117
+ tabValues: readonly TabValue[];
118
+ }) {
119
+ return tabValues.some((a) => a.value === value);
120
+ }
121
+
122
+ function getInitialStateValue({
123
+ defaultValue,
124
+ tabValues,
125
+ }: {
126
+ defaultValue: TabsProps['defaultValue'];
127
+ tabValues: readonly TabValue[];
128
+ }): string {
129
+ if (tabValues.length === 0) {
130
+ throw new Error(
131
+ 'Docusaurus error: the <Tabs> component requires at least one <TabItem> children component',
132
+ );
133
+ }
134
+ if (defaultValue) {
135
+ // Warn user about passing incorrect defaultValue as prop.
136
+ if (!isValidValue({value: defaultValue, tabValues})) {
137
+ throw new Error(
138
+ `Docusaurus error: The <Tabs> has a defaultValue "${defaultValue}" but none of its children has the corresponding value. Available values are: ${tabValues
139
+ .map((a) => a.value)
140
+ .join(
141
+ ', ',
142
+ )}. If you intend to show no default tab, use defaultValue={null} instead.`,
143
+ );
144
+ }
145
+ return defaultValue;
146
+ }
147
+ const defaultTabValue =
148
+ tabValues.find((tabValue) => tabValue.default) ?? tabValues[0];
149
+ if (!defaultTabValue) {
150
+ throw new Error('Unexpected error: 0 tabValues');
151
+ }
152
+ return defaultTabValue.value;
153
+ }
154
+
155
+ function getStorageKey(groupId: string | undefined) {
156
+ if (!groupId) {
157
+ return null;
158
+ }
159
+ return `docusaurus.tab.${groupId}`;
160
+ }
161
+
162
+ function getQueryStringKey({
163
+ queryString = false,
164
+ groupId,
165
+ }: Pick<TabsProps, 'queryString' | 'groupId'>) {
166
+ if (typeof queryString === 'string') {
167
+ return queryString;
168
+ }
169
+ if (queryString === false) {
170
+ return null;
171
+ }
172
+ if (queryString === true && !groupId) {
173
+ throw new Error(
174
+ `Docusaurus error: The <Tabs> component groupId prop is required if queryString=true, because this value is used as the search param name. You can also provide an explicit value such as queryString="my-search-param".`,
175
+ );
176
+ }
177
+ return groupId ?? null;
178
+ }
179
+
180
+ function useTabQueryString({
181
+ queryString = false,
182
+ groupId,
183
+ }: Pick<TabsProps, 'queryString' | 'groupId'>) {
184
+ const history = useHistory();
185
+ const key = getQueryStringKey({queryString, groupId});
186
+ const value = useQueryStringValue(key);
187
+
188
+ const setValue = useCallback(
189
+ (newValue: string) => {
190
+ if (!key) {
191
+ return; // no-op
192
+ }
193
+ const searchParams = new URLSearchParams(history.location.search);
194
+ searchParams.set(key, newValue);
195
+ history.replace({...history.location, search: searchParams.toString()});
196
+ },
197
+ [key, history],
198
+ );
199
+
200
+ return [value, setValue] as const;
201
+ }
202
+
203
+ function useTabStorage({groupId}: Pick<TabsProps, 'groupId'>) {
204
+ const key = getStorageKey(groupId);
205
+ const [value, storageSlot] = useStorageSlot(key);
206
+
207
+ const setValue = useCallback(
208
+ (newValue: string) => {
209
+ if (!key) {
210
+ return; // no-op
211
+ }
212
+ storageSlot.set(newValue);
213
+ },
214
+ [key, storageSlot],
215
+ );
216
+
217
+ return [value, setValue] as const;
218
+ }
219
+
220
+ export function useTabs(props: TabsProps): {
221
+ selectedValue: string;
222
+ selectValue: (value: string) => void;
223
+ tabValues: readonly TabValue[];
224
+ } {
225
+ const {defaultValue, queryString = false, groupId} = props;
226
+ const tabValues = useTabValues(props);
227
+
228
+ const [selectedValue, setSelectedValue] = useState(() =>
229
+ getInitialStateValue({defaultValue, tabValues}),
230
+ );
231
+
232
+ const [queryStringValue, setQueryString] = useTabQueryString({
233
+ queryString,
234
+ groupId,
235
+ });
236
+
237
+ const [storageValue, setStorageValue] = useTabStorage({
238
+ groupId,
239
+ });
240
+
241
+ // We sync valid querystring/storage value to state on change + hydration
242
+ const valueToSync = (() => {
243
+ const value = queryStringValue ?? storageValue;
244
+ if (!isValidValue({value, tabValues})) {
245
+ return null;
246
+ }
247
+ return value;
248
+ })();
249
+ // Sync in a layout/sync effect is important, for useScrollPositionBlocker
250
+ // See https://github.com/facebook/docusaurus/issues/8625
251
+ useLayoutEffect(() => {
252
+ if (valueToSync) {
253
+ setSelectedValue(valueToSync);
254
+ }
255
+ }, [valueToSync]);
256
+
257
+ const selectValue = useCallback(
258
+ (newValue: string) => {
259
+ if (!isValidValue({value: newValue, tabValues})) {
260
+ throw new Error(`Can't select invalid tab value=${newValue}`);
261
+ }
262
+ setSelectedValue(newValue);
263
+ setQueryString(newValue);
264
+ setStorageValue(newValue);
265
+ },
266
+ [setQueryString, setStorageValue, tabValues],
267
+ );
268
+
269
+ return {selectedValue, selectValue, tabValues};
270
+ }
@@ -1,21 +0,0 @@
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
- import { type ReactNode } from 'react';
8
- declare type ContextValue = {
9
- /** A map from `groupId` to the `value` of the saved choice. */
10
- readonly tabGroupChoices: {
11
- readonly [groupId: string]: string;
12
- };
13
- /** Set the new choice value of a group. */
14
- readonly setTabGroupChoices: (groupId: string, newChoice: string) => void;
15
- };
16
- export declare function TabGroupChoiceProvider({ children, }: {
17
- children: ReactNode;
18
- }): JSX.Element;
19
- export declare function useTabGroupChoice(): ContextValue;
20
- export {};
21
- //# sourceMappingURL=tabGroupChoice.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tabGroupChoice.d.ts","sourceRoot":"","sources":["../../src/contexts/tabGroupChoice.tsx"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAc,EAMZ,KAAK,SAAS,EACf,MAAM,OAAO,CAAC;AAMf,aAAK,YAAY,GAAG;IAClB,+DAA+D;IAC/D,QAAQ,CAAC,eAAe,EAAE;QAAC,QAAQ,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAAA;KAAC,CAAC;IAC/D,2CAA2C;IAC3C,QAAQ,CAAC,kBAAkB,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;CAC3E,CAAC;AA4CF,wBAAgB,sBAAsB,CAAC,EACrC,QAAQ,GACT,EAAE;IACD,QAAQ,EAAE,SAAS,CAAC;CACrB,GAAG,GAAG,CAAC,OAAO,CAGd;AAED,wBAAgB,iBAAiB,IAAI,YAAY,CAMhD"}
@@ -1,49 +0,0 @@
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
- import React, { useState, useCallback, useEffect, useMemo, useContext, } from 'react';
8
- import { createStorageSlot, listStorageKeys } from '../utils/storageUtils';
9
- import { ReactContextError } from '../utils/reactUtils';
10
- const TAB_CHOICE_PREFIX = 'docusaurus.tab.';
11
- const Context = React.createContext(undefined);
12
- function useContextValue() {
13
- const [tabGroupChoices, setChoices] = useState({});
14
- const setChoiceSyncWithLocalStorage = useCallback((groupId, newChoice) => {
15
- createStorageSlot(`${TAB_CHOICE_PREFIX}${groupId}`).set(newChoice);
16
- }, []);
17
- useEffect(() => {
18
- try {
19
- const localStorageChoices = {};
20
- listStorageKeys().forEach((storageKey) => {
21
- if (storageKey.startsWith(TAB_CHOICE_PREFIX)) {
22
- const groupId = storageKey.substring(TAB_CHOICE_PREFIX.length);
23
- localStorageChoices[groupId] = createStorageSlot(storageKey).get();
24
- }
25
- });
26
- setChoices(localStorageChoices);
27
- }
28
- catch (err) {
29
- console.error(err);
30
- }
31
- }, []);
32
- const setTabGroupChoices = useCallback((groupId, newChoice) => {
33
- setChoices((oldChoices) => ({ ...oldChoices, [groupId]: newChoice }));
34
- setChoiceSyncWithLocalStorage(groupId, newChoice);
35
- }, [setChoiceSyncWithLocalStorage]);
36
- return useMemo(() => ({ tabGroupChoices, setTabGroupChoices }), [tabGroupChoices, setTabGroupChoices]);
37
- }
38
- export function TabGroupChoiceProvider({ children, }) {
39
- const value = useContextValue();
40
- return <Context.Provider value={value}>{children}</Context.Provider>;
41
- }
42
- export function useTabGroupChoice() {
43
- const context = useContext(Context);
44
- if (context == null) {
45
- throw new ReactContextError('TabGroupChoiceProvider');
46
- }
47
- return context;
48
- }
49
- //# sourceMappingURL=tabGroupChoice.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tabGroupChoice.js","sourceRoot":"","sources":["../../src/contexts/tabGroupChoice.tsx"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,EACZ,QAAQ,EACR,WAAW,EACX,SAAS,EACT,OAAO,EACP,UAAU,GAEX,MAAM,OAAO,CAAC;AACf,OAAO,EAAC,iBAAiB,EAAE,eAAe,EAAC,MAAM,uBAAuB,CAAC;AACzE,OAAO,EAAC,iBAAiB,EAAC,MAAM,qBAAq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AC,CAAC;IACpD,CAAC,EACD,CAAC,6BAA6B,CAAC,CAChC,CAAC;IAEF,OAAO,OAAO,CACZ,GAAG,EAAE,CAAC,CAAC,EAAC,eAAe,EAAE,kBAAkB,EAAC,CAAC,EAC7C,CAAC,eAAe,EAAE,kBAAkB,CAAC,CACtC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,EACrC,QAAQ,GAGT;IACC,MAAM,KAAK,GAAG,eAAe,EAAE,CAAC;IAChC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;AACvE,CAAC;AAED,MAAM,UAAU,iBAAiB;IAC/B,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC;IACpC,IAAI,OAAO,IAAI,IAAI,EAAE;QACnB,MAAM,IAAI,iBAAiB,CAAC,wBAAwB,CAAC,CAAC;KACvD;IACD,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -1,85 +0,0 @@
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
- useState,
10
- useCallback,
11
- useEffect,
12
- useMemo,
13
- useContext,
14
- type ReactNode,
15
- } from 'react';
16
- import {createStorageSlot, listStorageKeys} from '../utils/storageUtils';
17
- import {ReactContextError} from '../utils/reactUtils';
18
-
19
- const TAB_CHOICE_PREFIX = 'docusaurus.tab.';
20
-
21
- type ContextValue = {
22
- /** A map from `groupId` to the `value` of the saved choice. */
23
- readonly tabGroupChoices: {readonly [groupId: string]: string};
24
- /** Set the new choice value of a group. */
25
- readonly setTabGroupChoices: (groupId: string, newChoice: string) => void;
26
- };
27
-
28
- const Context = React.createContext<ContextValue | undefined>(undefined);
29
-
30
- function useContextValue(): ContextValue {
31
- const [tabGroupChoices, setChoices] = useState<{
32
- readonly [groupId: string]: string;
33
- }>({});
34
- const setChoiceSyncWithLocalStorage = useCallback(
35
- (groupId: string, newChoice: string) => {
36
- createStorageSlot(`${TAB_CHOICE_PREFIX}${groupId}`).set(newChoice);
37
- },
38
- [],
39
- );
40
-
41
- useEffect(() => {
42
- try {
43
- const localStorageChoices: {[groupId: string]: string} = {};
44
- listStorageKeys().forEach((storageKey) => {
45
- if (storageKey.startsWith(TAB_CHOICE_PREFIX)) {
46
- const groupId = storageKey.substring(TAB_CHOICE_PREFIX.length);
47
- localStorageChoices[groupId] = createStorageSlot(storageKey).get()!;
48
- }
49
- });
50
- setChoices(localStorageChoices);
51
- } catch (err) {
52
- console.error(err);
53
- }
54
- }, []);
55
-
56
- const setTabGroupChoices = useCallback(
57
- (groupId: string, newChoice: string) => {
58
- setChoices((oldChoices) => ({...oldChoices, [groupId]: newChoice}));
59
- setChoiceSyncWithLocalStorage(groupId, newChoice);
60
- },
61
- [setChoiceSyncWithLocalStorage],
62
- );
63
-
64
- return useMemo(
65
- () => ({tabGroupChoices, setTabGroupChoices}),
66
- [tabGroupChoices, setTabGroupChoices],
67
- );
68
- }
69
-
70
- export function TabGroupChoiceProvider({
71
- children,
72
- }: {
73
- children: ReactNode;
74
- }): JSX.Element {
75
- const value = useContextValue();
76
- return <Context.Provider value={value}>{children}</Context.Provider>;
77
- }
78
-
79
- export function useTabGroupChoice(): ContextValue {
80
- const context = useContext(Context);
81
- if (context == null) {
82
- throw new ReactContextError('TabGroupChoiceProvider');
83
- }
84
- return context;
85
- }