Allow custom attributes to parse single attributes as well

This commit is contained in:
Marcus Blättermann 2022-11-13 16:04:30 +01:00
parent cc1597e4c5
commit 67893b4d90
No known key found for this signature in database
GPG Key ID: A1E1F04008AC450D

View File

@ -1,3 +1,17 @@
const parseAttribute = (expression) => {
if (expression.type !== 'AssignmentExpression' || !expression.left || !expression.right) {
return
}
const { left, right } = expression
if (left.type !== 'Identifier' || right.type !== 'Literal' || !left.name || !right.value) {
return
}
return { type: 'mdxJsxAttribute', name: left.name, value: right.value }
}
const parseAstTree = (markdownAST) => { const parseAstTree = (markdownAST) => {
markdownAST.children.map((node, index) => { markdownAST.children.map((node, index) => {
if (node.type !== 'heading' || !node.children || node.children < 2) { if (node.type !== 'heading' || !node.children || node.children < 2) {
@ -24,48 +38,24 @@ const parseAstTree = (markdownAST) => {
const estreeBodyFirstNode = estree.body[0] const estreeBodyFirstNode = estree.body[0]
if ( if (estreeBodyFirstNode.type !== 'ExpressionStatement' || !estreeBodyFirstNode.expression) {
estreeBodyFirstNode.type !== 'ExpressionStatement' ||
!estreeBodyFirstNode.expression ||
estreeBodyFirstNode.expression.type !== 'SequenceExpression'
) {
return return
} }
const sequenceExpression = estreeBodyFirstNode.expression const statement = estreeBodyFirstNode.expression
if (!sequenceExpression.expressions) { const attributeExpressions = [
return ...(statement.type === 'SequenceExpression' && statement.expressions
} ? statement.expressions
: []),
const attributes = sequenceExpression.expressions.map((expression) => { ...(statement.type === 'AssignmentExpression' ? [statement] : []),
if ( ]
expression.type !== 'AssignmentExpression' ||
!expression.left ||
!expression.right
) {
return
}
const { left, right } = expression
if (
left.type !== 'Identifier' ||
right.type !== 'Literal' ||
!left.name ||
!right.value
) {
return
}
return { type: 'mdxJsxAttribute', name: left.name, value: right.value }
})
// This replaces the markdown heading with a JSX element // This replaces the markdown heading with a JSX element
markdownAST.children[index] = { markdownAST.children[index] = {
type: 'mdxJsxFlowElement', type: 'mdxJsxFlowElement',
name: `h${node.depth}`, name: `h${node.depth}`,
attributes, attributes: attributeExpressions.map(parseAttribute),
children: [node.children[0]], children: [node.children[0]],
} }
}) })