import { Component, ComponentRef, ChangeDetectionStrategy, ViewContainerRef, ElementRef, Renderer2, OnChanges, SimpleChanges, Type, Injector, EnvironmentInjector, createComponent, reflectComponentType, inject, input, } from '@angular/core' import type { ElementNode, Node as MarkdownAstNode, NodeRenderData, NodeTransform } from 'comark' import { resolveIfWrapper, selectIfBranch, shouldRenderIf, type IfProps } from 'comark/plugins/binding' import { applyNodeTransforms, isHtmlVoidElement, pascalCase, resolveAttributes, toNativeAttributes } from 'comark/utils' interface StructuralComponent extends Type { ɵcomarkIf?: boolean } /** * Helper to get tag from a Node */ function getTag(node: MarkdownAstNode): string | null { if (Array.isArray(node) && node.length >= 1) { return node[0] as string } return null } /** * Helper to get props from a Node */ function getProps(node: MarkdownAstNode): Record { if (Array.isArray(node) && node.length >= 2) { return (node[1] as Record) || {} } return {} } /** * Helper to get children from a Node */ function getChildren(node: MarkdownAstNode): MarkdownAstNode[] { if (Array.isArray(node) && node.length > 2) { return node.slice(2) as MarkdownAstNode[] } return [] } /** * Resolve a custom component from the components map. */ function resolveComponent(tag: string, components: Record>): Type | undefined { const pascalTag = pascalCase(tag) const proseTag = `Prose${pascalTag}` return components[proseTag] || components[pascalTag] || components[tag] } interface PreparedNode { tag: string props: Record customComponent?: Type childrenRenderData: NodeRenderData } /** * Resolve an element node's bindings, run `transformNode`, and pick the * component to render it with. */ function prepareNode( node: ElementNode, components: Record>, renderData: NodeRenderData, parent: MarkdownAstNode | undefined, transformNode: NodeTransform | readonly NodeTransform[] | undefined ): PreparedNode { const nodeProps = getProps(node) const ownProps = resolveAttributes(nodeProps, renderData, { parseJson: true }) const transformed = applyNodeTransforms(transformNode, node, ownProps, renderData, parent as ElementNode | undefined) const tag = transformed ? transformed.tag : node[0] const props = transformed ? transformed.props : ownProps const as = transformed ? props.as : nodeProps.as let customComponent: Type | undefined if ((parent as ElementNode | undefined)?.[0] !== 'pre') { if (typeof as === 'string' && as) { customComponent = resolveComponent(as, components) } if (!customComponent) { customComponent = resolveComponent(tag, components) } } // Only shadow the parent scope when the element has its own attributes. // The check uses the raw attributes: resolving can omit all of them. Props // a transform returned count as the element's own. let hasOwnAttrs = props !== ownProps for (const key in nodeProps) { if (key !== '$') { hasOwnAttrs = true break } } const childrenRenderData: NodeRenderData = hasOwnAttrs ? { ...renderData, props } : renderData return { tag, props, customComponent, childrenRenderData } } /** * MarkdownNode - recursive component that renders a single Comark AST node. * * For text nodes, it inserts the text directly. * For element nodes, it creates a native DOM element or instantiates * a custom Angular component via ViewContainerRef. */ @Component({ selector: 'comark-markdown-node', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: '', }) export class MarkdownNode implements OnChanges { /** The Comark AST node to render */ readonly node = input.required() /** Custom component mappings */ readonly components = input>>({}) /** Render data for :binding resolution */ readonly renderData = input({ frontmatter: {}, meta: {}, data: {}, props: {} }) /** Parent node (for context like `pre` tag detection) */ readonly parent = input() /** Change the tag or props of element nodes just before they render */ readonly transformNode = input() private vcr = inject(ViewContainerRef) private renderer = inject(Renderer2) private elementRef = inject(ElementRef) private injector = inject(Injector) ngOnChanges(_changes: SimpleChanges): void { this.render() } private render(): void { this.vcr.clear() const hostEl = this.elementRef.nativeElement as HTMLElement // Clear previous content from the host while (hostEl.firstChild) { hostEl.removeChild(hostEl.firstChild) } if (this.node() === undefined || this.node() === null) return // Text node if (typeof this.node() === 'string') { const text = this.renderer.createText(this.node() as string) this.renderer.appendChild(hostEl, text) return } // Element node const node = this.node() if (Array.isArray(node)) { if (!getTag(node)) return const children = getChildren(node) const { tag, props: resolved, customComponent, childrenRenderData, } = prepareNode(node as ElementNode, this.components(), this.renderData(), this.parent(), this.transformNode()) if ((customComponent as StructuralComponent | undefined)?.ɵcomarkIf) { this.renderIf(resolved, children, childrenRenderData) } else if (customComponent) { this.renderCustomComponent(customComponent, resolved, children, childrenRenderData) } else { this.renderNativeElement(tag, resolved, children, childrenRenderData) } } } /** Apply resolved attributes to a DOM element. */ private applyAttributes(el: HTMLElement, attrs: Record): void { for (const key in attrs) { const value = attrs[key] if (key === 'as' || key === 'innerHTML' || key === 'dangerouslySetInnerHTML') { continue } else if (key === 'className' || key === 'class') { this.renderer.setAttribute(el, 'class', String(value)) } else if (key === 'style' && typeof value === 'string') { this.renderer.setAttribute(el, 'style', value) } else if (key === 'tabindex') { this.renderer.setAttribute(el, 'tabindex', String(value)) } else if (typeof value === 'boolean') { if (value) this.renderer.setAttribute(el, key, '') } else if (value != null) { this.renderer.setAttribute(el, key, String(value)) } } } /** Create a native DOM element with attributes and children, append to parent. */ private renderNativeEl( parentEl: HTMLElement, tag: string, attrs: Record, children: MarkdownAstNode[], childrenRenderData: NodeRenderData, node?: MarkdownAstNode ): void { const el = this.renderer.createElement(tag) this.applyAttributes(el, node ? toNativeAttributes(tag, node, attrs) : attrs) // `innerHTML` from document attributes is never applied — resolveAttributes // drops DOM sink props, and raw HTML has its own explicit parse path. if (!isHtmlVoidElement(tag)) { this.renderChildren(el, children, childrenRenderData) } this.renderer.appendChild(parentEl, el) } private renderNativeElement( tag: string, attrs: Record, children: MarkdownAstNode[], childrenRenderData: NodeRenderData ): void { this.renderNativeEl( this.elementRef.nativeElement as HTMLElement, tag, attrs, children, childrenRenderData, this.node() ) } /** Evaluate an `::if` before rendering any of its descendants. */ private renderIf(props: IfProps, children: MarkdownAstNode[], childrenRenderData: NodeRenderData): void { const branch = selectIfBranch(children, shouldRenderIf(props)) if (!branch) return const hostEl = this.elementRef.nativeElement as HTMLElement const wrapper = resolveIfWrapper(props.as) if (wrapper) { this.renderNativeEl(hostEl, wrapper, {}, branch, childrenRenderData) } else { this.renderChildren(hostEl, branch, childrenRenderData) } } private renderCustomComponent( componentType: Type, attrs: Record, children: MarkdownAstNode[], childrenRenderData: NodeRenderData ): void { // Separate slots from regular children const slots: Record = {} const regularChildren: MarkdownAstNode[] = [] for (const child of children) { if (child === undefined || child === null) continue const childTag = getTag(child) const childProps = getProps(child) if (childTag === 'template' && childProps) { let slotName: string | undefined if (childProps.name) { slotName = childProps.name } else { for (const pk in childProps) { if (pk.startsWith('v-slot:') || pk.startsWith('#')) { slotName = pk.startsWith('#') ? pk.substring(1) : pk.substring(7) break } } } if (slotName) { slots[slotName] = getChildren(child) continue } } regularChildren.push(child) } // Pre-render children into a temporary container so we can pass them as projectableNodes for Angular's content projection const tempContainer = this.renderer.createElement('div') // Render regular children if (regularChildren.length > 0) { this.renderChildren(tempContainer, regularChildren, childrenRenderData) } // Render named slot "default" children too if (slots['default']) { this.renderChildren(tempContainer, slots['default'], childrenRenderData) } // Collect all rendered child nodes for the default slot const defaultSlotNodes: Node[] = Array.from(tempContainer.childNodes) // Build projectableNodes array - index 0 is the default const projectableNodes: Node[][] = [defaultSlotNodes] // Create the Angular component with projected content const componentRef = createComponent(componentType, { environmentInjector: this.injector.get(EnvironmentInjector), elementInjector: this.injector, projectableNodes, }) // Set inputs const mirror = reflectComponentType(componentType) const inputNames = new Set(mirror?.inputs.map((i) => i.propName) || []) for (const key in attrs) { if (key === 'as') continue if (inputNames.has(key)) { componentRef.setInput(key, attrs[key]) } } // Pass __node if the component accepts it if (inputNames.has('__node')) { componentRef.setInput('__node', this.node()) } // Render non-default named slots into the component's host element for (const slotName in slots) { if (slotName === 'default') continue const slotEl = this.renderer.createElement('div') this.renderer.setAttribute(slotEl, 'slot', slotName) this.renderer.setStyle(slotEl, 'display', 'contents') this.renderChildren(slotEl, slots[slotName], childrenRenderData) this.renderer.appendChild(componentRef.location.nativeElement, slotEl) } // Attach to DOM and detect changes this.vcr.insert(componentRef.hostView) // The container's anchor stays where this node was first attached, so when this node // was moved into a parent element, place the component right after this node's host. const hostEl = this.elementRef.nativeElement as HTMLElement const hostParent = this.renderer.parentNode(hostEl) if (hostParent) { this.renderer.insertBefore(hostParent, componentRef.location.nativeElement, this.renderer.nextSibling(hostEl)) } componentRef.changeDetectorRef.detectChanges() } /** * Render an array of Node children into a parent DOM element. * Each child gets its own `comark-node` component created dynamically. */ private renderChildren(parentEl: HTMLElement, children: MarkdownAstNode[], renderData: NodeRenderData): void { for (const child of children) { if (child === undefined || child === null) continue // For text nodes, insert directly if (typeof child === 'string') { const text = this.renderer.createText(child) this.renderer.appendChild(parentEl, text) continue } // For element nodes, recursively create MarkdownNode if (Array.isArray(child)) { const childTag = getTag(child) if (!childTag) continue const grandChildren = getChildren(child) const prepared = prepareNode( child as ElementNode, this.components(), renderData, this.node(), this.transformNode() ) if (prepared.customComponent) { let componentRef: ComponentRef | undefined try { componentRef = this.vcr.createComponent(MarkdownNode) componentRef.setInput('node', child) componentRef.setInput('components', this.components()) componentRef.setInput('renderData', renderData) componentRef.setInput('parent', this.node()) componentRef.setInput('transformNode', this.transformNode()) // Move the component's host element into the parent before change detection, // so the custom component it inserts lands next to it inside `parentEl` const nativeEl = componentRef.location.nativeElement as HTMLElement nativeEl.style.display = 'contents' this.renderer.appendChild(parentEl, nativeEl) componentRef.changeDetectorRef.detectChanges() } catch (error) { componentRef?.destroy() console.error(`Failed to render custom component "${childTag}"`, error) } } else { this.renderNativeEl(parentEl, prepared.tag, prepared.props, grandChildren, prepared.childrenRenderData, child) } } } } }