feat(embeds): add lazy IntersectionObserver hydration runtime and embed styles
This commit is contained in:
@@ -180,14 +180,18 @@
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
/* Embeds expanded from the Blog Editor's placeholders (app/utils/embeds.ts) */
|
||||
/* Embeds expanded or hydrated from the Blog Editor's placeholders (app/utils/embeds.ts) */
|
||||
.journal-embed {
|
||||
display: block;
|
||||
width: 100%;
|
||||
aspect-ratio: 16 / 9;
|
||||
margin: var(--journal-space-4) 0;
|
||||
}
|
||||
|
||||
.journal-embed--youtube,
|
||||
.journal-embed:has(> iframe) {
|
||||
aspect-ratio: 16 / 9;
|
||||
}
|
||||
|
||||
.journal-embed iframe {
|
||||
display: block;
|
||||
width: 100%;
|
||||
@@ -195,6 +199,23 @@
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.journal-embed img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.journal-embed figcaption {
|
||||
margin-top: var(--journal-space-2);
|
||||
color: var(--journal-color-muted);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.journal-embed__stage {
|
||||
display: block;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Listings */
|
||||
.journal-post-list {
|
||||
display: grid;
|
||||
|
||||
@@ -11,9 +11,12 @@ import { expandEmbeds } from '../../utils/embeds.ts'
|
||||
import { sanitizeJournalHtml } from '../../utils/htmlGate.ts'
|
||||
|
||||
const props = defineProps<{ category: JournalCategory; page?: number }>()
|
||||
const contentRef = ref<HTMLElement | null>(null)
|
||||
const content = computed(() =>
|
||||
props.page && props.page > 1 ? '' : expandEmbeds(sanitizeJournalHtml(props.category.content, { demoteH1: props.category.content_h1_to_h2 !== false })),
|
||||
)
|
||||
|
||||
useJournalEmbedHydration(contentRef, content)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -22,6 +25,6 @@ const content = computed(() =>
|
||||
{{ category.name }}<template v-if="page && page > 1"> · {{ $t('journal.pagination.pageTitle', { page }) }}</template>
|
||||
</h1>
|
||||
<p v-if="category.description" class="journal-category-header__description">{{ category.description }}</p>
|
||||
<div v-if="content" class="journal-category-header__content journal-post-body" v-html="content" />
|
||||
<div v-if="content" ref="contentRef" class="journal-category-header__content journal-post-body" v-html="content" />
|
||||
</header>
|
||||
</template>
|
||||
|
||||
@@ -20,6 +20,7 @@ import { expandEmbeds } from '../../utils/embeds.ts'
|
||||
import { renderJournalBody, type JournalBodyLinkSteps } from '../../utils/htmlGate.ts'
|
||||
|
||||
const props = defineProps<{ html: string | null | undefined; demoteH1?: boolean }>()
|
||||
const bodyRef = ref<HTMLElement | null>(null)
|
||||
|
||||
const answer = useSeoAnswer()
|
||||
const route = useRoute()
|
||||
@@ -71,8 +72,10 @@ const html = computed(() => {
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
useJournalEmbedHydration(bodyRef, html)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="journal-post-body" v-html="html" />
|
||||
<div ref="bodyRef" class="journal-post-body" v-html="html" />
|
||||
</template>
|
||||
|
||||
277
app/composables/useJournalEmbedHydration.ts
Normal file
277
app/composables/useJournalEmbedHydration.ts
Normal file
@@ -0,0 +1,277 @@
|
||||
// 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
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user