fix(embeds): address Phase 38 review findings in hydration runtime, plugin sync, and docs

This commit is contained in:
Jakub Zych
2026-11-28 13:13:09 +01:00
parent 47de196516
commit 14558e4677
4 changed files with 46 additions and 10 deletions

View File

@@ -32,7 +32,7 @@ Route paths are configuration, not files. The layer's page components live in `a
- **Post cards**: one link per card, the title; the whole card is clickable through a CSS stretched link, with the focus ring on the card.
- **Body links and images**: the CMS's phrase auto-links, the outbound link rules (nofollow or sponsored from the domain lists; new tab, `noopener` and a visually hidden hint while the CMS's links_new_tab is on) and lazy, async body images, applied at SSR on the sanitized body.
- **Breadcrumbs and pagination**: `<SeoBreadcrumbs>` at the top of every journal page (`journal.breadcrumbs`), and `JournalPagination` as `<SeoPagination>` with the journal's class names.
- **HTML sanitizer**: post bodies and category content go through `sanitizeJournalHtml` before `v-html` and before they reach the SSR payload. It is [sanitize-html](https://github.com/apostrophecms/sanitize-html) with the Journal API's own allow-list: the usual content elements, `footer`, `class`, schema.org microdata, the `color`, `font-size`, `font-weight` and `text-align` inline styles, and `http`, `https`, `mailto` or relative URLs. Five rules keep the Journal Blog Editor's own markup, mirroring the API's policy: `data-embed` (`youtube`) and `data-id` (an 11-character video id) on `figure`, `alt` with any text on `img` (`alt=""` of a decorative image included), an integer `start` on `ol`, and a `rel` of only `nofollow`, `sponsored` and `ugc` on `a`. `target` is never kept; the outbound link rules add it. With `{ demoteH1: true }`, `h1` headings come out as `h2`. Anything else (`script`, `style`, `iframe`, `svg`, forms, event-handler attributes, `javascript:` URLs in any spelling) is removed and the rest of the value is kept, so a post never renders blank because of one stray tag. Server and browser produce the same string, so hydration matches. See `docs/decisions/0001-sanitize-html.md`.
- **HTML sanitizer**: post bodies and category content go through `sanitizeJournalHtml` before `v-html` and before they reach the SSR payload. It is [sanitize-html](https://github.com/apostrophecms/sanitize-html) with the Journal API's own allow-list: the usual content elements, `footer`, `class`, schema.org microdata, the `color`, `font-size`, `font-weight` and `text-align` inline styles, and `http`, `https`, `mailto` or relative URLs. Rules keep the Journal Blog Editor's own markup, mirroring the API's policy: pair-aware `data-embed` and `data-id` on `figure` against the active embed provider registry (`youtube` by default, plus app-registered providers) alongside validated `data-aspect` and `data-height` CLS hints, `alt` with any text on `img` (`alt=""` of a decorative image included), an integer `start` on `ol`, and a `rel` of only `nofollow`, `sponsored` and `ugc` on `a`. `target` is never kept; the outbound link rules add it. With `{ demoteH1: true }`, `h1` headings come out as `h2`. Anything else (`script`, `style`, `iframe`, `svg`, forms, event-handler attributes, `javascript:` URLs in any spelling) is removed and the rest of the value is kept, so a post never renders blank because of one stray tag. Server and browser produce the same string, so hydration matches. See `docs/decisions/0001-sanitize-html.md`.
- **Embeds**: built-in YouTube privacy-enhanced iframes plus an app-extensible embed provider registry (`app.config.ts` and Nuxt plugin helpers) with SSR static fallback preservation, CLS height reservation, `IntersectionObserver` lazy hydration, and `prefers-reduced-motion` support (see [Embeds](#embeds)).
- **i18n**: English and Polish UI strings, registered only for the locales the app enables.

View File

@@ -11,6 +11,7 @@
// inline `<script>` injection.
import {
createVNode,
getCurrentInstance,
onBeforeUnmount,
onMounted,
ref,
@@ -46,13 +47,21 @@ export interface JournalEmbedHydrationOptions {
rootMargin?: string
}
function replaceChildrenSafe(parent: HTMLElement, child: HTMLElement): void {
function replaceChildrenSafe(parent: HTMLElement, ...children: Node[]): void {
if (typeof parent.replaceChildren === 'function') {
parent.replaceChildren(child)
parent.replaceChildren(...children)
return
}
while (parent.firstChild) parent.removeChild(parent.firstChild)
parent.appendChild(child)
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 {
@@ -90,6 +99,8 @@ export async function hydrateEmbedFigure(
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) {
@@ -108,13 +119,16 @@ export async function hydrateEmbedFigure(
})
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
}
replaceChildrenSafe(figure, host)
figure.classList.add('journal-embed--hydrated')
return () => {
@@ -134,13 +148,16 @@ export async function hydrateEmbedFigure(
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
}
replaceChildrenSafe(figure, host)
figure.classList.add('journal-embed--hydrated')
return () => {
@@ -149,6 +166,14 @@ export async function hydrateEmbedFigure(
}
}
} 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
@@ -169,6 +194,12 @@ export function useJournalEmbedHydration(
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) => {
@@ -202,8 +233,6 @@ export function useJournalEmbedHydration(
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) {

View File

@@ -4,13 +4,17 @@
// agree on the exact same provider set.
import { defineJournalEmbedProviders, type JournalEmbedProvider } from '../utils/embedRegistry.ts'
const syncedEmbedMaps = new WeakSet<object>()
export default defineNuxtPlugin({
name: 'journal-embeds',
enforce: 'pre',
setup() {
const appConfig = useAppConfig() as { journal?: { embeds?: Record<string, JournalEmbedProvider> } }
if (appConfig?.journal?.embeds) {
defineJournalEmbedProviders(appConfig.journal.embeds)
const embeds = appConfig?.journal?.embeds
if (embeds && typeof embeds === 'object' && !syncedEmbedMaps.has(embeds)) {
defineJournalEmbedProviders(embeds)
syncedEmbedMaps.add(embeds)
}
},
})

View File

@@ -244,10 +244,12 @@ test('hydrateEmbedFigure mounts a plain DOM provider, reserves CLS minHeight, pa
let cleanedUp = false
let receivedCtx: Record<string, unknown> | 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,
@@ -272,6 +274,7 @@ test('hydrateEmbedFigure mounts a plain DOM provider, reserves CLS minHeight, pa
})
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)