// Embed expansion for Journal HTML. The Blog Editor (Journal plugin, // assets/src/blogeditor/embed.ts) never stores an iframe: it writes a // `
` placeholder (optionally // with `data-aspect`, `data-height`, and sanitized static fallback children // such as `` and `
`). Both `sm-journal-plugin` and // `htmlGate.ts` validate `(data-embed, data-id)` pair-aware against the // registered embed providers. // // expandEmbeds is the very last step before v-html, after sanitizeJournalHtml: // its input is always sanitizer output, and its output is never sanitized // again (the sanitizer strips every iframe, including the one built here). // Built-in `youtube` expands empty placeholders to a privacy-enhanced iframe // on youtube-nocookie.com; client-hydrated providers (`component` or `mount`) // keep their SSR fallback DOM intact with `journal-embed` classes and optional // CLS layout reservation (`aspect-ratio` / `min-height`). import { EMBED_ASPECT, EMBED_HEIGHT, getJournalEmbedRegistry, type JournalEmbedRegistry, } from './embedRegistry.ts' /** One allowlisted embed provider (legacy shape kept for backward compatibility). */ export type EmbedProvider = { /** The id a placeholder must match to expand. */ id: RegExp /** The iframe src for a validated id. */ src: (id: string) => string /** The iframe's accessible title. */ title: string } /** Providers a placeholder may name. YouTube only, on its privacy-enhanced host. */ export const EMBED_PROVIDERS: Readonly> = Object.freeze({ youtube: { id: /^[A-Za-z0-9_-]{11}$/, src: (id: string) => `https://www.youtube-nocookie.com/embed/${id}`, title: 'YouTube video', }, }) /** * The placeholder exactly as the editor writes it and sanitize-html * serializes it. Group 1 is the provider, group 2 the id; neither may hold a * quote or an angle bracket. */ export const EMBED_PLACEHOLDER = /
]*)" data-id="([^"<>]*)"><\/figure>/g // Matches a sanitize-html serialized `
...
` (lowercase tag, // single-space-separated double-quoted attributes, no nested `
`). const EMBED_FIGURE_RE = /]*")+)>((?:(?!<\/?figure\b)[\s\S])*?)<\/figure>/g const ATTR_PAIR_RE = / ([a-z][a-z0-9-]*)="([^"<>]*)"/g function normalizeCssHeight(value: string): string { return value.endsWith('px') ? value : `${value}px` } function mergeClasses(existing: string | undefined, required: readonly string[]): string { const tokens = existing ? existing.split(/\s+/).filter(Boolean) : [] for (const cls of required) { if (!tokens.includes(cls)) tokens.push(cls) } return tokens.join(' ') } function mergeClsStyle(existing: string | undefined, aspect?: string, height?: string): string | undefined { const decls = existing ? existing .split(';') .map((s) => s.trim()) .filter(Boolean) : [] const hasProp = (prop: string) => decls.some((d) => d.toLowerCase().startsWith(`${prop}:`)) if (aspect && EMBED_ASPECT.test(aspect) && !hasProp('aspect-ratio')) { decls.push(`aspect-ratio:${aspect.replace(/\s+/g, '')}`) } if (height && EMBED_HEIGHT.test(height) && !hasProp('min-height')) { decls.push(`min-height:${normalizeCssHeight(height)}`) } return decls.length > 0 ? decls.join(';') : undefined } /** * Expands validated embed placeholders using the active (or supplied) * `JournalEmbedRegistry`: * - Providers with `renderSsr` (e.g. built-in `youtube` on an empty figure) * emit their SSR HTML directly. * - Client-hydrated providers (`component` or `mount`) preserve the `
` * and its static SSR fallback children while adding `journal-embed` / * `journal-embed--` classes and safe CLS `aspect-ratio` / * `min-height` reservation styles. * - Unknown providers or mismatched IDs remain untouched and inert. * * Call on `sanitizeJournalHtml` output only, and never sanitize its result. */ export function expandEmbeds( html: string | null | undefined, registry: JournalEmbedRegistry = getJournalEmbedRegistry(), ): string { if (!html) return '' return html.replace(EMBED_FIGURE_RE, (match: string, attrText: string, innerHtml: string) => { const attrs: Array<[string, string]> = [] const byName = new Map() for (const m of attrText.matchAll(ATTR_PAIR_RE)) { const name = m[1]! const value = m[2]! attrs.push([name, value]) if (!byName.has(name)) byName.set(name, value) } const providerName = byName.get('data-embed') const id = byName.get('data-id') if (!providerName || !id) return match const provider = registry.get(providerName) if (!provider || !provider.idPattern.test(id)) return match const rawAspect = byName.get('data-aspect') const rawHeight = byName.get('data-height') const aspect = rawAspect && EMBED_ASPECT.test(rawAspect) ? rawAspect : undefined const height = rawHeight && EMBED_HEIGHT.test(rawHeight) ? rawHeight : undefined if (provider.renderSsr) { if (provider._builtinYoutube) { // Built-in YouTube keeps strict placeholder shape: data-embed before // data-id, no extra attributes beyond data-aspect/data-height, empty body. const allowedKeys = new Set(['data-embed', 'data-id', 'data-aspect', 'data-height']) const embedIdx = attrs.findIndex(([k]) => k === 'data-embed') const idIdx = attrs.findIndex(([k]) => k === 'data-id') const allAllowed = attrs.every(([k]) => allowedKeys.has(k)) if (innerHtml !== '' || !allAllowed || embedIdx < 0 || idIdx < 0 || embedIdx > idIdx) { return match } } const rendered = provider.renderSsr(id, { provider: providerName, innerHtml, aspect, height }) if (typeof rendered === 'string') return rendered } if (provider.component || provider.mount) { const nextClass = mergeClasses(byName.get('class'), ['journal-embed', `journal-embed--${providerName}`]) const nextStyle = mergeClsStyle(byName.get('style'), aspect ?? provider.aspectRatio, height ?? provider.minHeight) const outAttrs: Array<[string, string]> = [] let wroteClass = false let wroteStyle = false for (const [k, v] of attrs) { if (k === 'class') { if (!wroteClass) { outAttrs.push(['class', nextClass]) wroteClass = true } } else if (k === 'style') { if (!wroteStyle && nextStyle) { outAttrs.push(['style', nextStyle]) wroteStyle = true } } else { outAttrs.push([k, v]) } } if (!wroteClass) outAttrs.unshift(['class', nextClass]) if (!wroteStyle && nextStyle) outAttrs.push(['style', nextStyle]) const serialized = outAttrs.map(([k, v]) => ` ${k}="${v}"`).join('') return `${innerHtml}
` } return match }) }