feat(embeds): add extensible embed registry, universal plugin, and pair-aware sanitizer
This commit is contained in:
@@ -1,20 +1,27 @@
|
||||
// Embed expansion for Journal HTML. The Blog Editor (Journal plugin,
|
||||
// assets/src/blogeditor/embed.ts) never stores an iframe: it writes the
|
||||
// placeholder <figure data-embed="youtube" data-id="ID"></figure>, and the
|
||||
// plugin's bluemonday policy (classes/format_html.go) keeps exactly that, with
|
||||
// data-embed matching ^youtube$ and data-id matching ^[A-Za-z0-9_-]{11}$.
|
||||
// htmlGate.ts mirrors those two rules, so the placeholder survives the layer's
|
||||
// sanitizer too.
|
||||
// assets/src/blogeditor/embed.ts) never stores an iframe: it writes a
|
||||
// `<figure data-embed="<provider>" data-id="<id>">` placeholder (optionally
|
||||
// with `data-aspect`, `data-height`, and sanitized static fallback children
|
||||
// such as `<img>` and `<figcaption>`). 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). The
|
||||
// regex matches the serialization sanitize-html gives the placeholder:
|
||||
// attribute order kept, double quotes, empty figure. Only a known provider
|
||||
// with a valid id becomes an iframe, whose src is a fixed host plus that id;
|
||||
// anything else is returned unchanged and stays an inert empty figure.
|
||||
// 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`).
|
||||
|
||||
/** One allowlisted embed provider. */
|
||||
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
|
||||
@@ -40,24 +47,123 @@ export const EMBED_PROVIDERS: Readonly<Record<string, EmbedProvider>> = Object.f
|
||||
*/
|
||||
export const EMBED_PLACEHOLDER = /<figure data-embed="([^"<>]*)" data-id="([^"<>]*)"><\/figure>/g
|
||||
|
||||
// Matches a sanitize-html serialized `<figure ...>...</figure>` (lowercase tag,
|
||||
// single-space-separated double-quoted attributes, no nested `<figure>`).
|
||||
const EMBED_FIGURE_RE = /<figure((?: [a-z][a-z0-9-]*="[^"<>]*")+)>((?:(?!<\/?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
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces every placeholder whose provider is in EMBED_PROVIDERS and whose
|
||||
* id passes the provider's pattern with a figure holding the provider's
|
||||
* iframe. Every other match is returned unchanged. Empty input gives "".
|
||||
* Call it on sanitizeJournalHtml output only, and never sanitize its result.
|
||||
* 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 `<figure>`
|
||||
* and its static SSR fallback children while adding `journal-embed` /
|
||||
* `journal-embed--<provider>` 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): string {
|
||||
export function expandEmbeds(
|
||||
html: string | null | undefined,
|
||||
registry: JournalEmbedRegistry = getJournalEmbedRegistry(),
|
||||
): string {
|
||||
if (!html) return ''
|
||||
return html.replace(EMBED_PLACEHOLDER, (match: string, provider: string, id: string) => {
|
||||
if (!Object.hasOwn(EMBED_PROVIDERS, provider)) return match
|
||||
const p = EMBED_PROVIDERS[provider]!
|
||||
if (!p.id.test(id)) return match
|
||||
return (
|
||||
`<figure class="journal-embed journal-embed--${provider}">` +
|
||||
`<iframe src="${p.src(id)}" title="${p.title}" loading="lazy" ` +
|
||||
'referrerpolicy="strict-origin-when-cross-origin" ' +
|
||||
'allow="encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe>' +
|
||||
'</figure>'
|
||||
)
|
||||
return html.replace(EMBED_FIGURE_RE, (match: string, attrText: string, innerHtml: string) => {
|
||||
const attrs: Array<[string, string]> = []
|
||||
const byName = new Map<string, string>()
|
||||
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 `<figure${serialized}>${innerHtml}</figure>`
|
||||
}
|
||||
|
||||
return match
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user