Extract function to own file

This commit is contained in:
Marcus Blättermann 2022-11-27 02:37:23 +01:00
parent e5c4b18ccc
commit 46fb76c281
No known key found for this signature in database
GPG Key ID: A1E1F04008AC450D
2 changed files with 44 additions and 39 deletions

View File

@ -0,0 +1,38 @@
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 [left.name, right.value]
}
const getProps = (estree) => {
if (estree.type !== 'Program' || !estree.body || estree.body.length <= 0 || !estree.body[0]) {
return {}
}
const estreeBodyFirstNode = estree.body[0]
if (estreeBodyFirstNode.type !== 'ExpressionStatement' || !estreeBodyFirstNode.expression) {
return {}
}
const statement = estreeBodyFirstNode.expression
const attributeExpressions = [
...(statement.type === 'SequenceExpression' && statement.expressions
? statement.expressions
: []),
...(statement.type === 'AssignmentExpression' ? [statement] : []),
]
return Object.fromEntries(attributeExpressions.map(parseAttribute))
}
export default getProps

View File

@ -1,16 +1,4 @@
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 }
}
import getProps from './getProps.mjs'
const handleNode = (node) => {
if (node.type === 'section' && node.children) {
@ -31,34 +19,13 @@ const handleNode = (node) => {
return node
}
const { estree } = lastNode.data
const data = node.data || (node.data = {})
data.hProperties = getProps(lastNode.data.estree)
if (estree.type !== 'Program' || !estree.body || estree.body.length <= 0 || !estree.body[0]) {
return node
}
// Only keep the text, drop the rest
node.children = [node.children[0]]
const estreeBodyFirstNode = estree.body[0]
if (estreeBodyFirstNode.type !== 'ExpressionStatement' || !estreeBodyFirstNode.expression) {
return node
}
const statement = estreeBodyFirstNode.expression
const attributeExpressions = [
...(statement.type === 'SequenceExpression' && statement.expressions
? statement.expressions
: []),
...(statement.type === 'AssignmentExpression' ? [statement] : []),
]
// This replaces the markdown heading with a JSX element
return {
type: 'mdxJsxFlowElement',
name: `h${node.depth}`,
attributes: attributeExpressions.map(parseAttribute),
children: [node.children[0]],
}
return node
}
const parseAstTree = (markdownAST) => ({