-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathwithExamples.mjs
62 lines (56 loc) · 1.47 KB
/
withExamples.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { visit } from 'unist-util-visit'
import { Parser } from 'acorn'
import acornJsx from 'acorn-jsx'
const JsxParser = Parser.extend(acornJsx())
export default () => {
return (tree) => {
visit(tree, 'code', (node, nodeIndex, parentNode) => {
if (node.lang !== 'html') {
return
}
let meta = node.meta?.trim()
if (!meta) {
return
}
if (!/^{\s*{.*?example:/.test(meta)) {
return
}
node.type = 'mdxJsxFlowElement'
node.name = 'Example'
node.children = []
let next = parentNode.children[nodeIndex + 1]
node.attributes = [
{
type: 'mdxJsxAttribute',
name: 'containerClassName',
value: next?.type === 'code' ? 'mt-4 -mb-3' : 'my-6',
},
{
type: 'mdxJsxAttribute',
name: 'html',
value: node.value,
},
]
if (!/\bexample:\s*true/.test(meta)) {
let props = `...(${meta.slice(1, -1)}).example`
node.attributes.push({
type: 'mdxJsxExpressionAttribute',
value: props,
data: {
estree: {
type: 'Program',
body: [
{
type: 'ExpressionStatement',
expression: JsxParser.parseExpressionAt(`{${props}}`, 0, {
ecmaVersion: 'latest',
}),
},
],
},
},
})
}
})
}
}