feat(blogeditor): support dynamic embed providers, fallbacks, and adaptive form

This commit is contained in:
Jakub Zych
2026-11-28 12:44:52 +01:00
parent 55ac26e0d3
commit 37e89e56db
9 changed files with 808 additions and 133 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -70,7 +70,8 @@ golem15-journal-blogeditor .blogeditor__form label {
color: var(--c-muted);
}
golem15-journal-blogeditor .blogeditor__form input {
golem15-journal-blogeditor .blogeditor__form input,
golem15-journal-blogeditor .blogeditor__form select {
box-sizing: border-box;
width: 100%;
padding: 5px 8px;
@@ -86,11 +87,62 @@ golem15-journal-blogeditor .blogeditor__form input::placeholder {
color: var(--c-placeholder);
}
golem15-journal-blogeditor .blogeditor__form input:focus {
golem15-journal-blogeditor .blogeditor__form input:focus,
golem15-journal-blogeditor .blogeditor__form select:focus {
outline: 2px solid var(--c-ring);
outline-offset: -1px;
}
golem15-journal-blogeditor .blogeditor__embed-fields {
display: flex;
flex-basis: 100%;
flex-wrap: wrap;
align-items: flex-end;
gap: 6px 8px;
}
golem15-journal-blogeditor .blogeditor__embed-row {
display: flex;
align-items: center;
gap: 6px;
}
golem15-journal-blogeditor .blogeditor__embed-row input {
flex: 1 1 auto;
}
golem15-journal-blogeditor .blogeditor__embed-head {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
flex-wrap: wrap;
}
golem15-journal-blogeditor .blogeditor__embed-badge {
padding: 1px 6px;
border-radius: 4px;
background: var(--c-surface);
border: 1px solid var(--c-border);
font-family: "DM Mono", ui-monospace, monospace;
font-size: 11px;
}
golem15-journal-blogeditor .blogeditor__embed-thumb {
display: block;
max-width: 320px;
max-height: 180px;
margin: 8px auto 0;
border-radius: 6px;
object-fit: contain;
}
golem15-journal-blogeditor .blogeditor__embed-caption {
margin: 6px 0 0;
font-size: 12px;
color: var(--c-muted);
}
golem15-journal-blogeditor .blogeditor__form button[data-action="apply"],
golem15-journal-blogeditor .blogeditor__form button[data-action="insert"] {
background: var(--c-primary);

View File

@@ -1,5 +1,14 @@
import { Editor } from '@tiptap/core'
import { parseEmbedUrl } from './embed'
import {
findEmbedProvider,
isValidAspect,
isValidHeight,
parseEmbedUrl,
parseEmbedUrlWith,
resolveEmbedProviders,
validateEmbedId,
type ResolvedEmbedProvider,
} from './embed'
import { DEFAULT_HEADING_LEVELS, EDIT_HTML_EVENT, isPolicyUrl, preservationExtensions } from './extensions'
import { buildImageForm, type ImageChoice, type ImageForm } from './imageform'
import { format, labelsFor, type Labels } from './labels'
@@ -38,12 +47,15 @@ export interface EditorOptions {
headingLevels: number[]
/** The generic link texts, normalized (normalizeAnchor). */
genericAnchors: string[]
/** Registered embed providers from Go EmbedRegistry (defaults to YouTube). */
embedProviders: ResolvedEmbedProvider[]
}
/**
* readOptions reads the options attribute (JSON): headingLevels (integers 1
* to 6, default [2, 3, 4]) and genericAnchors (strings, default
* DEFAULT_GENERIC_ANCHORS). Anything else, or invalid JSON, is the default.
* to 6, default [2, 3, 4]), genericAnchors (strings, default
* DEFAULT_GENERIC_ANCHORS), and embedProviders (default YouTube). Anything
* else, or invalid JSON, is the default.
*/
export function readOptions(raw: string | null): EditorOptions {
let parsed: Record<string, unknown> = {}
@@ -62,6 +74,7 @@ export function readOptions(raw: string | null): EditorOptions {
return {
headingLevels: levels.length > 0 ? levels : [...DEFAULT_HEADING_LEVELS],
genericAnchors: [...new Set(anchors.map(normalizeAnchor).filter((t) => t !== ''))],
embedProviders: resolveEmbedProviders(parsed.embedProviders),
}
}
@@ -112,7 +125,8 @@ export class BlogEditorElement extends HTMLElement {
#options: EditorOptions = readOptions(null)
#showingSource = false
#pending = new Map<string, { name: string; choice: ImageChoice; timer: ReturnType<typeof setTimeout> }>()
#pendingMediaPick = new Set<string>()
#pendingMediaPick = new Map<string, 'insert' | 'embedFallback'>()
#embedFallbackDims: { width: string | null; height: string | null } = { width: null, height: null }
/** The picked files waiting for their image form (J4). */
#queue: File[] = []
/** Whether this element shows the preview pane (per instance, off by default). */
@@ -194,10 +208,12 @@ export class BlogEditorElement extends HTMLElement {
const urlField = this.#linkForm.root.querySelector('label')!
urlField.after(extras.fieldset, extras.warning)
urlField.querySelector('input')!.addEventListener('input', (event) => extras.setUrl((event.target as HTMLInputElement).value))
this.#embedForm = this.#form('embed', labels.embedUrl, [
['insert', labels.embedInsert, () => this.#insertEmbed()],
['cancel', labels.cancel, () => this.#close(this.#embedForm)],
])
this.#embedForm = this.#hasCustomEmbedProviders(options.embedProviders)
? this.#buildAdaptiveEmbedForm(labels, options.embedProviders)
: this.#form('embed', labels.embedUrl, [
['insert', labels.embedInsert, () => this.#insertEmbed()],
['cancel', labels.cancel, () => this.#close(this.#embedForm)],
])
this.#imageForm = buildImageForm(labels, () => this.#insertImage(), () => this.#nextImage())
const mount = document.createElement('div')
@@ -276,7 +292,7 @@ export class BlogEditorElement extends HTMLElement {
element: mount,
injectCSS: false,
editable: !this.hasAttribute('disabled'),
extensions: preservationExtensions(labels, options.headingLevels),
extensions: preservationExtensions(labels, options.headingLevels, options.embedProviders),
content: initial,
editorProps: {
handleDrop: (_view, event, _slice, moved) => {
@@ -383,6 +399,7 @@ export class BlogEditorElement extends HTMLElement {
const doc = buildPreviewDocument(html, {
labels: this.#labels,
lang: this.getAttribute('locale'),
providers: this.#options.embedProviders,
...resolvePreviewColors(this),
})
// An identical document would only reload the frame.
@@ -608,19 +625,204 @@ export class BlogEditorElement extends HTMLElement {
// Embeds ---------------------------------------------------------------------
#hasCustomEmbedProviders(providers: readonly ResolvedEmbedProvider[]): boolean {
return providers.length > 1 || providers[0]?.key !== 'youtube' || providers[0]?.mode !== 'url'
}
#buildAdaptiveEmbedForm(labels: Labels, providers: readonly ResolvedEmbedProvider[]): InlineForm {
const root = document.createElement('div')
root.className = 'blogeditor__form'
root.dataset.form = 'embed'
root.hidden = true
const onKey = (event: KeyboardEvent) => {
if (event.key === 'Enter') {
event.preventDefault()
this.#insertEmbed()
} else if (event.key === 'Escape') {
event.preventDefault()
this.#close(form)
}
}
const providerField = document.createElement('label')
const providerCaption = document.createElement('span')
providerCaption.textContent = labels.embedProvider
const select = document.createElement('select')
select.name = 'provider'
for (const p of providers) {
const opt = document.createElement('option')
opt.value = p.key
opt.textContent = p.name
select.append(opt)
}
providerField.append(providerCaption, select)
const urlField = document.createElement('label')
urlField.dataset.embedMode = 'url'
const urlCaption = document.createElement('span')
urlCaption.textContent = labels.embedUrl
const urlInput = document.createElement('input')
urlInput.type = 'text'
urlInput.name = 'url'
urlInput.autocomplete = 'off'
urlInput.addEventListener('keydown', onKey)
urlField.append(urlCaption, urlInput)
const idGroup = document.createElement('div')
idGroup.className = 'blogeditor__embed-fields'
idGroup.dataset.embedMode = 'id'
const makeTextField = (name: string, text: string, placeholder = ''): { label: HTMLLabelElement; input: HTMLInputElement } => {
const label = document.createElement('label')
const span = document.createElement('span')
span.textContent = text
const input = document.createElement('input')
input.type = 'text'
input.name = name
input.autocomplete = 'off'
if (placeholder) input.placeholder = placeholder
input.addEventListener('keydown', onKey)
label.append(span, input)
return { label, input }
}
const idField = makeTextField('embedId', labels.embedId)
const fallbackField = document.createElement('label')
const fallbackCaption = document.createElement('span')
fallbackCaption.textContent = labels.embedFallbackImage
const fallbackRow = document.createElement('div')
fallbackRow.className = 'blogeditor__embed-row'
const fallbackInput = document.createElement('input')
fallbackInput.type = 'text'
fallbackInput.name = 'fallbackSrc'
fallbackInput.autocomplete = 'off'
fallbackInput.addEventListener('keydown', onKey)
fallbackInput.addEventListener('input', () => {
this.#embedFallbackDims = { width: null, height: null }
})
const pickBtn = this.#action('pick-fallback', labels.embedFallbackPick, () => this.#pickEmbedFallbackFromMediaLibrary())
fallbackRow.append(fallbackInput, pickBtn)
fallbackField.append(fallbackCaption, fallbackRow)
const altField = makeTextField('fallbackAlt', labels.embedFallbackAlt)
const captionField = makeTextField('caption', labels.embedCaption)
const aspectField = makeTextField('aspect', labels.embedAspect, '16/9')
const heightField = makeTextField('height', labels.embedHeight, '420px')
idGroup.append(idField.label, fallbackField, altField.label, captionField.label, aspectField.label, heightField.label)
const syncMode = () => {
const active = findEmbedProvider(providers, select.value) ?? providers[0]
const isUrl = active?.mode === 'url'
urlField.hidden = !isUrl
idGroup.hidden = isUrl
idField.input.placeholder = active?.placeholder ?? ''
form.error.textContent = ''
}
select.addEventListener('change', syncMode)
const error = document.createElement('p')
error.className = 'blogeditor__error'
error.dataset.error = ''
error.setAttribute('aria-live', 'polite')
const form: InlineForm = { root, error }
root.append(
providerField,
urlField,
idGroup,
this.#action('insert', labels.embedInsert, () => this.#insertEmbed()),
this.#action('cancel', labels.cancel, () => this.#close(form)),
error,
)
syncMode()
return form
}
#openEmbed(): void {
if (!this.#editor?.isEditable) return
this.#embedFallbackDims = { width: null, height: null }
this.#open(this.#embedForm)
const form = this.#embedForm
if (!form) return
for (const input of Array.from(form.root.querySelectorAll('input'))) input.value = ''
const select = form.root.querySelector<HTMLSelectElement>('select[name="provider"]')
if (select) {
select.dispatchEvent(new Event('change'))
const active = findEmbedProvider(this.#options.embedProviders, select.value)
const target = active?.mode === 'id'
? form.root.querySelector<HTMLInputElement>('input[name="embedId"]')
: form.root.querySelector<HTMLInputElement>('input[name="url"]')
target?.focus()
}
}
#insertEmbed(): void {
if (!this.#editor || !this.#embedForm) return
const embed = parseEmbedUrl(this.#inputOf(this.#embedForm))
if (!embed) {
this.#embedForm.error.textContent = this.#labels.embedInvalid
const select = this.#embedForm.root.querySelector<HTMLSelectElement>('select[name="provider"]')
if (!select) {
const embed = parseEmbedUrl(this.#inputOf(this.#embedForm))
if (!embed) {
this.#embedForm.error.textContent = this.#labels.embedInvalid
return
}
this.#editor.chain().focus().setEmbed(embed).run()
this.#close(this.#embedForm)
return
}
this.#editor.chain().focus().setEmbed(embed).run()
const provider = findEmbedProvider(this.#options.embedProviders, select.value)
if (!provider) {
this.#embedForm.error.textContent = this.#labels.embedIdInvalid
return
}
if (provider.mode === 'url') {
const parsed = parseEmbedUrlWith([provider], this.#inputOf(this.#embedForm, 'url'))
if (!parsed) {
this.#embedForm.error.textContent = this.#labels.embedInvalid
return
}
this.#editor.chain().focus().setEmbed(parsed).run()
this.#close(this.#embedForm)
return
}
const id = this.#inputOf(this.#embedForm, 'embedId')
if (!validateEmbedId(this.#options.embedProviders, provider.key, id)) {
this.#embedForm.error.textContent = this.#labels.embedIdInvalid
return
}
const fallbackSrc = this.#inputOf(this.#embedForm, 'fallbackSrc')
if (fallbackSrc !== '' && !isPolicyUrl(fallbackSrc)) {
this.#embedForm.error.textContent = this.#labels.linkInvalid
return
}
const aspect = this.#inputOf(this.#embedForm, 'aspect')
if (aspect !== '' && !isValidAspect(aspect)) {
this.#embedForm.error.textContent = this.#labels.embedIdInvalid
return
}
const height = this.#inputOf(this.#embedForm, 'height')
if (height !== '' && !isValidHeight(height)) {
this.#embedForm.error.textContent = this.#labels.embedIdInvalid
return
}
const fallbackAlt = this.#inputOf(this.#embedForm, 'fallbackAlt')
const caption = this.#inputOf(this.#embedForm, 'caption')
this.#editor
.chain()
.focus()
.setEmbed({
provider: provider.key,
id,
aspect: aspect || null,
height: height || null,
fallbackSrc: fallbackSrc || null,
fallbackAlt: fallbackSrc ? fallbackAlt : null,
fallbackWidth: fallbackSrc ? this.#embedFallbackDims.width : null,
fallbackHeight: fallbackSrc ? this.#embedFallbackDims.height : null,
caption: caption || null,
})
.run()
this.#close(this.#embedForm)
}
@@ -736,7 +938,20 @@ export class BlogEditorElement extends HTMLElement {
#pickFromMediaLibrary(): void {
if (!this.#editor?.isEditable) return
const id = uploadRequestId()
this.#pendingMediaPick.add(id)
this.#pendingMediaPick.set(id, 'insert')
this.dispatchEvent(
new CustomEvent(MEDIA_PICK_EVENT, {
bubbles: true,
composed: true,
detail: { id, mode: 'image', defaultFolder: 'journal', showAlt: true },
}),
)
}
#pickEmbedFallbackFromMediaLibrary(): void {
if (!this.#editor?.isEditable) return
const id = uploadRequestId()
this.#pendingMediaPick.set(id, 'embedFallback')
this.dispatchEvent(
new CustomEvent(MEDIA_PICK_EVENT, {
bubbles: true,
@@ -755,16 +970,32 @@ export class BlogEditorElement extends HTMLElement {
}>
).detail ?? {}
const id = typeof detail.id === 'string' ? detail.id : ''
if (!this.#pendingMediaPick.delete(id)) return
const purpose = this.#pendingMediaPick.get(id)
if (!purpose) return
this.#pendingMediaPick.delete(id)
if (detail.cancelled === true || !detail.item) return
const url = typeof detail.item.url === 'string' ? detail.item.url.trim() : ''
if (!url || !isPolicyUrl(url)) return
const editor = this.#editor
if (!editor) return
const alt = typeof detail.item.alt === 'string' ? detail.item.alt : ''
const caption = typeof detail.item.caption === 'string' ? detail.item.caption.trim() : ''
const width = typeof detail.item.width === 'number' && detail.item.width > 0 ? String(detail.item.width) : null
const height = typeof detail.item.height === 'number' && detail.item.height > 0 ? String(detail.item.height) : null
if (purpose === 'embedFallback') {
const form = this.#embedForm
if (!form) return
const srcInput = form.root.querySelector<HTMLInputElement>('input[name="fallbackSrc"]')
if (srcInput) srcInput.value = url
const altInput = form.root.querySelector<HTMLInputElement>('input[name="fallbackAlt"]')
if (altInput && alt) altInput.value = alt
const capInput = form.root.querySelector<HTMLInputElement>('input[name="caption"]')
if (capInput && caption && !capInput.value) capInput.value = caption
this.#embedFallbackDims = { width, height }
return
}
const editor = this.#editor
if (!editor) return
if (caption) {
editor.chain().focus().setFigure({ src: url, alt, caption, width, height }).run()
} else {

View File

@@ -1,9 +1,10 @@
/**
* Embed providers (D-05). Stored posts hold only the placeholder
* <figure data-embed="PROVIDER" data-id="ID"></figure>; the layer turns it
* into the real iframe. Adding a provider is one entry here and one in the
* layer's table.
* Embed providers (D-05, Phase 38 D-06). Stored posts hold only the placeholder
* <figure data-embed="PROVIDER" data-id="ID">[optional fallback <img> / <figcaption>]</figure>;
* the site layer expands or hydrates it.
*/
export type EmbedInputMode = 'url' | 'id'
export interface EmbedProvider {
/** The name shown on the editor card. */
name: string
@@ -13,7 +14,37 @@ export interface EmbedProvider {
idFromUrl: (url: URL) => string | null
}
const YOUTUBE_HOSTS = new Set(['youtube.com', 'www.youtube.com', 'm.youtube.com', 'music.youtube.com', 'youtube-nocookie.com', 'www.youtube-nocookie.com'])
/** JSON shape sent by Go blogRequestOptions under "embedProviders". */
export interface EmbedProviderConfig {
key: string
name: string
idPattern: string
mode?: EmbedInputMode
placeholder?: string
}
/** Validated runtime provider used by the Blog Editor schema, form, and preview. */
export interface ResolvedEmbedProvider {
key: string
name: string
idPattern: RegExp
mode: EmbedInputMode
placeholder?: string
idFromUrl?: (url: URL) => string | null
}
const YOUTUBE_HOSTS = new Set([
'youtube.com',
'www.youtube.com',
'm.youtube.com',
'music.youtube.com',
'youtube-nocookie.com',
'www.youtube-nocookie.com',
])
const EMBED_KEY_RE = /^[a-z][a-z0-9_-]{0,31}$/
const EMBED_ASPECT_RE = /^[1-9][0-9]{0,3}(?:\s*\/\s*[1-9][0-9]{0,3}|\.[0-9]{1,4})?$/
const EMBED_HEIGHT_RE = /^[1-9][0-9]{0,3}(?:px)?$/
export const EMBED_PROVIDERS = {
youtube: {
@@ -34,26 +65,117 @@ export const EMBED_PROVIDERS = {
export type EmbedProviderName = keyof typeof EMBED_PROVIDERS
export const DEFAULT_EMBED_PROVIDERS: readonly ResolvedEmbedProvider[] = [
{
key: 'youtube',
name: EMBED_PROVIDERS.youtube.name,
idPattern: EMBED_PROVIDERS.youtube.idPattern,
mode: 'url',
idFromUrl: EMBED_PROVIDERS.youtube.idFromUrl,
},
]
export function isEmbedProvider(name: string): name is EmbedProviderName {
return Object.prototype.hasOwnProperty.call(EMBED_PROVIDERS, name)
}
/**
* resolveEmbedProviders validates raw options JSON into runtime embed
* providers, rejecting invalid keys, duplicate keys, or uncompilable regexes.
* Falls back to built-in YouTube when absent or empty.
*/
export function resolveEmbedProviders(raw: unknown): ResolvedEmbedProvider[] {
if (!Array.isArray(raw)) return [...DEFAULT_EMBED_PROVIDERS]
const seen = new Set<string>()
const out: ResolvedEmbedProvider[] = []
for (const item of raw) {
if (!item || typeof item !== 'object' || Array.isArray(item)) continue
const cfg = item as Record<string, unknown>
const key = typeof cfg.key === 'string' ? cfg.key.trim() : ''
if (!EMBED_KEY_RE.test(key) || seen.has(key)) continue
const patternSrc = typeof cfg.idPattern === 'string' ? cfg.idPattern.trim() : ''
if (!patternSrc) continue
let idPattern: RegExp
try {
new RegExp(patternSrc)
idPattern = new RegExp(`^(?:${patternSrc})$`)
} catch {
continue
}
const name = typeof cfg.name === 'string' && cfg.name.trim() !== '' ? cfg.name.trim() : key
const rawMode = typeof cfg.mode === 'string' ? cfg.mode.trim() : ''
const mode: EmbedInputMode =
rawMode === 'url' || rawMode === 'id' ? rawMode : key === 'youtube' ? 'url' : 'id'
const placeholder = typeof cfg.placeholder === 'string' && cfg.placeholder.trim() !== '' ? cfg.placeholder.trim() : undefined
const resolved: ResolvedEmbedProvider = {
key,
name,
idPattern,
mode,
...(placeholder ? { placeholder } : {}),
...(key === 'youtube' ? { idFromUrl: EMBED_PROVIDERS.youtube.idFromUrl } : {}),
}
seen.add(key)
out.push(resolved)
}
return out.length > 0 ? out : [...DEFAULT_EMBED_PROVIDERS]
}
export function findEmbedProvider(
providers: readonly ResolvedEmbedProvider[],
key: string,
): ResolvedEmbedProvider | undefined {
return providers.find((p) => p.key === key)
}
export function validateEmbedId(
providers: readonly ResolvedEmbedProvider[],
key: string,
id: string,
): boolean {
const provider = findEmbedProvider(providers, key)
return Boolean(provider && id !== '' && provider.idPattern.test(id))
}
export const isValidEmbed = validateEmbedId
export function isValidAspect(value: string): boolean {
return EMBED_ASPECT_RE.test(value.trim())
}
export function isValidHeight(value: string): boolean {
return EMBED_HEIGHT_RE.test(value.trim())
}
/**
* parseEmbedUrlWith parses a provider URL against the given providers list.
*/
export function parseEmbedUrlWith(
providers: readonly ResolvedEmbedProvider[],
input: string,
): { provider: string; id: string } | null {
let url: URL
try {
url = new URL(input.trim())
} catch {
return null
}
if (url.protocol !== 'https:' && url.protocol !== 'http:') return null
for (const p of providers) {
if (!p.idFromUrl) continue
const id = p.idFromUrl(url)
if (id && p.idPattern.test(id)) return { provider: p.key, id }
}
return null
}
/**
* parseEmbedUrl returns the provider and id for a supported video URL
* (youtube.com/watch?v=, youtu.be/, youtube.com/shorts/ and
* youtube.com/embed/ for YouTube), or null for anything else.
*/
export function parseEmbedUrl(input: string): { provider: EmbedProviderName; id: string } | null {
let url: URL
try {
url = new URL(input.trim())
} catch {
return null
}
if (url.protocol !== 'https:' && url.protocol !== 'http:') return null
for (const provider of Object.keys(EMBED_PROVIDERS) as EmbedProviderName[]) {
const id = EMBED_PROVIDERS[provider].idFromUrl(url)
if (id && EMBED_PROVIDERS[provider].idPattern.test(id)) return { provider, id }
}
return null
const parsed = parseEmbedUrlWith(DEFAULT_EMBED_PROVIDERS, input)
if (!parsed || !isEmbedProvider(parsed.provider)) return null
return { provider: parsed.provider, id: parsed.id }
}

View File

@@ -3,7 +3,14 @@ import type { DOMOutputSpec } from '@tiptap/pm/model'
import Image from '@tiptap/extension-image'
import { Table, TableCell, TableHeader, TableRow } from '@tiptap/extension-table'
import StarterKit from '@tiptap/starter-kit'
import { EMBED_PROVIDERS, isEmbedProvider } from './embed'
import {
DEFAULT_EMBED_PROVIDERS,
findEmbedProvider,
isValidAspect,
isValidEmbed,
isValidHeight,
type ResolvedEmbedProvider,
} from './embed'
import { labelsFor, type Labels } from './labels'
/** The event a raw HTML card dispatches to open its source in the Source tab. */
@@ -210,6 +217,18 @@ export function inert(): Document {
return inertDocument
}
export interface SetEmbedAttributes {
provider: string
id: string
aspect?: string | null
height?: string | null
fallbackSrc?: string | null
fallbackAlt?: string | null
fallbackWidth?: string | null
fallbackHeight?: string | null
caption?: string | null
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
rawHtml: {
@@ -218,7 +237,7 @@ declare module '@tiptap/core' {
}
embed: {
/** Inserts an embed placeholder for an allowlisted provider. */
setEmbed: (attributes: { provider: string; id: string }) => ReturnType
setEmbed: (attributes: SetEmbedAttributes) => ReturnType
}
figure: {
/** Inserts an image with a caption as figure, img and figcaption. */
@@ -324,12 +343,85 @@ export const RawHtml = Node.create<RawHtmlOptions>({
export interface EmbedOptions {
labels: Labels
providers: readonly ResolvedEmbedProvider[]
}
const EMBED_FIGURE_ATTRS = new Set(['data-embed', 'data-id', 'data-aspect', 'data-height'])
const EMBED_IMG_ATTRS = new Set(['src', 'alt', 'width', 'height'])
function parseEmbedFigure(
el: HTMLElement,
providers: readonly ResolvedEmbedProvider[],
): SetEmbedAttributes | null {
const provider = el.getAttribute('data-embed') ?? ''
const id = el.getAttribute('data-id') ?? ''
if (!isValidEmbed(providers, provider, id)) return null
for (const attr of Array.from(el.attributes)) {
if (!EMBED_FIGURE_ATTRS.has(attr.name.toLowerCase())) return null
}
const rawAspect = el.getAttribute('data-aspect')?.trim() ?? ''
if (rawAspect !== '' && !isValidAspect(rawAspect)) return null
const rawHeight = el.getAttribute('data-height')?.trim() ?? ''
if (rawHeight !== '' && !isValidHeight(rawHeight)) return null
let fallbackSrc: string | null = null
let fallbackAlt: string | null = null
let fallbackWidth: string | null = null
let fallbackHeight: string | null = null
let caption: string | null = null
let sawImg = false
let sawCaption = false
for (const child of Array.from(el.childNodes)) {
if (child.nodeType === 3) {
if (/[^ \t\r\n\f]/.test(child.nodeValue ?? '')) return null
continue
}
if (child.nodeType !== 1) return null
const childEl = child as Element
if (childEl.nodeName === 'IMG' && !sawImg) {
for (const attr of Array.from(childEl.attributes)) {
if (!EMBED_IMG_ATTRS.has(attr.name.toLowerCase())) return null
}
const src = childEl.getAttribute('src')?.trim() ?? ''
if (!src || /^\s*data:/i.test(src) || !isPolicyUrl(src)) return null
sawImg = true
fallbackSrc = src
fallbackAlt = childEl.getAttribute('alt') ?? ''
const w = childEl.getAttribute('width')?.trim() ?? ''
const h = childEl.getAttribute('height')?.trim() ?? ''
fallbackWidth = w || null
fallbackHeight = h || null
continue
}
if (childEl.nodeName === 'FIGCAPTION' && !sawCaption) {
if (childEl.attributes.length > 0 || childEl.children.length > 0) return null
sawCaption = true
caption = childEl.textContent ?? ''
continue
}
return null
}
return {
provider,
id,
aspect: rawAspect || null,
height: rawHeight || null,
fallbackSrc,
fallbackAlt,
fallbackWidth,
fallbackHeight,
caption: caption && caption.trim() !== '' ? caption : null,
}
}
/**
* Embed is the allowlisted video placeholder (D-05). It renders exactly
* <figure data-embed="PROVIDER" data-id="ID"></figure>; the editor shows a
* card and never an iframe. The layer expands the placeholder on the site.
* Embed is the allowlisted embed placeholder (D-05, Phase 38 D-06). It renders
* <figure data-embed="PROVIDER" data-id="ID">[optional <img> / <figcaption>]</figure>;
* the editor shows a card and never an iframe. The layer expands or hydrates
* the placeholder on the site.
*/
export const Embed = Node.create<EmbedOptions>({
name: 'embed',
@@ -340,59 +432,145 @@ export const Embed = Node.create<EmbedOptions>({
priority: 70,
addOptions() {
return { labels: labelsFor('en') }
return { labels: labelsFor('en'), providers: DEFAULT_EMBED_PROVIDERS }
},
addAttributes() {
return {
provider: { default: null, parseHTML: (element: HTMLElement) => element.getAttribute('data-embed'), renderHTML: () => ({}) },
id: { default: null, parseHTML: (element: HTMLElement) => element.getAttribute('data-id'), renderHTML: () => ({}) },
provider: { default: null, renderHTML: () => ({}) },
id: { default: null, renderHTML: () => ({}) },
aspect: { default: null, renderHTML: () => ({}) },
height: { default: null, renderHTML: () => ({}) },
fallbackSrc: { default: null, renderHTML: () => ({}) },
fallbackAlt: { default: null, renderHTML: () => ({}) },
fallbackWidth: { default: null, renderHTML: () => ({}) },
fallbackHeight: { default: null, renderHTML: () => ({}) },
caption: { default: null, renderHTML: () => ({}) },
}
},
parseHTML() {
const providers = this.options.providers
return [
{
tag: 'figure[data-embed]',
priority: 70,
getAttrs: (element) => {
const el = element as HTMLElement
const provider = el.getAttribute('data-embed') ?? ''
const id = el.getAttribute('data-id') ?? ''
// Exactly the placeholder: two attributes and no content.
if (el.attributes.length !== 2 || el.childNodes.length !== 0) return false
if (!isEmbedProvider(provider) || !EMBED_PROVIDERS[provider].idPattern.test(id)) return false
return null
const parsed = parseEmbedFigure(element as HTMLElement, providers)
return parsed ? { ...parsed } : false
},
},
]
},
renderHTML({ node }) {
return ['figure', { 'data-embed': node.attrs.provider, 'data-id': node.attrs.id }]
const figAttrs: Record<string, string> = {
'data-embed': String(node.attrs.provider ?? ''),
'data-id': String(node.attrs.id ?? ''),
}
const aspect = typeof node.attrs.aspect === 'string' ? node.attrs.aspect.trim() : ''
if (aspect && isValidAspect(aspect)) figAttrs['data-aspect'] = aspect
const height = typeof node.attrs.height === 'string' ? node.attrs.height.trim() : ''
if (height && isValidHeight(height)) figAttrs['data-height'] = height
const children: DOMOutputSpec[] = []
const fallbackSrc = typeof node.attrs.fallbackSrc === 'string' ? node.attrs.fallbackSrc.trim() : ''
if (fallbackSrc && isPolicyUrl(fallbackSrc)) {
const imgAttrs: Record<string, string> = {
src: fallbackSrc,
alt: typeof node.attrs.fallbackAlt === 'string' ? node.attrs.fallbackAlt : '',
}
const w = typeof node.attrs.fallbackWidth === 'string' ? node.attrs.fallbackWidth.trim() : ''
const h = typeof node.attrs.fallbackHeight === 'string' ? node.attrs.fallbackHeight.trim() : ''
if (w) imgAttrs.width = w
if (h) imgAttrs.height = h
children.push(['img', imgAttrs])
}
const caption = typeof node.attrs.caption === 'string' ? node.attrs.caption.trim() : ''
if (caption) {
children.push(['figcaption', {}, caption])
}
if (children.length === 0) {
return ['figure', figAttrs]
}
return ['figure', figAttrs, ...children]
},
addCommands() {
const providers = this.options.providers
return {
setEmbed:
({ provider, id }) =>
(attrs) =>
({ commands }) => {
if (!isEmbedProvider(provider) || !EMBED_PROVIDERS[provider].idPattern.test(id)) return false
return commands.insertContent({ type: this.name, attrs: { provider, id } })
const provider = String(attrs.provider ?? '').trim()
const id = String(attrs.id ?? '').trim()
if (!isValidEmbed(providers, provider, id)) return false
const aspect = attrs.aspect && isValidAspect(attrs.aspect) ? attrs.aspect.trim() : null
const height = attrs.height && isValidHeight(attrs.height) ? attrs.height.trim() : null
const rawSrc = attrs.fallbackSrc?.trim() ?? ''
const fallbackSrc = rawSrc && isPolicyUrl(rawSrc) ? rawSrc : null
const fallbackAlt = fallbackSrc ? (attrs.fallbackAlt ?? '') : null
const fallbackWidth = fallbackSrc && attrs.fallbackWidth ? String(attrs.fallbackWidth).trim() : null
const fallbackHeight = fallbackSrc && attrs.fallbackHeight ? String(attrs.fallbackHeight).trim() : null
const caption = attrs.caption?.trim() ? attrs.caption.trim() : null
return commands.insertContent({
type: this.name,
attrs: { provider, id, aspect, height, fallbackSrc, fallbackAlt, fallbackWidth, fallbackHeight, caption },
})
},
}
},
addNodeView() {
const labels = this.options.labels
const providers = this.options.providers
return ({ node }) => {
const dom = document.createElement('div')
dom.className = 'blogeditor__embed'
dom.contentEditable = 'false'
const render = (n: typeof node) => {
const provider = String(n.attrs.provider ?? '')
const name = isEmbedProvider(provider) ? EMBED_PROVIDERS[provider].name : provider
dom.textContent = `${labels.embedCard}: ${name} ${String(n.attrs.id ?? '')}`
const id = String(n.attrs.id ?? '')
const spec = findEmbedProvider(providers, provider)
const name = spec ? spec.name : provider
const aspect = typeof n.attrs.aspect === 'string' ? n.attrs.aspect.trim() : ''
const height = typeof n.attrs.height === 'string' ? n.attrs.height.trim() : ''
const fallbackSrc = typeof n.attrs.fallbackSrc === 'string' ? n.attrs.fallbackSrc.trim() : ''
const fallbackAlt = typeof n.attrs.fallbackAlt === 'string' ? n.attrs.fallbackAlt : ''
const caption = typeof n.attrs.caption === 'string' ? n.attrs.caption.trim() : ''
dom.replaceChildren()
if (!aspect && !height && !fallbackSrc && !caption) {
dom.textContent = `${labels.embedCard}: ${name} ${id}`
return
}
const head = document.createElement('div')
head.className = 'blogeditor__embed-head'
const title = document.createElement('span')
title.textContent = `${labels.embedCard}: ${name} ${id}`
head.append(title)
const meta = [aspect, height].filter(Boolean).join(' · ')
if (meta) {
const badge = document.createElement('span')
badge.className = 'blogeditor__embed-badge'
badge.textContent = meta
head.append(badge)
}
dom.append(head)
if (fallbackSrc && isPolicyUrl(fallbackSrc)) {
const img = document.createElement('img')
img.className = 'blogeditor__embed-thumb'
img.setAttribute('src', fallbackSrc)
img.setAttribute('alt', fallbackAlt)
dom.append(img)
}
if (caption) {
const cap = document.createElement('p')
cap.className = 'blogeditor__embed-caption'
cap.textContent = caption
dom.append(cap)
}
}
render(node)
let current = node
@@ -628,7 +806,11 @@ const SizedImage = Image.extend({
},
})
export function preservationExtensions(labels: Labels = labelsFor('en'), headingLevels: readonly number[] = DEFAULT_HEADING_LEVELS): AnyExtension[] {
export function preservationExtensions(
labels: Labels = labelsFor('en'),
headingLevels: readonly number[] = DEFAULT_HEADING_LEVELS,
embedProviders: readonly ResolvedEmbedProvider[] = DEFAULT_EMBED_PROVIDERS,
): AnyExtension[] {
const levels = schemaHeadingLevels(headingLevels)
return [
StarterKit.configure({
@@ -659,7 +841,7 @@ export function preservationExtensions(labels: Labels = labelsFor('en'), heading
Figure,
FigureImage,
Figcaption,
Embed.configure({ labels }),
Embed.configure({ labels, providers: embedProviders }),
RawHtml.configure({ labels }),
Span,
HtmlAttributes,

View File

@@ -40,6 +40,16 @@ export interface Labels {
embedUrl: string
embedInsert: string
embedInvalid: string
embedProvider: string
embedId: string
embedIdInvalid: string
embedFallbackImage: string
embedFallbackPick: string
embedFallbackAlt: string
embedCaption: string
embedAspect: string
embedHeight: string
embedGeneric: string
cancel: string
uploading: string
uploadFailed: string
@@ -115,6 +125,16 @@ const en: Labels = {
embedUrl: 'YouTube URL',
embedInsert: 'Insert',
embedInvalid: 'This video URL is not supported. Paste a YouTube link.',
embedProvider: 'Provider',
embedId: 'Embed ID',
embedIdInvalid: 'Enter a valid ID for this embed provider.',
embedFallbackImage: 'Fallback image URL (optional)',
embedFallbackPick: 'Choose from Media Library',
embedFallbackAlt: 'Fallback alt text (optional)',
embedCaption: 'Caption (optional)',
embedAspect: 'Aspect ratio (optional)',
embedHeight: 'Height (optional)',
embedGeneric: 'Embed',
cancel: 'Cancel',
uploading: 'Uploading {name}…',
uploadFailed: 'Upload failed: {error}',
@@ -187,6 +207,16 @@ const pl: Labels = {
embedUrl: 'Adres filmu YouTube',
embedInsert: 'Wstaw',
embedInvalid: 'Ten adres filmu nie jest obsługiwany. Wklej link do YouTube.',
embedProvider: 'Dostawca',
embedId: 'Identyfikator osadzenia',
embedIdInvalid: 'Wpisz poprawny identyfikator dla tego dostawcy.',
embedFallbackImage: 'Adres obrazu zastępczego (opcjonalny)',
embedFallbackPick: 'Wybierz z biblioteki mediów',
embedFallbackAlt: 'Tekst alternatywny obrazu (opcjonalny)',
embedCaption: 'Podpis (opcjonalny)',
embedAspect: 'Proporcje (opcjonalne)',
embedHeight: 'Wysokość (opcjonalna)',
embedGeneric: 'Osadź',
cancel: 'Anuluj',
uploading: 'Wysyłanie {name}…',
uploadFailed: 'Wysyłanie nie powiodło się: {error}',

View File

@@ -1,5 +1,10 @@
import { EMBED_PROVIDERS, isEmbedProvider } from './embed'
import { inert } from './extensions'
import {
DEFAULT_EMBED_PROVIDERS,
findEmbedProvider,
isValidEmbed,
type ResolvedEmbedProvider,
} from './embed'
import { inert, isPolicyUrl } from './extensions'
import type { Labels } from './labels'
/**
@@ -49,6 +54,7 @@ export interface PreviewOptions {
lang?: string | null
colors?: PreviewColors
fontFamily?: string
providers?: readonly ResolvedEmbedProvider[]
}
/** The host variable each preview colour is read from. */
@@ -107,7 +113,11 @@ export function youtubeThumbnail(id: string): string {
* (defense in depth on top of the sandbox) and each embed placeholder
* becomes a thumbnail card, never a player. The stored value never changes.
*/
export function previewBody(html: string, labels: Labels): string {
export function previewBody(
html: string,
labels: Labels,
providers: readonly ResolvedEmbedProvider[] = DEFAULT_EMBED_PROVIDERS,
): string {
const doc = inert()
const template = doc.createElement('template')
template.innerHTML = html
@@ -123,21 +133,63 @@ export function previewBody(html: string, labels: Labels): string {
for (const figure of Array.from(root.querySelectorAll('figure[data-embed]'))) {
const provider = figure.getAttribute('data-embed') ?? ''
const id = figure.getAttribute('data-id') ?? ''
// Exactly the editor's placeholder, the same test as the Embed node.
if (figure.attributes.length !== 2 || figure.childNodes.length !== 0) continue
if (!isEmbedProvider(provider) || !EMBED_PROVIDERS[provider].idPattern.test(id)) continue
if (!isValidEmbed(providers, provider, id)) continue
const spec = findEmbedProvider(providers, provider)
const providerName = spec?.name ?? provider
const fallbackImg = figure.querySelector('img[src]')
const fallbackSrc = fallbackImg?.getAttribute('src')?.trim() ?? ''
const fallbackCaption = figure.querySelector('figcaption')?.textContent?.trim() ?? ''
if (fallbackImg && fallbackSrc !== '' && isPolicyUrl(fallbackSrc)) {
const card = doc.createElement('figure')
card.className = 'embed-card'
const img = doc.createElement('img')
img.setAttribute('src', fallbackSrc)
img.setAttribute('alt', fallbackImg.getAttribute('alt') ?? '')
const w = fallbackImg.getAttribute('width')
const h = fallbackImg.getAttribute('height')
if (w) img.setAttribute('width', w)
if (h) img.setAttribute('height', h)
img.setAttribute('referrerpolicy', 'no-referrer')
img.setAttribute('loading', 'lazy')
const caption = doc.createElement('figcaption')
caption.textContent = fallbackCaption || `${labels.embedCard}: ${providerName} ${id}`
card.append(img, caption)
figure.replaceWith(card)
continue
}
if (provider === 'youtube' && figure.childNodes.length === 0) {
const card = doc.createElement('figure')
card.className = 'embed-card'
const img = doc.createElement('img')
img.setAttribute('src', youtubeThumbnail(id))
img.setAttribute('alt', '')
img.setAttribute('referrerpolicy', 'no-referrer')
img.setAttribute('loading', 'lazy')
img.setAttribute('width', '480')
img.setAttribute('height', '360')
const caption = doc.createElement('figcaption')
caption.textContent = `${labels.embedCard}: ${providerName} ${id}`
card.append(img, caption)
figure.replaceWith(card)
continue
}
const card = doc.createElement('figure')
card.className = 'embed-card'
const img = doc.createElement('img')
img.setAttribute('src', youtubeThumbnail(id))
img.setAttribute('alt', '')
img.setAttribute('referrerpolicy', 'no-referrer')
img.setAttribute('loading', 'lazy')
img.setAttribute('width', '480')
img.setAttribute('height', '360')
const caption = doc.createElement('figcaption')
caption.textContent = `${labels.embedCard}: ${EMBED_PROVIDERS[provider].name} ${id}`
card.append(img, caption)
const box = doc.createElement('div')
box.className = 'embed-card__placeholder'
const aspect = figure.getAttribute('data-aspect')?.trim() ?? ''
const height = figure.getAttribute('data-height')?.trim() ?? ''
const meta = [aspect, height].filter(Boolean).join(' · ')
box.textContent = meta ? `${providerName}: ${id} (${meta})` : `${providerName}: ${id}`
card.append(box)
if (fallbackCaption) {
const caption = doc.createElement('figcaption')
caption.textContent = fallbackCaption
card.append(caption)
}
figure.replaceWith(card)
}
@@ -169,6 +221,7 @@ function previewStyles(c: PreviewColors, font: string): string {
`figcaption{font-size:13px;color:${c.muted};margin-top:4px}`,
`.embed-card{max-width:480px;border:1px solid ${c.border};border-radius:8px;overflow:hidden;background:${c.subtle}}`,
'.embed-card img{display:block;width:100%;height:auto;aspect-ratio:16/9;object-fit:cover}',
`.embed-card__placeholder{padding:24px 16px;text-align:center;font-size:14px;color:${c.muted}}`,
'.embed-card figcaption{padding:8px 12px;margin:0}',
].join('\n')
}
@@ -191,7 +244,7 @@ export function buildPreviewDocument(html: string, options: PreviewOptions): str
'<meta name="referrer" content="no-referrer">' +
`<style>${previewStyles(colors, font)}</style>` +
'</head><body>' +
`<article class="post-body">${previewBody(html, options.labels)}</article>` +
`<article class="post-body">${previewBody(html, options.labels, options.providers)}</article>` +
'</body></html>'
)
}

View File

@@ -25,11 +25,16 @@ function openOutline(el: HTMLElement): HTMLElement {
describe('options', () => {
it('reads headingLevels and genericAnchors with defaults', () => {
expect(readOptions(null)).toEqual({ headingLevels: [2, 3, 4], genericAnchors: expect.arrayContaining(['click here', 'czytaj więcej']) })
expect(readOptions(null)).toEqual({
headingLevels: [2, 3, 4],
genericAnchors: expect.arrayContaining(['click here', 'czytaj więcej']),
embedProviders: [expect.objectContaining({ key: 'youtube', mode: 'url' })],
})
expect(readOptions('not json').headingLevels).toEqual([2, 3, 4])
expect(readOptions(JSON.stringify({ headingLevels: [4, 1, 9, 'x', 2.5, 2], genericAnchors: [' Read More! ', 3] }))).toEqual({
headingLevels: [1, 2, 4],
genericAnchors: ['read more'],
embedProviders: [expect.objectContaining({ key: 'youtube', mode: 'url' })],
})
})
})