@docusaurus/theme-common 2.0.0-beta.fc64c12e4 → 2.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 (274) hide show
  1. package/lib/components/Collapsible/index.d.ts +35 -6
  2. package/lib/components/Collapsible/index.d.ts.map +1 -0
  3. package/lib/components/Collapsible/index.js +33 -30
  4. package/lib/components/Collapsible/index.js.map +1 -0
  5. package/lib/components/Details/index.d.ts +8 -3
  6. package/lib/components/Details/index.d.ts.map +1 -0
  7. package/lib/components/Details/index.js +31 -19
  8. package/lib/components/Details/index.js.map +1 -0
  9. package/lib/components/Details/styles.module.css +14 -11
  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 +15 -19
  104. package/lib/index.d.ts.map +1 -0
  105. package/lib/index.js +22 -15
  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 +6 -0
  184. package/lib/utils/useLocalPathname.d.ts.map +1 -0
  185. package/lib/utils/useLocalPathname.js +7 -4
  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 -29
  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 -15
  200. package/src/components/Collapsible/index.tsx +57 -48
  201. package/src/components/Details/index.tsx +27 -12
  202. package/src/components/Details/styles.module.css +14 -11
  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 +49 -42
  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 +6 -4
  249. package/src/utils/useLocationChange.ts +24 -20
  250. package/src/utils/usePluralForm.ts +50 -38
  251. package/src/utils/useThemeConfig.ts +55 -31
  252. package/copyUntypedFiles.js +0 -20
  253. package/lib/.tsbuildinfo +0 -1
  254. package/lib/utils/announcementBarUtils.d.ts +0 -17
  255. package/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.d.ts +0 -21
  256. package/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.js +0 -94
  257. package/lib/utils/docsPreferredVersion/DocsPreferredVersionStorage.d.ts +0 -13
  258. package/lib/utils/docsPreferredVersion/DocsPreferredVersionStorage.js +0 -20
  259. package/lib/utils/docsPreferredVersion/useDocsPreferredVersion.d.ts +0 -5
  260. package/lib/utils/docsPreferredVersion/useDocsPreferredVersion.js +0 -41
  261. package/lib/utils/mobileSecondaryMenu.d.ts +0 -20
  262. package/lib/utils/mobileSecondaryMenu.js +0 -50
  263. package/lib/utils/pathUtils.js +0 -13
  264. package/lib/utils/usePrevious.js +0 -14
  265. package/src/utils/__tests__/codeBlockUtils.test.ts +0 -54
  266. package/src/utils/__tests__/pathUtils.test.ts +0 -32
  267. package/src/utils/docsPreferredVersion/DocsPreferredVersionProvider.tsx +0 -165
  268. package/src/utils/docsPreferredVersion/DocsPreferredVersionStorage.ts +0 -34
  269. package/src/utils/docsPreferredVersion/useDocsPreferredVersion.ts +0 -66
  270. package/src/utils/docsUtils.ts +0 -11
  271. package/src/utils/mobileSecondaryMenu.tsx +0 -115
  272. package/src/utils/pathUtils.ts +0 -17
  273. package/src/utils/usePrevious.ts +0 -18
  274. package/tsconfig.json +0 -10
@@ -11,8 +11,12 @@ export type StorageType = typeof StorageTypes[number];
11
11
 
12
12
  const DefaultStorageType: StorageType = 'localStorage';
13
13
 
14
- // Will return null browser storage is unavailable (like running Docusaurus in iframe)
15
- // See https://github.com/facebook/docusaurus/pull/4501
14
+ /**
15
+ * Will return `null` if browser storage is unavailable (like running Docusaurus
16
+ * in an iframe). This should NOT be called in SSR.
17
+ *
18
+ * @see https://github.com/facebook/docusaurus/pull/4501
19
+ */
16
20
  function getBrowserStorage(
17
21
  storageType: StorageType = DefaultStorageType,
18
22
  ): Storage | null {
@@ -23,21 +27,21 @@ function getBrowserStorage(
23
27
  }
24
28
  if (storageType === 'none') {
25
29
  return null;
26
- } else {
27
- try {
28
- return window[storageType];
29
- } catch (e) {
30
- logOnceBrowserStorageNotAvailableWarning(e);
31
- return null;
32
- }
30
+ }
31
+ try {
32
+ return window[storageType];
33
+ } catch (err) {
34
+ logOnceBrowserStorageNotAvailableWarning(err as Error);
35
+ return null;
33
36
  }
34
37
  }
35
38
 
39
+ let hasLoggedBrowserStorageNotAvailableWarning = false;
36
40
  /**
37
- * Poor man's memoization to avoid logging multiple times the same warning
38
- * Sometimes, localStorage/sessionStorage is unavailable due to browser policies
41
+ * Poor man's memoization to avoid logging multiple times the same warning.
42
+ * Sometimes, `localStorage`/`sessionStorage` is unavailable due to browser
43
+ * policies.
39
44
  */
40
- let hasLoggedBrowserStorageNotAvailableWarning = false;
41
45
  function logOnceBrowserStorageNotAvailableWarning(error: Error) {
42
46
  if (!hasLoggedBrowserStorageNotAvailableWarning) {
43
47
  console.warn(
@@ -50,11 +54,11 @@ Possible reasons: running Docusaurus in an iframe, in an incognito browser sessi
50
54
  }
51
55
 
52
56
  // Convenient storage interface for a single storage key
53
- export interface StorageSlot {
57
+ export type StorageSlot = {
54
58
  get: () => string | null;
55
59
  set: (value: string) => void;
56
60
  del: () => void;
57
- }
61
+ };
58
62
 
59
63
  const NoopStorageSlot: StorageSlot = {
60
64
  get: () => null,
@@ -62,7 +66,7 @@ const NoopStorageSlot: StorageSlot = {
62
66
  del: () => {},
63
67
  };
64
68
 
65
- // Fail-fast, as storage APIs should not be used during the SSR process
69
+ // Fail-fast, as storage APIs should not be used during the SSR process
66
70
  function createServerStorageSlot(key: string): StorageSlot {
67
71
  function throwError(): never {
68
72
  throw new Error(`Illegal storage API usage for storage key "${key}".
@@ -78,12 +82,19 @@ Please only call storage APIs in effects and event handlers.`);
78
82
  }
79
83
 
80
84
  /**
81
- * Creates an object for accessing a particular key in localStorage.
85
+ * Creates an interface to work on a particular key in the storage model.
86
+ * Note that this function only initializes the interface, but doesn't allocate
87
+ * anything by itself (i.e. no side-effects).
88
+ *
89
+ * The API is fail-safe, since usage of browser storage should be considered
90
+ * unreliable. Local storage might simply be unavailable (iframe + browser
91
+ * security) or operations might fail individually. Please assume that using
92
+ * this API can be a no-op. See also https://github.com/facebook/docusaurus/issues/6036
82
93
  */
83
- export const createStorageSlot = (
94
+ export function createStorageSlot(
84
95
  key: string,
85
96
  options?: {persistence?: StorageType},
86
- ): StorageSlot => {
97
+ ): StorageSlot {
87
98
  if (typeof window === 'undefined') {
88
99
  return createServerStorageSlot(key);
89
100
  }
@@ -92,14 +103,36 @@ export const createStorageSlot = (
92
103
  return NoopStorageSlot;
93
104
  }
94
105
  return {
95
- get: () => browserStorage.getItem(key),
96
- set: (value) => browserStorage.setItem(key, value),
97
- del: () => browserStorage.removeItem(key),
106
+ get: () => {
107
+ try {
108
+ return browserStorage.getItem(key);
109
+ } catch (err) {
110
+ console.error(`Docusaurus storage error, can't get key=${key}`, err);
111
+ return null;
112
+ }
113
+ },
114
+ set: (value) => {
115
+ try {
116
+ browserStorage.setItem(key, value);
117
+ } catch (err) {
118
+ console.error(
119
+ `Docusaurus storage error, can't set ${key}=${value}`,
120
+ err,
121
+ );
122
+ }
123
+ },
124
+ del: () => {
125
+ try {
126
+ browserStorage.removeItem(key);
127
+ } catch (err) {
128
+ console.error(`Docusaurus storage error, can't delete key=${key}`, err);
129
+ }
130
+ },
98
131
  };
99
- };
132
+ }
100
133
 
101
134
  /**
102
- * Returns a list of all the keys currently stored in browser storage
135
+ * Returns a list of all the keys currently stored in browser storage,
103
136
  * or an empty list if browser storage can't be accessed.
104
137
  */
105
138
  export function listStorageKeys(
@@ -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 {translate} from '@docusaurus/Translate';
9
+ import type {TagsListItem} from '@docusaurus/utils';
10
+
11
+ export const translateTagsPageTitle = (): string =>
12
+ translate({
13
+ id: 'theme.tags.tagsPageTitle',
14
+ message: 'Tags',
15
+ description: 'The title of the tag list page',
16
+ });
17
+
18
+ export type TagLetterEntry = {letter: string; tags: TagsListItem[]};
19
+
20
+ function getTagLetter(tag: string): string {
21
+ return tag[0]!.toUpperCase();
22
+ }
23
+
24
+ /**
25
+ * Takes a list of tags (as provided by the content plugins), and groups them by
26
+ * their initials.
27
+ */
28
+ export function listTagsByLetters(
29
+ tags: readonly TagsListItem[],
30
+ ): TagLetterEntry[] {
31
+ const groups: {[initial: string]: TagsListItem[]} = {};
32
+ Object.values(tags).forEach((tag) => {
33
+ const initial = getTagLetter(tag.label);
34
+ groups[initial] ??= [];
35
+ groups[initial]!.push(tag);
36
+ });
37
+
38
+ return (
39
+ Object.entries(groups)
40
+ // Sort letters
41
+ .sort(([letter1], [letter2]) => letter1.localeCompare(letter2))
42
+ .map(([letter, letterTags]) => {
43
+ // Sort tags inside a letter
44
+ const sortedTags = letterTags.sort((tag1, tag2) =>
45
+ tag1.label.localeCompare(tag2.label),
46
+ );
47
+ return {letter, tags: sortedTags};
48
+ })
49
+ );
50
+ }
@@ -0,0 +1,119 @@
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 type {TOCItem} from '@docusaurus/mdx-loader';
10
+
11
+ export type TOCTreeNode = {
12
+ readonly value: string;
13
+ readonly id: string;
14
+ readonly level: number;
15
+ readonly children: readonly TOCTreeNode[];
16
+ };
17
+
18
+ function treeifyTOC(flatTOC: readonly TOCItem[]): TOCTreeNode[] {
19
+ const headings = flatTOC.map((heading) => ({
20
+ ...heading,
21
+ parentIndex: -1,
22
+ children: [] as TOCTreeNode[],
23
+ }));
24
+
25
+ // Keep track of which previous index would be the current heading's direct
26
+ // parent. Each entry <i> is the last index of the `headings` array at heading
27
+ // level <i>. We will modify these indices as we iterate through all headings.
28
+ // e.g. if an ### H3 was last seen at index 2, then prevIndexForLevel[3] === 2
29
+ // indices 0 and 1 will remain unused.
30
+ const prevIndexForLevel = Array<number>(7).fill(-1);
31
+
32
+ headings.forEach((curr, currIndex) => {
33
+ // Take the last seen index for each ancestor level. the highest index will
34
+ // be the direct ancestor of the current heading.
35
+ const ancestorLevelIndexes = prevIndexForLevel.slice(2, curr.level);
36
+ curr.parentIndex = Math.max(...ancestorLevelIndexes);
37
+ // Mark that curr.level was last seen at the current index.
38
+ prevIndexForLevel[curr.level] = currIndex;
39
+ });
40
+
41
+ const rootNodes: TOCTreeNode[] = [];
42
+
43
+ // For a given parentIndex, add each Node into that parent's `children` array
44
+ headings.forEach((heading) => {
45
+ const {parentIndex, ...rest} = heading;
46
+ if (parentIndex >= 0) {
47
+ headings[parentIndex]!.children.push(rest);
48
+ } else {
49
+ rootNodes.push(rest);
50
+ }
51
+ });
52
+ return rootNodes;
53
+ }
54
+
55
+ /**
56
+ * Takes a flat TOC list (from the MDX loader) and treeifies it into what the
57
+ * TOC components expect. Memoized for performance.
58
+ */
59
+ export function useTreeifiedTOC(toc: TOCItem[]): readonly TOCTreeNode[] {
60
+ return useMemo(() => treeifyTOC(toc), [toc]);
61
+ }
62
+
63
+ function filterTOC({
64
+ toc,
65
+ minHeadingLevel,
66
+ maxHeadingLevel,
67
+ }: {
68
+ toc: readonly TOCTreeNode[];
69
+ minHeadingLevel: number;
70
+ maxHeadingLevel: number;
71
+ }): TOCTreeNode[] {
72
+ function isValid(item: TOCTreeNode) {
73
+ return item.level >= minHeadingLevel && item.level <= maxHeadingLevel;
74
+ }
75
+
76
+ return toc.flatMap((item) => {
77
+ const filteredChildren = filterTOC({
78
+ toc: item.children,
79
+ minHeadingLevel,
80
+ maxHeadingLevel,
81
+ });
82
+ if (isValid(item)) {
83
+ return [
84
+ {
85
+ ...item,
86
+ children: filteredChildren,
87
+ },
88
+ ];
89
+ }
90
+ return filteredChildren;
91
+ });
92
+ }
93
+
94
+ /**
95
+ * Takes a flat TOC list (from the MDX loader) and treeifies it into what the
96
+ * TOC components expect, applying the `minHeadingLevel` and `maxHeadingLevel`.
97
+ * Memoized for performance.
98
+ *
99
+ * **Important**: this is not the same as `useTreeifiedTOC(toc.filter(...))`,
100
+ * because we have to filter the TOC after it has been treeified. This is mostly
101
+ * to ensure that weird TOC structures preserve their semantics. For example, an
102
+ * h3-h2-h4 sequence should not be treeified as an "h3 > h4" hierarchy with
103
+ * min=3, max=4, but should rather be "[h3, h4]" (since the h2 heading has split
104
+ * the two headings and they are not parent-children)
105
+ */
106
+ export function useFilteredAndTreeifiedTOC({
107
+ toc,
108
+ minHeadingLevel,
109
+ maxHeadingLevel,
110
+ }: {
111
+ toc: readonly TOCItem[];
112
+ minHeadingLevel: number;
113
+ maxHeadingLevel: number;
114
+ }): readonly TOCTreeNode[] {
115
+ return useMemo(
116
+ () => filterTOC({toc: treeifyTOC(toc), minHeadingLevel, maxHeadingLevel}),
117
+ [toc, minHeadingLevel, maxHeadingLevel],
118
+ );
119
+ }
@@ -8,12 +8,26 @@
8
8
  import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
9
9
  import {useLocation} from '@docusaurus/router';
10
10
 
11
- // Permits to obtain the url of the current page in another locale
12
- // Useful to generate hreflang meta headers etc...
13
- // See https://developers.google.com/search/docs/advanced/crawling/localized-versions
11
+ /**
12
+ * Permits to obtain the url of the current page in another locale, useful to
13
+ * generate hreflang meta headers etc...
14
+ *
15
+ * @see https://developers.google.com/search/docs/advanced/crawling/localized-versions
16
+ */
14
17
  export function useAlternatePageUtils(): {
18
+ /**
19
+ * Everything (pathname, base URL, etc.) is read from the context. Just tell
20
+ * it which locale to link to and it will give you the alternate link for the
21
+ * current page.
22
+ */
15
23
  createUrl: ({
24
+ /** The locale name to link to. */
16
25
  locale,
26
+ /**
27
+ * For hreflang SEO headers, we need it to be fully qualified (full
28
+ * protocol/domain/path...); but for locale dropdowns, using a pathname is
29
+ * good enough.
30
+ */
17
31
  fullyQualified,
18
32
  }: {
19
33
  locale: string;
@@ -39,14 +53,13 @@ export function useAlternatePageUtils(): {
39
53
  : `${baseUrlUnlocalized}${locale}/`;
40
54
  }
41
55
 
42
- // TODO support correct alternate url when localized site is deployed on another domain
56
+ // TODO support correct alternate url when localized site is deployed on
57
+ // another domain
43
58
  function createUrl({
44
59
  locale,
45
60
  fullyQualified,
46
61
  }: {
47
62
  locale: string;
48
- // For hreflang SEO headers, we need it to be fully qualified (full protocol/domain/path...)
49
- // For locale dropdown, using a path is good enough
50
63
  fullyQualified: boolean;
51
64
  }) {
52
65
  return `${fullyQualified ? url : ''}${getLocalizedBaseUrl(
@@ -5,12 +5,14 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
9
8
  import {useLocation} from '@docusaurus/router';
9
+ import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
10
10
 
11
- // Get the pathname of current route, without the optional site baseUrl
12
- // - /docs/myDoc => /docs/myDoc
13
- // - /baseUrl/docs/myDoc => /docs/myDoc
11
+ /**
12
+ * Get the pathname of current route, without the optional site baseUrl.
13
+ * - `/docs/myDoc` => `/docs/myDoc`
14
+ * - `/baseUrl/docs/myDoc` => `/docs/myDoc`
15
+ */
14
16
  export function useLocalPathname(): string {
15
17
  const {
16
18
  siteConfig: {baseUrl},
@@ -5,33 +5,37 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- import {useEffect, useRef} from 'react';
8
+ import {useEffect} from 'react';
9
9
  import {useLocation} from '@docusaurus/router';
10
- import {Location} from '@docusaurus/history';
11
- import {usePrevious} from './usePrevious';
10
+ import {useEvent, usePrevious} from './reactUtils';
11
+ import type {Location} from 'history';
12
12
 
13
- type LocationChangeEvent = {
14
- location: Location;
15
- previousLocation: Location | undefined;
16
- };
17
-
18
- type OnLocationChange = (locationChangeEvent: LocationChangeEvent) => void;
19
-
20
- export function useLocationChange(onLocationChange: OnLocationChange): void {
13
+ /**
14
+ * Fires an effect when the location changes (which includes hash, query, etc.).
15
+ * Importantly, doesn't fire when there's no previous location: see
16
+ * https://github.com/facebook/docusaurus/pull/6696
17
+ */
18
+ export function useLocationChange(
19
+ onLocationChange: (locationChangeEvent: {
20
+ location: Location;
21
+ previousLocation: Location | undefined;
22
+ }) => void,
23
+ ): void {
21
24
  const location = useLocation();
22
25
  const previousLocation = usePrevious(location);
23
- const isFirst = useRef<boolean>(true);
26
+
27
+ const onLocationChangeDynamic = useEvent(onLocationChange);
24
28
 
25
29
  useEffect(() => {
26
- // Prevent first effect to trigger the listener on mount
27
- if (isFirst.current) {
28
- isFirst.current = false;
30
+ if (!previousLocation) {
29
31
  return;
30
32
  }
31
33
 
32
- onLocationChange({
33
- location,
34
- previousLocation,
35
- });
36
- }, [location]);
34
+ if (location !== previousLocation) {
35
+ onLocationChangeDynamic({
36
+ location,
37
+ previousLocation,
38
+ });
39
+ }
40
+ }, [onLocationChangeDynamic, location, previousLocation]);
37
41
  }
@@ -49,36 +49,34 @@ function createLocalePluralForms(locale: string): LocalePluralForms {
49
49
  };
50
50
  }
51
51
 
52
- // Poor man's PluralSelector implementation, using an english fallback.
53
- // We want a lightweight, future-proof and good-enough solution.
54
- // We don't want a perfect and heavy solution.
55
- //
56
- // Docusaurus classic theme has only 2 deeply nested labels requiring complex plural rules
57
- // We don't want to use Intl + PluralRules polyfills + full ICU syntax (react-intl) just for that.
58
- //
59
- // Notes:
60
- // - 2021: 92+% Browsers support Intl.PluralRules, and support will increase in the future
61
- // - NodeJS >= 13 has full ICU support by default
62
- // - In case of "mismatch" between SSR and Browser ICU support, React keeps working!
52
+ /**
53
+ * Poor man's `PluralSelector` implementation, using an English fallback. We
54
+ * want a lightweight, future-proof and good-enough solution. We don't want a
55
+ * perfect and heavy solution.
56
+ *
57
+ * Docusaurus classic theme has only 2 deeply nested labels requiring complex
58
+ * plural rules. We don't want to use `Intl` + `PluralRules` polyfills + full
59
+ * ICU syntax (react-intl) just for that.
60
+ *
61
+ * Notes:
62
+ * - 2021: 92+% Browsers support `Intl.PluralRules`, and support will increase
63
+ * in the future
64
+ * - NodeJS >= 13 has full ICU support by default
65
+ * - In case of "mismatch" between SSR and Browser ICU support, React keeps
66
+ * working!
67
+ */
63
68
  function useLocalePluralForms(): LocalePluralForms {
64
69
  const {
65
70
  i18n: {currentLocale},
66
71
  } = useDocusaurusContext();
67
72
  return useMemo(() => {
68
- // @ts-expect-error checking Intl.PluralRules in case browser doesn't have it (e.g Safari 12-)
69
- if (Intl.PluralRules) {
70
- try {
71
- return createLocalePluralForms(currentLocale);
72
- } catch (e) {
73
- console.error(`Failed to use Intl.PluralRules for locale "${currentLocale}".
74
- Docusaurus will fallback to a default/fallback (English) Intl.PluralRules implementation.
73
+ try {
74
+ return createLocalePluralForms(currentLocale);
75
+ } catch (err) {
76
+ console.error(`Failed to use Intl.PluralRules for locale "${currentLocale}".
77
+ Docusaurus will fallback to the default (English) implementation.
78
+ Error: ${(err as Error).message}
75
79
  `);
76
- return EnglishPluralForms;
77
- }
78
- } else {
79
- console.error(`Intl.PluralRules not available!
80
- Docusaurus will fallback to a default/fallback (English) Intl.PluralRules implementation.
81
- `);
82
80
  return EnglishPluralForms;
83
81
  }
84
82
  }, [currentLocale]);
@@ -93,27 +91,41 @@ function selectPluralMessage(
93
91
  const parts = pluralMessages.split(separator);
94
92
 
95
93
  if (parts.length === 1) {
96
- return parts[0];
97
- } else {
98
- if (parts.length > localePluralForms.pluralForms.length) {
99
- console.error(
100
- `For locale=${localePluralForms.locale}, a maximum of ${localePluralForms.pluralForms.length} plural forms are expected (${localePluralForms.pluralForms}), but the message contains ${parts.length} plural forms: ${pluralMessages} `,
101
- );
102
- }
103
- const pluralForm = localePluralForms.select(count);
104
- const pluralFormIndex = localePluralForms.pluralForms.indexOf(pluralForm);
105
- // In case of not enough plural form messages, we take the last one (other) instead of returning undefined
106
- return parts[Math.min(pluralFormIndex, parts.length - 1)];
94
+ return parts[0]!;
95
+ }
96
+ if (parts.length > localePluralForms.pluralForms.length) {
97
+ console.error(
98
+ `For locale=${localePluralForms.locale}, a maximum of ${
99
+ localePluralForms.pluralForms.length
100
+ } plural forms are expected (${localePluralForms.pluralForms.join(
101
+ ',',
102
+ )}), but the message contains ${parts.length}: ${pluralMessages}`,
103
+ );
107
104
  }
105
+ const pluralForm = localePluralForms.select(count);
106
+ const pluralFormIndex = localePluralForms.pluralForms.indexOf(pluralForm);
107
+ // In case of not enough plural form messages, we take the last one (other)
108
+ // instead of returning undefined
109
+ return parts[Math.min(pluralFormIndex, parts.length - 1)]!;
108
110
  }
109
111
 
112
+ /**
113
+ * Reads the current locale and returns an interface very similar to
114
+ * `Intl.PluralRules`.
115
+ */
110
116
  export function usePluralForm(): {
117
+ /**
118
+ * Give it a `count` and it will select the relevant message from
119
+ * `pluralMessages`. `pluralMessages` should be separated by `|`, and in the
120
+ * order of "zero", "one", "two", "few", "many", "other". The actual selection
121
+ * is done by `Intl.PluralRules`, which tells us all plurals the locale has
122
+ * and which plural we should use for `count`.
123
+ */
111
124
  selectMessage: (count: number, pluralMessages: string) => string;
112
125
  } {
113
126
  const localePluralForm = useLocalePluralForms();
114
127
  return {
115
- selectMessage: (count: number, pluralMessages: string): string => {
116
- return selectPluralMessage(pluralMessages, count, localePluralForm);
117
- },
128
+ selectMessage: (count: number, pluralMessages: string): string =>
129
+ selectPluralMessage(pluralMessages, count, localePluralForm),
118
130
  };
119
131
  }