Files
KantSites/public/assets/rich-text.js
T
kantarciandClaude Opus 5 790f42213c Formatierter Text mit Werkzeugleiste und HTML-Ansicht (Schema v12)
Textblöcke dürfen ab v12 Auszeichnung tragen: fett, kursiv,
unterstrichen, durchgestrichen, Code, hervorgehoben, hoch- und
tiefgestellt, Absätze, Listen und Links.

Die Entscheidung, was erlaubt ist, fällt auf dem Server beim
Speichern - nicht im Editor und nicht beim Rendern. Was in der
Datenbank landet, ist damit schon sicher, also kann kein Renderer das
Filtern vergessen, und eine manipulierte Anfrage speichert nichts,
was der Editor nicht anbietet.

Nicht erlaubte Elemente werden ausgepackt, nicht gelöscht: der Text
bleibt, nur die Auszeichnung geht. script, style, iframe und
Verwandte verschwinden samt Inhalt, weil Auspacken ihren Code als
Text sichtbar machen würde. Attribute fallen weg außer href an a,
und auch das nur nach Adressprüfung.

Ausgegeben wird formatierter Text nur ab v12, dann in einem div statt
einem p, weil die Positivliste Absätze und Listen enthält. Ältere
Dokumente behalten Klartextsemantik und werden weiter maskiert.

Eine Inkonsistenz nebenbei behoben: ein Text mit einem < behielt
echte Zeilenumbrüche, während alles andere <br> benutzte.

Geprüft: 182 PHP-Tests / 685 Assertions unter PHP 8.2.12 und 8.4.22,
darunter dreizehn Fälle durch den Filter mit acht Angriffen, dazu
Editortest mit axe und öffentliche Browserprüfung. Die Werkzeugleiste
selbst ist nicht bedient und nicht mit einem Screenreader geprüft.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-12 16:54:35 +02:00

143 lines
5.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Formatted text for text blocks.
*
* Two views on the same value: a formatting view with a toolbar and an HTML view with the markup.
* Whatever is typed here is a *proposal* – the server filters it against its allowlist when it is
* stored, so this file never decides what is allowed. It only offers what the allowlist accepts.
*
* execCommand is deprecated but is still the only thing every browser implements for this job, and
* the alternative would be a selection engine of our own. The formatting it produces is normalised
* on the server anyway, so a browser quirk cannot store something unexpected.
*/
/** Mirrors RichText::ALLOWED. Only used for the hint text and for cleaning up on paste. */
export const ALLOWED_TAGS = ['p', 'br', 'strong', 'b', 'em', 'i', 'u', 's', 'code', 'mark', 'sup', 'sub', 'ul', 'ol', 'li', 'a'];
const COMMANDS = [
{ command: 'bold', label: 'B', title: 'Fett (Strg+B)', style: 'font-weight:700' },
{ command: 'italic', label: 'I', title: 'Kursiv (Strg+I)', style: 'font-style:italic' },
{ command: 'underline', label: 'U', title: 'Unterstrichen (Strg+U)', style: 'text-decoration:underline' },
{ command: 'strikeThrough', label: 'S', title: 'Durchgestrichen', style: 'text-decoration:line-through' },
{ command: 'insertUnorderedList', label: '•', title: 'Liste' },
{ command: 'insertOrderedList', label: '1.', title: 'Nummerierte Liste' },
{ command: 'removeFormat', label: '⌫', title: 'Formatierung entfernen' },
];
function button(label, title, onClick, className = 'rt-button') {
const node = document.createElement('button');
node.type = 'button';
node.className = className;
node.textContent = label;
node.title = title;
node.setAttribute('aria-label', title);
node.addEventListener('mousedown', event => event.preventDefault()); // keep the selection
node.addEventListener('click', onClick);
return node;
}
/**
* Builds the control. `apply` is called with the markup whenever it changes; the caller decides
* what to do with it (history entry, preview refresh).
*/
export function createRichText(value, apply, { label = 'Text' } = {}) {
const wrap = document.createElement('div');
wrap.className = 'rich-text';
const bar = document.createElement('div');
bar.className = 'rt-bar';
bar.setAttribute('role', 'toolbar');
bar.setAttribute('aria-label', `${label} formatieren`);
const surface = document.createElement('div');
surface.className = 'rt-surface';
surface.contentEditable = 'true';
surface.spellcheck = true;
surface.setAttribute('role', 'textbox');
surface.setAttribute('aria-multiline', 'true');
surface.setAttribute('aria-label', label);
surface.innerHTML = value ?? '';
const source = document.createElement('textarea');
source.className = 'rt-source';
source.hidden = true;
source.setAttribute('aria-label', `${label} als HTML`);
source.value = value ?? '';
const push = markup => { source.value = markup; apply(markup); };
for (const entry of COMMANDS) {
const node = button(entry.label, entry.title, () => {
surface.focus();
document.execCommand(entry.command);
push(surface.innerHTML);
});
if (entry.style) node.style.cssText = entry.style;
bar.append(node);
}
// Link insertion without a browser prompt: a field appears in the bar and takes the target.
const linkRow = document.createElement('div');
linkRow.className = 'rt-link';
linkRow.hidden = true;
const linkInput = document.createElement('input');
linkInput.type = 'text';
linkInput.placeholder = '/kontakt, #abschnitt, https://…, mailto:…';
linkInput.setAttribute('aria-label', 'Linkziel');
let savedRange = null;
const confirmLink = () => {
const target = linkInput.value.trim();
linkRow.hidden = true;
surface.focus();
if (savedRange) {
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(savedRange);
}
if (target) document.execCommand('createLink', false, target);
else document.execCommand('unlink');
push(surface.innerHTML);
linkInput.value = '';
};
linkInput.addEventListener('keydown', event => {
if ('Enter' === event.key) { event.preventDefault(); confirmLink(); }
if ('Escape' === event.key) { event.preventDefault(); linkRow.hidden = true; surface.focus(); }
});
linkRow.append(linkInput, button('Übernehmen', 'Linkziel übernehmen', confirmLink, 'text-button'));
bar.append(button('🔗', 'Link setzen oder entfernen', () => {
const selection = window.getSelection();
savedRange = selection.rangeCount > 0 ? selection.getRangeAt(0).cloneRange() : null;
linkRow.hidden = false;
linkInput.focus();
}));
const toggle = button('HTML', 'Zwischen Formatierung und HTML wechseln', () => {
const toSource = source.hidden;
if (toSource) {
source.value = surface.innerHTML;
} else {
surface.innerHTML = source.value;
apply(source.value);
}
source.hidden = !toSource;
surface.hidden = toSource;
toggle.setAttribute('aria-pressed', String(toSource));
(toSource ? source : surface).focus();
}, 'rt-button rt-toggle');
toggle.setAttribute('aria-pressed', 'false');
bar.append(toggle);
surface.addEventListener('input', () => push(surface.innerHTML));
// Paste as plain text: pasted markup would be stripped on the server anyway, and pasting a
// whole web page into a text block is never what someone means.
surface.addEventListener('paste', event => {
event.preventDefault();
const text = event.clipboardData?.getData('text/plain') ?? '';
document.execCommand('insertText', false, text);
});
source.addEventListener('change', () => { surface.innerHTML = source.value; apply(source.value); });
wrap.append(bar, linkRow, surface, source);
return { element: wrap, focus: () => surface.focus() };
}