2023-02-06 21:11:15 +00:00
|
|
|
import { RenderableTreeNode, Tag, renderers, NodeType } from '@markdoc/markdoc';
|
|
|
|
import { escape } from 'html-escaper';
|
|
|
|
|
|
|
|
// TODO: expose `AstroComponentFactory` type from core
|
|
|
|
type AstroComponentFactory = (props: Record<string, any>) => any & {
|
|
|
|
isAstroComponentFactory: true;
|
|
|
|
};
|
|
|
|
|
|
|
|
export type ComponentRenderer =
|
|
|
|
| AstroComponentFactory
|
|
|
|
| {
|
|
|
|
component: AstroComponentFactory;
|
|
|
|
props?(params: { attributes: Record<string, any>; getTreeNode(): Tag }): Record<string, any>;
|
|
|
|
};
|
|
|
|
|
|
|
|
export type AstroNode =
|
|
|
|
| string
|
|
|
|
| {
|
|
|
|
component: AstroComponentFactory;
|
|
|
|
props: Record<string, any>;
|
|
|
|
children: AstroNode[];
|
|
|
|
}
|
|
|
|
| {
|
|
|
|
tag: string;
|
|
|
|
attributes: Record<string, any>;
|
|
|
|
children: AstroNode[];
|
|
|
|
};
|
|
|
|
|
|
|
|
export function createAstroNode(
|
|
|
|
node: RenderableTreeNode,
|
|
|
|
components: Record<string, ComponentRenderer> = {}
|
|
|
|
): AstroNode {
|
|
|
|
if (typeof node === 'string' || typeof node === 'number') {
|
|
|
|
return escape(String(node));
|
|
|
|
} else if (node === null || typeof node !== 'object' || !Tag.isTag(node)) {
|
|
|
|
return '';
|
|
|
|
}
|
|
|
|
|
2023-02-08 14:53:35 +00:00
|
|
|
if (node.name in components) {
|
2023-02-06 21:11:15 +00:00
|
|
|
const componentRenderer = components[node.name];
|
|
|
|
const component =
|
2023-02-06 21:33:27 +00:00
|
|
|
'component' in componentRenderer ? componentRenderer.component : componentRenderer;
|
2023-02-06 21:11:15 +00:00
|
|
|
const props =
|
2023-02-08 14:53:35 +00:00
|
|
|
'props' in componentRenderer && typeof componentRenderer.props === 'function'
|
2023-02-06 21:11:15 +00:00
|
|
|
? componentRenderer.props({
|
|
|
|
attributes: node.attributes,
|
|
|
|
getTreeNode() {
|
|
|
|
return node;
|
|
|
|
},
|
|
|
|
})
|
|
|
|
: node.attributes;
|
|
|
|
|
|
|
|
const children = node.children.map((child) => createAstroNode(child, components));
|
|
|
|
|
|
|
|
return {
|
|
|
|
component,
|
|
|
|
props,
|
|
|
|
children,
|
|
|
|
};
|
|
|
|
} else {
|
|
|
|
return {
|
|
|
|
tag: node.name,
|
|
|
|
attributes: node.attributes,
|
|
|
|
children: node.children.map((child) => createAstroNode(child, components)),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|