Add plugin for custom attributes on Markdown elements

This commit is contained in:
Marcus Blättermann 2022-11-13 14:53:15 +01:00
parent f216853b01
commit cc1597e4c5
No known key found for this signature in database
GPG Key ID: A1E1F04008AC450D
2 changed files with 81 additions and 1 deletions

View File

@ -1,3 +1,5 @@
const remarkPlugins = [] import remarkCustomAttrs from './remarkCustomAttrs.mjs'
const remarkPlugins = [remarkCustomAttrs]
export default remarkPlugins export default remarkPlugins

View File

@ -0,0 +1,78 @@
const parseAstTree = (markdownAST) => {
markdownAST.children.map((node, index) => {
if (node.type !== 'heading' || !node.children || node.children < 2) {
return
}
const indexLast = node.children.length - 1
const lastNode = node.children[indexLast]
if (lastNode.type !== 'mdxTextExpression' || !lastNode.data || !lastNode.data.estree) {
return
}
const { estree } = lastNode.data
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 ||
estreeBodyFirstNode.expression.type !== 'SequenceExpression'
) {
return
}
const sequenceExpression = estreeBodyFirstNode.expression
if (!sequenceExpression.expressions) {
return
}
const attributes = sequenceExpression.expressions.map((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 }
})
// This replaces the markdown heading with a JSX element
markdownAST.children[index] = {
type: 'mdxJsxFlowElement',
name: `h${node.depth}`,
attributes,
children: [node.children[0]],
}
})
return markdownAST
}
const remarkCustomAttrs = () => parseAstTree
export default remarkCustomAttrs