forked from mdx-js/mdx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmdx-hast-to-jsx.js
286 lines (248 loc) · 7.99 KB
/
mdx-hast-to-jsx.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
const {transformSync} = require('@babel/core')
const styleToObject = require('style-to-object')
const camelCaseCSS = require('camelcase-css')
const uniq = require('lodash.uniq')
const {paramCase, toTemplateLiteral} = require('@mdx-js/util')
const BabelPluginApplyMdxProp = require('babel-plugin-apply-mdx-type-prop')
const BabelPluginExtractImportNames = require('babel-plugin-extract-import-names')
// From https://github.com/wooorm/property-information/blob/ca74feb1fcd40753367c75b63c893353cd7d8c70/lib/html.js
const spaceSeparatedProperties = [
'acceptCharset',
'accessKey',
'autoComplete',
'className',
'controlsList',
'headers',
'htmlFor',
'httpEquiv',
'itemProp',
'itemRef',
'itemType',
'ping',
'rel',
'sandbox'
]
// eslint-disable-next-line complexity
function toJSX(node, parentNode = {}, options = {}) {
const {
// Default options
skipExport = false,
preserveNewlines = false,
wrapExport,
file
} = options
let children = ''
if (node.properties != null) {
// Turn style strings into JSX-friendly style object
if (typeof node.properties.style === 'string') {
let styleObject = {}
styleToObject(node.properties.style, function (name, value) {
styleObject[camelCaseCSS(name)] = value
})
node.properties.style = styleObject
}
// Transform class property to JSX-friendly className
if (node.properties.class) {
node.properties.className = node.properties.class
delete node.properties.class
}
// AriaProperty => aria-property
// dataProperty => data-property
const paramCaseRe = /^(aria[A-Z])|(data[A-Z])/
node.properties = Object.entries(node.properties).reduce(
(properties, [key, value]) =>
Object.assign({}, properties, {
[paramCaseRe.test(key) ? paramCase(key) : key]: value
}),
{}
)
}
if (node.type === 'root') {
const importNodes = []
const exportNodes = []
const jsxNodes = []
let layout
for (const childNode of node.children) {
if (childNode.type === 'import') {
importNodes.push(childNode)
continue
}
if (childNode.type === 'export') {
if (childNode.default) {
layout = childNode.value
.replace(/^export\s+default\s+/, '')
.replace(/;\s*$/, '')
continue
}
exportNodes.push(childNode)
continue
}
jsxNodes.push(childNode)
}
const exportNames = exportNodes
.map(node =>
node.value.match(/^export\s*(var|const|let|class|function)?\s*(\w+)/)
)
.map(match => (Array.isArray(match) ? match[2] : null))
.filter(Boolean)
const importStatements = importNodes
.map(childNode => toJSX(childNode, node))
.join('\n')
const exportStatements = exportNodes
.map(childNode => toJSX(childNode, node))
.join('\n')
const layoutProps = `const layoutProps = {
${exportNames.join(',\n')}
};`
const mdxLayout = `const MDXLayout = ${layout ? layout : '"wrapper"'}`
let mustCheckContent = false;
const fn = `function MDXContent({ components, ...props }) {
return (
<MDXLayout
{...layoutProps}
{...props}
components={components}>
${(() => {
const nodes = jsxNodes.map(childNode => toJSX(childNode, node));
if(nodes[0] == "<!doctype html>") {
nodes[0] = "";
console.log("Attempted to fix doctype html issue, must be successful");
mustCheckContent = true;
}
return nodes.join('');
})()}
</MDXLayout>
)
};
MDXContent.isMDXComponent = true`
if (mustCheckContent) {
console.log(fn);
mustCheckContent = false;
}
// Check JSX nodes against imports
const babelPluginExtractImportNamesInstance = new BabelPluginExtractImportNames()
const filename = options.file && options.file.path
transformSync(importStatements, {
filename,
configFile: false,
babelrc: false,
plugins: [
require('@babel/plugin-syntax-jsx'),
require('@babel/plugin-syntax-object-rest-spread'),
babelPluginExtractImportNamesInstance.plugin
]
})
const importNames = babelPluginExtractImportNamesInstance.state.names
const babelPluginApplyMdxPropInstance = new BabelPluginApplyMdxProp()
const babelPluginApplyMdxPropToExportsInstance = new BabelPluginApplyMdxProp()
const fnPostMdxTypeProp = transformSync(fn, {
filename,
configFile: false,
babelrc: false,
plugins: [
require('@babel/plugin-syntax-jsx'),
require('@babel/plugin-syntax-object-rest-spread'),
babelPluginApplyMdxPropInstance.plugin
]
}).code
const exportStatementsPostMdxTypeProps = transformSync(exportStatements, {
filename,
configFile: false,
babelrc: false,
plugins: [
require('@babel/plugin-syntax-jsx'),
require('@babel/plugin-syntax-object-rest-spread'),
babelPluginApplyMdxPropToExportsInstance.plugin
]
}).code
const allJsxNames = [
...babelPluginApplyMdxPropInstance.state.names,
...babelPluginApplyMdxPropToExportsInstance.state.names
]
const jsxNames = allJsxNames.filter(name => name !== 'MDXLayout')
const importExportNames = importNames.concat(exportNames)
const shortCodeDef = `const makeShortcode = name => function MDXDefaultShortcode(props) {
console.warn("Component " + name + " was not imported, exported, or provided by MDXProvider as global scope")
return <div {...props}/>
};
`
const fakedModulesForGlobalScope = uniq(jsxNames)
.filter(name => !importExportNames.includes(name))
.map(name => `const ${name} = makeShortcode("${name}");`)
.join('\n')
const fakedModules =
(fakedModulesForGlobalScope &&
[shortCodeDef, fakedModulesForGlobalScope].join('')) ||
''
const moduleBase = `${importStatements}
${exportStatementsPostMdxTypeProps}
${fakedModules}
${layoutProps}
${mdxLayout}`
if (skipExport) {
return `${moduleBase}
${fnPostMdxTypeProp}`
}
if (wrapExport) {
return `${moduleBase}
${fnPostMdxTypeProp}
export default ${wrapExport}(MDXContent)`
}
return `${moduleBase}
export default ${fnPostMdxTypeProp}`
}
// Recursively walk through children
if (node.children) {
children = node.children
.map(childNode => {
const childOptions = Object.assign({}, options, {
// Tell all children inside <pre> tags to preserve newlines as text nodes
preserveNewlines: preserveNewlines || node.tagName === 'pre'
})
return toJSX(childNode, node, childOptions)
})
.join('')
}
if (node.type === 'element') {
let props = ''
if (node.properties) {
spaceSeparatedProperties.forEach(prop => {
if (Array.isArray(node.properties[prop])) {
node.properties[prop] = node.properties[prop].join(' ')
}
})
if (Object.keys(node.properties).length > 0) {
props = JSON.stringify(node.properties)
}
}
return `<${node.tagName}${
parentNode.tagName ? ` parentName="${parentNode.tagName}"` : ''
}${props ? ` {...${props}}` : ''}>${children}</${node.tagName}>`
}
// Wraps text nodes inside template string, so that we don't run into escaping issues.
if (node.type === 'text') {
// Don't wrap newlines unless specifically instructed to by the flag,
// to avoid issues like React warnings caused by text nodes in tables.
const shouldPreserveNewlines =
preserveNewlines || parentNode.tagName === 'p'
if (node.value === '\n' && !shouldPreserveNewlines) {
return node.value
}
return toTemplateLiteral(node.value)
}
if (node.type === 'comment') {
return `{/*${node.value}*/}`
}
if (node.type === 'import' || node.type === 'export' || node.type === 'jsx') {
return node.value
}
}
function compile(options = {}) {
this.Compiler = function (tree, file) {
return toJSX(tree, {}, {file: file || {}, ...options})
}
}
module.exports = compile
exports = compile
exports.toJSX = toJSX
exports.default = compile