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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (261) hide show
  1. package/README.md +2 -2
  2. package/lib/components/Collapsible/index.d.ts +59 -0
  3. package/lib/components/Collapsible/index.d.ts.map +1 -0
  4. package/lib/components/Collapsible/index.js +145 -0
  5. package/lib/components/Collapsible/index.js.map +1 -0
  6. package/lib/components/Details/index.d.ts +20 -0
  7. package/lib/components/Details/index.d.ts.map +1 -0
  8. package/lib/components/Details/index.js +86 -0
  9. package/lib/components/Details/index.js.map +1 -0
  10. package/lib/components/Details/styles.module.css +66 -0
  11. package/lib/components/ThemedComponent/index.d.ts +31 -0
  12. package/lib/components/ThemedComponent/index.d.ts.map +1 -0
  13. package/lib/components/ThemedComponent/index.js +47 -0
  14. package/lib/components/ThemedComponent/index.js.map +1 -0
  15. package/lib/components/ThemedComponent/styles.module.css +26 -0
  16. package/lib/contexts/announcementBar.d.ts +21 -0
  17. package/lib/contexts/announcementBar.d.ts.map +1 -0
  18. package/lib/contexts/announcementBar.js +72 -0
  19. package/lib/contexts/announcementBar.js.map +1 -0
  20. package/lib/contexts/colorMode.d.ts +23 -0
  21. package/lib/contexts/colorMode.d.ts.map +1 -0
  22. package/lib/contexts/colorMode.js +163 -0
  23. package/lib/contexts/colorMode.js.map +1 -0
  24. package/lib/contexts/navbarMobileSidebar.d.ts +31 -0
  25. package/lib/contexts/navbarMobileSidebar.d.ts.map +1 -0
  26. package/lib/contexts/navbarMobileSidebar.js +65 -0
  27. package/lib/contexts/navbarMobileSidebar.js.map +1 -0
  28. package/lib/contexts/navbarSecondaryMenu/content.d.ts +37 -0
  29. package/lib/contexts/navbarSecondaryMenu/content.d.ts.map +1 -0
  30. package/lib/contexts/navbarSecondaryMenu/content.js +50 -0
  31. package/lib/contexts/navbarSecondaryMenu/content.js.map +1 -0
  32. package/lib/contexts/navbarSecondaryMenu/display.d.ts +24 -0
  33. package/lib/contexts/navbarSecondaryMenu/display.d.ts.map +1 -0
  34. package/lib/contexts/navbarSecondaryMenu/display.js +62 -0
  35. package/lib/contexts/navbarSecondaryMenu/display.js.map +1 -0
  36. package/lib/hooks/useBackToTopButton.d.ts +27 -0
  37. package/lib/hooks/useBackToTopButton.d.ts.map +1 -0
  38. package/lib/hooks/useBackToTopButton.js +50 -0
  39. package/lib/hooks/useBackToTopButton.js.map +1 -0
  40. package/lib/hooks/useCodeWordWrap.d.ts +15 -0
  41. package/lib/hooks/useCodeWordWrap.d.ts.map +1 -0
  42. package/lib/hooks/useCodeWordWrap.js +67 -0
  43. package/lib/hooks/useCodeWordWrap.js.map +1 -0
  44. package/lib/hooks/useHideableNavbar.d.ts +17 -0
  45. package/lib/hooks/useHideableNavbar.d.ts.map +1 -0
  46. package/lib/hooks/useHideableNavbar.js +65 -0
  47. package/lib/hooks/useHideableNavbar.js.map +1 -0
  48. package/lib/hooks/useLockBodyScroll.d.ts +12 -0
  49. package/lib/hooks/useLockBodyScroll.d.ts.map +1 -0
  50. package/lib/hooks/useLockBodyScroll.js +20 -0
  51. package/lib/hooks/useLockBodyScroll.js.map +1 -0
  52. package/lib/hooks/useMutationObserver.d.ts +4 -0
  53. package/lib/hooks/useMutationObserver.d.ts.map +1 -0
  54. package/lib/hooks/useMutationObserver.js +29 -0
  55. package/lib/hooks/useMutationObserver.js.map +1 -0
  56. package/lib/hooks/usePrismTheme.d.ts +13 -0
  57. package/lib/hooks/usePrismTheme.d.ts.map +1 -0
  58. package/lib/hooks/usePrismTheme.js +21 -0
  59. package/lib/hooks/usePrismTheme.js.map +1 -0
  60. package/lib/hooks/useTOCHighlight.d.ts +25 -0
  61. package/lib/hooks/useTOCHighlight.d.ts.map +1 -0
  62. package/lib/hooks/useTOCHighlight.js +130 -0
  63. package/lib/hooks/useTOCHighlight.js.map +1 -0
  64. package/lib/hooks/useWindowSize.d.ts +27 -0
  65. package/lib/hooks/useWindowSize.d.ts.map +1 -0
  66. package/lib/hooks/useWindowSize.js +49 -0
  67. package/lib/hooks/useWindowSize.js.map +1 -0
  68. package/lib/index.d.ts +30 -0
  69. package/lib/index.d.ts.map +1 -0
  70. package/lib/index.js +37 -0
  71. package/lib/index.js.map +1 -0
  72. package/lib/internal.d.ts +35 -0
  73. package/lib/internal.d.ts.map +1 -0
  74. package/lib/internal.js +45 -0
  75. package/lib/internal.js.map +1 -0
  76. package/lib/translations/blogTranslations.d.ts +20 -0
  77. package/lib/translations/blogTranslations.d.ts.map +1 -0
  78. package/lib/translations/blogTranslations.js +52 -0
  79. package/lib/translations/blogTranslations.js.map +1 -0
  80. package/lib/translations/contentVisibilityTranslations.d.ts +12 -0
  81. package/lib/translations/contentVisibilityTranslations.d.ts.map +1 -0
  82. package/lib/translations/contentVisibilityTranslations.js +30 -0
  83. package/lib/translations/contentVisibilityTranslations.js.map +1 -0
  84. package/lib/translations/docsTranslations.d.ts +8 -0
  85. package/lib/translations/docsTranslations.d.ts.map +1 -0
  86. package/lib/translations/docsTranslations.js +17 -0
  87. package/lib/translations/docsTranslations.js.map +1 -0
  88. package/lib/utils/IntlUtils.d.ts +2 -0
  89. package/lib/utils/IntlUtils.d.ts.map +1 -0
  90. package/lib/utils/IntlUtils.js +20 -0
  91. package/lib/utils/IntlUtils.js.map +1 -0
  92. package/lib/utils/ThemeClassNames.d.ts +99 -0
  93. package/lib/utils/ThemeClassNames.d.ts.map +1 -0
  94. package/lib/utils/ThemeClassNames.js +107 -0
  95. package/lib/utils/ThemeClassNames.js.map +1 -0
  96. package/lib/utils/accessibilityUtils.d.ts +8 -0
  97. package/lib/utils/accessibilityUtils.d.ts.map +1 -0
  98. package/lib/utils/accessibilityUtils.js +10 -0
  99. package/lib/utils/accessibilityUtils.js.map +1 -0
  100. package/lib/utils/admonitionUtils.d.ts +12 -0
  101. package/lib/utils/admonitionUtils.d.ts.map +1 -0
  102. package/lib/utils/admonitionUtils.js +32 -0
  103. package/lib/utils/admonitionUtils.js.map +1 -0
  104. package/lib/utils/anchorUtils.d.ts +16 -0
  105. package/lib/utils/anchorUtils.d.ts.map +1 -0
  106. package/lib/utils/anchorUtils.js +26 -0
  107. package/lib/utils/anchorUtils.js.map +1 -0
  108. package/lib/utils/anchorUtils.module.css +14 -0
  109. package/lib/utils/codeBlockUtils.d.ts +101 -0
  110. package/lib/utils/codeBlockUtils.d.ts.map +1 -0
  111. package/lib/utils/codeBlockUtils.js +310 -0
  112. package/lib/utils/codeBlockUtils.js.map +1 -0
  113. package/lib/utils/emojiUtils.d.ts +20 -0
  114. package/lib/utils/emojiUtils.d.ts.map +1 -0
  115. package/lib/utils/emojiUtils.js +32 -0
  116. package/lib/utils/emojiUtils.js.map +1 -0
  117. package/lib/utils/errorBoundaryUtils.d.ts +31 -0
  118. package/lib/utils/errorBoundaryUtils.d.ts.map +1 -0
  119. package/lib/utils/errorBoundaryUtils.js +48 -0
  120. package/lib/utils/errorBoundaryUtils.js.map +1 -0
  121. package/lib/utils/errorBoundaryUtils.module.css +16 -0
  122. package/lib/utils/footerUtils.d.ts +13 -0
  123. package/lib/utils/footerUtils.d.ts.map +1 -0
  124. package/lib/utils/footerUtils.js +14 -0
  125. package/lib/utils/footerUtils.js.map +1 -0
  126. package/lib/utils/historyUtils.d.ts +39 -0
  127. package/lib/utils/historyUtils.d.ts.map +1 -0
  128. package/lib/utils/historyUtils.js +148 -0
  129. package/lib/utils/historyUtils.js.map +1 -0
  130. package/lib/utils/jsUtils.d.ts +24 -0
  131. package/lib/utils/jsUtils.d.ts.map +1 -0
  132. package/lib/utils/jsUtils.js +43 -0
  133. package/lib/utils/jsUtils.js.map +1 -0
  134. package/lib/utils/metadataUtils.d.ts +38 -0
  135. package/lib/utils/metadataUtils.d.ts.map +1 -0
  136. package/lib/utils/metadataUtils.js +87 -0
  137. package/lib/utils/metadataUtils.js.map +1 -0
  138. package/lib/utils/navbarUtils.d.ts +21 -0
  139. package/lib/utils/navbarUtils.d.ts.map +1 -0
  140. package/lib/utils/navbarUtils.js +35 -0
  141. package/lib/utils/navbarUtils.js.map +1 -0
  142. package/lib/utils/reactUtils.d.ts +60 -0
  143. package/lib/utils/reactUtils.d.ts.map +1 -0
  144. package/lib/utils/reactUtils.js +91 -0
  145. package/lib/utils/reactUtils.js.map +1 -0
  146. package/lib/utils/regexpUtils.d.ts +12 -0
  147. package/lib/utils/regexpUtils.d.ts.map +1 -0
  148. package/lib/utils/regexpUtils.js +18 -0
  149. package/lib/utils/regexpUtils.js.map +1 -0
  150. package/lib/utils/routesUtils.d.ts +26 -0
  151. package/lib/utils/routesUtils.d.ts.map +1 -0
  152. package/lib/utils/routesUtils.js +54 -0
  153. package/lib/utils/routesUtils.js.map +1 -0
  154. package/lib/utils/scrollUtils.d.ts +83 -0
  155. package/lib/utils/scrollUtils.d.ts.map +1 -0
  156. package/lib/utils/scrollUtils.js +201 -0
  157. package/lib/utils/scrollUtils.js.map +1 -0
  158. package/lib/utils/searchUtils.d.ts +8 -0
  159. package/lib/utils/searchUtils.d.ts.map +1 -0
  160. package/lib/utils/searchUtils.js +8 -0
  161. package/lib/utils/searchUtils.js.map +1 -0
  162. package/lib/utils/skipToContentUtils.d.ts +20 -0
  163. package/lib/utils/skipToContentUtils.d.ts.map +1 -0
  164. package/lib/utils/skipToContentUtils.js +75 -0
  165. package/lib/utils/skipToContentUtils.js.map +1 -0
  166. package/lib/utils/storageUtils.d.ts +36 -0
  167. package/lib/utils/storageUtils.d.ts.map +1 -0
  168. package/lib/utils/storageUtils.js +193 -0
  169. package/lib/utils/storageUtils.js.map +1 -0
  170. package/lib/utils/tabsUtils.d.ts +55 -0
  171. package/lib/utils/tabsUtils.d.ts.map +1 -0
  172. package/lib/utils/tabsUtils.js +179 -0
  173. package/lib/utils/tabsUtils.js.map +1 -0
  174. package/lib/utils/tagsUtils.d.ts +20 -0
  175. package/lib/utils/tagsUtils.d.ts.map +1 -0
  176. package/lib/utils/tagsUtils.js +41 -0
  177. package/lib/utils/tagsUtils.js.map +1 -0
  178. package/lib/utils/titleFormatterUtils.d.ts +59 -0
  179. package/lib/utils/titleFormatterUtils.d.ts.map +1 -0
  180. package/lib/utils/titleFormatterUtils.js +49 -0
  181. package/lib/utils/titleFormatterUtils.js.map +1 -0
  182. package/lib/utils/tocUtils.d.ts +36 -0
  183. package/lib/utils/tocUtils.d.ts.map +1 -0
  184. package/lib/utils/tocUtils.js +84 -0
  185. package/lib/utils/tocUtils.js.map +1 -0
  186. package/lib/utils/useAlternatePageUtils.d.ts +32 -0
  187. package/lib/utils/useAlternatePageUtils.d.ts.map +1 -0
  188. package/lib/utils/useAlternatePageUtils.js +42 -0
  189. package/lib/utils/useAlternatePageUtils.js.map +1 -0
  190. package/lib/utils/useLocalPathname.d.ts +13 -0
  191. package/lib/utils/useLocalPathname.d.ts.map +1 -0
  192. package/lib/utils/useLocalPathname.js +19 -0
  193. package/lib/utils/useLocalPathname.js.map +1 -0
  194. package/lib/utils/useLocationChange.d.ts +17 -0
  195. package/lib/utils/useLocationChange.d.ts.map +1 -0
  196. package/lib/utils/useLocationChange.js +31 -0
  197. package/lib/utils/useLocationChange.js.map +1 -0
  198. package/lib/utils/usePluralForm.d.ts +21 -0
  199. package/lib/utils/usePluralForm.d.ts.map +1 -0
  200. package/lib/utils/usePluralForm.js +93 -0
  201. package/lib/utils/usePluralForm.js.map +1 -0
  202. package/lib/utils/useThemeConfig.d.ts +120 -0
  203. package/lib/utils/useThemeConfig.d.ts.map +1 -0
  204. package/lib/utils/useThemeConfig.js +14 -0
  205. package/lib/utils/useThemeConfig.js.map +1 -0
  206. package/package.json +58 -4
  207. package/src/components/Collapsible/index.tsx +250 -0
  208. package/src/components/Details/index.tsx +130 -0
  209. package/src/components/Details/styles.module.css +66 -0
  210. package/src/components/ThemedComponent/index.tsx +75 -0
  211. package/src/components/ThemedComponent/styles.module.css +26 -0
  212. package/src/contexts/announcementBar.tsx +117 -0
  213. package/src/contexts/colorMode.tsx +257 -0
  214. package/src/contexts/navbarMobileSidebar.tsx +119 -0
  215. package/src/contexts/navbarSecondaryMenu/content.tsx +100 -0
  216. package/src/contexts/navbarSecondaryMenu/display.tsx +102 -0
  217. package/src/hooks/useBackToTopButton.ts +73 -0
  218. package/src/hooks/useCodeWordWrap.ts +107 -0
  219. package/src/hooks/useHideableNavbar.ts +81 -0
  220. package/src/hooks/useLockBodyScroll.ts +21 -0
  221. package/src/hooks/useMutationObserver.ts +38 -0
  222. package/src/hooks/usePrismTheme.ts +24 -0
  223. package/src/hooks/useTOCHighlight.ts +189 -0
  224. package/src/hooks/useWindowSize.ts +67 -0
  225. package/src/index.ts +112 -0
  226. package/src/internal.ts +107 -0
  227. package/src/translations/blogTranslations.tsx +89 -0
  228. package/src/translations/contentVisibilityTranslations.tsx +51 -0
  229. package/src/translations/docsTranslations.tsx +28 -0
  230. package/src/types.d.ts +8 -0
  231. package/src/utils/IntlUtils.ts +27 -0
  232. package/src/utils/ThemeClassNames.ts +119 -0
  233. package/src/utils/accessibilityUtils.ts +10 -0
  234. package/src/utils/admonitionUtils.tsx +44 -0
  235. package/src/utils/anchorUtils.module.css +14 -0
  236. package/src/utils/anchorUtils.ts +31 -0
  237. package/src/utils/codeBlockUtils.tsx +494 -0
  238. package/src/utils/emojiUtils.ts +40 -0
  239. package/src/utils/errorBoundaryUtils.module.css +16 -0
  240. package/src/utils/errorBoundaryUtils.tsx +71 -0
  241. package/src/utils/footerUtils.ts +18 -0
  242. package/src/utils/historyUtils.ts +199 -0
  243. package/src/utils/jsUtils.ts +54 -0
  244. package/src/utils/metadataUtils.tsx +145 -0
  245. package/src/utils/navbarUtils.tsx +45 -0
  246. package/src/utils/reactUtils.tsx +120 -0
  247. package/src/utils/regexpUtils.ts +24 -0
  248. package/src/utils/routesUtils.ts +75 -0
  249. package/src/utils/scrollUtils.tsx +303 -0
  250. package/src/utils/searchUtils.ts +8 -0
  251. package/src/utils/skipToContentUtils.tsx +108 -0
  252. package/src/utils/storageUtils.ts +260 -0
  253. package/src/utils/tabsUtils.tsx +307 -0
  254. package/src/utils/tagsUtils.tsx +61 -0
  255. package/src/utils/titleFormatterUtils.tsx +120 -0
  256. package/src/utils/tocUtils.ts +119 -0
  257. package/src/utils/useAlternatePageUtils.ts +80 -0
  258. package/src/utils/useLocalPathname.ts +22 -0
  259. package/src/utils/useLocationChange.ts +41 -0
  260. package/src/utils/usePluralForm.ts +131 -0
  261. package/src/utils/useThemeConfig.ts +147 -0
@@ -0,0 +1,494 @@
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 {CSSProperties, ReactNode} from 'react';
9
+ import {createContext, useContext, useMemo} from 'react';
10
+ import clsx from 'clsx';
11
+ import rangeParser from 'parse-numeric-range';
12
+ import {ReactContextError} from './reactUtils';
13
+ import type {PrismTheme, PrismThemeEntry} from 'prism-react-renderer';
14
+ import type {WordWrap} from '../hooks/useCodeWordWrap';
15
+
16
+ const codeBlockTitleRegex = /title=(?<quote>["'])(?<title>.*?)\1/;
17
+ const metastringLinesRangeRegex = /\{(?<range>[\d,-]+)\}/;
18
+
19
+ // Supported types of highlight comments
20
+ const popularCommentPatterns = {
21
+ js: {start: '\\/\\/', end: ''},
22
+ jsBlock: {start: '\\/\\*', end: '\\*\\/'},
23
+ jsx: {start: '\\{\\s*\\/\\*', end: '\\*\\/\\s*\\}'},
24
+ bash: {start: '#', end: ''},
25
+ html: {start: '<!--', end: '-->'},
26
+ } as const;
27
+
28
+ const commentPatterns = {
29
+ ...popularCommentPatterns, // shallow copy is sufficient
30
+ // minor comment styles
31
+ lua: {start: '--', end: ''},
32
+ wasm: {start: '\\;\\;', end: ''},
33
+ tex: {start: '%', end: ''},
34
+ vb: {start: "['‘’]", end: ''},
35
+ vbnet: {start: "(?:_\\s*)?['‘’]", end: ''}, // Visual Studio 2019 or later
36
+ rem: {start: '[Rr][Ee][Mm]\\b', end: ''},
37
+ f90: {start: '!', end: ''}, // Free format only
38
+ ml: {start: '\\(\\*', end: '\\*\\)'},
39
+ cobol: {start: '\\*>', end: ''}, // Free format only
40
+ } as const;
41
+
42
+ type CommentType = keyof typeof commentPatterns;
43
+ const popularCommentTypes = Object.keys(
44
+ popularCommentPatterns,
45
+ ) as CommentType[];
46
+
47
+ export type MagicCommentConfig = {
48
+ className: string;
49
+ line?: string;
50
+ block?: {start: string; end: string};
51
+ };
52
+
53
+ function getCommentPattern(
54
+ languages: CommentType[],
55
+ magicCommentDirectives: MagicCommentConfig[],
56
+ ) {
57
+ // To be more reliable, the opening and closing comment must match
58
+ const commentPattern = languages
59
+ .map((lang) => {
60
+ const {start, end} = commentPatterns[lang];
61
+ return `(?:${start}\\s*(${magicCommentDirectives
62
+ .flatMap((d) => [d.line, d.block?.start, d.block?.end].filter(Boolean))
63
+ .join('|')})\\s*${end})`;
64
+ })
65
+ .join('|');
66
+ // White space is allowed, but otherwise it should be on it's own line
67
+ return new RegExp(`^\\s*(?:${commentPattern})\\s*$`);
68
+ }
69
+
70
+ /**
71
+ * Select comment styles based on language
72
+ */
73
+ function getAllMagicCommentDirectiveStyles(
74
+ lang: string,
75
+ magicCommentDirectives: MagicCommentConfig[],
76
+ ) {
77
+ switch (lang) {
78
+ case 'js':
79
+ case 'javascript':
80
+ case 'ts':
81
+ case 'typescript':
82
+ return getCommentPattern(['js', 'jsBlock'], magicCommentDirectives);
83
+
84
+ case 'jsx':
85
+ case 'tsx':
86
+ return getCommentPattern(
87
+ ['js', 'jsBlock', 'jsx'],
88
+ magicCommentDirectives,
89
+ );
90
+
91
+ case 'html':
92
+ return getCommentPattern(
93
+ ['js', 'jsBlock', 'html'],
94
+ magicCommentDirectives,
95
+ );
96
+
97
+ case 'python':
98
+ case 'py':
99
+ case 'bash':
100
+ return getCommentPattern(['bash'], magicCommentDirectives);
101
+
102
+ case 'markdown':
103
+ case 'md':
104
+ // Text uses HTML, front matter uses bash
105
+ return getCommentPattern(['html', 'jsx', 'bash'], magicCommentDirectives);
106
+
107
+ case 'tex':
108
+ case 'latex':
109
+ case 'matlab':
110
+ return getCommentPattern(['tex'], magicCommentDirectives);
111
+
112
+ case 'lua':
113
+ case 'haskell':
114
+ return getCommentPattern(['lua'], magicCommentDirectives);
115
+
116
+ case 'sql':
117
+ return getCommentPattern(['lua', 'jsBlock'], magicCommentDirectives);
118
+
119
+ case 'wasm':
120
+ return getCommentPattern(['wasm'], magicCommentDirectives);
121
+
122
+ case 'vb':
123
+ case 'vba':
124
+ case 'visual-basic':
125
+ return getCommentPattern(['vb', 'rem'], magicCommentDirectives);
126
+ case 'vbnet':
127
+ return getCommentPattern(['vbnet', 'rem'], magicCommentDirectives);
128
+
129
+ case 'batch':
130
+ return getCommentPattern(['rem'], magicCommentDirectives);
131
+
132
+ case 'basic': // https://github.com/PrismJS/prism/blob/master/components/prism-basic.js#L3
133
+ return getCommentPattern(['rem', 'f90'], magicCommentDirectives);
134
+
135
+ case 'fsharp':
136
+ return getCommentPattern(['js', 'ml'], magicCommentDirectives);
137
+
138
+ case 'ocaml':
139
+ case 'sml':
140
+ return getCommentPattern(['ml'], magicCommentDirectives);
141
+
142
+ case 'fortran':
143
+ return getCommentPattern(['f90'], magicCommentDirectives);
144
+
145
+ case 'cobol':
146
+ return getCommentPattern(['cobol'], magicCommentDirectives);
147
+
148
+ default:
149
+ // All popular comment types
150
+ return getCommentPattern(popularCommentTypes, magicCommentDirectives);
151
+ }
152
+ }
153
+
154
+ export function parseCodeBlockTitle(metastring?: string): string {
155
+ return metastring?.match(codeBlockTitleRegex)?.groups!.title ?? '';
156
+ }
157
+
158
+ function getMetaLineNumbersStart(metastring?: string): number | undefined {
159
+ const showLineNumbersMeta = metastring
160
+ ?.split(' ')
161
+ .find((str) => str.startsWith('showLineNumbers'));
162
+
163
+ if (showLineNumbersMeta) {
164
+ if (showLineNumbersMeta.startsWith('showLineNumbers=')) {
165
+ const value = showLineNumbersMeta.replace('showLineNumbers=', '');
166
+ return parseInt(value, 10);
167
+ }
168
+ return 1;
169
+ }
170
+
171
+ return undefined;
172
+ }
173
+
174
+ export function getLineNumbersStart({
175
+ showLineNumbers,
176
+ metastring,
177
+ }: {
178
+ showLineNumbers: boolean | number | undefined;
179
+ metastring: string | undefined;
180
+ }): number | undefined {
181
+ const defaultStart = 1;
182
+ if (typeof showLineNumbers === 'boolean') {
183
+ return showLineNumbers ? defaultStart : undefined;
184
+ }
185
+ if (typeof showLineNumbers === 'number') {
186
+ return showLineNumbers;
187
+ }
188
+ return getMetaLineNumbersStart(metastring);
189
+ }
190
+
191
+ type ParseCodeLinesParam = {
192
+ /**
193
+ * The full metastring, as received from MDX. Line ranges declared here
194
+ * start at 1.
195
+ */
196
+ metastring: string | undefined;
197
+ /**
198
+ * Language of the code block, used to determine which kinds of magic
199
+ * comment styles to enable.
200
+ */
201
+ language: string | undefined;
202
+ /**
203
+ * Magic comment types that we should try to parse. Each entry would
204
+ * correspond to one class name to apply to each line.
205
+ */
206
+ magicComments: MagicCommentConfig[];
207
+ };
208
+
209
+ /**
210
+ * The highlighted lines, 0-indexed. e.g. `{ 0: ["highlight", "sample"] }`
211
+ * means the 1st line should have `highlight` and `sample` as class names.
212
+ */
213
+ type CodeLineClassNames = {[lineIndex: number]: string[]};
214
+
215
+ /**
216
+ * Code lines after applying magic comments or metastring highlight ranges
217
+ */
218
+ type ParsedCodeLines = {
219
+ code: string;
220
+ lineClassNames: CodeLineClassNames;
221
+ };
222
+
223
+ function parseCodeLinesFromMetastring(
224
+ code: string,
225
+ {metastring, magicComments}: ParseCodeLinesParam,
226
+ ): ParsedCodeLines | null {
227
+ // Highlighted lines specified in props: don't parse the content
228
+ if (metastring && metastringLinesRangeRegex.test(metastring)) {
229
+ const linesRange = metastring.match(metastringLinesRangeRegex)!.groups!
230
+ .range!;
231
+ if (magicComments.length === 0) {
232
+ throw new Error(
233
+ `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.`,
234
+ );
235
+ }
236
+ const metastringRangeClassName = magicComments[0]!.className;
237
+ const lines = rangeParser(linesRange)
238
+ .filter((n) => n > 0)
239
+ .map((n) => [n - 1, [metastringRangeClassName]] as [number, string[]]);
240
+ return {lineClassNames: Object.fromEntries(lines), code};
241
+ }
242
+ return null;
243
+ }
244
+
245
+ function parseCodeLinesFromContent(
246
+ code: string,
247
+ params: ParseCodeLinesParam,
248
+ ): ParsedCodeLines {
249
+ const {language, magicComments} = params;
250
+ if (language === undefined) {
251
+ return {lineClassNames: {}, code};
252
+ }
253
+ const directiveRegex = getAllMagicCommentDirectiveStyles(
254
+ language,
255
+ magicComments,
256
+ );
257
+ // Go through line by line
258
+ const lines = code.split(/\r?\n/);
259
+ const blocks = Object.fromEntries(
260
+ magicComments.map((d) => [d.className, {start: 0, range: ''}]),
261
+ );
262
+ const lineToClassName: {[comment: string]: string} = Object.fromEntries(
263
+ magicComments
264
+ .filter((d) => d.line)
265
+ .map(({className, line}) => [line!, className] as [string, string]),
266
+ );
267
+ const blockStartToClassName: {[comment: string]: string} = Object.fromEntries(
268
+ magicComments
269
+ .filter((d) => d.block)
270
+ .map(({className, block}) => [block!.start, className]),
271
+ );
272
+ const blockEndToClassName: {[comment: string]: string} = Object.fromEntries(
273
+ magicComments
274
+ .filter((d) => d.block)
275
+ .map(({className, block}) => [block!.end, className]),
276
+ );
277
+ for (let lineNumber = 0; lineNumber < lines.length; ) {
278
+ const line = lines[lineNumber]!;
279
+ const match = line.match(directiveRegex);
280
+ if (!match) {
281
+ // Lines without directives are unchanged
282
+ lineNumber += 1;
283
+ continue;
284
+ }
285
+ const directive = match
286
+ .slice(1)
287
+ .find((item: string | undefined) => item !== undefined)!;
288
+ if (lineToClassName[directive]) {
289
+ blocks[lineToClassName[directive]!]!.range += `${lineNumber},`;
290
+ } else if (blockStartToClassName[directive]) {
291
+ blocks[blockStartToClassName[directive]!]!.start = lineNumber;
292
+ } else if (blockEndToClassName[directive]) {
293
+ blocks[blockEndToClassName[directive]!]!.range += `${
294
+ blocks[blockEndToClassName[directive]!]!.start
295
+ }-${lineNumber - 1},`;
296
+ }
297
+ lines.splice(lineNumber, 1);
298
+ }
299
+
300
+ const lineClassNames: {[lineIndex: number]: string[]} = {};
301
+ Object.entries(blocks).forEach(([className, {range}]) => {
302
+ rangeParser(range).forEach((l) => {
303
+ lineClassNames[l] ??= [];
304
+ lineClassNames[l]!.push(className);
305
+ });
306
+ });
307
+
308
+ return {code: lines.join('\n'), lineClassNames};
309
+ }
310
+
311
+ /**
312
+ * Parses the code content, strips away any magic comments, and returns the
313
+ * clean content and the highlighted lines marked by the comments or metastring.
314
+ *
315
+ * If the metastring contains a range, the `content` will be returned as-is
316
+ * without any parsing. The returned `lineClassNames` will be a map from that
317
+ * number range to the first magic comment config entry (which _should_ be for
318
+ * line highlight directives.)
319
+ */
320
+ export function parseLines(
321
+ code: string,
322
+ params: ParseCodeLinesParam,
323
+ ): ParsedCodeLines {
324
+ // Historical behavior: we remove last line break
325
+ const newCode = code.replace(/\r?\n$/, '');
326
+ // Historical behavior: we try one strategy after the other
327
+ // we don't support mixing metastring ranges + magic comments
328
+ return (
329
+ parseCodeLinesFromMetastring(newCode, {...params}) ??
330
+ parseCodeLinesFromContent(newCode, {...params})
331
+ );
332
+ }
333
+
334
+ /**
335
+ * Gets the language name from the class name (set by MDX).
336
+ * e.g. `"language-javascript"` => `"javascript"`.
337
+ * Returns undefined if there is no language class name.
338
+ */
339
+ export function parseClassNameLanguage(
340
+ className: string | undefined,
341
+ ): string | undefined {
342
+ if (!className) {
343
+ return undefined;
344
+ }
345
+ const languageClassName = className
346
+ .split(' ')
347
+ .find((str) => str.startsWith('language-'));
348
+ return languageClassName?.replace(/language-/, '');
349
+ }
350
+
351
+ // Prism languages are always lowercase
352
+ // We want to fail-safe and allow both "php" and "PHP"
353
+ // See https://github.com/facebook/docusaurus/issues/9012
354
+ function normalizeLanguage(language: string | undefined): string | undefined {
355
+ return language?.toLowerCase();
356
+ }
357
+
358
+ function getLanguage(params: {
359
+ language: string | undefined;
360
+ className: string | undefined;
361
+ defaultLanguage: string | undefined;
362
+ }): string {
363
+ return (
364
+ normalizeLanguage(
365
+ params.language ??
366
+ parseClassNameLanguage(params.className) ??
367
+ params.defaultLanguage,
368
+ ) ?? 'text'
369
+ ); // There's always a language, required by Prism;
370
+ }
371
+
372
+ /**
373
+ * This ensures that we always have the code block language as className
374
+ * For MDX code blocks this is provided automatically by MDX
375
+ * For JSX code blocks, the language gets added by this function
376
+ * This ensures both cases lead to a consistent HTML output
377
+ */
378
+ function ensureLanguageClassName({
379
+ className,
380
+ language,
381
+ }: {
382
+ className: string | undefined;
383
+ language: string;
384
+ }): string {
385
+ return clsx(
386
+ className,
387
+ language &&
388
+ !className?.includes(`language-${language}`) &&
389
+ `language-${language}`,
390
+ );
391
+ }
392
+
393
+ export interface CodeBlockMetadata {
394
+ codeInput: string; // Including magic comments
395
+ code: string; // Rendered code, excluding magic comments
396
+ className: string; // There's always a "language-<lang>" className
397
+ language: string;
398
+ title: ReactNode;
399
+ lineNumbersStart: number | undefined;
400
+ lineClassNames: CodeLineClassNames;
401
+ }
402
+
403
+ export function createCodeBlockMetadata(params: {
404
+ code: string;
405
+ className: string | undefined;
406
+ language: string | undefined;
407
+ defaultLanguage: string | undefined;
408
+ metastring: string | undefined;
409
+ magicComments: MagicCommentConfig[];
410
+ title: ReactNode;
411
+ showLineNumbers: boolean | number | undefined;
412
+ }): CodeBlockMetadata {
413
+ const language = getLanguage({
414
+ language: params.language,
415
+ defaultLanguage: params.defaultLanguage,
416
+ className: params.className,
417
+ });
418
+
419
+ const {lineClassNames, code} = parseLines(params.code, {
420
+ metastring: params.metastring,
421
+ magicComments: params.magicComments,
422
+ language,
423
+ });
424
+
425
+ const className = ensureLanguageClassName({
426
+ className: params.className,
427
+ language,
428
+ });
429
+
430
+ const title = parseCodeBlockTitle(params.metastring) || params.title;
431
+
432
+ const lineNumbersStart = getLineNumbersStart({
433
+ showLineNumbers: params.showLineNumbers,
434
+ metastring: params.metastring,
435
+ });
436
+
437
+ return {
438
+ codeInput: params.code,
439
+ code,
440
+ className,
441
+ language,
442
+ title,
443
+ lineNumbersStart,
444
+ lineClassNames,
445
+ };
446
+ }
447
+
448
+ export function getPrismCssVariables(prismTheme: PrismTheme): CSSProperties {
449
+ const mapping: PrismThemeEntry = {
450
+ color: '--prism-color',
451
+ backgroundColor: '--prism-background-color',
452
+ };
453
+
454
+ const properties: {[key: string]: string} = {};
455
+ Object.entries(prismTheme.plain).forEach(([key, value]) => {
456
+ const varName = mapping[key as keyof PrismThemeEntry];
457
+ if (varName && typeof value === 'string') {
458
+ properties[varName] = value;
459
+ }
460
+ });
461
+ return properties;
462
+ }
463
+
464
+ type CodeBlockContextValue = {
465
+ metadata: CodeBlockMetadata;
466
+ wordWrap: WordWrap;
467
+ };
468
+
469
+ const CodeBlockContext = createContext<CodeBlockContextValue | null>(null);
470
+
471
+ export function CodeBlockContextProvider({
472
+ metadata,
473
+ wordWrap,
474
+ children,
475
+ }: {
476
+ metadata: CodeBlockMetadata;
477
+ wordWrap: WordWrap;
478
+ children: ReactNode;
479
+ }): ReactNode {
480
+ // Should we optimize this in 2 contexts?
481
+ // Unlike metadata, wordWrap is stateful and likely to trigger re-renders
482
+ const value: CodeBlockContextValue = useMemo(() => {
483
+ return {metadata, wordWrap};
484
+ }, [metadata, wordWrap]);
485
+ return <CodeBlockContext value={value}>{children}</CodeBlockContext>;
486
+ }
487
+
488
+ export function useCodeBlockContext(): CodeBlockContextValue {
489
+ const value = useContext(CodeBlockContext);
490
+ if (value === null) {
491
+ throw new ReactContextError('CodeBlockContextProvider');
492
+ }
493
+ return value;
494
+ }
@@ -0,0 +1,40 @@
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
+ const segmenter = new Intl.Segmenter(undefined, {granularity: 'grapheme'});
9
+
10
+ /**
11
+ * This method splits "⚠️ Hello World" into "⚠️" + " Hello World".
12
+ * It is quite strict and dumb, only useful to handle best-effort heuristics.
13
+ * It only extracts a leading emoji if it is the first grapheme of the string.
14
+ * It only extracts one emoji, even if multiples are present.
15
+ * It doesn't trim the remaining string.
16
+ * If you need something more clever, it should be built on top.
17
+ * @param input
18
+ */
19
+ export function extractLeadingEmoji(input: string): {
20
+ emoji: string | null;
21
+ rest: string;
22
+ } {
23
+ const it = segmenter.segment(input)[Symbol.iterator]();
24
+
25
+ // const first = segmenter.segment(input).containing(0)?.segment;
26
+ const grapheme = it.next().value?.segment;
27
+
28
+ if (!grapheme) {
29
+ return {emoji: null, rest: input};
30
+ }
31
+
32
+ // Leading grapheme contains an emoji
33
+ // Covers flags/ZWJ/skin tones, excludes digits
34
+ // See https://github.com/facebook/docusaurus/pull/12072
35
+ if (!/^\p{RGI_Emoji}$/v.test(grapheme)) {
36
+ return {emoji: null, rest: input};
37
+ }
38
+
39
+ return {emoji: grapheme, rest: input.slice(grapheme.length)};
40
+ }
@@ -0,0 +1,16 @@
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
+ .errorBoundaryError {
9
+ white-space: pre-wrap;
10
+ color: red;
11
+ }
12
+
13
+ .errorBoundaryFallback {
14
+ color: red;
15
+ padding: 0.55rem;
16
+ }
@@ -0,0 +1,71 @@
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, {type ComponentProps, type ReactNode} from 'react';
9
+ import Translate from '@docusaurus/Translate';
10
+ import {getErrorCausalChain} from '@docusaurus/utils-common';
11
+ import type {Props as ErrorProps} from '@theme/Error';
12
+ import styles from './errorBoundaryUtils.module.css';
13
+
14
+ export function ErrorBoundaryTryAgainButton(
15
+ props: ComponentProps<'button'>,
16
+ ): ReactNode {
17
+ return (
18
+ <button type="button" {...props}>
19
+ <Translate
20
+ id="theme.ErrorPageContent.tryAgain"
21
+ description="The label of the button to try again rendering when the React error boundary captures an error">
22
+ Try again
23
+ </Translate>
24
+ </button>
25
+ );
26
+ }
27
+
28
+ // A very simple reusable ErrorBoundary fallback component
29
+ export function ErrorBoundaryErrorMessageFallback({
30
+ error,
31
+ tryAgain,
32
+ }: ErrorProps): ReactNode {
33
+ return (
34
+ <div className={styles.errorBoundaryFallback}>
35
+ <p>{error.message}</p>
36
+ <ErrorBoundaryTryAgainButton onClick={tryAgain} />
37
+ </div>
38
+ );
39
+ }
40
+
41
+ export function ErrorBoundaryError({error}: {error: Error}): ReactNode {
42
+ const causalChain = getErrorCausalChain(error);
43
+ const fullMessage = causalChain.map((e) => e.message).join('\n\nCause:\n');
44
+ return <p className={styles.errorBoundaryError}>{fullMessage}</p>;
45
+ }
46
+
47
+ /**
48
+ * This component is useful to wrap a low-level error into a more meaningful
49
+ * error with extra context, using the ES error-cause feature.
50
+ *
51
+ * <ErrorCauseBoundary
52
+ * onError={(error) => new Error("extra context message",{cause: error})}
53
+ * >
54
+ * <RiskyComponent>
55
+ * </ErrorCauseBoundary>
56
+ */
57
+ export class ErrorCauseBoundary extends React.Component<
58
+ {
59
+ children: React.ReactNode;
60
+ onError: (error: Error, errorInfo: React.ErrorInfo) => Error;
61
+ },
62
+ unknown
63
+ > {
64
+ override componentDidCatch(error: Error, errorInfo: React.ErrorInfo): never {
65
+ throw this.props.onError(error, errorInfo);
66
+ }
67
+
68
+ override render(): React.ReactNode {
69
+ return this.props.children;
70
+ }
71
+ }
@@ -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
+ }