Files
vue-journal-layer/app/composables/useJournalEmbedHydration.ts

307 lines
9.8 KiB
TypeScript

// Client-side progressive-enhancement hydration runtime for Journal embeds.
//
// Observes validated `<figure data-embed="..." data-id="...">` elements inside
// a rendered HTML container via `IntersectionObserver`, reserves layout height
// before swapping (zero CLS), tracks `prefers-reduced-motion`, supports both
// Vue async components (inheriting `nuxtApp.vueApp._context`) and plain DOM
// `mount(el, ctx)` callbacks, cleans up on unmount or HTML changes, and catches
// errors leaving the SSR static fallback DOM untouched.
//
// Strictly `script-src 'self'` CSP compliant: zero `eval`, `new Function`, or
// inline `<script>` injection.
import {
createVNode,
getCurrentInstance,
onBeforeUnmount,
onMounted,
ref,
render,
watch,
type AppContext,
type Component,
type Ref,
type WatchSource,
} from 'vue'
import {
EMBED_ASPECT,
EMBED_HEIGHT,
getJournalEmbedRegistry,
type JournalEmbedMountContext,
type JournalEmbedRegistry,
type NormalizedJournalEmbedProvider,
} from '../utils/embedRegistry.ts'
/** Options for hydrating a single `<figure data-embed>` element. */
export interface HydrateEmbedFigureOptions {
id: string
providerName: string
reducedMotion: Readonly<{ value: boolean }>
appContext?: AppContext | null
signal?: { aborted: boolean }
onError?: (err: unknown, figure: HTMLElement) => void
}
/** Options for `useJournalEmbedHydration`. */
export interface JournalEmbedHydrationOptions {
registry?: JournalEmbedRegistry
rootMargin?: string
}
function replaceChildrenSafe(parent: HTMLElement, ...children: Node[]): void {
if (typeof parent.replaceChildren === 'function') {
parent.replaceChildren(...children)
return
}
while (parent.firstChild) parent.removeChild(parent.firstChild)
for (const child of children) parent.appendChild(child)
}
function restoreFallback(figure: HTMLElement, savedChildren: Node[], fallbackHtml: string): void {
if (savedChildren.length > 0) {
replaceChildrenSafe(figure, ...savedChildren)
} else {
figure.innerHTML = fallbackHtml
}
}
function warnDev(providerName: string, id: string, err: unknown): void {
const isDev = typeof import.meta !== 'undefined' && (import.meta as { dev?: boolean }).dev === true
if (isDev && typeof console !== 'undefined' && typeof console.warn === 'function') {
console.warn(`[vue-journal-layer] Failed to hydrate embed "${providerName}:${id}":`, err)
}
}
/**
* Hydrates a single validated `<figure data-embed>` element using a registered
* provider (`component` or `mount`). Returns a cleanup callback on success, or
* `null` if hydration failed or was aborted (leaving SSR fallback DOM intact).
*/
export async function hydrateEmbedFigure(
figure: HTMLElement,
provider: NormalizedJournalEmbedProvider,
options: HydrateEmbedFigureOptions,
): Promise<(() => void) | null> {
if (!provider.component && !provider.mount) return null
if (options.signal?.aborted) return null
const fallbackHtml = figure.innerHTML
const rawAspect = figure.getAttribute('data-aspect') ?? undefined
const rawHeight = figure.getAttribute('data-height') ?? undefined
const aspect = rawAspect && EMBED_ASPECT.test(rawAspect) ? rawAspect : undefined
const height = rawHeight && EMBED_HEIGHT.test(rawHeight) ? rawHeight : undefined
// Reserve measured height before swapping to prevent layout shift (CLS).
const rectHeight = typeof figure.getBoundingClientRect === 'function' ? figure.getBoundingClientRect().height : 0
if (rectHeight > 0 && !figure.style.minHeight) {
figure.style.minHeight = `${Math.ceil(rectHeight)}px`
}
const doc = figure.ownerDocument
const host = doc.createElement('div')
host.className = 'journal-embed__stage'
const savedChildren = Array.from(figure.childNodes)
let attached = false
try {
if (provider.component) {
const mod = await provider.component()
if (options.signal?.aborted) return null
const comp = (mod && typeof mod === 'object' && 'default' in mod ? (mod as { default: unknown }).default : mod) as Component | undefined
if (!comp) throw new Error(`Embed provider "${options.providerName}" component loader returned an empty module`)
const vnode = createVNode(comp, {
id: options.id,
provider: options.providerName,
aspect,
height,
fallbackHtml,
reducedMotion: options.reducedMotion,
})
if (options.appContext) vnode.appContext = options.appContext
// Attach host before render so onMounted sees real layout dimensions (WR-02).
replaceChildrenSafe(figure, host)
attached = true
render(vnode, host)
if (options.signal?.aborted) {
render(null, host)
restoreFallback(figure, savedChildren, fallbackHtml)
return null
}
figure.classList.add('journal-embed--hydrated')
return () => {
render(null, host)
figure.classList.remove('journal-embed--hydrated')
}
}
if (provider.mount) {
const ctx: JournalEmbedMountContext = {
id: options.id,
provider: options.providerName,
figure,
aspect,
height,
fallbackHtml,
reducedMotion: options.reducedMotion,
isReducedMotion: options.reducedMotion.value,
}
// Attach host before mount so layout-measuring widgets see real dimensions (WR-02).
replaceChildrenSafe(figure, host)
attached = true
const unmount = await provider.mount(host, ctx)
if (options.signal?.aborted) {
if (typeof unmount === 'function') unmount()
restoreFallback(figure, savedChildren, fallbackHtml)
return null
}
figure.classList.add('journal-embed--hydrated')
return () => {
if (typeof unmount === 'function') unmount()
figure.classList.remove('journal-embed--hydrated')
}
}
} catch (err) {
if (attached) {
try {
render(null, host)
} catch {
// Ignore cleanup errors on failed mount.
}
restoreFallback(figure, savedChildren, fallbackHtml)
}
if (options.onError) options.onError(err, figure)
else warnDev(options.providerName, options.id, err)
return null
}
return null
}
/**
* Observes validated `<figure data-embed>` elements inside `containerRef` and
* lazily hydrates them on the client when they near the viewport. No-op on SSR.
*/
export function useJournalEmbedHydration(
containerRef: Ref<HTMLElement | null>,
htmlSource: WatchSource<string | null | undefined>,
options: JournalEmbedHydrationOptions = {},
): void {
const isServer = (typeof import.meta !== 'undefined' && (import.meta as { server?: boolean }).server === true) || typeof window === 'undefined'
if (isServer) return
// Capture appContext synchronously in setup() rather than inside onMounted/watch (WR-01).
const instance = getCurrentInstance()
const appContext: AppContext | null =
instance?.appContext ??
(typeof useNuxtApp === 'function' ? ((useNuxtApp()?.vueApp?._context as AppContext | undefined) ?? null) : null)
const reducedMotion = ref(false)
let mediaQuery: MediaQueryList | null = null
const onMotionChange = (event: MediaQueryListEvent) => {
reducedMotion.value = event.matches
}
const observers: IntersectionObserver[] = []
const cleanups: Array<() => void> = []
let activeSignal = { aborted: false }
const teardown = () => {
activeSignal.aborted = true
for (const observer of observers.splice(0)) {
observer.disconnect()
}
for (const cleanup of cleanups.splice(0)) {
try {
cleanup()
} catch {
// Ignore teardown errors so every mounted embed gets cleaned up.
}
}
}
const scan = () => {
teardown()
const signal = { aborted: false }
activeSignal = signal
const root = containerRef.value
if (!root) return
const registry = options.registry ?? getJournalEmbedRegistry()
const figures = root.querySelectorAll<HTMLElement>('figure[data-embed][data-id]')
for (const figure of figures) {
const providerName = figure.getAttribute('data-embed') ?? ''
const id = figure.getAttribute('data-id') ?? ''
const provider = registry.get(providerName)
if (!provider || !provider.idPattern.test(id)) continue
if (!provider.component && !provider.mount) continue
const trigger = () => {
void hydrateEmbedFigure(figure, provider, {
id,
providerName,
reducedMotion,
appContext,
signal,
}).then((cleanup) => {
if (!cleanup) return
if (signal.aborted) {
try {
cleanup()
} catch {
// Already torn down.
}
return
}
cleanups.push(cleanup)
})
}
if (typeof IntersectionObserver === 'function') {
const observer = new IntersectionObserver(
(entries, obs) => {
if (entries.some((entry) => entry.isIntersecting)) {
obs.disconnect()
trigger()
}
},
{ rootMargin: provider.rootMargin ?? options.rootMargin ?? '200px' },
)
observer.observe(figure)
observers.push(observer)
} else {
trigger()
}
}
}
onMounted(() => {
if (typeof window.matchMedia === 'function') {
mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)')
reducedMotion.value = mediaQuery.matches
if (typeof mediaQuery.addEventListener === 'function') {
mediaQuery.addEventListener('change', onMotionChange)
}
}
scan()
})
watch(htmlSource, () => {
scan()
}, { flush: 'post' })
onBeforeUnmount(() => {
teardown()
if (mediaQuery && typeof mediaQuery.removeEventListener === 'function') {
mediaQuery.removeEventListener('change', onMotionChange)
}
mediaQuery = null
})
}