@brillout/docpress 0.15.10 → 0.15.11

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 (51) hide show
  1. package/components/CodeSnippets/useSelectCodeLang.ts +60 -0
  2. package/components/CodeSnippets.css +78 -0
  3. package/components/CodeSnippets.tsx +50 -0
  4. package/components/Pre.css +51 -0
  5. package/components/Pre.tsx +72 -0
  6. package/components/index.ts +1 -0
  7. package/components/useMDXComponents.tsx +13 -0
  8. package/css/button.css +23 -0
  9. package/css/code.css +3 -21
  10. package/css/index.css +1 -0
  11. package/css/tooltip.css +10 -2
  12. package/dist/+config.js +1 -1
  13. package/dist/NavItemComponent.js +38 -46
  14. package/dist/components/CodeBlockTransformer.js +2 -3
  15. package/dist/components/CodeSnippets/useSelectCodeLang.d.ts +7 -0
  16. package/dist/components/CodeSnippets/useSelectCodeLang.js +50 -0
  17. package/dist/components/CodeSnippets.d.ts +11 -0
  18. package/dist/components/CodeSnippets.js +35 -0
  19. package/dist/components/Comment.js +1 -2
  20. package/dist/components/FileRemoved.js +4 -6
  21. package/dist/components/HorizontalLine.js +1 -2
  22. package/dist/components/ImportMeta.js +2 -3
  23. package/dist/components/Link.js +34 -50
  24. package/dist/components/Note.js +17 -29
  25. package/dist/components/P.js +1 -12
  26. package/dist/components/RepoLink.js +7 -9
  27. package/dist/components/index.d.ts +1 -0
  28. package/dist/components/index.js +1 -0
  29. package/dist/determineNavItemsColumnLayout.js +48 -63
  30. package/dist/parseMarkdownMini.js +5 -17
  31. package/dist/parsePageSections.js +41 -82
  32. package/dist/rehypeMetaToProps.d.ts +19 -0
  33. package/dist/rehypeMetaToProps.js +62 -0
  34. package/dist/remarkDetype.d.ts +4 -0
  35. package/dist/remarkDetype.js +146 -0
  36. package/dist/renderer/usePageContext.js +6 -7
  37. package/dist/resolvePageContext.js +103 -110
  38. package/dist/utils/Emoji/Emoji.js +13 -21
  39. package/dist/utils/assert.js +14 -16
  40. package/dist/utils/cls.js +1 -1
  41. package/dist/utils/determineSectionUrlHash.js +5 -5
  42. package/dist/utils/filter.js +2 -2
  43. package/dist/utils/getGlobalObject.js +3 -3
  44. package/dist/vite.config.js +12 -7
  45. package/index.ts +15 -5
  46. package/package.json +5 -1
  47. package/rehypeMetaToProps.ts +69 -0
  48. package/remarkDetype.ts +172 -0
  49. package/resolvePageContext.ts +19 -15
  50. package/tsconfig.json +2 -1
  51. package/vite.config.ts +9 -4
@@ -0,0 +1,69 @@
1
+ export { rehypeMetaToProps }
2
+
3
+ import { visit } from 'unist-util-visit'
4
+ import type { ElementData, Root } from 'hast'
5
+
6
+ /**
7
+ * Rehype plugin to extract metadata from `<code>` blocks in markdown
8
+ * and attach them as props to the parent `<pre>` element.
9
+ *
10
+ * This allows using those props inside a custom `<Pre>` component.
11
+ *
12
+ * Example:
13
+ * ~~~mdx
14
+ * ```js foo="bar" hide_copy='true'
15
+ * export function add(a, b) {
16
+ * return a + b
17
+ * }
18
+ * ```
19
+ * ~~~
20
+ * These props are then added to the `<pre>` element
21
+ */
22
+ function rehypeMetaToProps() {
23
+ return (tree: Root) => {
24
+ visit(tree, 'element', (node, _index, parent) => {
25
+ if (node.tagName === 'code' && parent?.type === 'element' && parent.tagName === 'pre') {
26
+ const props = parseMetaString(node.data?.meta)
27
+ parent.properties ??= {}
28
+ parent.properties = { ...parent.properties, ...props }
29
+ }
30
+ })
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Minimal parser for a metadata string into key-value pairs.
36
+ *
37
+ * Supports simple patterns: key or key="value".
38
+ *
39
+ * Keys must contain only letters, dashes, or underscores (no digits).
40
+ * Keys are converted to kebab-case. Values default to "true" if missing.
41
+ *
42
+ * Example:
43
+ * parseMetaString('foo fooBar="value"')
44
+ * => { foo: 'true', foo_bar: 'value' }
45
+ *
46
+ * @param metaString - The input metadata string.
47
+ * @returns A plain object of parsed key-value pairs.
48
+ */
49
+ function parseMetaString(metaString: ElementData['meta']): Record<string, string> {
50
+ if (!metaString) return {}
51
+
52
+ const props: Record<string, string> = {}
53
+
54
+ const keyValuePairRE = /([a-zA-Z_-]+)(?:="([^"]*)")?(?=\s|$)/g
55
+ for (const match of metaString.matchAll(keyValuePairRE)) {
56
+ let [_, key, value] = match
57
+ props[kebabCase(key)] = value || 'true'
58
+ }
59
+
60
+ return props
61
+ }
62
+
63
+ // Simple function to convert a camelCase or PascalCase string to kebab-case.
64
+ function kebabCase(str: string) {
65
+ return str
66
+ .replace(/([a-z])([A-Z])/g, '$1-$2')
67
+ .replace('_', '-')
68
+ .toLowerCase()
69
+ }
@@ -0,0 +1,172 @@
1
+ export { remarkDetype }
2
+
3
+ import type { Root, Parent, Code } from 'mdast'
4
+ import type { VFile } from '@mdx-js/mdx/internal-create-format-aware-processors'
5
+ import { visit } from 'unist-util-visit'
6
+ import { assertUsage } from './utils/assert.js'
7
+ import pc from '@brillout/picocolors'
8
+ import module from 'node:module'
9
+ // Cannot use `import { transform } from 'detype'` as it results in errors,
10
+ // and the package has no default export. Using `module.createRequire` instead.
11
+ const { transform: detype } = module.createRequire(import.meta.url)('detype') as typeof import('detype')
12
+
13
+ const prettierOptions: NonNullable<Parameters<typeof detype>[2]>['prettierOptions'] = {
14
+ semi: false,
15
+ singleQuote: true,
16
+ printWidth: 100,
17
+ trailingComma: 'none',
18
+ }
19
+
20
+ type CodeNode = {
21
+ codeBlock: Code
22
+ index: number
23
+ parent: Parent
24
+ }
25
+
26
+ function remarkDetype() {
27
+ return async function transformer(tree: Root, file: VFile) {
28
+ const code_nodes: CodeNode[] = []
29
+
30
+ visit(tree, 'code', (node, index, parent) => {
31
+ if (!parent || typeof index === 'undefined') return
32
+ // Skip if `node.lang` is not ts, tsx, vue, or yaml
33
+ if (!['ts', 'tsx', 'vue', 'yaml'].includes(node.lang || '')) return
34
+
35
+ // Skip if 'ts-only' meta is present
36
+ if (node.meta?.includes('ts-only')) return
37
+
38
+ // Collect this node for post-processing
39
+ code_nodes.push({ codeBlock: node, index, parent })
40
+ })
41
+
42
+ for (const node of code_nodes.reverse()) {
43
+ if (node.codeBlock.lang === 'yaml') {
44
+ transformYaml(node)
45
+ } else {
46
+ await transformTsToJs(node, file)
47
+ }
48
+ }
49
+ }
50
+ }
51
+
52
+ function transformYaml(node: CodeNode) {
53
+ const { codeBlock, index, parent } = node
54
+ const codeBlockContentJs = replaceFileNameSuffixes(codeBlock.value)
55
+
56
+ // Skip wrapping if the YAML code block hasn't changed
57
+ if (codeBlockContentJs === codeBlock.value) return
58
+
59
+ const { position, ...rest } = codeBlock
60
+
61
+ // Create a new code node for the JS version based on the modified YAML
62
+ const yamlJsCode: Code = {
63
+ ...rest,
64
+ value: codeBlockContentJs,
65
+ }
66
+
67
+ // Wrap both the original YAML and `yamlJsCode` with <CodeSnippets>
68
+ const yamlContainer = {
69
+ type: 'mdxJsxFlowElement' as const,
70
+ name: 'CodeSnippets',
71
+ children: [yamlJsCode, codeBlock],
72
+ attributes: [],
73
+ }
74
+ parent.children.splice(index, 1, yamlContainer)
75
+ }
76
+
77
+ async function transformTsToJs(node: CodeNode, file: VFile) {
78
+ const { codeBlock, index, parent } = node
79
+ let codeBlockContentJs = replaceFileNameSuffixes(codeBlock.value)
80
+
81
+ // Remove TypeScript from the TS/TSX/Vue code node
82
+ try {
83
+ codeBlockContentJs = await detype(codeBlockContentJs, `some-dummy-filename.${codeBlock.lang}`, {
84
+ customizeBabelConfig(config) {
85
+ // Add `onlyRemoveTypeImports: true` to the internal `@babel/preset-typescript` config
86
+ // https://github.com/cyco130/detype/blob/46ec867e9efd31d31a312a215ca169bd6bff4726/src/transform.ts#L206
87
+ assertUsage(config.presets && config.presets.length === 1, 'Unexpected Babel config presets')
88
+ config.presets = [[config.presets[0], { onlyRemoveTypeImports: true }]]
89
+ },
90
+ removeTsComments: true,
91
+ prettierOptions,
92
+ })
93
+ } catch (error) {
94
+ // Log errors and return original content instead of throwing
95
+ console.error(pc.red((error as SyntaxError).message))
96
+ console.error(
97
+ [
98
+ `Failed to transform the code block in: ${pc.bold(pc.blue(file.path))}.`,
99
+ "This likely happened due to invalid TypeScript syntax (see detype's error message above). You can either:",
100
+ '- Fix the code block syntax',
101
+ '- Set the code block language to js instead of ts',
102
+ '- Use custom meta or comments https://github.com/brillout/docpress#detype',
103
+ ].join('\n') + '\n',
104
+ )
105
+ return
106
+ }
107
+
108
+ // Clean up both JS and TS code contents: correct diff comments (for js only) and apply custom magic comment replacements
109
+ codeBlockContentJs = cleanUpCode(codeBlockContentJs.trimEnd(), true)
110
+ codeBlock.value = cleanUpCode(codeBlock.value)
111
+
112
+ // No wrapping needed if JS and TS code are still identical
113
+ if (codeBlockContentJs === codeBlock.value) return
114
+
115
+ const { position, lang, ...rest } = codeBlock
116
+
117
+ const jsCode: Code = {
118
+ ...rest,
119
+ // The jsCode lang should be js|jsx|vue
120
+ lang: lang!.replace('t', 'j'),
121
+ value: codeBlockContentJs,
122
+ }
123
+
124
+ // Wrap both the original `codeBlock` and `jsCode` with <CodeSnippets>
125
+ const container = {
126
+ type: 'mdxJsxFlowElement' as const,
127
+ name: 'CodeSnippets',
128
+ children: [jsCode, codeBlock],
129
+ attributes: [],
130
+ }
131
+ parent.children.splice(index, 1, container)
132
+ }
133
+
134
+ // Replace all '.ts' extensions with '.js'
135
+ function replaceFileNameSuffixes(codeBlockValue: string) {
136
+ return codeBlockValue.replaceAll('.ts', '.js')
137
+ }
138
+
139
+ function cleanUpCode(code: string, isJsCode: boolean = false) {
140
+ if (isJsCode) {
141
+ code = correctCodeDiffComments(code)
142
+ }
143
+ return processMagicComments(code)
144
+ }
145
+ function processMagicComments(code: string) {
146
+ // @detype-replace DummyLayout Layout
147
+ const renameCommentRE = /^\/\/\s@detype-replace\s([^ ]+) ([^ ]+)\n/gm
148
+ const matches = Array.from(code.matchAll(renameCommentRE))
149
+
150
+ if (matches.length) {
151
+ for (let i = matches.length - 1; i >= 0; i--) {
152
+ const match = matches[i]
153
+ const [fullMatch, renameFrom, renameTo] = match
154
+ code = code.split(fullMatch).join('').replaceAll(renameFrom, renameTo)
155
+ }
156
+ }
157
+ code = code.replaceAll('// @detype-uncomment ', '')
158
+
159
+ return code
160
+ }
161
+ /**
162
+ * Correct code diff comments that detype() unexpectedly reformatted (using Prettier and Babel internally)
163
+ * after removing TypeScript.
164
+ * See https://github.com/brillout/docpress/pull/47#issuecomment-3263953899
165
+ * @param code Transformed Javascript code.
166
+ * @returns The corrected code.
167
+ */
168
+ function correctCodeDiffComments(code: string) {
169
+ // Expected to match the code diff comments: `// [!code ++]` and `// [!code --]` started with newline and optional spaces
170
+ const codeDiffRE = /\n\s*\/\/\s\[!code.+\]/g
171
+ return code.replaceAll(codeDiffRE, (codeDiff) => codeDiff.trimStart())
172
+ }
@@ -13,7 +13,7 @@ import type {
13
13
  HeadingDetachedResolved,
14
14
  StringArray,
15
15
  } from './types/Heading'
16
- import { assert } from './utils/assert'
16
+ import { assert, assertUsage } from './utils/assert'
17
17
  import { jsxToTextContent } from './utils/jsxToTextContent'
18
18
  import pc from '@brillout/picocolors'
19
19
  import { parseMarkdownMini } from './parseMarkdownMini'
@@ -149,6 +149,16 @@ function getActiveHeading(
149
149
  headingsDetachedResolved: HeadingDetachedResolved[],
150
150
  urlPathname: string,
151
151
  ) {
152
+ const URLs =
153
+ '\n' +
154
+ [...headingsResolved, ...headingsDetachedResolved]
155
+ .filter(Boolean)
156
+ .map((h) => h.url)
157
+ .sort()
158
+ .map((url) => ` ${url}`)
159
+ .join('\n')
160
+ const errNotFound = `URL ${pc.bold(urlPathname)} not found in following URLs:${URLs}`
161
+ const errFoundTwice = `URL ${pc.bold(urlPathname)} found twice in following URLs:${URLs}`
152
162
  let activeHeading: HeadingResolved | HeadingDetachedResolved | null = null
153
163
  let activeCategoryName = 'Miscellaneous'
154
164
  let headingCategory: string | undefined
@@ -158,6 +168,7 @@ function getActiveHeading(
158
168
  headingCategory = heading.title
159
169
  }
160
170
  if (heading.url === urlPathname) {
171
+ assertUsage(!activeHeading, errFoundTwice)
161
172
  activeHeading = heading
162
173
  assert(headingCategory)
163
174
  activeCategoryName = headingCategory
@@ -167,21 +178,14 @@ function getActiveHeading(
167
178
  }
168
179
  const isDetachedPage = !activeHeading
169
180
  if (!activeHeading) {
170
- activeHeading = headingsDetachedResolved.find(({ url }) => urlPathname === url) ?? null
171
- }
172
- if (!activeHeading) {
173
- throw new Error(
174
- [
175
- `URL ${pc.bold(urlPathname)} not found in following URLs:`,
176
- [...headingsResolved, ...headingsDetachedResolved]
177
- .filter(Boolean)
178
- .map((h) => h.url)
179
- .sort()
180
- .map((url) => ` ${url}`)
181
- .join('\n'),
182
- ].join('\n'),
183
- )
181
+ const found = headingsDetachedResolved.filter(({ url }) => urlPathname === url)
182
+ if (found.length > 0) {
183
+ assertUsage(found.length === 1, errFoundTwice)
184
+ assertUsage(!activeHeading, errFoundTwice)
185
+ activeHeading = found[0]!
186
+ }
184
187
  }
188
+ assertUsage(activeHeading, errNotFound)
185
189
  if (activeHeading.category) activeCategoryName = activeHeading.category
186
190
  return { activeHeading, isDetachedPage, activeCategoryName }
187
191
  }
package/tsconfig.json CHANGED
@@ -2,7 +2,8 @@
2
2
  "compilerOptions": {
3
3
  "outDir": "./dist/",
4
4
  "jsx": "react",
5
- "module": "ES2020",
5
+ "module": "ES2022",
6
+ "target": "ES2022",
6
7
  "moduleResolution": "Bundler",
7
8
  "lib": ["DOM", "DOM.Iterable", "ESNext"],
8
9
  "types": ["vite/client"],
package/vite.config.ts CHANGED
@@ -7,17 +7,22 @@ import { parsePageSections } from './parsePageSections.js'
7
7
  import rehypePrettyCode from 'rehype-pretty-code'
8
8
  import remarkGfm from 'remark-gfm'
9
9
  import { transformerNotationDiff } from '@shikijs/transformers'
10
+ import { remarkDetype } from './remarkDetype.js'
11
+ import { rehypeMetaToProps } from './rehypeMetaToProps.js'
10
12
 
11
13
  const root = process.cwd()
12
- const prettyCode = [rehypePrettyCode, { theme: 'github-light', transformers: [transformerNotationDiff()] }]
13
- const rehypePlugins: any = [prettyCode]
14
- const remarkPlugins = [remarkGfm]
14
+ const prettyCode = [
15
+ rehypePrettyCode,
16
+ { theme: 'github-light', keepBackground: false, transformers: [transformerNotationDiff()] },
17
+ ]
18
+ const rehypePlugins: any = [prettyCode, [rehypeMetaToProps]]
19
+ const remarkPlugins = [remarkGfm, remarkDetype]
15
20
 
16
21
  const config: UserConfig = {
17
22
  root,
18
23
  plugins: [
19
24
  parsePageSections(),
20
- mdx({ rehypePlugins, remarkPlugins }) as PluginOption,
25
+ mdx({ rehypePlugins, remarkPlugins, providerImportSource: '@brillout/docpress' }) as PluginOption,
21
26
  // @vitejs/plugin-react-swc needs to be added *after* the mdx plugins
22
27
  react(),
23
28
  ],