278 lines
8.7 KiB
TypeScript
278 lines
8.7 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,
|
|
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, child: HTMLElement): void {
|
|
if (typeof parent.replaceChildren === 'function') {
|
|
parent.replaceChildren(child)
|
|
return
|
|
}
|
|
while (parent.firstChild) parent.removeChild(parent.firstChild)
|
|
parent.appendChild(child)
|
|
}
|
|
|
|
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'
|
|
|
|
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
|
|
|
|
render(vnode, host)
|
|
if (options.signal?.aborted) {
|
|
render(null, host)
|
|
return null
|
|
}
|
|
|
|
replaceChildrenSafe(figure, host)
|
|
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,
|
|
}
|
|
const unmount = await provider.mount(host, ctx)
|
|
if (options.signal?.aborted) {
|
|
if (typeof unmount === 'function') unmount()
|
|
return null
|
|
}
|
|
|
|
replaceChildrenSafe(figure, host)
|
|
figure.classList.add('journal-embed--hydrated')
|
|
|
|
return () => {
|
|
if (typeof unmount === 'function') unmount()
|
|
figure.classList.remove('journal-embed--hydrated')
|
|
}
|
|
}
|
|
} catch (err) {
|
|
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
|
|
|
|
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 nuxtApp = typeof useNuxtApp === 'function' ? useNuxtApp() : undefined
|
|
const appContext = (nuxtApp?.vueApp?._context as AppContext | undefined) ?? null
|
|
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
|
|
})
|
|
}
|