Skip to content

Commit

Permalink
fix: traverse nested mdast for JSX registrations
Browse files Browse the repository at this point in the history
Fixes #203
  • Loading branch information
petyosi committed Nov 28, 2023
1 parent 9d33280 commit 918c319
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/plugins/jsx/LexicalJsxVisitor.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
import { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx'
import { $isLexicalJsxNode, LexicalJsxNode } from './LexicalJsxNode'
import { LexicalExportVisitor } from '../../exportMarkdownFromLexical'
import * as Mdast from 'mdast'
import { isMdastJsxNode } from '.'

export const LexicalJsxVisitor: LexicalExportVisitor<LexicalJsxNode, MdxJsxFlowElement | MdxJsxTextElement> = {
testLexicalNode: $isLexicalJsxNode,
visitLexicalNode({ actions, mdastParent, lexicalNode }) {
function traverseNestedJsxNodes(node: Mdast.Content | Mdast.Parent) {
if ('children' in node && node.children instanceof Array) {
node.children.forEach((child: Mdast.Content | Mdast.Parent) => {
if (isMdastJsxNode(child)) {
actions.registerReferredComponent(child.name!)
}
traverseNestedJsxNodes(child)
})
}
}

const mdastNode = lexicalNode.getMdastNode()
actions.registerReferredComponent(mdastNode.name!)
traverseNestedJsxNodes(mdastNode)
actions.appendToParent(mdastParent, mdastNode)
}
}
5 changes: 5 additions & 0 deletions src/plugins/jsx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { $createLexicalJsxNode, LexicalJsxNode } from './LexicalJsxNode'
import { LexicalJsxVisitor } from './LexicalJsxVisitor'
import { MdastMdxJsEsmVisitor } from './MdastMdxJsEsmVisitor'
import { MdastMdxJsxElementVisitor } from './MdastMdxJsxElementVisitor'
import * as Mdast from 'mdast'

/**
* @internal
Expand Down Expand Up @@ -93,6 +94,10 @@ type JsxFlowPayload = {

type InsertJsxPayload = JsxTextPayload | JsxFlowPayload

export function isMdastJsxNode(node: Mdast.Content | Mdast.Parent | Mdast.Root): node is MdastJsx {
return node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement'
}

function toMdastJsxAttributes(attributes: Record<string, string>): MdastJsx['attributes'] {
return Object.entries(attributes).map(([name, value]) => ({
type: 'mdxJsxAttribute',
Expand Down

0 comments on commit 918c319

Please sign in to comment.