// Client-side lazy embed hydration tests (Phase 38, D-08). // Runs directly under `node --test` using lightweight DOM, IntersectionObserver, // and matchMedia doubles (zero browser/DOM test-runner dependency). import { afterEach, test } from 'node:test' import assert from 'node:assert/strict' import type { AppContext } from 'vue' import { createJournalEmbedRegistry, resetJournalEmbedRegistry } from '../app/utils/embedRegistry.ts' // --------------------------------------------------------------------------- // Minimal DOM double sufficient for Vue 3 `render(vnode, host)` and // `useJournalEmbedHydration` / `hydrateEmbedFigure`. // --------------------------------------------------------------------------- class FakeNode { nodeType: number parentNode: FakeElement | null = null childNodes: FakeNode[] = [] ownerDocument: FakeDocument constructor(nodeType: number, ownerDocument: FakeDocument) { this.nodeType = nodeType this.ownerDocument = ownerDocument } get firstChild(): FakeNode | null { return this.childNodes[0] ?? null } get nextSibling(): FakeNode | null { if (!this.parentNode) return null const idx = this.parentNode.childNodes.indexOf(this) return idx >= 0 ? (this.parentNode.childNodes[idx + 1] ?? null) : null } } class FakeText extends FakeNode { nodeValue: string constructor(text: string, ownerDocument: FakeDocument) { super(3, ownerDocument) this.nodeValue = String(text) } get textContent(): string { return this.nodeValue } set textContent(v: string) { this.nodeValue = String(v ?? '') } } class FakeComment extends FakeNode { nodeValue: string constructor(text: string, ownerDocument: FakeDocument) { super(8, ownerDocument) this.nodeValue = String(text) } } class FakeClassList { private readonly set = new Set() add(...tokens: string[]): void { for (const t of tokens) if (t) this.set.add(t) } remove(...tokens: string[]): void { for (const t of tokens) this.set.delete(t) } contains(token: string): boolean { return this.set.has(token) } toString(): string { return [...this.set].join(' ') } } class FakeElement extends FakeNode { readonly tagName: string readonly attrs = new Map() readonly classList = new FakeClassList() readonly style: Record = {} measuredHeight = 0 private _rawInnerHtml = '' constructor(tagName: string, ownerDocument: FakeDocument) { super(1, ownerDocument) this.tagName = tagName.toUpperCase() } get className(): string { return this.classList.toString() } set className(val: string) { for (const t of val.split(/\s+/).filter(Boolean)) this.classList.add(t) } get innerHTML(): string { if (this.childNodes.length === 0) return this._rawInnerHtml return this.childNodes .map((c) => { if (c instanceof FakeText) return c.nodeValue if (c instanceof FakeComment) return `` if (c instanceof FakeElement) { const tag = c.tagName.toLowerCase() const attrStr = [...c.attrs.entries()].map(([k, v]) => ` ${k}="${v}"`).join('') const cls = c.className ? ` class="${c.className}"` : '' return `<${tag}${cls}${attrStr}>${c.innerHTML}` } return '' }) .join('') } set innerHTML(val: string) { this.childNodes = [] this._rawInnerHtml = val } get textContent(): string { if (this.childNodes.length === 0) return this._rawInnerHtml return this.childNodes.map((c) => (c instanceof FakeText || c instanceof FakeElement ? c.textContent : '')).join('') } set textContent(val: string) { this.childNodes = [] this._rawInnerHtml = '' if (val !== '') this.appendChild(new FakeText(String(val), this.ownerDocument)) } getAttribute(name: string): string | null { return this.attrs.get(name) ?? null } setAttribute(name: string, value: string): void { if (name === 'class') this.className = value else this.attrs.set(name, String(value)) } removeAttribute(name: string): void { this.attrs.delete(name) } getBoundingClientRect(): { height: number; width: number } { return { height: this.measuredHeight, width: 800 } } appendChild(child: FakeNode): FakeNode { if (child.parentNode) child.parentNode.removeChild(child) child.parentNode = this this.childNodes.push(child) return child } insertBefore(child: FakeNode, anchor: FakeNode | null): FakeNode { if (child.parentNode) child.parentNode.removeChild(child) child.parentNode = this if (!anchor) { this.childNodes.push(child) return child } const idx = this.childNodes.indexOf(anchor) if (idx < 0) this.childNodes.push(child) else this.childNodes.splice(idx, 0, child) return child } removeChild(child: FakeNode): FakeNode { const idx = this.childNodes.indexOf(child) if (idx >= 0) { this.childNodes.splice(idx, 1) child.parentNode = null } return child } replaceChildren(...nodes: FakeNode[]): void { for (const c of this.childNodes) c.parentNode = null this.childNodes = [] this._rawInnerHtml = '' for (const n of nodes) this.appendChild(n) } querySelectorAll(selector: string): FakeElement[] { if (selector !== 'figure[data-embed][data-id]') return [] const out: FakeElement[] = [] const walk = (el: FakeElement) => { for (const c of el.childNodes) { if (c instanceof FakeElement) { if (c.tagName === 'FIGURE' && c.attrs.has('data-embed') && c.attrs.has('data-id')) out.push(c) walk(c) } } } walk(this) return out } } class FakeDocument { createElement(tag: string): FakeElement { return new FakeElement(tag, this) } createElementNS(_ns: string, tag: string): FakeElement { return new FakeElement(tag, this) } createTextNode(text: string): FakeText { return new FakeText(text, this) } createComment(text: string): FakeComment { return new FakeComment(text, this) } } function makeFigure( doc: FakeDocument, attrs: Record, fallbackHtml: string, measuredHeight = 360, ): FakeElement { const fig = doc.createElement('figure') for (const [k, v] of Object.entries(attrs)) fig.setAttribute(k, v) fig.innerHTML = fallbackHtml fig.measuredHeight = measuredHeight return fig } const origWindow = globalThis.window const origIO = globalThis.IntersectionObserver // Install FakeDocument BEFORE importing `vue` so `@vue/runtime-dom` binds its // module-level `doc` reference to our lightweight DOM double. const sharedDoc = new FakeDocument() ;(globalThis as Record).document = sharedDoc const { createApp, createVNode, defineComponent, h, inject, onUnmounted, ref, render } = await import('vue') const { hydrateEmbedFigure, useJournalEmbedHydration } = await import('../app/composables/useJournalEmbedHydration.ts') afterEach(() => { resetJournalEmbedRegistry() if (origWindow === undefined) delete (globalThis as Record).window else (globalThis as Record).window = origWindow if (origIO === undefined) delete (globalThis as Record).IntersectionObserver else (globalThis as Record).IntersectionObserver = origIO }) test('hydrateEmbedFigure mounts a plain DOM provider, reserves CLS minHeight, passes reducedMotion, and runs cleanup', async () => { const doc = new FakeDocument() const fallback = 'Chart
Fig 1
' const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'chart-1', 'data-aspect': '16/9' }, fallback, 342.4) let cleanedUp = false let receivedCtx: Record | null = null let attachedDuringMount = false const registry = createJournalEmbedRegistry({ viz: { idPattern: /^[a-z0-9-]+$/, mount(el, ctx) { attachedDuringMount = (el as unknown as FakeElement).parentNode === fig receivedCtx = { id: ctx.id, provider: ctx.provider, aspect: ctx.aspect, fallbackHtml: ctx.fallbackHtml, isReducedMotion: ctx.isReducedMotion, reducedMotionValue: ctx.reducedMotion.value, } el.textContent = `mounted:${ctx.id}` return () => { cleanedUp = true } }, }, }) const reducedMotion = ref(true) const cleanup = await hydrateEmbedFigure(fig as unknown as HTMLElement, registry.get('viz')!, { id: 'chart-1', providerName: 'viz', reducedMotion, }) assert.ok(cleanup, 'expected cleanup function') assert.equal(attachedDuringMount, true, 'host element must be attached to figure before mount() runs') // CLS height reservation from measured fallback box (Math.ceil(342.4) = 343px). assert.equal(fig.style.minHeight, '343px') assert.equal(fig.classList.contains('journal-embed--hydrated'), true) assert.deepEqual(receivedCtx, { id: 'chart-1', provider: 'viz', aspect: '16/9', fallbackHtml: fallback, isReducedMotion: true, reducedMotionValue: true, }) assert.match(fig.innerHTML, /class="journal-embed__stage"/) assert.match(fig.innerHTML, /mounted:chart-1/) cleanup() assert.equal(cleanedUp, true) assert.equal(fig.classList.contains('journal-embed--hydrated'), false) }) test('hydrateEmbedFigure mounts a Vue async component inheriting appContext and unmounts cleanly', async () => { const doc = new FakeDocument() ;(globalThis as Record).document = doc const fallback = 'Chart' const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'vue-chart', 'data-height': '420px' }, fallback, 420) let unmounted = false const injectedKey = Symbol('app-i18n') const FakeChart = defineComponent({ props: { id: { type: String, required: true }, provider: { type: String, required: true }, height: { type: String, default: undefined }, fallbackHtml: { type: String, default: '' }, reducedMotion: { type: Object, required: true }, }, setup(props) { const injected = inject(injectedKey, 'missing') onUnmounted(() => { unmounted = true }) return () => h( 'div', { class: 'vue-chart-root' }, `${props.provider}:${props.id}:${props.height}:${injected}:rm=${(props.reducedMotion as { value: boolean }).value}`, ) }, }) const registry = createJournalEmbedRegistry({ viz: { idPattern: /^[a-z0-9-]+$/, component: async () => ({ default: FakeChart }), }, }) const fakeApp = createApp({ render: () => null }) fakeApp.provide(injectedKey, 'from-nuxt-app') const appContext = fakeApp._context as AppContext const reducedMotion = ref(false) const cleanup = await hydrateEmbedFigure(fig as unknown as HTMLElement, registry.get('viz')!, { id: 'vue-chart', providerName: 'viz', reducedMotion, appContext, onError: (err) => { throw err }, }) assert.ok(cleanup) assert.equal(fig.classList.contains('journal-embed--hydrated'), true) assert.match(fig.innerHTML, /viz:vue-chart:420px:from-nuxt-app:rm=false/) // Reactive reducedMotion update propagates into the mounted Vue component. reducedMotion.value = true await Promise.resolve() assert.match(fig.innerHTML, /rm=true/) cleanup() assert.equal(unmounted, true) assert.equal(fig.classList.contains('journal-embed--hydrated'), false) }) test('hydrateEmbedFigure catches rejected import or mount throw and leaves SSR fallback DOM intact', async () => { const doc = new FakeDocument() const fallback = 'Fallback
Still here
' // 1. Rejected dynamic component import const fig1 = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'broken-import' }, fallback, 300) const reg1 = createJournalEmbedRegistry({ viz: { idPattern: /^[a-z0-9-]+$/, component: async () => { throw new Error('chunk load failed') }, }, }) const errors: unknown[] = [] const cleanup1 = await hydrateEmbedFigure(fig1 as unknown as HTMLElement, reg1.get('viz')!, { id: 'broken-import', providerName: 'viz', reducedMotion: ref(false), onError: (err) => errors.push(err), }) assert.equal(cleanup1, null) assert.equal(errors.length, 1) assert.equal(fig1.innerHTML, fallback) assert.equal(fig1.classList.contains('journal-embed--hydrated'), false) // 2. Thrown error inside plain DOM mount const fig2 = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'broken-mount' }, fallback, 300) const reg2 = createJournalEmbedRegistry({ viz: { idPattern: /^[a-z0-9-]+$/, mount() { throw new Error('mount exploded') }, }, }) const cleanup2 = await hydrateEmbedFigure(fig2 as unknown as HTMLElement, reg2.get('viz')!, { id: 'broken-mount', providerName: 'viz', reducedMotion: ref(false), onError: (err) => errors.push(err), }) assert.equal(cleanup2, null) assert.equal(errors.length, 2) assert.equal(fig2.innerHTML, fallback) assert.equal(fig2.classList.contains('journal-embed--hydrated'), false) }) test('useJournalEmbedHydration defers hydration until IntersectionObserver fires and reacts to matchMedia changes', async () => { const doc = new FakeDocument() ;(globalThis as Record).document = doc const motionListeners: Array<(e: { matches: boolean }) => void> = [] const fakeWindow = { matchMedia: (query: string) => ({ media: query, matches: false, addEventListener: (_type: string, fn: (e: { matches: boolean }) => void) => motionListeners.push(fn), removeEventListener: (_type: string, fn: (e: { matches: boolean }) => void) => { const idx = motionListeners.indexOf(fn) if (idx >= 0) motionListeners.splice(idx, 1) }, }), } ;(globalThis as Record).window = fakeWindow const observed: Array<{ target: unknown options: { rootMargin?: string } | undefined trigger: (isIntersecting: boolean) => void disconnected: boolean }> = [] class FakeIntersectionObserver { private readonly cb: (entries: Array<{ isIntersecting: boolean }>, obs: FakeIntersectionObserver) => void private readonly opts: { rootMargin?: string } | undefined private record: (typeof observed)[number] | null = null constructor(cb: (entries: Array<{ isIntersecting: boolean }>, obs: FakeIntersectionObserver) => void, opts?: { rootMargin?: string }) { this.cb = cb this.opts = opts } observe(target: unknown): void { this.record = { target, options: this.opts, disconnected: false, trigger: (isIntersecting: boolean) => this.cb([{ isIntersecting }], this), } observed.push(this.record) } disconnect(): void { if (this.record) this.record.disconnected = true } } ;(globalThis as Record).IntersectionObserver = FakeIntersectionObserver const container = doc.createElement('div') const fallback = 'Chart' const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'lazy-chart' }, fallback, 320) container.appendChild(fig) let mountCalls = 0 let unmountCalls = 0 let seenMotionRef: Readonly<{ value: boolean }> | null = null const registry = createJournalEmbedRegistry({ viz: { idPattern: /^[a-z0-9-]+$/, rootMargin: '250px', mount(el, ctx) { mountCalls += 1 seenMotionRef = ctx.reducedMotion el.textContent = `hydrated:${ctx.id}` return () => { unmountCalls += 1 } }, }, }) // Mount a minimal host Vue component using `useJournalEmbedHydration`. const html = ref('
') const Host = defineComponent({ setup() { const elRef = ref(container as unknown as HTMLElement) useJournalEmbedHydration(elRef, html, { registry }) return () => h('div') }, }) const appRoot = doc.createElement('div') render(createVNode(Host), appRoot as unknown as Element) // Before intersection: observer registered with provider rootMargin, not yet hydrated. assert.equal(observed.length, 1) assert.equal(observed[0]!.options?.rootMargin, '250px') assert.equal(mountCalls, 0) assert.equal(fig.innerHTML, fallback) // Non-intersecting event does not trigger hydration. observed[0]!.trigger(false) await Promise.resolve() assert.equal(mountCalls, 0) // Intersecting event disconnects observer and hydrates the figure. observed[0]!.trigger(true) await new Promise((r) => setTimeout(r, 0)) assert.equal(observed[0]!.disconnected, true) assert.equal(mountCalls, 1) assert.equal(fig.classList.contains('journal-embed--hydrated'), true) assert.equal(seenMotionRef!.value, false) // matchMedia change updates the reactive reducedMotion ref. assert.equal(motionListeners.length, 1) motionListeners[0]!({ matches: true }) assert.equal(seenMotionRef!.value, true) // Unmounting the host component runs embed cleanup and removes matchMedia listener. render(null, appRoot as unknown as Element) assert.equal(unmountCalls, 1) assert.equal(motionListeners.length, 0) })