UNPKG

2.41 kBJavaScriptView Raw
1const toHAST = require('mdast-util-to-hast')
2const detab = require('detab')
3const u = require('unist-builder')
4
5function mdxAstToMdxHast() {
6 return (tree, _file) => {
7 const handlers = {
8 // `inlineCode` gets passed as `code` by the HAST transform.
9 // This makes sure it ends up being `inlineCode`
10 inlineCode(h, node) {
11 return Object.assign({}, node, {
12 type: 'element',
13 tagName: 'inlineCode',
14 properties: {},
15 children: [
16 {
17 type: 'text',
18 value: node.value
19 }
20 ]
21 })
22 },
23 code(h, node) {
24 const value = node.value ? detab(node.value + '\n') : ''
25 const lang = node.lang
26 const props = {}
27
28 if (lang) {
29 props.className = ['language-' + lang]
30 }
31
32 // MDAST sets `node.meta` to `null` instead of `undefined` if
33 // not present, which React doesn't like.
34 props.metastring = node.meta || undefined
35
36 const meta =
37 node.meta &&
38 node.meta.split(' ').reduce((acc, cur) => {
39 if (cur.split('=').length > 1) {
40 const t = cur.split('=')
41 acc[t[0]] = t[1]
42 return acc
43 }
44
45 acc[cur] = true
46 return acc
47 }, {})
48
49 if (meta) {
50 Object.keys(meta).forEach(key => {
51 const isClassKey = key === 'class' || key === 'className'
52 if (props.className && isClassKey) {
53 props.className.push(meta[key])
54 } else {
55 props[key] = meta[key]
56 }
57 })
58 }
59
60 return h(node.position, 'pre', [
61 h(node, 'code', props, [u('text', value)])
62 ])
63 },
64 import(h, node) {
65 return Object.assign({}, node, {
66 type: 'import'
67 })
68 },
69 export(h, node) {
70 return Object.assign({}, node, {
71 type: 'export'
72 })
73 },
74 comment(h, node) {
75 return Object.assign({}, node, {
76 type: 'comment'
77 })
78 },
79 jsx(h, node) {
80 return Object.assign({}, node, {
81 type: 'jsx'
82 })
83 }
84 }
85
86 const hast = toHAST(tree, {
87 handlers,
88 // Enable passing of HTML nodes to HAST as raw nodes
89 allowDangerousHtml: true
90 })
91
92 return hast
93 }
94}
95
96module.exports = mdxAstToMdxHast