@docusaurus/theme-common 2.0.0-beta.2 → 2.0.0-beta.20

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 (253) hide show
  1. package/Details.d.ts +14 -0
  2. package/lib/components/Collapsible/index.d.ts +64 -0
  3. package/lib/components/Collapsible/index.d.ts.map +1 -0
  4. package/lib/components/Collapsible/index.js +152 -0
  5. package/lib/components/Collapsible/index.js.map +1 -0
  6. package/lib/components/Details/index.d.ts +17 -0
  7. package/lib/components/Details/index.d.ts.map +1 -0
  8. package/lib/components/Details/index.js +71 -0
  9. package/lib/components/Details/index.js.map +1 -0
  10. package/lib/components/Details/styles.module.css +62 -0
  11. package/lib/contexts/announcementBar.d.ts +22 -0
  12. package/lib/contexts/announcementBar.d.ts.map +1 -0
  13. package/lib/{utils/announcementBarUtils.js → contexts/announcementBar.js} +30 -31
  14. package/lib/contexts/announcementBar.js.map +1 -0
  15. package/lib/contexts/colorMode.d.ts +27 -0
  16. package/lib/contexts/colorMode.d.ts.map +1 -0
  17. package/lib/contexts/colorMode.js +132 -0
  18. package/lib/contexts/colorMode.js.map +1 -0
  19. package/lib/contexts/docSidebarItemsExpandedState.d.ts +31 -0
  20. package/lib/contexts/docSidebarItemsExpandedState.d.ts.map +1 -0
  21. package/lib/contexts/docSidebarItemsExpandedState.js +28 -0
  22. package/lib/contexts/docSidebarItemsExpandedState.js.map +1 -0
  23. package/lib/contexts/docsPreferredVersion.d.ts +31 -0
  24. package/lib/contexts/docsPreferredVersion.d.ts.map +1 -0
  25. package/lib/contexts/docsPreferredVersion.js +128 -0
  26. package/lib/contexts/docsPreferredVersion.js.map +1 -0
  27. package/lib/contexts/docsSidebar.d.ts +26 -0
  28. package/lib/contexts/docsSidebar.d.ts.map +1 -0
  29. package/lib/contexts/docsSidebar.js +30 -0
  30. package/lib/contexts/docsSidebar.js.map +1 -0
  31. package/lib/contexts/docsVersion.d.ts +20 -0
  32. package/lib/contexts/docsVersion.d.ts.map +1 -0
  33. package/lib/contexts/docsVersion.js +26 -0
  34. package/lib/contexts/docsVersion.js.map +1 -0
  35. package/lib/contexts/navbarMobileSidebar.d.ts +31 -0
  36. package/lib/contexts/navbarMobileSidebar.d.ts.map +1 -0
  37. package/lib/contexts/navbarMobileSidebar.js +56 -0
  38. package/lib/contexts/navbarMobileSidebar.js.map +1 -0
  39. package/lib/contexts/navbarSecondaryMenu/content.d.ts +37 -0
  40. package/lib/contexts/navbarSecondaryMenu/content.d.ts.map +1 -0
  41. package/lib/contexts/navbarSecondaryMenu/content.js +56 -0
  42. package/lib/contexts/navbarSecondaryMenu/content.js.map +1 -0
  43. package/lib/contexts/navbarSecondaryMenu/display.d.ts +24 -0
  44. package/lib/contexts/navbarSecondaryMenu/display.d.ts.map +1 -0
  45. package/lib/contexts/navbarSecondaryMenu/display.js +62 -0
  46. package/lib/contexts/navbarSecondaryMenu/display.js.map +1 -0
  47. package/lib/contexts/tabGroupChoice.d.ts +21 -0
  48. package/lib/contexts/tabGroupChoice.d.ts.map +1 -0
  49. package/lib/contexts/tabGroupChoice.js +49 -0
  50. package/lib/contexts/tabGroupChoice.js.map +1 -0
  51. package/lib/{utils/usePrevious.d.ts → hooks/styles.css} +4 -1
  52. package/lib/hooks/useBackToTopButton.d.ts +27 -0
  53. package/lib/hooks/useBackToTopButton.d.ts.map +1 -0
  54. package/lib/hooks/useBackToTopButton.js +50 -0
  55. package/lib/hooks/useBackToTopButton.js.map +1 -0
  56. package/lib/hooks/useCodeWordWrap.d.ts +14 -0
  57. package/lib/hooks/useCodeWordWrap.d.ts.map +1 -0
  58. package/lib/hooks/useCodeWordWrap.js +41 -0
  59. package/lib/hooks/useCodeWordWrap.js.map +1 -0
  60. package/lib/hooks/useHideableNavbar.d.ts +17 -0
  61. package/lib/hooks/useHideableNavbar.d.ts.map +1 -0
  62. package/lib/hooks/useHideableNavbar.js +60 -0
  63. package/lib/hooks/useHideableNavbar.js.map +1 -0
  64. package/lib/hooks/useKeyboardNavigation.d.ts +20 -0
  65. package/lib/hooks/useKeyboardNavigation.d.ts.map +1 -0
  66. package/lib/hooks/useKeyboardNavigation.js +39 -0
  67. package/lib/hooks/useKeyboardNavigation.js.map +1 -0
  68. package/lib/hooks/useLockBodyScroll.d.ts +12 -0
  69. package/lib/hooks/useLockBodyScroll.d.ts.map +1 -0
  70. package/lib/hooks/useLockBodyScroll.js +20 -0
  71. package/lib/hooks/useLockBodyScroll.js.map +1 -0
  72. package/lib/hooks/usePrismTheme.d.ts +13 -0
  73. package/lib/hooks/usePrismTheme.d.ts.map +1 -0
  74. package/lib/hooks/usePrismTheme.js +21 -0
  75. package/lib/hooks/usePrismTheme.js.map +1 -0
  76. package/lib/hooks/useSearchPage.d.ts +25 -0
  77. package/lib/hooks/useSearchPage.d.ts.map +1 -0
  78. package/lib/hooks/useSearchPage.js +43 -0
  79. package/lib/hooks/useSearchPage.js.map +1 -0
  80. package/lib/hooks/useSkipToContent.d.ts +25 -0
  81. package/lib/hooks/useSkipToContent.d.ts.map +1 -0
  82. package/lib/hooks/useSkipToContent.js +35 -0
  83. package/lib/hooks/useSkipToContent.js.map +1 -0
  84. package/lib/hooks/useTOCHighlight.d.ts +25 -0
  85. package/lib/hooks/useTOCHighlight.d.ts.map +1 -0
  86. package/lib/hooks/useTOCHighlight.js +130 -0
  87. package/lib/hooks/useTOCHighlight.js.map +1 -0
  88. package/lib/hooks/useWindowSize.d.ts +28 -0
  89. package/lib/hooks/useWindowSize.d.ts.map +1 -0
  90. package/lib/hooks/useWindowSize.js +59 -0
  91. package/lib/hooks/useWindowSize.js.map +1 -0
  92. package/lib/index.d.ts +38 -10
  93. package/lib/index.d.ts.map +1 -0
  94. package/lib/index.js +38 -9
  95. package/lib/index.js.map +1 -0
  96. package/lib/utils/ThemeClassNames.d.ts +47 -12
  97. package/lib/utils/ThemeClassNames.d.ts.map +1 -0
  98. package/lib/utils/ThemeClassNames.js +45 -4
  99. package/lib/utils/ThemeClassNames.js.map +1 -0
  100. package/lib/utils/codeBlockUtils.d.ts +63 -0
  101. package/lib/utils/codeBlockUtils.d.ts.map +1 -0
  102. package/lib/utils/codeBlockUtils.js +157 -3
  103. package/lib/utils/codeBlockUtils.js.map +1 -0
  104. package/lib/utils/docsUtils.d.ts +91 -0
  105. package/lib/utils/docsUtils.d.ts.map +1 -0
  106. package/lib/utils/docsUtils.js +217 -1
  107. package/lib/utils/docsUtils.js.map +1 -0
  108. package/lib/utils/footerUtils.d.ts +13 -0
  109. package/lib/utils/footerUtils.d.ts.map +1 -0
  110. package/lib/utils/footerUtils.js +14 -0
  111. package/lib/utils/footerUtils.js.map +1 -0
  112. package/lib/utils/generalUtils.d.ts +11 -1
  113. package/lib/utils/generalUtils.d.ts.map +1 -0
  114. package/lib/utils/generalUtils.js +9 -5
  115. package/lib/utils/generalUtils.js.map +1 -0
  116. package/lib/utils/historyUtils.d.ts +17 -0
  117. package/lib/utils/historyUtils.d.ts.map +1 -0
  118. package/lib/utils/historyUtils.js +38 -0
  119. package/lib/utils/historyUtils.js.map +1 -0
  120. package/lib/utils/jsUtils.d.ts +23 -0
  121. package/lib/utils/jsUtils.d.ts.map +1 -0
  122. package/lib/utils/jsUtils.js +29 -0
  123. package/lib/utils/jsUtils.js.map +1 -0
  124. package/lib/utils/metadataUtils.d.ts +38 -0
  125. package/lib/utils/metadataUtils.d.ts.map +1 -0
  126. package/lib/utils/metadataUtils.js +61 -0
  127. package/lib/utils/metadataUtils.js.map +1 -0
  128. package/lib/utils/navbarUtils.d.ts +21 -0
  129. package/lib/utils/navbarUtils.d.ts.map +1 -0
  130. package/lib/utils/navbarUtils.js +32 -0
  131. package/lib/utils/navbarUtils.js.map +1 -0
  132. package/lib/utils/reactUtils.d.ts +42 -0
  133. package/lib/utils/reactUtils.d.ts.map +1 -0
  134. package/lib/utils/reactUtils.js +64 -0
  135. package/lib/utils/reactUtils.js.map +1 -0
  136. package/lib/utils/regexpUtils.d.ts +12 -0
  137. package/lib/utils/regexpUtils.d.ts.map +1 -0
  138. package/lib/utils/regexpUtils.js +18 -0
  139. package/lib/utils/regexpUtils.js.map +1 -0
  140. package/lib/utils/routesUtils.d.ts +26 -0
  141. package/lib/utils/routesUtils.d.ts.map +1 -0
  142. package/lib/utils/routesUtils.js +54 -0
  143. package/lib/utils/routesUtils.js.map +1 -0
  144. package/lib/utils/scrollUtils.d.ts +83 -0
  145. package/lib/utils/scrollUtils.d.ts.map +1 -0
  146. package/lib/utils/scrollUtils.js +200 -0
  147. package/lib/utils/scrollUtils.js.map +1 -0
  148. package/lib/utils/searchUtils.d.ts +13 -0
  149. package/lib/utils/searchUtils.d.ts.map +1 -0
  150. package/lib/utils/searchUtils.js +37 -0
  151. package/lib/utils/searchUtils.js.map +1 -0
  152. package/lib/utils/storageUtils.d.ts +15 -7
  153. package/lib/utils/storageUtils.d.ts.map +1 -0
  154. package/lib/utils/storageUtils.js +55 -22
  155. package/lib/utils/storageUtils.js.map +1 -0
  156. package/lib/utils/tagsUtils.d.ts +18 -0
  157. package/lib/utils/tagsUtils.d.ts.map +1 -0
  158. package/lib/utils/tagsUtils.js +36 -0
  159. package/lib/utils/tagsUtils.js.map +1 -0
  160. package/lib/utils/tocUtils.d.ts +36 -0
  161. package/lib/utils/tocUtils.d.ts.map +1 -0
  162. package/lib/utils/tocUtils.js +84 -0
  163. package/lib/utils/tocUtils.js.map +1 -0
  164. package/lib/utils/useAlternatePageUtils.d.ts +21 -1
  165. package/lib/utils/useAlternatePageUtils.d.ts.map +1 -0
  166. package/lib/utils/useAlternatePageUtils.js +9 -4
  167. package/lib/utils/useAlternatePageUtils.js.map +1 -0
  168. package/lib/utils/useLocalPathname.d.ts +13 -0
  169. package/lib/utils/useLocalPathname.d.ts.map +1 -0
  170. package/lib/utils/useLocalPathname.js +19 -0
  171. package/lib/utils/useLocalPathname.js.map +1 -0
  172. package/lib/utils/useLocationChange.d.ts +9 -6
  173. package/lib/utils/useLocationChange.d.ts.map +1 -0
  174. package/lib/utils/useLocationChange.js +17 -11
  175. package/lib/utils/useLocationChange.js.map +1 -0
  176. package/lib/utils/usePluralForm.d.ts +12 -0
  177. package/lib/utils/usePluralForm.d.ts.map +1 -0
  178. package/lib/utils/usePluralForm.js +36 -37
  179. package/lib/utils/usePluralForm.js.map +1 -0
  180. package/lib/utils/useThemeConfig.d.ts +55 -24
  181. package/lib/utils/useThemeConfig.d.ts.map +1 -0
  182. package/lib/utils/useThemeConfig.js +4 -0
  183. package/lib/utils/useThemeConfig.js.map +1 -0
  184. package/package.json +26 -13
  185. package/src/components/Collapsible/index.tsx +265 -0
  186. package/src/components/Details/index.tsx +109 -0
  187. package/src/components/Details/styles.module.css +62 -0
  188. package/src/{utils/announcementBarUtils.tsx → contexts/announcementBar.tsx} +43 -39
  189. package/src/contexts/colorMode.tsx +199 -0
  190. package/src/contexts/docSidebarItemsExpandedState.tsx +55 -0
  191. package/src/contexts/docsPreferredVersion.tsx +253 -0
  192. package/src/contexts/docsSidebar.tsx +50 -0
  193. package/src/contexts/docsVersion.tsx +36 -0
  194. package/src/contexts/navbarMobileSidebar.tsx +99 -0
  195. package/src/contexts/navbarSecondaryMenu/content.tsx +110 -0
  196. package/src/contexts/navbarSecondaryMenu/display.tsx +102 -0
  197. package/src/contexts/tabGroupChoice.tsx +85 -0
  198. package/{lib/utils/pathUtils.d.ts → src/hooks/styles.css} +4 -1
  199. package/src/hooks/useBackToTopButton.ts +73 -0
  200. package/src/hooks/useCodeWordWrap.ts +56 -0
  201. package/src/hooks/useHideableNavbar.ts +75 -0
  202. package/src/hooks/useKeyboardNavigation.ts +45 -0
  203. package/src/hooks/useLockBodyScroll.ts +21 -0
  204. package/src/hooks/usePrismTheme.ts +24 -0
  205. package/src/hooks/useSearchPage.ts +79 -0
  206. package/src/hooks/useSkipToContent.ts +58 -0
  207. package/src/hooks/useTOCHighlight.ts +192 -0
  208. package/src/hooks/useWindowSize.ts +72 -0
  209. package/src/index.ts +130 -19
  210. package/src/types.d.ts +0 -2
  211. package/src/utils/ThemeClassNames.ts +51 -5
  212. package/src/utils/codeBlockUtils.ts +239 -2
  213. package/src/utils/docsUtils.tsx +334 -0
  214. package/src/utils/footerUtils.ts +18 -0
  215. package/src/utils/generalUtils.ts +9 -5
  216. package/src/utils/historyUtils.ts +45 -0
  217. package/src/utils/jsUtils.ts +36 -0
  218. package/src/utils/metadataUtils.tsx +115 -0
  219. package/src/utils/navbarUtils.tsx +45 -0
  220. package/src/utils/reactUtils.tsx +76 -0
  221. package/src/utils/regexpUtils.ts +24 -0
  222. package/src/utils/routesUtils.ts +75 -0
  223. package/src/utils/scrollUtils.tsx +308 -0
  224. package/src/utils/searchUtils.ts +51 -0
  225. package/src/utils/storageUtils.ts +56 -23
  226. package/src/utils/tagsUtils.ts +50 -0
  227. package/src/utils/tocUtils.ts +119 -0
  228. package/src/utils/useAlternatePageUtils.ts +19 -6
  229. package/src/utils/useLocalPathname.ts +22 -0
  230. package/src/utils/useLocationChange.ts +24 -20
  231. package/src/utils/usePluralForm.ts +46 -38
  232. package/src/utils/useThemeConfig.ts +54 -26
  233. package/lib/.tsbuildinfo +0 -1
  234. package/lib/utils/announcementBarInlineJavaScript.d.ts +0 -0
  235. package/lib/utils/announcementBarInlineJavaScript.js +0 -1
  236. package/lib/utils/announcementBarUtils.d.ts +0 -17
  237. package/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.d.ts +0 -21
  238. package/lib/utils/docsPreferredVersion/DocsPreferredVersionProvider.js +0 -94
  239. package/lib/utils/docsPreferredVersion/DocsPreferredVersionStorage.d.ts +0 -13
  240. package/lib/utils/docsPreferredVersion/DocsPreferredVersionStorage.js +0 -20
  241. package/lib/utils/docsPreferredVersion/useDocsPreferredVersion.d.ts +0 -5
  242. package/lib/utils/docsPreferredVersion/useDocsPreferredVersion.js +0 -41
  243. package/lib/utils/pathUtils.js +0 -13
  244. package/lib/utils/usePrevious.js +0 -14
  245. package/src/utils/__tests__/codeBlockUtils.test.ts +0 -54
  246. package/src/utils/__tests__/pathUtils.test.ts +0 -32
  247. package/src/utils/docsPreferredVersion/DocsPreferredVersionProvider.tsx +0 -165
  248. package/src/utils/docsPreferredVersion/DocsPreferredVersionStorage.ts +0 -34
  249. package/src/utils/docsPreferredVersion/useDocsPreferredVersion.ts +0 -66
  250. package/src/utils/docsUtils.ts +0 -11
  251. package/src/utils/pathUtils.ts +0 -17
  252. package/src/utils/usePrevious.ts +0 -18
  253. package/tsconfig.json +0 -10
@@ -5,20 +5,66 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- // These class names are used to style page layouts in Docusaurus
8
+ // Please do not modify the classnames! This is a breaking change, and annoying
9
+ // for users!
10
+
11
+ /**
12
+ * These class names are used to style page layouts in Docusaurus, meant to be
13
+ * targeted by user-provided custom CSS selectors.
14
+ */
9
15
  export const ThemeClassNames = {
10
16
  page: {
11
17
  blogListPage: 'blog-list-page',
12
18
  blogPostPage: 'blog-post-page',
13
19
  blogTagsListPage: 'blog-tags-list-page',
14
- blogTagsPostPage: 'blog-tags-post-page',
15
- docPage: 'doc-page',
20
+ blogTagPostListPage: 'blog-tags-post-list-page',
21
+
22
+ docsDocPage: 'docs-doc-page',
23
+ docsTagsListPage: 'docs-tags-list-page',
24
+ docsTagDocListPage: 'docs-tags-doc-list-page',
25
+
16
26
  mdxPage: 'mdx-page',
17
27
  },
18
28
  wrapper: {
19
29
  main: 'main-wrapper',
20
30
  blogPages: 'blog-wrapper',
21
- docPages: 'docs-wrapper',
31
+ docsPages: 'docs-wrapper',
22
32
  mdxPages: 'mdx-wrapper',
23
33
  },
24
- };
34
+
35
+ /**
36
+ * Follows the naming convention "theme-{blog,doc,version,page}?-<suffix>"
37
+ */
38
+ common: {
39
+ editThisPage: 'theme-edit-this-page',
40
+ lastUpdated: 'theme-last-updated',
41
+ backToTopButton: 'theme-back-to-top-button',
42
+ codeBlock: 'theme-code-block',
43
+ },
44
+ layout: {
45
+ // TODO add other stable classNames here
46
+ },
47
+ docs: {
48
+ docVersionBanner: 'theme-doc-version-banner',
49
+ docVersionBadge: 'theme-doc-version-badge',
50
+ docBreadcrumbs: 'theme-doc-breadcrumbs',
51
+ docMarkdown: 'theme-doc-markdown',
52
+ docTocMobile: 'theme-doc-toc-mobile',
53
+ docTocDesktop: 'theme-doc-toc-desktop',
54
+ docFooter: 'theme-doc-footer',
55
+ docFooterTagsRow: 'theme-doc-footer-tags-row',
56
+ docFooterEditMetaRow: 'theme-doc-footer-edit-meta-row',
57
+ docSidebarContainer: 'theme-doc-sidebar-container',
58
+ docSidebarMenu: 'theme-doc-sidebar-menu',
59
+ docSidebarItemCategory: 'theme-doc-sidebar-item-category',
60
+ docSidebarItemLink: 'theme-doc-sidebar-item-link',
61
+ docSidebarItemCategoryLevel: (level: number) =>
62
+ `theme-doc-sidebar-item-category-level-${level}` as const,
63
+ docSidebarItemLinkLevel: (level: number) =>
64
+ `theme-doc-sidebar-item-link-level-${level}` as const,
65
+ // TODO add other stable classNames here
66
+ },
67
+ blog: {
68
+ // TODO add other stable classNames here
69
+ },
70
+ } as const;
@@ -5,8 +5,245 @@
5
5
  * LICENSE file in the root directory of this source tree.
6
6
  */
7
7
 
8
- const codeBlockTitleRegex = /title=(["'])(.*?)\1/;
8
+ import rangeParser from 'parse-numeric-range';
9
+ import type {PrismTheme} from 'prism-react-renderer';
10
+ import type {CSSProperties} from 'react';
11
+
12
+ const codeBlockTitleRegex = /title=(?<quote>["'])(?<title>.*?)\1/;
13
+ const metastringLinesRangeRegex = /\{(?<range>[\d,-]+)\}/;
14
+
15
+ // Supported types of highlight comments
16
+ const commentPatterns = {
17
+ js: {start: '\\/\\/', end: ''},
18
+ jsBlock: {start: '\\/\\*', end: '\\*\\/'},
19
+ jsx: {start: '\\{\\s*\\/\\*', end: '\\*\\/\\s*\\}'},
20
+ bash: {start: '#', end: ''},
21
+ html: {start: '<!--', end: '-->'},
22
+ };
23
+
24
+ type CommentType = keyof typeof commentPatterns;
25
+
26
+ export type MagicCommentConfig = {
27
+ className: string;
28
+ line?: string;
29
+ block?: {start: string; end: string};
30
+ };
31
+
32
+ function getCommentPattern(
33
+ languages: CommentType[],
34
+ magicCommentDirectives: MagicCommentConfig[],
35
+ ) {
36
+ // To be more reliable, the opening and closing comment must match
37
+ const commentPattern = languages
38
+ .map((lang) => {
39
+ const {start, end} = commentPatterns[lang];
40
+ return `(?:${start}\\s*(${magicCommentDirectives
41
+ .flatMap((d) => [d.line, d.block?.start, d.block?.end].filter(Boolean))
42
+ .join('|')})\\s*${end})`;
43
+ })
44
+ .join('|');
45
+ // White space is allowed, but otherwise it should be on it's own line
46
+ return new RegExp(`^\\s*(?:${commentPattern})\\s*$`);
47
+ }
48
+
49
+ /**
50
+ * Select comment styles based on language
51
+ */
52
+ function getAllMagicCommentDirectiveStyles(
53
+ lang: string,
54
+ magicCommentDirectives: MagicCommentConfig[],
55
+ ) {
56
+ switch (lang) {
57
+ case 'js':
58
+ case 'javascript':
59
+ case 'ts':
60
+ case 'typescript':
61
+ return getCommentPattern(['js', 'jsBlock'], magicCommentDirectives);
62
+
63
+ case 'jsx':
64
+ case 'tsx':
65
+ return getCommentPattern(
66
+ ['js', 'jsBlock', 'jsx'],
67
+ magicCommentDirectives,
68
+ );
69
+
70
+ case 'html':
71
+ return getCommentPattern(
72
+ ['js', 'jsBlock', 'html'],
73
+ magicCommentDirectives,
74
+ );
75
+
76
+ case 'python':
77
+ case 'py':
78
+ case 'bash':
79
+ return getCommentPattern(['bash'], magicCommentDirectives);
80
+
81
+ case 'markdown':
82
+ case 'md':
83
+ // Text uses HTML, front matter uses bash
84
+ return getCommentPattern(['html', 'jsx', 'bash'], magicCommentDirectives);
85
+
86
+ default:
87
+ // All comment types
88
+ return getCommentPattern(
89
+ Object.keys(commentPatterns) as CommentType[],
90
+ magicCommentDirectives,
91
+ );
92
+ }
93
+ }
9
94
 
10
95
  export function parseCodeBlockTitle(metastring?: string): string {
11
- return metastring?.match(codeBlockTitleRegex)?.[2] ?? '';
96
+ return metastring?.match(codeBlockTitleRegex)?.groups!.title ?? '';
97
+ }
98
+
99
+ export function containsLineNumbers(metastring?: string): boolean {
100
+ return metastring?.includes('showLineNumbers') || false;
101
+ }
102
+
103
+ /**
104
+ * Gets the language name from the class name (set by MDX).
105
+ * e.g. `"language-javascript"` => `"javascript"`.
106
+ * Returns undefined if there is no language class name.
107
+ */
108
+ export function parseLanguage(className: string): string | undefined {
109
+ const languageClassName = className
110
+ .split(' ')
111
+ .find((str) => str.startsWith('language-'));
112
+ return languageClassName?.replace(/language-/, '');
113
+ }
114
+
115
+ /**
116
+ * Parses the code content, strips away any magic comments, and returns the
117
+ * clean content and the highlighted lines marked by the comments or metastring.
118
+ *
119
+ * If the metastring contains a range, the `content` will be returned as-is
120
+ * without any parsing. The returned `lineClassNames` will be a map from that
121
+ * number range to the first magic comment config entry (which _should_ be for
122
+ * line highlight directives.)
123
+ *
124
+ * @param content The raw code with magic comments. Trailing newline will be
125
+ * trimmed upfront.
126
+ * @param options Options for parsing behavior.
127
+ */
128
+ export function parseLines(
129
+ content: string,
130
+ options: {
131
+ /**
132
+ * The full metastring, as received from MDX. Line ranges declared here
133
+ * start at 1.
134
+ */
135
+ metastring: string | undefined;
136
+ /**
137
+ * Language of the code block, used to determine which kinds of magic
138
+ * comment styles to enable.
139
+ */
140
+ language: string | undefined;
141
+ /**
142
+ * Magic comment types that we should try to parse. Each entry would
143
+ * correspond to one class name to apply to each line.
144
+ */
145
+ magicComments: MagicCommentConfig[];
146
+ },
147
+ ): {
148
+ /**
149
+ * The highlighted lines, 0-indexed. e.g. `{ 0: ["highlight", "sample"] }`
150
+ * means the 1st line should have `highlight` and `sample` as class names.
151
+ */
152
+ lineClassNames: {[lineIndex: number]: string[]};
153
+ /**
154
+ * If there's number range declared in the metastring, the code block is
155
+ * returned as-is (no parsing); otherwise, this is the clean code with all
156
+ * magic comments stripped away.
157
+ */
158
+ code: string;
159
+ } {
160
+ let code = content.replace(/\n$/, '');
161
+ const {language, magicComments, metastring} = options;
162
+ // Highlighted lines specified in props: don't parse the content
163
+ if (metastring && metastringLinesRangeRegex.test(metastring)) {
164
+ const linesRange = metastring.match(metastringLinesRangeRegex)!.groups!
165
+ .range!;
166
+ if (magicComments.length === 0) {
167
+ throw new Error(
168
+ `A highlight range has been given in code block's metastring (\`\`\` ${metastring}), but no magic comment config is available. Docusaurus applies the first magic comment entry's className for metastring ranges.`,
169
+ );
170
+ }
171
+ const metastringRangeClassName = magicComments[0]!.className;
172
+ const lines = rangeParser(linesRange)
173
+ .filter((n) => n > 0)
174
+ .map((n) => [n - 1, [metastringRangeClassName]]);
175
+ return {lineClassNames: Object.fromEntries(lines), code};
176
+ }
177
+ if (language === undefined) {
178
+ return {lineClassNames: {}, code};
179
+ }
180
+ const directiveRegex = getAllMagicCommentDirectiveStyles(
181
+ language,
182
+ magicComments,
183
+ );
184
+ // Go through line by line
185
+ const lines = code.split('\n');
186
+ const blocks = Object.fromEntries(
187
+ magicComments.map((d) => [d.className, {start: 0, range: ''}]),
188
+ );
189
+ const lineToClassName: {[comment: string]: string} = Object.fromEntries(
190
+ magicComments
191
+ .filter((d) => d.line)
192
+ .map(({className, line}) => [line, className]),
193
+ );
194
+ const blockStartToClassName: {[comment: string]: string} = Object.fromEntries(
195
+ magicComments
196
+ .filter((d) => d.block)
197
+ .map(({className, block}) => [block!.start, className]),
198
+ );
199
+ const blockEndToClassName: {[comment: string]: string} = Object.fromEntries(
200
+ magicComments
201
+ .filter((d) => d.block)
202
+ .map(({className, block}) => [block!.end, className]),
203
+ );
204
+ for (let lineNumber = 0; lineNumber < lines.length; ) {
205
+ const line = lines[lineNumber]!;
206
+ const match = line.match(directiveRegex);
207
+ if (!match) {
208
+ // Lines without directives are unchanged
209
+ lineNumber += 1;
210
+ continue;
211
+ }
212
+ const directive = match.slice(1).find((item) => item !== undefined)!;
213
+ if (lineToClassName[directive]) {
214
+ blocks[lineToClassName[directive]!]!.range += `${lineNumber},`;
215
+ } else if (blockStartToClassName[directive]) {
216
+ blocks[blockStartToClassName[directive]!]!.start = lineNumber;
217
+ } else if (blockEndToClassName[directive]) {
218
+ blocks[blockEndToClassName[directive]!]!.range += `${
219
+ blocks[blockEndToClassName[directive]!]!.start
220
+ }-${lineNumber - 1},`;
221
+ }
222
+ lines.splice(lineNumber, 1);
223
+ }
224
+ code = lines.join('\n');
225
+ const lineClassNames: {[lineIndex: number]: string[]} = {};
226
+ Object.entries(blocks).forEach(([className, {range}]) => {
227
+ rangeParser(range).forEach((l) => {
228
+ lineClassNames[l] ??= [];
229
+ lineClassNames[l]!.push(className);
230
+ });
231
+ });
232
+ return {lineClassNames, code};
233
+ }
234
+
235
+ export function getPrismCssVariables(prismTheme: PrismTheme): CSSProperties {
236
+ const mapping: {[name: keyof PrismTheme['plain']]: string} = {
237
+ color: '--prism-color',
238
+ backgroundColor: '--prism-background-color',
239
+ };
240
+
241
+ const properties: {[key: string]: string} = {};
242
+ Object.entries(prismTheme.plain).forEach(([key, value]) => {
243
+ const varName = mapping[key];
244
+ if (varName && typeof value === 'string') {
245
+ properties[varName] = value;
246
+ }
247
+ });
248
+ return properties;
12
249
  }
@@ -0,0 +1,334 @@
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 {
10
+ useAllDocsData,
11
+ useActivePlugin,
12
+ useActiveDocContext,
13
+ useLatestVersion,
14
+ type GlobalVersion,
15
+ type GlobalSidebar,
16
+ type GlobalDoc,
17
+ } from '@docusaurus/plugin-content-docs/client';
18
+ import type {
19
+ PropSidebar,
20
+ PropSidebarItem,
21
+ PropSidebarItemCategory,
22
+ PropVersionDoc,
23
+ PropSidebarBreadcrumbsItem,
24
+ } from '@docusaurus/plugin-content-docs';
25
+ import type {Props as DocPageProps} from '@theme/DocPage';
26
+ import {useDocsPreferredVersion} from '../contexts/docsPreferredVersion';
27
+ import {useDocsVersion} from '../contexts/docsVersion';
28
+ import {useDocsSidebar} from '../contexts/docsSidebar';
29
+ import {uniq} from './jsUtils';
30
+ import {isSamePath} from './routesUtils';
31
+ import {matchPath, useLocation} from '@docusaurus/router';
32
+ import renderRoutes from '@docusaurus/renderRoutes';
33
+
34
+ // TODO not ideal, see also "useDocs"
35
+ export const isDocsPluginEnabled: boolean = !!useAllDocsData;
36
+
37
+ /**
38
+ * A null-safe way to access a doc's data by ID in the active version.
39
+ */
40
+ export function useDocById(id: string): PropVersionDoc;
41
+ /**
42
+ * A null-safe way to access a doc's data by ID in the active version.
43
+ */
44
+ export function useDocById(id: string | undefined): PropVersionDoc | undefined;
45
+ export function useDocById(id: string | undefined): PropVersionDoc | undefined {
46
+ const version = useDocsVersion();
47
+ if (!id) {
48
+ return undefined;
49
+ }
50
+ const doc = version.docs[id];
51
+ if (!doc) {
52
+ throw new Error(`no version doc found by id=${id}`);
53
+ }
54
+ return doc;
55
+ }
56
+
57
+ /**
58
+ * Pure function, similar to `Array#find`, but works on the sidebar tree.
59
+ */
60
+ export function findSidebarCategory(
61
+ sidebar: PropSidebar,
62
+ predicate: (category: PropSidebarItemCategory) => boolean,
63
+ ): PropSidebarItemCategory | undefined {
64
+ for (const item of sidebar) {
65
+ if (item.type === 'category') {
66
+ if (predicate(item)) {
67
+ return item;
68
+ }
69
+ const subItem = findSidebarCategory(item.items, predicate);
70
+ if (subItem) {
71
+ return subItem;
72
+ }
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+
78
+ /**
79
+ * Best effort to assign a link to a sidebar category. If the category doesn't
80
+ * have a link itself, we link to the first sub item with a link.
81
+ */
82
+ export function findFirstCategoryLink(
83
+ item: PropSidebarItemCategory,
84
+ ): string | undefined {
85
+ if (item.href) {
86
+ return item.href;
87
+ }
88
+
89
+ for (const subItem of item.items) {
90
+ if (subItem.type === 'link') {
91
+ return subItem.href;
92
+ } else if (subItem.type === 'category') {
93
+ const categoryLink = findFirstCategoryLink(subItem);
94
+ if (categoryLink) {
95
+ return categoryLink;
96
+ }
97
+ }
98
+ // Could be "html" items
99
+ }
100
+ return undefined;
101
+ }
102
+
103
+ /**
104
+ * Gets the category associated with the current location. Should only be used
105
+ * on category index pages.
106
+ */
107
+ export function useCurrentSidebarCategory(): PropSidebarItemCategory {
108
+ const {pathname} = useLocation();
109
+ const sidebar = useDocsSidebar();
110
+ if (!sidebar) {
111
+ throw new Error('Unexpected: cant find current sidebar in context');
112
+ }
113
+ const category = findSidebarCategory(sidebar.items, (item) =>
114
+ isSamePath(item.href, pathname),
115
+ );
116
+ if (!category) {
117
+ throw new Error(
118
+ `${pathname} is not associated with a category. useCurrentSidebarCategory() should only be used on category index pages.`,
119
+ );
120
+ }
121
+ return category;
122
+ }
123
+
124
+ const isActive = (testedPath: string | undefined, activePath: string) =>
125
+ typeof testedPath !== 'undefined' && isSamePath(testedPath, activePath);
126
+ const containsActiveSidebarItem = (
127
+ items: PropSidebarItem[],
128
+ activePath: string,
129
+ ) => items.some((subItem) => isActiveSidebarItem(subItem, activePath));
130
+
131
+ /**
132
+ * Checks if a sidebar item should be active, based on the active path.
133
+ */
134
+ export function isActiveSidebarItem(
135
+ item: PropSidebarItem,
136
+ activePath: string,
137
+ ): boolean {
138
+ if (item.type === 'link') {
139
+ return isActive(item.href, activePath);
140
+ }
141
+
142
+ if (item.type === 'category') {
143
+ return (
144
+ isActive(item.href, activePath) ||
145
+ containsActiveSidebarItem(item.items, activePath)
146
+ );
147
+ }
148
+
149
+ return false;
150
+ }
151
+
152
+ /**
153
+ * Gets the breadcrumbs of the current doc page, based on its sidebar location.
154
+ * Returns `null` if there's no sidebar or breadcrumbs are disabled.
155
+ */
156
+ export function useSidebarBreadcrumbs(): PropSidebarBreadcrumbsItem[] | null {
157
+ const sidebar = useDocsSidebar();
158
+ const {pathname} = useLocation();
159
+ const breadcrumbsOption = useActivePlugin()?.pluginData.breadcrumbs;
160
+
161
+ if (breadcrumbsOption === false || !sidebar) {
162
+ return null;
163
+ }
164
+
165
+ const breadcrumbs: PropSidebarBreadcrumbsItem[] = [];
166
+
167
+ function extract(items: PropSidebar) {
168
+ for (const item of items) {
169
+ if (
170
+ (item.type === 'category' &&
171
+ (isSamePath(item.href, pathname) || extract(item.items))) ||
172
+ (item.type === 'link' && isSamePath(item.href, pathname))
173
+ ) {
174
+ breadcrumbs.push(item);
175
+ return true;
176
+ }
177
+ }
178
+
179
+ return false;
180
+ }
181
+
182
+ extract(sidebar.items);
183
+
184
+ return breadcrumbs.reverse();
185
+ }
186
+
187
+ /**
188
+ * "Version candidates" are mostly useful for the layout components, which must
189
+ * be able to work on all pages. For example, if a user has `{ type: "doc",
190
+ * docId: "intro" }` as a navbar item, which version does that refer to? We
191
+ * believe that it could refer to at most three version candidates:
192
+ *
193
+ * 1. The **active version**, the one that the user is currently browsing. See
194
+ * {@link useActiveDocContext}.
195
+ * 2. The **preferred version**, the one that the user last visited. See
196
+ * {@link useDocsPreferredVersion}.
197
+ * 3. The **latest version**, the "default". See {@link useLatestVersion}.
198
+ *
199
+ * @param docsPluginId The plugin ID to get versions from.
200
+ * @returns An array of 1~3 versions with priorities defined above, guaranteed
201
+ * to be unique and non-sparse. Will be memoized, hence stable for deps array.
202
+ */
203
+ export function useDocsVersionCandidates(
204
+ docsPluginId?: string,
205
+ ): [GlobalVersion, ...GlobalVersion[]] {
206
+ const {activeVersion} = useActiveDocContext(docsPluginId);
207
+ const {preferredVersion} = useDocsPreferredVersion(docsPluginId);
208
+ const latestVersion = useLatestVersion(docsPluginId);
209
+ return useMemo(
210
+ () =>
211
+ uniq(
212
+ [activeVersion, preferredVersion, latestVersion].filter(Boolean),
213
+ ) as [GlobalVersion, ...GlobalVersion[]],
214
+ [activeVersion, preferredVersion, latestVersion],
215
+ );
216
+ }
217
+
218
+ /**
219
+ * The layout components, like navbar items, must be able to work on all pages,
220
+ * even on non-doc ones where there's no version context, so a sidebar ID could
221
+ * be ambiguous. This hook would always return a sidebar to be linked to. See
222
+ * also {@link useDocsVersionCandidates} for how this selection is done.
223
+ *
224
+ * @throws This hook throws if a sidebar with said ID is not found.
225
+ */
226
+ export function useLayoutDocsSidebar(
227
+ sidebarId: string,
228
+ docsPluginId?: string,
229
+ ): GlobalSidebar {
230
+ const versions = useDocsVersionCandidates(docsPluginId);
231
+ return useMemo(() => {
232
+ const allSidebars = versions.flatMap((version) =>
233
+ version.sidebars ? Object.entries(version.sidebars) : [],
234
+ );
235
+ const sidebarEntry = allSidebars.find(
236
+ (sidebar) => sidebar[0] === sidebarId,
237
+ );
238
+ if (!sidebarEntry) {
239
+ throw new Error(
240
+ `Can't find any sidebar with id "${sidebarId}" in version${
241
+ versions.length > 1 ? 's' : ''
242
+ } ${versions.map((version) => version.name).join(', ')}".
243
+ Available sidebar ids are:
244
+ - ${Object.keys(allSidebars).join('\n- ')}`,
245
+ );
246
+ }
247
+ return sidebarEntry[1];
248
+ }, [sidebarId, versions]);
249
+ }
250
+
251
+ /**
252
+ * The layout components, like navbar items, must be able to work on all pages,
253
+ * even on non-doc ones where there's no version context, so a doc ID could be
254
+ * ambiguous. This hook would always return a doc to be linked to. See also
255
+ * {@link useDocsVersionCandidates} for how this selection is done.
256
+ *
257
+ * @throws This hook throws if a doc with said ID is not found.
258
+ */
259
+ export function useLayoutDoc(
260
+ docId: string,
261
+ docsPluginId?: string,
262
+ ): GlobalDoc | null {
263
+ const versions = useDocsVersionCandidates(docsPluginId);
264
+ return useMemo(() => {
265
+ const allDocs = versions.flatMap((version) => version.docs);
266
+ const doc = allDocs.find((versionDoc) => versionDoc.id === docId);
267
+ if (!doc) {
268
+ const isDraft = versions
269
+ .flatMap((version) => version.draftIds)
270
+ .includes(docId);
271
+ // Drafts should be silently filtered instead of throwing
272
+ if (isDraft) {
273
+ return null;
274
+ }
275
+ throw new Error(
276
+ `DocNavbarItem: couldn't find any doc with id "${docId}" in version${
277
+ versions.length > 1 ? 's' : ''
278
+ } ${versions.map((version) => version.name).join(', ')}".
279
+ Available doc ids are:
280
+ - ${uniq(allDocs.map((versionDoc) => versionDoc.id)).join('\n- ')}`,
281
+ );
282
+ }
283
+ return doc;
284
+ }, [docId, versions]);
285
+ }
286
+
287
+ // TODO later read version/route directly from context
288
+ /**
289
+ * The docs plugin creates nested routes, with the top-level route providing the
290
+ * version metadata, and the subroutes creating individual doc pages. This hook
291
+ * will match the current location against all known sub-routes.
292
+ *
293
+ * @param props The props received by `@theme/DocPage`
294
+ * @returns The data of the relevant document at the current location, or `null`
295
+ * if no document associated with the current location can be found.
296
+ */
297
+ export function useDocRouteMetadata({
298
+ route,
299
+ versionMetadata,
300
+ }: DocPageProps): null | {
301
+ /** The element that should be rendered at the current location. */
302
+ docElement: JSX.Element;
303
+ /**
304
+ * The name of the sidebar associated with the current doc. `sidebarName` and
305
+ * `sidebarItems` correspond to the value of {@link useDocsSidebar}.
306
+ */
307
+ sidebarName: string | undefined;
308
+ /** The items of the sidebar associated with the current doc. */
309
+ sidebarItems: PropSidebar | undefined;
310
+ } {
311
+ const location = useLocation();
312
+ const docRoutes = route.routes!;
313
+ const currentDocRoute = docRoutes.find((docRoute) =>
314
+ matchPath(location.pathname, docRoute),
315
+ );
316
+ if (!currentDocRoute) {
317
+ return null;
318
+ }
319
+
320
+ // For now, the sidebarName is added as route config: not ideal!
321
+ const sidebarName = currentDocRoute.sidebar;
322
+
323
+ const sidebarItems = sidebarName
324
+ ? versionMetadata.docsSidebars[sidebarName]
325
+ : undefined;
326
+
327
+ const docElement = renderRoutes(docRoutes, {versionMetadata});
328
+
329
+ return {
330
+ docElement,
331
+ sidebarName,
332
+ sidebarItems,
333
+ };
334
+ }
@@ -0,0 +1,18 @@
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 {MultiColumnFooter, SimpleFooter} from './useThemeConfig';
9
+
10
+ /**
11
+ * A rough duck-typing about whether the `footer.links` is intended to be multi-
12
+ * column.
13
+ */
14
+ export function isMultiColumnFooterLinks(
15
+ links: MultiColumnFooter['links'] | SimpleFooter['links'],
16
+ ): links is MultiColumnFooter['links'] {
17
+ return 'title' in links[0]!;
18
+ }
@@ -4,12 +4,16 @@
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
- export const useTitleFormatter = (title?: string | undefined): string => {
10
- const {siteConfig = {}} = useDocusaurusContext();
11
- const {title: siteTitle, titleDelimiter = '|'} = siteConfig;
12
- return title && title.trim().length
10
+ /**
11
+ * Formats the page's title based on relevant site config and other contexts.
12
+ */
13
+ export function useTitleFormatter(title?: string | undefined): string {
14
+ const {siteConfig} = useDocusaurusContext();
15
+ const {title: siteTitle, titleDelimiter} = siteConfig;
16
+ return title?.trim().length
13
17
  ? `${title.trim()} ${titleDelimiter} ${siteTitle}`
14
18
  : siteTitle;
15
- };
19
+ }