feat(17-02): richeditor field on TipTap with the untouched rule
- RichEditorField: Reka toolbar, link popover with the http/https/mailto/tel and relative URL policy, Edit HTML view, lossy note, skeleton while the lazily imported TipTap chunk loads, HTML view fallback when it fails - untouched values are submitted byte-identical; after an edit the value is the editor HTML (empty paragraph -> ""); a value from outside (the save's sanitized answer) reloads the editor - read-only renders through a client display allowlist, never as stored - TipTap 3.31.4 (core, pm, starter-kit) pinned exact after the package check - richeditor.* phrase keys (en, pl), smoke specs, forms docs
This commit is contained in:
133
admin/src/components/form/richeditor/LinkPopover.vue
Normal file
133
admin/src/components/form/richeditor/LinkPopover.vue
Normal file
@@ -0,0 +1,133 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from 'vue'
|
||||
import { CircleAlert } from '@lucide/vue'
|
||||
import { PopoverAnchor, PopoverContent, PopoverPortal, PopoverRoot } from 'reka-ui'
|
||||
import { t } from '../../../app/i18n'
|
||||
import Button from '../../ui/Button.vue'
|
||||
import { controlClass } from '../control'
|
||||
import { isAllowedLink } from './html'
|
||||
|
||||
// The richeditor link popover (UI-SPEC RichEditorField, "Link popover"),
|
||||
// anchored on the toolbar's Link button (the default slot). Enter applies,
|
||||
// Esc closes; on close the field decides where focus goes (`closed` tells it
|
||||
// whether a link was applied or removed). A URL outside the client policy
|
||||
// (http, https, mailto, tel or relative) shows richeditor.link_invalid and
|
||||
// is not applied; the server sanitizer is still the gate.
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
/** The current link's href, or "" when the selection is not in a link. */
|
||||
href: string
|
||||
/** Whether the selection is inside a link: offers "Remove link". */
|
||||
inLink: boolean
|
||||
/** Prefix of the element ids. */
|
||||
idPrefix: string
|
||||
}>()
|
||||
const emit = defineEmits<{
|
||||
apply: [url: string]
|
||||
remove: []
|
||||
/** Esc or a click outside asks to close. */
|
||||
'update:open': [open: boolean]
|
||||
/** The popover has closed; `changed` is true after apply or remove. */
|
||||
closed: [changed: boolean]
|
||||
}>()
|
||||
|
||||
const url = ref('')
|
||||
const invalid = ref(false)
|
||||
const input = ref<HTMLInputElement | null>(null)
|
||||
let changed = false
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
async (open) => {
|
||||
if (!open) {
|
||||
return
|
||||
}
|
||||
url.value = props.href
|
||||
invalid.value = false
|
||||
changed = false
|
||||
await nextTick()
|
||||
input.value?.focus()
|
||||
input.value?.select()
|
||||
},
|
||||
)
|
||||
|
||||
function apply(): void {
|
||||
const value = url.value.trim()
|
||||
if (!isAllowedLink(value)) {
|
||||
invalid.value = true
|
||||
input.value?.focus()
|
||||
return
|
||||
}
|
||||
changed = true
|
||||
emit('apply', value)
|
||||
}
|
||||
|
||||
function remove(): void {
|
||||
changed = true
|
||||
emit('remove')
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'Enter') {
|
||||
// The popover sits in a form: Enter applies the link, it never submits.
|
||||
event.preventDefault()
|
||||
apply()
|
||||
}
|
||||
}
|
||||
|
||||
function onOpenChange(open: boolean): void {
|
||||
emit('update:open', open)
|
||||
}
|
||||
|
||||
function onCloseAutoFocus(event: Event): void {
|
||||
// There is no trigger to return to: the field focuses the Link button or
|
||||
// the editor itself.
|
||||
event.preventDefault()
|
||||
emit('closed', changed)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PopoverRoot :open="open" @update:open="onOpenChange">
|
||||
<PopoverAnchor as-child>
|
||||
<slot />
|
||||
</PopoverAnchor>
|
||||
<PopoverPortal>
|
||||
<PopoverContent
|
||||
data-richeditor-link
|
||||
align="start"
|
||||
:side-offset="8"
|
||||
class="z-50 flex w-[320px] flex-col gap-2 rounded-inner border border-border bg-surface p-4 text-text shadow-menu"
|
||||
@close-auto-focus="onCloseAutoFocus"
|
||||
>
|
||||
<label :for="`${idPrefix}-link-url`" class="font-semibold">{{ t('backend::lang.richeditor.link_url') }}</label>
|
||||
<input
|
||||
:id="`${idPrefix}-link-url`"
|
||||
ref="input"
|
||||
v-model="url"
|
||||
type="url"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:class="controlClass(invalid)"
|
||||
class="h-input"
|
||||
:aria-invalid="invalid ? 'true' : undefined"
|
||||
:aria-describedby="invalid ? `${idPrefix}-link-error` : undefined"
|
||||
@input="invalid = false"
|
||||
@keydown="onKeydown"
|
||||
/>
|
||||
<p v-if="invalid" :id="`${idPrefix}-link-error`" class="flex items-center gap-1.5 text-[13px] text-danger">
|
||||
<CircleAlert :size="14" class="shrink-0" aria-hidden="true" />
|
||||
<span>{{ t('backend::lang.richeditor.link_invalid') }}</span>
|
||||
</p>
|
||||
<div class="flex justify-end gap-2">
|
||||
<Button v-if="inLink" variant="ghost" size="sm" data-action="richeditor-unlink" @click="remove">
|
||||
{{ t('backend::lang.richeditor.unlink') }}
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" data-action="richeditor-link-apply" @click="apply">
|
||||
{{ t('backend::lang.richeditor.link_apply') }}
|
||||
</Button>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</PopoverPortal>
|
||||
</PopoverRoot>
|
||||
</template>
|
||||
71
admin/src/components/form/richeditor/editor.ts
Normal file
71
admin/src/components/form/richeditor/editor.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
// The TipTap editor of the richeditor field (D-10). RichEditorField loads
|
||||
// this module with a dynamic import, so TipTap is its own chunk and a form
|
||||
// without a richeditor never downloads it. The editor mounts on an element
|
||||
// the field owns (no @tiptap/vue-3) with StarterKit configured as the
|
||||
// UI-SPEC says: headings level 3 only; no code, code block or horizontal
|
||||
// rule; links that never open on click, never autolink and take only the
|
||||
// policy URLs; no trailing node (it would append a paragraph and count as an
|
||||
// edit); TipTap's injected CSS off, the content uses .summer-markdown.
|
||||
import { Editor } from '@tiptap/core'
|
||||
import StarterKit from '@tiptap/starter-kit'
|
||||
import { LINK_SCHEMES, isAllowedLink } from './html'
|
||||
|
||||
export type { Editor }
|
||||
|
||||
export interface RichEditorOptions {
|
||||
/** The element the editing area mounts in. */
|
||||
element: HTMLElement
|
||||
/** The stored HTML, parsed once; the field keeps the string itself. */
|
||||
content: string
|
||||
/** Attributes of the editing area (class, role, aria-*). */
|
||||
attributes: Record<string, string>
|
||||
/** Called after every transaction that changed the document. */
|
||||
onChange: () => void
|
||||
/** Called after every transaction (toolbar state). */
|
||||
onTransaction: () => void
|
||||
}
|
||||
|
||||
/** Builds the field's editor on options.element. */
|
||||
export function createRichEditor(options: RichEditorOptions): Editor {
|
||||
return new Editor({
|
||||
element: options.element,
|
||||
injectCSS: false,
|
||||
content: options.content,
|
||||
extensions: [
|
||||
StarterKit.configure({
|
||||
heading: { levels: [3] },
|
||||
code: false,
|
||||
codeBlock: false,
|
||||
horizontalRule: false,
|
||||
trailingNode: false,
|
||||
link: {
|
||||
openOnClick: false,
|
||||
autolink: false,
|
||||
protocols: [...LINK_SCHEMES],
|
||||
HTMLAttributes: { target: null, rel: null, class: null },
|
||||
isAllowedUri: (url) => isAllowedLink(url),
|
||||
},
|
||||
}),
|
||||
],
|
||||
editorProps: { attributes: options.attributes },
|
||||
onUpdate: ({ transaction, appendedTransactions }) => {
|
||||
if (transaction.docChanged || appendedTransactions.some((tr) => tr.docChanged)) {
|
||||
options.onChange()
|
||||
}
|
||||
},
|
||||
onTransaction: () => options.onTransaction(),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the document with html without an update event and outside the
|
||||
* undo history, so neither the untouched rule nor undo sees the load.
|
||||
*/
|
||||
export function loadContent(editor: Editor, html: string): void {
|
||||
editor.chain().setMeta('addToHistory', false).setContent(html, { emitUpdate: false }).run()
|
||||
}
|
||||
|
||||
/** The editor's value: its HTML, or "" when it holds only an empty paragraph. */
|
||||
export function editorValue(editor: Editor): string {
|
||||
return editor.isEmpty ? '' : editor.getHTML()
|
||||
}
|
||||
104
admin/src/components/form/richeditor/html.ts
Normal file
104
admin/src/components/form/richeditor/html.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
// Link and display policy of the richeditor field (D-10, T-17-10, T-17-11).
|
||||
// The server sanitizer (seaglass) is the gate on every save; these client
|
||||
// checks keep the editor from offering what the gate would remove and keep a
|
||||
// stored value that predates the gate from running in the admin.
|
||||
import { EDITOR_TAGS, inertFragment } from './lossy'
|
||||
|
||||
/** Link schemes the editor applies; anything else must be a relative URL. */
|
||||
export const LINK_SCHEMES: readonly string[] = ['http', 'https', 'mailto', 'tel']
|
||||
|
||||
// Browsers ignore ASCII control characters, spaces and DEL inside a scheme,
|
||||
// so "java\tscript:" is read with them removed.
|
||||
const URL_IGNORED = /[\x00-\x20\x7f]+/g
|
||||
const URL_SCHEME = /^([a-z][a-z0-9+.-]*):/i
|
||||
|
||||
/**
|
||||
* Whether url may be a link href: an http, https, mailto or tel URL, or a
|
||||
* relative one (a path starting with /, #, ? or ./, or a bare relative path).
|
||||
*/
|
||||
export function isAllowedLink(url: string | null | undefined): boolean {
|
||||
if (url == null) {
|
||||
return false
|
||||
}
|
||||
const cleaned = url.replace(URL_IGNORED, '')
|
||||
if (cleaned === '') {
|
||||
return false
|
||||
}
|
||||
const scheme = URL_SCHEME.exec(cleaned)
|
||||
if (scheme) {
|
||||
return LINK_SCHEMES.includes(scheme[1]!.toLowerCase())
|
||||
}
|
||||
try {
|
||||
new URL(cleaned, 'https://admin.invalid/')
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** Elements dropped with their content when a value is displayed. */
|
||||
const DROPPED = new Set([
|
||||
'script',
|
||||
'style',
|
||||
'template',
|
||||
'noscript',
|
||||
'iframe',
|
||||
'frame',
|
||||
'frameset',
|
||||
'object',
|
||||
'embed',
|
||||
'applet',
|
||||
'svg',
|
||||
'math',
|
||||
'title',
|
||||
'head',
|
||||
'meta',
|
||||
'link',
|
||||
'base',
|
||||
])
|
||||
|
||||
function clean(parent: ParentNode): void {
|
||||
for (const node of Array.from(parent.childNodes)) {
|
||||
if (node.nodeType === Node.COMMENT_NODE) {
|
||||
node.remove()
|
||||
continue
|
||||
}
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) {
|
||||
continue
|
||||
}
|
||||
const element = node as Element
|
||||
const name = element.localName.toLowerCase()
|
||||
if (DROPPED.has(name)) {
|
||||
element.remove()
|
||||
continue
|
||||
}
|
||||
clean(element)
|
||||
if (!EDITOR_TAGS.has(name)) {
|
||||
// Another element keeps its text: its children take its place.
|
||||
element.replaceWith(...Array.from(element.childNodes))
|
||||
continue
|
||||
}
|
||||
for (const attribute of Array.from(element.attributes)) {
|
||||
const keep = name === 'a' && attribute.name === 'href' && isAllowedLink(attribute.value)
|
||||
if (!keep) {
|
||||
element.removeAttribute(attribute.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The read-only rendering of a stored value: only the editor's elements,
|
||||
* only allowed link hrefs, no other attribute, no comment. It is what may be
|
||||
* bound as HTML in the admin; the stored value itself is never bound.
|
||||
*/
|
||||
export function displayHtml(html: string): string {
|
||||
if (html === '') {
|
||||
return ''
|
||||
}
|
||||
const fragment = inertFragment(html)
|
||||
clean(fragment)
|
||||
const holder = document.createElement('div')
|
||||
holder.append(fragment)
|
||||
return holder.innerHTML
|
||||
}
|
||||
52
admin/src/components/form/richeditor/lossy.ts
Normal file
52
admin/src/components/form/richeditor/lossy.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
// What the richeditor's TipTap schema can show (UI-SPEC RichEditorField,
|
||||
// "Lossy note"). Stored HTML with any other element still opens: the field
|
||||
// keeps the stored string until the administrator edits (the untouched
|
||||
// rule), and the HTML view edits it without loss. This module has no TipTap
|
||||
// import, so the field can decide before the editor chunk loads.
|
||||
|
||||
/** Elements the editor shows; compared by lower-cased tag name. */
|
||||
export const EDITOR_TAGS: ReadonlySet<string> = new Set([
|
||||
'p',
|
||||
'br',
|
||||
'strong',
|
||||
'b',
|
||||
'em',
|
||||
'i',
|
||||
'u',
|
||||
's',
|
||||
'h3',
|
||||
'ul',
|
||||
'ol',
|
||||
'li',
|
||||
'blockquote',
|
||||
'a',
|
||||
'div',
|
||||
'span',
|
||||
])
|
||||
|
||||
/**
|
||||
* Parses html into an inert template: nothing in it runs or loads (no
|
||||
* scripts, no image requests), so stored markup can be inspected safely.
|
||||
*/
|
||||
export function inertFragment(html: string): DocumentFragment {
|
||||
const template = document.createElement('template')
|
||||
template.innerHTML = html
|
||||
return template.content
|
||||
}
|
||||
|
||||
/** The distinct lower-cased tag names of html's elements, in document order. */
|
||||
export function tagNames(html: string): string[] {
|
||||
if (html === '') {
|
||||
return []
|
||||
}
|
||||
const out = new Set<string>()
|
||||
for (const element of Array.from(inertFragment(html).querySelectorAll('*'))) {
|
||||
out.add(element.localName.toLowerCase())
|
||||
}
|
||||
return [...out]
|
||||
}
|
||||
|
||||
/** Whether html holds an element the editor cannot show (the lossy note). */
|
||||
export function isLossy(html: string): boolean {
|
||||
return tagNames(html).some((name) => !EDITOR_TAGS.has(name))
|
||||
}
|
||||
Reference in New Issue
Block a user