From 918c319a658714bf39d8f31b70bd79bf01a80491 Mon Sep 17 00:00:00 2001 From: Petyo Ivanov Date: Tue, 28 Nov 2023 08:57:15 +0200 Subject: [PATCH] fix: traverse nested mdast for JSX registrations Fixes #203 --- src/plugins/jsx/LexicalJsxVisitor.ts | 14 ++++++++++++++ src/plugins/jsx/index.ts | 5 +++++ 2 files changed, 19 insertions(+) diff --git a/src/plugins/jsx/LexicalJsxVisitor.ts b/src/plugins/jsx/LexicalJsxVisitor.ts index e177db5a..206be35d 100644 --- a/src/plugins/jsx/LexicalJsxVisitor.ts +++ b/src/plugins/jsx/LexicalJsxVisitor.ts @@ -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 = { 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) } } diff --git a/src/plugins/jsx/index.ts b/src/plugins/jsx/index.ts index 9555c9eb..4a303257 100644 --- a/src/plugins/jsx/index.ts +++ b/src/plugins/jsx/index.ts @@ -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 @@ -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): MdastJsx['attributes'] { return Object.entries(attributes).map(([name, value]) => ({ type: 'mdxJsxAttribute',