|
| 1 | +import { RenderableTreeNode, Tag, renderers, NodeType } from '@markdoc/markdoc'; |
| 2 | +import { escape } from 'html-escaper'; |
| 3 | + |
| 4 | +// TODO: expose `AstroComponentFactory` type from core |
| 5 | +type AstroComponentFactory = (props: Record<string, any>) => any & { |
| 6 | + isAstroComponentFactory: true; |
| 7 | +}; |
| 8 | + |
| 9 | +export type ComponentRenderer = |
| 10 | + | AstroComponentFactory |
| 11 | + | { |
| 12 | + component: AstroComponentFactory; |
| 13 | + props?(params: { attributes: Record<string, any>; getTreeNode(): Tag }): Record<string, any>; |
| 14 | + }; |
| 15 | + |
| 16 | +export type AstroNode = |
| 17 | + | string |
| 18 | + | { |
| 19 | + component: AstroComponentFactory; |
| 20 | + props: Record<string, any>; |
| 21 | + children: AstroNode[]; |
| 22 | + } |
| 23 | + | { |
| 24 | + tag: string; |
| 25 | + attributes: Record<string, any>; |
| 26 | + children: AstroNode[]; |
| 27 | + }; |
| 28 | + |
| 29 | +export function createAstroNode( |
| 30 | + node: RenderableTreeNode, |
| 31 | + components: Record<string, ComponentRenderer> = {} |
| 32 | +): AstroNode { |
| 33 | + if (typeof node === 'string' || typeof node === 'number') { |
| 34 | + return escape(String(node)); |
| 35 | + } else if (node === null || typeof node !== 'object' || !Tag.isTag(node)) { |
| 36 | + return ''; |
| 37 | + } |
| 38 | + |
| 39 | + if (Object.hasOwn(components, node.name)) { |
| 40 | + const componentRenderer = components[node.name]; |
| 41 | + const component = |
| 42 | + 'Component' in componentRenderer ? componentRenderer.component : componentRenderer; |
| 43 | + const props = |
| 44 | + 'props' in componentRenderer |
| 45 | + ? componentRenderer.props({ |
| 46 | + attributes: node.attributes, |
| 47 | + getTreeNode() { |
| 48 | + return node; |
| 49 | + }, |
| 50 | + }) |
| 51 | + : node.attributes; |
| 52 | + |
| 53 | + const children = node.children.map((child) => createAstroNode(child, components)); |
| 54 | + |
| 55 | + return { |
| 56 | + component, |
| 57 | + props, |
| 58 | + children, |
| 59 | + }; |
| 60 | + } else { |
| 61 | + return { |
| 62 | + tag: node.name, |
| 63 | + attributes: node.attributes, |
| 64 | + children: node.children.map((child) => createAstroNode(child, components)), |
| 65 | + }; |
| 66 | + } |
| 67 | +} |
0 commit comments