Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions packages/comark-angular/src/components/markdown-node.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
ComponentRef,
ChangeDetectionStrategy,
ViewContainerRef,
ViewChild,
ElementRef,
Renderer2,
OnChanges,
Expand Down Expand Up @@ -106,7 +107,8 @@ function prepareNode(
selector: 'comark-markdown-node',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: '',
template: '<ng-container #container />',
host: { ngSkipHydration: 'true' },
})
export class MarkdownNode implements OnChanges {
/** The Comark AST node to render */
Expand All @@ -124,7 +126,8 @@ export class MarkdownNode implements OnChanges {
/** Change the tag or props of element nodes just before they render */
readonly transformNode = input<NodeTransform | readonly NodeTransform[]>()

private vcr = inject(ViewContainerRef)
@ViewChild('container', { read: ViewContainerRef, static: true })
private vcr!: ViewContainerRef
private renderer = inject(Renderer2)
private elementRef = inject(ElementRef)
private injector = inject(Injector)
Expand All @@ -137,8 +140,14 @@ export class MarkdownNode implements OnChanges {
this.vcr.clear()

const hostEl = this.elementRef.nativeElement as HTMLElement
while (hostEl.firstChild) {
hostEl.removeChild(hostEl.firstChild)
const anchor = this.vcr.element.nativeElement as Node
let child = hostEl.firstChild
while (child) {
const next = child.nextSibling
if (child !== anchor) {
hostEl.removeChild(child)
}
child = next
}

if (this.node() === undefined || this.node() === null) return
Expand Down Expand Up @@ -325,14 +334,6 @@ export class MarkdownNode implements OnChanges {
}

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()
}

Expand Down
137 changes: 137 additions & 0 deletions packages/comark-angular/test/ssr-hydration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import '@angular/compiler'
import { describe, expect, it } from 'vitest'
import { Component, input, provideZonelessChangeDetection } from '@angular/core'
import { TestBed } from '@angular/core/testing'
import { bootstrapApplication, provideClientHydration } from '@angular/platform-browser'
import { renderApplication } from '@angular/platform-server'
import { parseMarkdown, type MarkdownDocument as MarkdownDocumentType } from 'comark'
import { Markdown } from '../src/components/markdown.component.ts'
import { MarkdownDocument } from '../src/components/markdown-document.component.ts'
import { MarkdownNode } from '../src/components/markdown-node.component.ts'

@Component({
selector: 'markdown-code',
standalone: true,
template: `<div
class="code-block"
[attr.data-lang]="language()"
>
<ng-content />
</div>`,
})
class ProsePre {
readonly language = input<string>('')
readonly code = input<string>('')
}

@Component({
selector: 'custom-card',
standalone: true,
template: `<section class="card"><ng-content /></section>`,
})
class CustomCard {}

async function renderWithHydration(
template: string,
document: MarkdownDocumentType,
components: Record<string, any>
): Promise<string> {
class App {
document = document
components = components
}
Component({
selector: 'app-root',
standalone: true,
imports: [Markdown, MarkdownDocument, MarkdownNode],
template,
})(App)

return renderApplication(
(context) =>
bootstrapApplication(App, { providers: [provideZonelessChangeDetection(), provideClientHydration()] }, context),
{ document: '<!DOCTYPE html><html><head></head><body><app-root></app-root></body></html>' }
)
}

describe('MarkdownNode view container anchor', () => {
it('preserves the internal view container anchor across re-renders', async () => {
await TestBed.configureTestingModule({
imports: [MarkdownNode],
}).compileComponents()

const fixture = TestBed.createComponent(MarkdownNode)
const hostEl = fixture.nativeElement as HTMLElement

fixture.componentRef.setInput('components', { ProsePre })
fixture.componentRef.setInput('node', ['p', {}, 'hello'])
fixture.detectChanges()
expect(hostEl.querySelector('p')?.textContent).toBe('hello')

fixture.componentRef.setInput('node', ['pre', { language: 'ts' }, ['code', {}, 'const a = 1']])
fixture.detectChanges()
expect(hostEl.querySelector('p')).toBeNull()
expect(hostEl.querySelector('markdown-code')?.textContent).toContain('const a = 1')

fixture.componentRef.setInput('node', 'plain text')
fixture.detectChanges()
expect(hostEl.querySelector('markdown-code')).toBeNull()
expect(hostEl.textContent).toBe('plain text')

fixture.componentRef.setInput('node', ['pre', { language: 'js' }, ['code', {}, 'const b = 2']])
fixture.detectChanges()
expect(hostEl.querySelector('markdown-code')?.textContent).toContain('const b = 2')
})
})

describe('SSR hydration serialization', () => {
it('renders a fenced code block through a custom ProsePre component with hydration enabled', async () => {
const doc = await parseMarkdown('```ts\nconst x = 1\n```')
const html = await renderWithHydration(
'<comark-markdown-document [value]="document" [components]="components" />',
doc,
{ ProsePre }
)

expect(html).toContain('ngskiphydration="true"')
expect(html).toContain('<markdown-code')
expect(html).toContain('class="code-block"')
expect(html).toContain('data-lang="ts"')
expect(html).toContain('const x = 1')
})

it('renders a custom ProsePre component via comark-markdown with hydration enabled', async () => {
const doc = await parseMarkdown('```ts\nconst y = 2\n```')
const html = await renderWithHydration('<comark-markdown [value]="document" [components]="components" />', doc, {
ProsePre,
})

expect(html).toContain('<markdown-code')
expect(html).toContain('const y = 2')
})

it('renders nested custom components projecting content with hydration enabled', async () => {
const doc = await parseMarkdown('::custom-card\n```ts\nconst z = 3\n```\n::')
const html = await renderWithHydration(
'<comark-markdown-document [value]="document" [components]="components" />',
doc,
{ CustomCard, ProsePre }
)

expect(html).toContain('<custom-card')
expect(html).toContain('<markdown-code')
expect(html).toContain('const z = 3')
})

it('renders standalone comark-markdown-node with a custom component and hydration enabled', async () => {
const doc = await parseMarkdown('```ts\nconst solo = 4\n```')
const html = await renderWithHydration(
'<comark-markdown-node [node]="document.nodes[0]" [components]="components" />',
doc,
{ ProsePre }
)

expect(html).toContain('<markdown-code')
expect(html).toContain('const solo = 4')
})
})
2 changes: 1 addition & 1 deletion test/bundle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ describe('package bundle size', { timeout: 60_000 }, () => {

expect(report).toMatchInlineSnapshot(`
{
"@comark/angular": "70.5k (63 files)",
"@comark/angular": "70.8k (63 files)",
"@comark/ansi": "42.1k (109 files)",
"@comark/html": "17.7k (69 files)",
"@comark/nuxt": "11.0k (69 files)",
Expand Down
Loading