Speichere formatierte Texte als bereinigtes HTML mit einem Editor (ADR-50)

Ein Baustein (FormattedText) bereinigt, bringt Werte in die kanonische Form und
wandelt Klartext des Altbestands; RichField ist der eine Editor, ManagesRichFields
verbindet ihn mit den Arbeitsplätzen. Formatiert sind Texte der Übungen und
Textbausteine, Kurzbeschreibung und Beschreibung, Lernziel und Ausstattung.
Mitgliederansicht und PDF zeigen fett, kursiv, Listen, Überschrift, Zitat und Link
(PDF: schräge Schnitte, nur wenn gebraucht). Das Livewire-Limit für verschachtelte
Pfade steigt auf 30, weil Aufzählungen sonst abgelehnt werden.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Sonnet 5.5 committed 2026-11-23 23:45:54 +01:00
1 parent be24f3bf64
commit 9fbd933e1e
50 files changed
+1461 -181

No files matched your search

+1
View File
@@ -65,5 +65,6 @@ ## Verwaltungsoberfläche
- Maßgeblich sind `docs/ux/verwaltung/14-verwaltungsstandard.md` (Design und Interaktion) und `15-umbauauftrag.md` (Auftrag, Nachweise). Keine neue allgemeine Designabstimmung verlangen. Einstieg für alle Agenten: `AGENTS.md`, `.cursor/rules/verwaltung-ux.mdc`.
- Gemeinsame Bausteine wiederverwenden statt neue Masken bauen: `resources/views/filament/verwaltung/` (`kopf`, `redaktion`, `texte`, `praesentation`, `einordnung`, `picker`, `bestaetigung`, `abgang`, `aufbau`, `bestand`) mit dem Trait `App\Filament\Support\ManagesEditorialSurface`. Listen nutzen `verwaltung/bestand` mit `ShowsBestand` (bzw. `ListsCompositions`, `ListsCatalog`) und den Eintrag `<x-vw.eintrag>`, den auch der Picker verwendet; Katalogobjekte die Seite `catalog/objekt`. CMS: Seitenkopf `cms/seite-kopf` (Register, Kontexte „Abschnitt gestalten“ und „Konfigurieren“); Seiten und Menüs in der Webpräsenz (`App\Filament\Pages\Webpraesenz`, Menüs als Arbeitsstand mit einer Speicherhandlung). Der Picker liegt im Trait `ChoosesMedia` (Redaktion über `ManagesEditorialSurface`, CMS-Bilder über `ChoosesWebsiteImages`); keine eigenen Auswahllisten für Medien bauen. Redaktionelle Auswahlwerte (Materialart, Einordnung) nur über `App\Domain\Catalog\EditorialVocabulary` anbieten und prüfen (aktiv, zulässiger Kontext, vorhandene Zuordnungen erhalten); gepflegt werden sie unter „Redaktionelle Stammdaten“. Fachliche Säulen gibt es nur in der Säulenverwaltung (`pillars`); Zuordnung über `PillarService::assign`, nie über eine Dimension. Ersetzt eine Seite die Filament-Tabelle, muss sie den Dialogbereich ausgeben (in `bestand` enthalten), sonst öffnen „… anlegen“-Dialoge nicht. Gestaltungswerte nur in `verwaltung/styles.blade.php` (Tokens `--vw-…`, dokumentiert in `docs/ux/verwaltung/tokens.md`).
- Formatierte Texte (ADR-50): gespeichert wird bereinigtes HTML aus fester Auswahl, bearbeitet mit dem einen Editor `App\Filament\Support\RichField`, in den Arbeitsplätzen über `ManagesRichFields` (`richFelder()`, `kind => 'rich'`). Ausgabe nur über `App\Domain\Catalog\FormattedText` (`html()`, `display()`, `plain()`, `blocks()` fürs PDF), nie ungeprüft; verglichen wird nur `FormattedText::same()`/`canonical()`. Klartext des Altbestands bleibt in der Datenbank, bis jemand ihn ändert. Keine eigenen Textfelder mit `textarea` für Texte, die formatiert sein sollen.
- Die Redaktion ist ein Arbeitsstand: nur „Redaktion speichern“ schreibt Texte, Einordnung, Präsentationsmedien und Abweichungen. Kein verdecktes Mitspeichern aus anderen Dialogen, offene Eingaben bleiben beim Wechsel erhalten.
- Jede UI-Änderung in der echten Anwendung prüfen (luf-test, breite und schmale Fenster, Tastatur) und mit Screenshots in `docs/ux/verwaltung/abnahme/` belegen. Stand der Abnahme: `abnahme/teil-a.md`, `abnahme/teil-b.md`, `abnahme/teil-c.md`, `abnahme/stammdaten.md`.
+23
View File
@@ -27,11 +27,34 @@ public function text(string $field): ResolvedText
return $this->texts[$field] ?? new ResolvedText(null, 'leer', null);
}
/**
* Text einer Angabe. Formatierte Angaben (Kurzbeschreibung, Beschreibung) kommen hier als Klartext, damit nirgends
* Auszeichnung in Karten, Listen, Suchergebnisse oder Meta-Angaben gelangt; wer die Formatierung zeigt, nutzt
* {@see self::html()}.
*/
public function value(string $field): ?string
{
$value = $this->text($field)->value;
if ($value !== null && in_array($field, FormattedText::FIELDS, true)) {
return FormattedText::plain($value) ?: null;
}
return $value;
}
/** Gespeicherter Wert unverändert (HTML oder Klartext des Altbestands), für Bearbeitung und Vergleich. */
public function raw(string $field): ?string
{
return $this->text($field)->value;
}
/** Sicheres HTML einer formatierten Angabe; leer, wenn nichts da ist. */
public function html(string $field): string
{
return FormattedText::html($this->text($field)->value);
}
public function origin(string $field): string
{
return $this->text($field)->origin;
+3 -1
View File
@@ -145,7 +145,8 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
'grant' => $decision->grant,
'download_grant' => $download?->grant,
'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
'blocks' => $decision->allowed && $class === 'text' ? GuideText::blocks($version->body) : null,
'blocks' => $decision->allowed && $class === 'text' ? FormattedText::blocks($version->body) : null,
'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body) : null,
];
}
@@ -169,6 +170,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
'exercise' => $exercise,
'title' => $library->text($exercise->composition)['title'],
'summary' => $library->text($exercise->composition)['summary'],
'summary_html' => $library->text($exercise->composition)['summary_html'],
'learning_goal' => $exercise->learning_goal,
'duration_minutes' => $exercise->duration_minutes,
'duration_max' => $exercise->duration_max,
+158 -30
View File
@@ -77,17 +77,18 @@ public function render(array $guide, array $sections, string $licensee, string $
$this->write(self::printable('Variante: '.$variantName), 11, true, 6);
}
$facts = array_filter([
filled($guide['learning_goal']) ? 'Lernziel: '.$guide['learning_goal'] : null,
$guide['duration_minutes'] !== null ? 'Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten' : null,
filled($guide['prerequisites']) ? 'Voraussetzungen: '.$guide['prerequisites'] : null,
filled($guide['material_note']) ? 'Ausstattung: '.$guide['material_note'] : null,
]);
$this->fact('Lernziel', $guide['learning_goal']);
foreach ($facts as $fact) {
$this->write(self::printable($fact), 10.5, false, 4);
if ($guide['duration_minutes'] !== null) {
$this->write(self::printable('Dauer: '.$guide['duration_minutes'].($guide['duration_max'] !== null ? ' bis '.$guide['duration_max'] : '').' Minuten'), 10.5, false, 4);
}
if (filled($guide['prerequisites'])) {
$this->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4);
}
$this->fact('Ausstattung', $guide['material_note']);
$this->y -= 6;
foreach ($sections as $section) {
@@ -137,41 +138,168 @@ private function section(array $section, string $guideUrl): void
$this->write($title, 12.5, true, 5);
foreach ($section['blocks'] ?? [] as $block) {
match ($block['type']) {
'heading' => $this->write(self::printable($block['text']), 11, true, 4),
'paragraph' => $this->write(self::printable($block['text']), 10.5, false, 5),
'bullets' => $this->items($block['items'], fn (int $n): string => '•'),
'numbered' => $this->items($block['items'], fn (int $n): string => $n.'.'),
};
}
$this->formatted($section['blocks'] ?? []);
$this->y -= 4;
}
/** Angabe mit Bezeichnung; formatierte Angaben stehen unter der Bezeichnung, einfache dahinter. */
private function fact(string $label, ?string $value): void
{
$blocks = FormattedText::blocks($value);
if ($blocks === []) {
return;
}
if (count($blocks) === 1 && $blocks[0]['type'] === 'paragraph') {
$this->runs([['text' => $label.': ', 'bold' => true, 'italic' => false, 'href' => null], ...$blocks[0]['runs']], self::LEFT, 10.5, after: 4);
return;
}
$this->write(self::printable($label.':'), 10.5, true, 2);
$this->formatted($blocks);
}
/**
* @param list<string> $items
* Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat und Listen mit fett und kursiv.
*
* @param list<array<string, mixed>> $blocks
*/
private function items(array $items, callable $marker): void
private function formatted(array $blocks): void
{
foreach ($blocks as $block) {
match ($block['type']) {
'heading' => $this->runs($block['runs'], self::LEFT, 11, bold: true, after: 4),
'quote' => $this->runs($block['runs'], self::LEFT + 14, 10.5, italic: true, after: 5),
'bullets' => $this->listItems($block['items'], fn (int $n): string => '•'),
'numbered' => $this->listItems($block['items'], fn (int $n): string => $n.'.'),
default => $this->runs($block['runs'] ?? [], self::LEFT, 10.5, after: 5),
};
}
}
/**
* @param list<list<array{text: string, bold: bool, italic: bool, href: ?string}>> $items
*/
private function listItems(array $items, callable $marker): void
{
foreach ($items as $index => $item) {
$lines = PdfDocument::wrap(self::printable($item), self::RIGHT - self::LEFT - 18, 10.5);
foreach ($lines as $line => $text) {
$this->room(14);
if ($line === 0) {
$this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5);
}
$this->pdf->text(self::LEFT + 18, $this->y, $text, 10.5);
$this->y -= 14;
}
$this->room(14);
$this->pdf->text(self::LEFT + 4, $this->y, $marker($index + 1), 10.5);
$this->runs($item, self::LEFT + 18, 10.5, after: 1);
}
$this->y -= 3;
}
/**
* Setzt Textabschnitte mit fett und kursiv in Zeilen um. Die Breite kommt aus den Schriftbreiten der Helvetica
* ({@see PdfDocument::exactWidth()}), damit verschiedene Schnitte in einer Zeile ohne Lücken aneinanderstoßen.
* Links erscheinen mit ausgeschriebener Adresse, weil sie auf Papier sonst verloren gehen.
*
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
*/
private function runs(array $runs, float $x, float $size, bool $bold = false, bool $italic = false, float $after = 0): void
{
$maxWidth = self::RIGHT - $x;
$lines = [];
$line = [];
$width = 0.0;
$pendingSpace = false;
$count = count($runs);
$flush = function () use (&$lines, &$line, &$width, &$pendingSpace): void {
if ($line !== []) {
$lines[] = $line;
}
$line = [];
$width = 0.0;
$pendingSpace = false;
};
$place = function (string $word, bool $isBold, bool $isItalic) use (&$line, &$width, &$pendingSpace, $maxWidth, $size, $flush): void {
$space = $pendingSpace && $line !== [] ? ' ' : '';
$need = PdfDocument::exactWidth($space.$word, $size, $isBold);
if ($line !== [] && $width + $need > $maxWidth) {
$flush();
$space = '';
$need = PdfDocument::exactWidth($word, $size, $isBold);
}
while ($need > $maxWidth && mb_strlen($word) > 1) {
$cut = mb_strlen($word) - 1;
while ($cut > 1 && PdfDocument::exactWidth(mb_substr($word, 0, $cut), $size, $isBold) > $maxWidth) {
$cut--;
}
$line[] = [mb_substr($word, 0, $cut), $isBold, $isItalic];
$flush();
$word = mb_substr($word, $cut);
$need = PdfDocument::exactWidth($word, $size, $isBold);
}
$last = $line === [] ? null : $line[array_key_last($line)];
if ($last !== null && $last[1] === $isBold && $last[2] === $isItalic) {
$line[array_key_last($line)][0] .= $space.$word;
} else {
$line[] = [$space.$word, $isBold, $isItalic];
}
$width += $need;
$pendingSpace = false;
};
foreach ($runs as $index => $run) {
$isBold = $bold || $run['bold'];
$isItalic = $italic || $run['italic'];
foreach (preg_split('/(\s+)/u', self::printable($run['text']), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) ?: [] as $token) {
if (trim($token) !== '') {
$place($token, $isBold, $isItalic);
continue;
}
if (str_contains($token, "\n")) {
$flush();
continue;
}
$pendingSpace = true;
}
$nextHref = $index + 1 < $count ? $runs[$index + 1]['href'] : null;
if ($run['href'] !== null && $nextHref !== $run['href'] && ! str_contains($run['text'], $run['href'])) {
$pendingSpace = true;
$place('('.self::printable($run['href']).')', false, false);
}
}
$flush();
foreach ($lines as $row) {
$this->room($size + 4);
$cursor = $x;
foreach ($row as [$text, $isBold, $isItalic]) {
$this->pdf->text($cursor, $this->y, $text, $size, $isBold, $isItalic);
$cursor += PdfDocument::exactWidth($text, $size, $isBold);
}
$this->y -= $size + 4;
}
$this->y -= $after;
}
private function write(string $text, float $size, bool $bold, float $after): void
{
foreach (PdfDocument::wrap($text, self::RIGHT - self::LEFT, $size, $bold) as $line) {
+375
View File
@@ -0,0 +1,375 @@
<?php
namespace App\Domain\Catalog;
use Dom\HTMLDocument;
use Dom\Node;
use Symfony\Component\HtmlSanitizer\HtmlSanitizer;
use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig;
/**
* Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50).
*
* Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschrift (h3), fett, kursiv, Aufzählung,
* nummerierte Liste, Zitat, Link und Zeilenumbruch. Alles andere fällt beim Speichern weg, auch Skripte, Ereignis­attribute
* und Links auf andere Schemata als http, https und mailto.
*
* Klartext aus dem Altbestand bleibt unverändert in der Datenbank. Er wird erst beim Anzeigen oder Bearbeiten in dieselbe
* Form gebracht ({@see self::html()}) und erst beim Speichern als HTML abgelegt. Erkannt wird HTML an einer Regel: Der
* Text beginnt (nach Leerraum) mit einem der Blockelemente dieser Auswahl. Gespeichertes HTML ist kanonisch und beginnt
* deshalb immer so; Klartext beginnt nie mit einem solchen Tag, wenn er nicht von Hand so geschrieben wurde.
*
* Verglichen und gehasht wird immer nur die kanonische Form ({@see self::canonical()}), damit das Öffnen im Editor oder
* eine andere Schreibweise desselben Inhalts keine neue Fassung und keinen Scheinkonflikt erzeugt.
*/
final class FormattedText
{
/** Blockelemente, mit denen gespeichertes HTML beginnt. */
private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote'];
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
public const FIELDS = ['summary', 'description'];
private static ?HtmlSanitizer $sanitizer = null;
/** Symbolleiste der Editoren; muss zur Auswahl oben passen. */
public const TOOLBAR = [['bold', 'italic', 'link'], ['h3'], ['bulletList', 'orderedList', 'blockquote'], ['undo', 'redo']];
/** Wird der Wert als HTML gelesen (sonst als Klartext des Altbestands)? */
public static function isHtml(?string $value): bool
{
return preg_match('/^\s*<(?:'.implode('|', self::BLOCKS).')[\s>\/]/i', (string) $value) === 1;
}
/**
* Kanonische Form eines gespeicherten oder eingegebenen Werts (HTML oder Klartext). Leer, wenn kein Text übrig ist.
*/
public static function canonical(?string $value): string
{
$value = trim((string) $value);
if ($value === '') {
return '';
}
return self::normalize(self::isHtml($value) ? $value : self::legacyToHtml($value));
}
/**
* Kanonische Form eines Werts, der sicher HTML ist (zum Beispiel aus der Quelle Shinkan), auch wenn er nicht mit
* einem Blockelement beginnt.
*/
public static function canonicalHtml(?string $html): string
{
$html = trim((string) $html);
return $html === '' ? '' : self::normalize($html);
}
/** Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt. */
public static function html(?string $value): string
{
return self::canonical($value);
}
/**
* Sicheres HTML zur Ausgabe an Stellen, die Klartext des Altbestands bisher mit Zeilenumbrüchen zeigten: HTML wird
* bereinigt ausgegeben, Klartext bleibt, wie er war (maskiert, Zeilenumbrüche erhalten).
*/
public static function display(?string $value): string
{
$value = (string) $value;
return self::isHtml($value) ? self::canonical($value) : nl2br(e($value));
}
public static function isBlank(?string $value): bool
{
return self::canonical($value) === '';
}
/** Sind beide Werte inhaltlich gleich (unabhängig von Klartext oder Schreibweise des HTML)? */
public static function same(?string $a, ?string $b): bool
{
return self::canonical($a) === self::canonical($b);
}
/**
* Text ohne Auszeichnung für Orte, die kein HTML vertragen (Zahlungsdienst, Meta-Beschreibung, Listen). Absätze sind
* durch Leerzeilen getrennt, Listenpunkte beginnen mit „- “ beziehungsweise „1. “.
*/
public static function plain(?string $value): string
{
$out = [];
foreach (self::blocks($value) as $block) {
$out[] = match ($block['type']) {
'bullets' => implode("\n", array_map(fn (array $item): string => '- '.self::runsText($item), $block['items'])),
'numbered' => implode("\n", array_map(fn (array $item, int $n): string => ($n + 1).'. '.self::runsText($item), $block['items'], array_keys($block['items']))),
default => self::runsText($block['runs']),
};
}
return trim(implode("\n\n", $out));
}
/** Kurzer Text für Listen und Karten. */
public static function excerpt(?string $value, int $length = 120): string
{
$text = trim((string) preg_replace('/\s+/u', ' ', self::plain($value)));
return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)).'…' : $text;
}
/**
* Zerlegung in Blöcke mit Textabschnitten für das PDF. Ein Textabschnitt (Run) trägt `text`, `bold`, `italic` und
* `href`.
*
* @return list<array{type: 'paragraph'|'heading'|'quote'|'bullets'|'numbered', runs?: list<array{text: string, bold: bool, italic: bool, href: ?string}>, items?: list<list<array{text: string, bold: bool, italic: bool, href: ?string}>>}>
*/
public static function blocks(?string $value): array
{
$html = self::canonical($value);
if ($html === '') {
return [];
}
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
$blocks = [];
foreach ($document->body->childNodes as $node) {
if ($node->nodeType !== XML_ELEMENT_NODE) {
continue;
}
$name = strtolower($node->nodeName);
if (in_array($name, ['ul', 'ol'], true)) {
$items = [];
foreach ($node->childNodes as $item) {
if ($item->nodeType === XML_ELEMENT_NODE && strtolower($item->nodeName) === 'li') {
$items[] = self::runs($item);
}
}
$blocks[] = ['type' => $name === 'ul' ? 'bullets' : 'numbered', 'items' => $items];
continue;
}
$blocks[] = [
'type' => match ($name) {
'h3' => 'heading',
'blockquote' => 'quote',
default => 'paragraph',
},
'runs' => self::runs($node),
];
}
return $blocks;
}
/**
* Klartext des Altbestands als HTML: Absätze an Leerzeilen, Listen mit „- “, „• “ oder „1. “, Zwischenüberschriften
* mit „## “. Dieselben Konventionen wie {@see GuideText}.
*/
public static function legacyToHtml(?string $text): string
{
$html = '';
foreach (GuideText::blocks($text) as $block) {
$html .= match ($block['type']) {
'heading' => '<h3>'.e($block['text']).'</h3>',
'bullets' => '<ul>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ul>',
'numbered' => '<ol>'.implode('', array_map(fn (string $item): string => '<li><p>'.e($item).'</p></li>', $block['items'])).'</ol>',
default => '<p>'.e($block['text']).'</p>',
};
}
return $html;
}
private static function normalize(string $html): string
{
$html = self::mapLegacyTags($html);
$html = trim(self::sanitizer()->sanitize($html));
if ($html === '') {
return '';
}
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
$body = $document->body;
$out = '';
$loose = '';
$flush = function () use (&$out, &$loose): void {
$loose = trim($loose);
if ($loose !== '' && trim(strip_tags(str_replace(['<br>', '<br/>', '<br />'], '', $loose))) !== '') {
$out .= '<p>'.$loose.'</p>';
}
$loose = '';
};
foreach ($body->childNodes as $node) {
if ($node->nodeType === XML_ELEMENT_NODE && in_array(strtolower($node->nodeName), self::BLOCKS, true)) {
$flush();
$out .= self::block($node);
continue;
}
$loose .= $document->saveHtml($node);
}
$flush();
return self::hasText($out) ? $out : '';
}
/** Ein Blockelement ohne Leerraum zwischen den Kindern; Listenpunkte tragen ihren Text immer in einem Absatz. */
private static function block(Node $node): string
{
$name = strtolower($node->nodeName);
if (in_array($name, ['ul', 'ol'], true)) {
$items = '';
foreach ($node->childNodes as $child) {
if ($child->nodeType !== XML_ELEMENT_NODE || strtolower($child->nodeName) !== 'li') {
continue;
}
$inner = self::inner($child);
if (! str_contains($inner, '<p>')) {
$inner = '<p>'.$inner.'</p>';
}
if (self::hasText($inner)) {
$items .= '<li>'.$inner.'</li>';
}
}
return $items === '' ? '' : '<'.$name.'>'.$items.'</'.$name.'>';
}
$inner = self::inner($node);
if ($name === 'blockquote' && ! str_contains($inner, '<p>')) {
$inner = '<p>'.$inner.'</p>';
}
return self::hasText($inner) ? '<'.$name.'>'.$inner.'</'.$name.'>' : '';
}
private static function inner(Node $node): string
{
$html = '';
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_ELEMENT_NODE && in_array(strtolower($child->nodeName), ['ul', 'ol', 'p', 'blockquote'], true)) {
$html .= self::block($child);
continue;
}
$html .= $node->ownerDocument->saveHtml($child);
}
return trim($html);
}
private static function hasText(string $html): bool
{
return trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')) !== '';
}
/** b, i und andere Überschriftsstufen der Quelle werden auf die feste Auswahl abgebildet; der Rest fällt in der Bereinigung weg. */
private static function mapLegacyTags(string $html): string
{
$html = (string) preg_replace('/<(\/?)b(?=[\s>\/])/i', '<$1strong', $html);
$html = (string) preg_replace('/<(\/?)i(?=[\s>\/])/i', '<$1em', $html);
$html = (string) preg_replace('/<(\/?)h[1-6](?=[\s>\/])/i', '<$1h3', $html);
return (string) preg_replace('/<(\/?)div(?=[\s>\/])/i', '<$1p', $html);
}
/**
* @return list<array{text: string, bold: bool, italic: bool, href: ?string}>
*/
private static function runs(Node $node, bool $bold = false, bool $italic = false, ?string $href = null): array
{
$runs = [];
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_TEXT_NODE) {
$runs[] = ['text' => (string) $child->textContent, 'bold' => $bold, 'italic' => $italic, 'href' => $href];
continue;
}
if ($child->nodeType !== XML_ELEMENT_NODE) {
continue;
}
$name = strtolower($child->nodeName);
if ($name === 'br') {
$runs[] = ['text' => "\n", 'bold' => $bold, 'italic' => $italic, 'href' => $href];
continue;
}
if (in_array($name, ['p', 'ul', 'ol', 'blockquote'], true)) {
// Verschachtelte Blöcke (Absatz im Listenpunkt) werden zu Fließtext.
$runs = [...$runs, ...self::runs($child, $bold, $italic, $href)];
continue;
}
$runs = [...$runs, ...self::runs(
$child,
$bold || $name === 'strong',
$italic || $name === 'em',
$name === 'a' ? ((string) $child->getAttribute('href') ?: $href) : $href,
)];
}
return $runs;
}
/**
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
*/
private static function runsText(array $runs): string
{
return trim(implode('', array_map(fn (array $run): string => $run['text'], $runs)));
}
private static function sanitizer(): HtmlSanitizer
{
return self::$sanitizer ??= new HtmlSanitizer(
(new HtmlSanitizerConfig)
->allowElement('p')
->allowElement('br')
->allowElement('h3')
->allowElement('strong')
->allowElement('em')
->allowElement('ul')
->allowElement('ol')
->allowElement('li')
->allowElement('blockquote')
->allowElement('a', ['href'])
->allowLinkSchemes(['http', 'https', 'mailto'])
->allowRelativeLinks(false)
->forceAttribute('a', 'rel', 'noopener noreferrer')
->withMaxInputLength(100000),
);
}
}
+42 -3
View File
@@ -17,14 +17,44 @@ final class PdfDocument
/** @var list<string> */
private array $pages = [];
/** Schräge Schnitte werden nur eingebunden, wenn das Dokument sie braucht (Belege bleiben unverändert). */
private bool $usesItalic = false;
/** Breiten der Helvetica (Tausendstel der Schrifthöhe) für Zeichen 32 bis 126; schräg wie aufrecht. */
private const REGULAR = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];
/** Breiten der Helvetica-Bold für Zeichen 32 bis 126; schräg wie aufrecht. */
private const BOLD = [278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584];
public function addPage(): void
{
$this->pages[] = '';
}
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false): void
public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false, bool $italic = false): void
{
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $bold ? 'F2' : 'F1', $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
$font = $italic ? ($bold ? 'F4' : 'F3') : ($bold ? 'F2' : 'F1');
$this->usesItalic = $this->usesItalic || $italic;
$this->append(sprintf("BT /%s %s Tf %s %s Td (%s) Tj ET\n", $font, $this->n($size), $this->n($x), $this->n($y), self::escape($text)));
}
/**
* Genaue Breite in Punkt nach den Schriftbreiten der Helvetica, damit Textabschnitte mit verschiedenen Schnitten in
* einer Zeile ohne Lücken aneinanderstoßen. Umlaute zählen wie ihr Grundbuchstabe, das ß wie ein kleines b, jedes
* andere Zeichen außerhalb von ASCII wie eine Ziffer.
*/
public static function exactWidth(string $text, float $size = 10, bool $bold = false): float
{
$table = $bold ? self::BOLD : self::REGULAR;
$units = 0;
$text = strtr($text, ['ä' => 'a', 'ö' => 'o', 'ü' => 'u', 'Ä' => 'A', 'Ö' => 'O', 'Ü' => 'U', 'ß' => 'b', "\u{2019}" => "'", "\u{2026}" => '...', "\u{00A0}" => ' ']);
foreach (mb_str_split($text) as $char) {
$code = strlen($char) === 1 ? ord($char) : 0;
$units += $code >= 32 && $code <= 126 ? $table[$code - 32] : 556;
}
return $units / 1000 * $size;
}
public function textRight(float $xRight, float $y, string $text, float $size = 10, bool $bold = false): void
@@ -117,11 +147,20 @@ public function output(string $title, ?string $keywords = null): string
foreach ($pages as $stream) {
$kids[] = $next.' 0 R';
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents '.($next + 1).' 0 R >>';
$objects[$next] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 '.self::WIDTH.' '.self::HEIGHT.'] /Resources << /Font << /F1 3 0 R /F2 4 0 R'.($this->usesItalic ? ' /F3 %ITALIC% 0 R /F4 %BOLDITALIC% 0 R' : '').' >> >> /Contents '.($next + 1).' 0 R >>';
$objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream';
$next += 2;
}
if ($this->usesItalic) {
$objects[$next] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Oblique /Encoding /WinAnsiEncoding >>';
$objects[$next + 1] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-BoldOblique /Encoding /WinAnsiEncoding >>';
foreach ($objects as $number => $body) {
$objects[$number] = str_replace(['%ITALIC%', '%BOLDITALIC%'], [(string) $next, (string) ($next + 1)], $body);
}
}
$objects[2] = '<< /Type /Pages /Kids ['.implode(' ', $kids).'] /Count '.count($pages).' >>';
$objects[3] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>';
$objects[4] = '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>';
@@ -16,6 +16,7 @@
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\EditorialWorkingDraft;
use App\Domain\Catalog\ForeignCompositions;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\IdentityProfile;
@@ -26,6 +27,7 @@
use App\Filament\Support\AssignsPillars;
use App\Filament\Support\EditorialCatalog;
use App\Filament\Support\ManagesEditorialSurface;
use App\Filament\Support\ManagesRichFields;
use App\Filament\Support\MediumForm;
use App\Filament\Support\WidgetEditor;
use App\Http\Controllers\ContentPreviewController;
@@ -48,6 +50,7 @@ abstract class EditComposition extends EditRecord
{
use AssignsPillars;
use ManagesEditorialSurface;
use ManagesRichFields;
use WithFileUploads;
protected string $view = 'filament.editorial.edit';
@@ -382,6 +385,14 @@ public function redaktionTitel(): string
return $title !== '' ? $title : $this->hostLabel();
}
/**
* @return list<string>
*/
protected function richFelder(): array
{
return ['summary', 'description', 'learningGoal', 'materialNote', 'partBody', 'newTextBody'];
}
/**
* @return list<array<string, mixed>>
*/
@@ -395,8 +406,8 @@ public function redaktionFelder(): array
['id' => 'name', 'label' => 'Name in der Verwaltung', 'model' => 'designation', 'kind' => 'text', 'stored' => $stored('designation'), 'required' => true, 'hilfe' => 'Pflichtangabe. Erscheint in Listen der Verwaltung.'],
['id' => 'titel', 'label' => 'Titel', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'hilfe' => 'Erscheint auf Karten und in der Bibliothek. Leer zeigt den Namen.'],
['id' => 'teaser', 'label' => 'Teaser', 'model' => 'teaser', 'kind' => 'textarea', 'rows' => 2, 'stored' => $stored('teaser')],
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'textarea', 'rows' => 3, 'stored' => $stored('summary')],
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'description', 'kind' => 'textarea', 'rows' => 8, 'stored' => $stored('description'), 'hilfe' => 'Beschreibt das Angebot. Kein Lehrtext und kein Lernziel.'],
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'rich', 'stored' => $stored('summary')],
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'description', 'kind' => 'rich', 'stored' => $stored('description'), 'hilfe' => 'Beschreibt das Angebot. Kein Lehrtext und kein Lernziel.'],
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'placeholder' => 'Begriffe, durch Komma getrennt'],
];
}
@@ -1248,7 +1259,7 @@ public function loadTemplate(int $versionId): void
public function addText(): void
{
$title = trim($this->newTextTitle);
$body = trim($this->newTextBody);
$body = FormattedText::canonical($this->newTextBody);
if ($title === '' || $body === '') {
$this->feedback = 'Der Text braucht einen Titel und einen Inhalt.';
@@ -1578,7 +1589,7 @@ private function writePartText(): string|false
}
$title = trim($this->partTitle);
$body = trim($this->partBody);
$body = FormattedText::canonical($this->partBody);
if ($title === '' || $body === '') {
$this->feedback = 'Der Text braucht einen Titel und einen Inhalt.';
@@ -1598,7 +1609,7 @@ private function writePartText(): string|false
return false;
}
$changed = $title !== (string) ($member['title'] ?? '') || $body !== trim((string) $version->body);
$changed = $title !== (string) ($member['title'] ?? '') || ! FormattedText::same($body, $version->body);
if (! $changed) {
return '';
@@ -1755,10 +1766,10 @@ public function publishRevision(): bool
$this->actor(),
$note !== '' ? $note : null,
[
'learning_goal' => $this->blank($this->learningGoal),
'learning_goal' => $this->richBlank('learningGoal'),
'duration_minutes' => $minutes,
'duration_max' => $this->blank($this->durationMax),
'material_note' => $this->blank($this->materialNote),
'material_note' => $this->richBlank('materialNote'),
'prerequisites' => $this->blank($this->prerequisites),
],
$this->releaseConsent,
@@ -2079,8 +2090,8 @@ protected function didacticChanged(CompositionVersion $version): bool
'key' => $variant->key, 'name' => $variant->name, 'description' => (string) $variant->description, 'origin' => $variant->origin,
])->all());
return $version->learning_goal !== $this->blank($this->learningGoal)
|| $version->material_note !== $this->blank($this->materialNote)
return ! FormattedText::same($version->learning_goal, $this->learningGoal)
|| ! FormattedText::same($version->material_note, $this->materialNote)
|| $version->prerequisites !== $this->blank($this->prerequisites)
|| ($version->duration_max === null ? null : (string) $version->duration_max) !== $this->blank($this->durationMax)
|| $storedVariants !== $this->normalizeVariants($this->variants)
@@ -2104,6 +2115,14 @@ protected function minutes(string $value): int|false|null
return $minutes > 0 ? $minutes : false;
}
/** Formatierte Eigenschaft in kanonischer Form für das Speichern; leer wird null. */
protected function richBlank(string $name): ?string
{
$value = $this->richWert($name);
return $value === '' ? null : $value;
}
protected function blank(string $value): ?string
{
$value = trim($value);
@@ -2138,9 +2157,9 @@ protected function persistRedaktion(): bool
app(IdentityProfile::class)->fill($record, [
'display_title' => $this->displayTitle,
'teaser' => $this->teaser,
'summary' => $this->summary,
'summary' => $this->richStore('summary', $record->summary),
'search_terms' => $this->searchTerms,
'description' => $this->description,
'description' => $this->richStore('description', $record->description),
], $this->actor());
$this->syncDimensions($record, array_map(intval(...), $this->dimensionIds));
$this->persistPillarIds($record);
@@ -2291,9 +2310,9 @@ protected function payload(): array
$minutes = $this->minutes($this->durationMinutes);
return [
'learning_goal' => $this->blank($this->learningGoal),
'learning_goal' => $this->richBlank('learningGoal'),
'duration_minutes' => $minutes === false ? $this->durationMinutes : $minutes,
'material_note' => $this->blank($this->materialNote),
'material_note' => $this->richBlank('materialNote'),
'duration_max' => $this->blank($this->durationMax),
'prerequisites' => $this->blank($this->prerequisites),
'variants' => $this->normalizeVariants($this->variants),
@@ -2392,9 +2411,10 @@ protected function normalizePayload(array $payload): array
}
return [
'learning_goal' => $payload['learning_goal'] ?? null,
// Formatierte Angaben nur in kanonischer Form vergleichen: Klartext des Altbestands und dasselbe als HTML sind gleich.
'learning_goal' => FormattedText::canonical($payload['learning_goal'] ?? null) ?: null,
'duration_minutes' => $payload['duration_minutes'] ?? null,
'material_note' => $payload['material_note'] ?? null,
'material_note' => FormattedText::canonical($payload['material_note'] ?? null) ?: null,
'duration_max' => isset($payload['duration_max']) && $payload['duration_max'] !== '' ? (string) $payload['duration_max'] : null,
'prerequisites' => $payload['prerequisites'] ?? null,
'variants' => $this->normalizeVariants($payload['variants'] ?? []),
@@ -8,6 +8,7 @@
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\IdentityProfile;
@@ -19,13 +20,13 @@
use App\Filament\Support\ElementRevision;
use App\Filament\Support\MediumForm;
use App\Filament\Support\ReportsDomainRules;
use App\Filament\Support\RichField;
use App\Jobs\DeriveThumbnail;
use Filament\Actions\Action;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
@@ -71,7 +72,7 @@ public function form(Schema $schema): Schema
...MediumForm::fields(creating: false, element: $element),
TextInput::make('display_title')->label('Anzeigetitel')
->helperText('Erscheint in der Bibliothek. Leer lässt den Arbeitstitel stehen. Speichern legt keine Fassung an.'),
Textarea::make('summary')->label('Kurzbeschreibung')->rows(3),
RichField::make('summary', 'Kurzbeschreibung', live: false),
Select::make('editorial_content_kind_id')
->label('Fachliche Materialart')
->options(fn (): array => app(EditorialVocabulary::class)->kindOptions('medium', $this->getRecord()->editorial_content_kind_id !== null ? (int) $this->getRecord()->editorial_content_kind_id : null))
@@ -194,12 +195,12 @@ protected function mutateFormDataBeforeFill(array $data): array
return [
'working_title' => $this->getRecord()->working_title,
'thumbnail_alt' => $this->getRecord()->thumbnail_alt,
'body' => $this->getRecord()->versions()->orderByDesc('number')->first()?->body,
'body' => FormattedText::html($this->getRecord()->versions()->orderByDesc('number')->first()?->body),
'display_title' => $this->getRecord()->display_title,
'description' => $this->getRecord()->description,
'description' => FormattedText::html($this->getRecord()->description),
'usage_note' => $this->getRecord()->usage_note,
'license_note' => $this->getRecord()->license_note,
'summary' => $this->getRecord()->summary,
'summary' => FormattedText::html($this->getRecord()->summary),
'editorial_content_kind_id' => $this->getRecord()->editorial_content_kind_id,
'dimension_ids' => IdentityDimensionValue::query()
->where('subject_type', $this->getRecord()->getMorphClass())
@@ -218,10 +219,15 @@ protected function handleRecordUpdate(Model $record, array $data): Model
{
/** @var ContentElement $record */
try {
app(ContentService::class)->describe($record, (string) $data['working_title'], $data['description'] ?? null);
$description = FormattedText::same((string) ($data['description'] ?? ''), $record->description)
? $record->description
: (FormattedText::canonical((string) ($data['description'] ?? '')) ?: null);
app(ContentService::class)->describe($record, (string) $data['working_title'], $description);
app(IdentityProfile::class)->fill($record, [
'display_title' => $data['display_title'] ?? null,
'summary' => $data['summary'] ?? null,
'summary' => FormattedText::same((string) ($data['summary'] ?? ''), $record->summary)
? $record->summary
: (FormattedText::canonical((string) ($data['summary'] ?? '')) ?: null),
'usage_note' => $data['usage_note'] ?? null,
'license_note' => $data['license_note'] ?? null,
'thumbnail_alt' => $data['thumbnail_alt'] ?? null,
@@ -229,8 +235,8 @@ protected function handleRecordUpdate(Model $record, array $data): Model
if ($record->output_class === 'text' && is_string($data['body'] ?? null)) {
$latest = $record->versions()->orderByDesc('number')->first();
if ($latest instanceof ContentElementVersion) {
app(ContentService::class)->reviseElementContent($latest, $data['body']);
if ($latest instanceof ContentElementVersion && ! FormattedText::same($data['body'], $latest->body)) {
app(ContentService::class)->reviseElementContent($latest, FormattedText::canonical($data['body']));
}
}
if (array_key_exists('editorial_content_kind_id', $data)) {
@@ -8,6 +8,7 @@
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityChange;
use App\Domain\Catalog\IdentityDimension;
use App\Domain\Catalog\IdentityDimensionValue;
@@ -26,6 +27,7 @@
use App\Filament\Support\EditorialCatalog;
use App\Filament\Support\ElementRevision;
use App\Filament\Support\ManagesEditorialSurface;
use App\Filament\Support\ManagesRichFields;
use App\Filament\Support\MediaLibrary;
use App\Filament\Support\ReportsDomainRules;
use App\Http\Controllers\ContentPreviewController;
@@ -45,6 +47,7 @@
class ViewContentElement extends ViewRecord
{
use ManagesEditorialSurface;
use ManagesRichFields;
use ReportsDomainRules;
use WithFileUploads;
@@ -211,7 +214,7 @@ public function textUnsaved(): bool
return $shown instanceof ContentElementVersion
&& $this->getRecord()->output_class === 'text'
&& $shown->status !== ContentVersionStatus::Gesperrt
&& trim($this->bodyDraft) !== trim((string) $shown->body);
&& ! FormattedText::same($this->bodyDraft, $shown->body);
}
public function discardShownText(): void
@@ -243,7 +246,7 @@ public function saveShownText(): void
}
try {
$saved = app(ContentService::class)->reviseElementContent($shown, $this->bodyDraft);
$saved = app(ContentService::class)->reviseElementContent($shown, FormattedText::canonical($this->bodyDraft));
} catch (DomainRuleException $exception) {
$this->fassungFeedback = $exception->getMessage();
$this->fassungFeedbackError = true;
@@ -687,9 +690,9 @@ protected function saveRedaktionTexte(): bool
'working_title' => $title,
'display_title' => $this->displayTitle,
'teaser' => $this->teaser,
'summary' => $this->summary,
'summary' => $this->richStore('summary', $element->summary),
'search_terms' => $this->searchTerms,
'description' => $this->descriptionText,
'description' => $this->richStore('descriptionText', $element->description),
'usage_note' => $this->usageNote,
'license_note' => $this->licenseNote,
'website_credit' => $this->websiteCredit,
@@ -780,6 +783,14 @@ public function redaktionTitel(): string
return $title !== '' ? $title : (string) $this->getRecord()->working_title;
}
/**
* @return list<string>
*/
protected function richFelder(): array
{
return ['summary', 'descriptionText', 'bodyDraft'];
}
/**
* @return list<array<string, mixed>>
*/
@@ -793,8 +804,8 @@ public function redaktionFelder(): array
['id' => 'arbeitstitel', 'label' => 'Arbeitstitel', 'model' => 'workingTitle', 'kind' => 'text', 'stored' => $stored('working_title'), 'required' => true, 'hilfe' => 'Bezeichnung in der Verwaltung. Pflichtangabe.'],
['id' => 'anzeigename', 'label' => 'Anzeigename', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'hilfe' => 'Erscheint auf Karten und in der Bibliothek. Leer zeigt den Arbeitstitel.'],
['id' => 'teaser', 'label' => 'Teaser', 'model' => 'teaser', 'kind' => 'textarea', 'rows' => 2, 'stored' => $stored('teaser')],
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'textarea', 'rows' => 3, 'stored' => $stored('summary'), 'hilfe' => 'Erscheint auf Website- und Bibliothekskarten.'],
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'descriptionText', 'kind' => 'textarea', 'rows' => 8, 'stored' => $stored('description'), 'hilfe' => 'Bleibt in der Verwaltung und in Detailansichten. Kein Lehrtext.'],
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'rich', 'stored' => $stored('summary'), 'hilfe' => 'Erscheint auf Website- und Bibliothekskarten.'],
['id' => 'beschreibung', 'label' => 'Ausführliche Beschreibung', 'model' => 'descriptionText', 'kind' => 'rich', 'stored' => $stored('description'), 'hilfe' => 'Bleibt in der Verwaltung und in Detailansichten. Kein Lehrtext.'],
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'placeholder' => 'Begriffe, durch Komma getrennt'],
['id' => 'einsatz', 'label' => 'Hinweise für den Einsatz', 'model' => 'usageNote', 'kind' => 'textarea', 'rows' => 3, 'gruppe' => 'weitere', 'stored' => $stored('usage_note')],
['id' => 'lizenz', 'label' => 'Interner Lizenzvermerk', 'model' => 'licenseNote', 'kind' => 'textarea', 'rows' => 3, 'gruppe' => 'weitere', 'stored' => $stored('license_note'), 'hilfe' => 'Nur intern sichtbar.'],
@@ -1040,7 +1051,7 @@ public function previewHtml(): string
$draft = [
'working_title' => $this->workingTitle,
'display_title' => $this->displayTitle,
'summary' => $this->summary,
'summary' => FormattedText::plain($this->summary),
'thumbnail_alt' => $this->thumbnailAlt,
];
@@ -1053,7 +1064,7 @@ public function previewHtml(): string
'type' => $element->output_class === 'film' ? 'film' : 'material',
'url' => '#vorschau',
'title' => $title !== '' ? $title : $element->working_title,
'summary' => trim($this->summary) !== '' ? trim($this->summary) : null,
'summary' => FormattedText::plain($this->summary) !== '' ? FormattedText::plain($this->summary) : null,
'kind' => PublicMaterialReader::outputLabel((string) $element->output_class),
'hide_status' => true,
'image' => trim($this->thumbnailAlt) !== '' ? trim($this->thumbnailAlt) : $title,
@@ -20,6 +20,7 @@
use App\Filament\Support\CatalogOptions;
use App\Filament\Support\EditorialCatalog;
use App\Filament\Support\ManagesEditorialSurface;
use App\Filament\Support\ManagesRichFields;
use App\Filament\Support\ReportsDomainRules;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
@@ -33,6 +34,7 @@ class ViewLicenseArticle extends ViewRecord
{
use AssignsPillars;
use ManagesEditorialSurface;
use ManagesRichFields;
use ReportsDomainRules;
protected static string $resource = LicenseArticleResource::class;
@@ -110,8 +112,8 @@ protected function saveRedaktionTexte(): bool
'working_title' => $this->workingTitle,
'display_title' => $this->displayTitle,
'teaser' => $this->teaser,
'summary' => $this->summary,
'description' => $this->descriptionText,
'summary' => $this->richStore('summary', $article->summary),
'description' => $this->richStore('descriptionText', $article->description),
'search_terms' => $this->searchTerms,
'editorial_content_kind_id' => filled($this->kindId) ? (int) $this->kindId : null,
], auth()->user());
@@ -199,6 +201,14 @@ public function redaktionTitel(): string
return $source !== null ? $this->sourceTitle($source) : (string) $this->getRecord()->code;
}
/**
* @return list<string>
*/
protected function richFelder(): array
{
return ['summary', 'descriptionText'];
}
/**
* @return list<array<string, mixed>>
*/
@@ -218,8 +228,8 @@ public function redaktionFelder(): array
['id' => 'arbeitstitel', 'label' => 'Interner Arbeitstitel', 'model' => 'workingTitle', 'kind' => 'text', 'stored' => $stored('working_title'), 'hilfe' => 'Nur in der Verwaltung sichtbar.'],
['id' => 'anzeigename', 'label' => 'Name', 'model' => 'displayTitle', 'kind' => 'text', 'stored' => $stored('display_title'), 'quelle' => $quelle('display_title')],
['id' => 'teaser', 'label' => 'Teaser', 'model' => 'teaser', 'kind' => 'textarea', 'rows' => 2, 'stored' => $stored('teaser'), 'quelle' => $quelle('teaser')],
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'textarea', 'rows' => 4, 'stored' => $stored('summary'), 'quelle' => $quelle('summary')],
['id' => 'beschreibung', 'label' => 'Beschreibung', 'model' => 'descriptionText', 'kind' => 'textarea', 'rows' => 6, 'stored' => $stored('description'), 'quelle' => $quelle('description')],
['id' => 'kurz', 'label' => 'Kurzbeschreibung', 'model' => 'summary', 'kind' => 'rich', 'stored' => $stored('summary'), 'quelle' => $quelle('summary')],
['id' => 'beschreibung', 'label' => 'Beschreibung', 'model' => 'descriptionText', 'kind' => 'rich', 'stored' => $stored('description'), 'quelle' => $quelle('description')],
['id' => 'suche', 'label' => 'Suchbegriffe', 'model' => 'searchTerms', 'kind' => 'text', 'gruppe' => 'weitere', 'stored' => $stored('search_terms'), 'quelle' => $quelle('search_terms')],
];
}
+7 -6
View File
@@ -13,6 +13,7 @@
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\EditorialContentKind;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\LicenseArticle;
use App\Domain\Catalog\OfferStatus;
@@ -108,8 +109,8 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
'kind' => $kind,
'output' => (string) $element->output_class,
'body' => (string) ($version->body ?? ''),
'summary' => (string) ($element->summary ?: $element->description ?: ''),
'medium_description' => (string) ($element->description ?? ''),
'summary' => FormattedText::plain((string) ($element->summary ?: $element->description ?: '')),
'medium_description' => FormattedText::plain((string) ($element->description ?? '')),
'usage_note' => (string) ($element->usage_note ?? ''),
'license_note' => (string) ($element->license_note ?? ''),
'tone' => $this->tone((string) $element->output_class, $kind),
@@ -159,7 +160,7 @@ public function rowForTarget(string $target, int $exceptCompositionId, bool $all
'target' => 'composition:'.$version->id,
'title' => $this->compositionTitle($composition),
'kind' => $kind,
'summary' => (string) ($composition->summary ?? ''),
'summary' => FormattedText::plain((string) ($composition->summary ?? '')),
'tone' => $this->tone('', $kind),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path),
'version_label' => $version->status === ContentVersionStatus::Gesperrt
@@ -194,7 +195,7 @@ private function draftCompositionRow(int $compositionId, int $exceptCompositionI
'target' => 'composition-draft:'.$composition->id,
'title' => $this->compositionTitle($composition),
'kind' => $kind,
'summary' => (string) ($composition->summary ?? ''),
'summary' => FormattedText::plain((string) ($composition->summary ?? '')),
'tone' => $this->tone('', $kind),
'image' => $this->cardUrl('komposition', $composition->id, $composition->thumbnail_path),
'version_label' => 'Entwurf',
@@ -510,8 +511,8 @@ private function rowForPresentationMedium(int $id): ?array
'kind' => $kind,
'output' => (string) $element->output_class,
'body' => '',
'summary' => (string) ($element->summary ?: $element->description ?: ''),
'medium_description' => (string) ($element->description ?? ''),
'summary' => FormattedText::plain((string) ($element->summary ?: $element->description ?: '')),
'medium_description' => FormattedText::plain((string) ($element->description ?? '')),
'usage_note' => (string) ($element->usage_note ?? ''),
'license_note' => (string) ($element->license_note ?? ''),
'tone' => $this->tone((string) $element->output_class, $kind),
+4 -4
View File
@@ -6,9 +6,9 @@
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\FormattedText;
use App\Filament\Resources\ContentElements\Pages\EditContentElement;
use Filament\Forms\Components\Component;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
@@ -37,14 +37,14 @@ public static function publish(ContentElement $record, array $data): string
$metadata['decision_seconds'] = $decision;
}
$body = is_string($data['body'] ?? null) ? $data['body'] : null;
$body = is_string($data['body'] ?? null) ? (FormattedText::canonical($data['body']) ?: null) : null;
$note = is_string($data['change_note'] ?? null) ? $data['change_note'] : null;
$previousDecision = is_array($latest?->metadata) && is_numeric($latest->metadata['decision_seconds'] ?? null)
? (int) $latest->metadata['decision_seconds']
: null;
$changed = $incoming !== null
|| $dropFile
|| trim((string) $body) !== trim((string) $latest?->body)
|| ! FormattedText::same($body, $latest?->body)
|| $decision !== $previousDecision
|| (is_string($note) && trim($note) !== '');
@@ -71,7 +71,7 @@ public static function fields(ContentElement $element): array
$latest = $element->versions()->orderByDesc('number')->first();
return [
Textarea::make('body')->label('Text')->rows(8)->default($latest?->body),
RichField::make('body', 'Text', live: false)->default(FormattedText::html($latest?->body)),
EditContentElement::uploadField(),
Toggle::make('drop_file')
->label('Datei in der neuen Fassung nicht mehr verwenden')
+3 -2
View File
@@ -8,6 +8,7 @@
use App\Domain\Catalog\ContentVersionStatus;
use App\Domain\Catalog\EditorialVocabulary;
use App\Domain\Catalog\ExerciseSource;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityDimensionValue;
use App\Domain\Catalog\Pillar;
use App\Domain\Catalog\PillarFilterCompat;
@@ -183,8 +184,8 @@ public function entries(): array
}
$title = $catalog->compositionTitle($composition);
$summary = trim((string) ($composition->summary ?? ''));
$haystack = mb_strtolower($title.' '.$composition->designation.' '.$summary.' '.(string) $composition->description);
$summary = FormattedText::plain((string) ($composition->summary ?? ''));
$haystack = mb_strtolower($title.' '.$composition->designation.' '.$summary.' '.FormattedText::plain((string) $composition->description));
if ($needle !== '' && ! str_contains($haystack, $needle)) {
continue;
@@ -9,6 +9,7 @@
use App\Domain\Catalog\EditorialProfile;
use App\Domain\Catalog\EditorialProfileReader;
use App\Domain\Catalog\EditorialTextVariant;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\PresentationMedia;
use App\Domain\Catalog\PresentationRole;
use App\Domain\Media\WebsiteRelease;
@@ -310,6 +311,10 @@ public function feldGeaendert(array $feld): bool
{
$model = (string) $feld['model'];
if (($feld['kind'] ?? null) === 'rich') {
return ! FormattedText::same((string) $this->{$model}, (string) ($feld['stored'] ?? ''));
}
return trim((string) $this->{$model}) !== trim((string) ($feld['stored'] ?? ''));
}
+126
View File
@@ -0,0 +1,126 @@
<?php
namespace App\Filament\Support;
use App\Domain\Catalog\FormattedText;
use Filament\Forms\Components\RichEditor;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Schema;
/**
* Formatierte Textfelder in den Arbeitsplätzen der Verwaltung (ADR-50).
*
* Die Arbeitsplätze halten ihre Texte als einfache Zeichenketten in öffentlichen Eigenschaften. Der Editor von Filament
* hält dagegen ein Dokument in seinem eigenen Zustand (`rich.<feld>`). Diese Eigenschaft ist der einzige Ort, an dem beide
* zusammenkommen:
*
* - Die Zeichenkette bleibt maßgeblich. Eine Eingabe im Editor wird beim Verlassen des Felds in kanonisches HTML gewandelt
* und in die Eigenschaft geschrieben ({@see self::updatedRich()}).
* - Setzt der Server eine Eigenschaft selbst (Laden, Zurücknehmen, Wechsel des Abschnitts), gleicht der Editor sich vor
* dem nächsten Rendern an ({@see self::renderingManagesRichFields()}). Klartext des Altbestands erscheint dabei
* formatiert, ohne dass etwas gespeichert wird.
*
* Verglichen wird nur in kanonischer Form ({@see FormattedText::canonical()}): Das Öffnen eines Felds im Editor ändert
* nichts am Arbeitsstand.
*/
trait ManagesRichFields
{
/** @var array<string, mixed> Zustand der Editoren (Dokumente) je Eigenschaft */
public array $rich = [];
/** @var array<string, string> Zuletzt abgeglichener kanonischer Wert je Eigenschaft */
public array $richSeen = [];
/**
* Eigenschaften dieser Seite, die mit dem Editor bearbeitet werden.
*
* @return list<string>
*/
protected function richFelder(): array
{
return [];
}
public function richTextSchema(Schema $schema): Schema
{
return $schema
->statePath('rich')
->components(array_map(fn (string $name): RichEditor => RichField::make($name), $this->richFelder()));
}
public function richKomponente(string $name): ?Component
{
return $this->getSchema('richTextSchema')?->getFlatComponents()[$name] ?? null;
}
/** Eingabe im Editor übernehmen. */
public function updatedRich(mixed $value = null, ?string $key = null): void
{
$name = explode('.', (string) $key)[0];
if ($name !== '' && in_array($name, $this->richFelder(), true)) {
$this->richPull($name);
}
}
/** Wert aus dem Editor in die Eigenschaft schreiben. */
protected function richPull(string $name): void
{
$component = $this->richKomponente($name);
if ($component === null) {
return;
}
$html = FormattedText::canonicalHtml((string) $component->getState());
$this->{$name} = $html;
$this->richSeen[$name] = $html;
}
/** Wert der Eigenschaft in den Editor schreiben. */
protected function richPush(string $name): void
{
$component = $this->richKomponente($name);
if ($component === null) {
return;
}
$canonical = FormattedText::canonical((string) $this->{$name});
$component->state($canonical === '' ? null : $canonical);
$this->richSeen[$name] = $canonical;
}
/** Vor dem Rendern: Eigenschaften, die der Server geändert hat, in den Editor übernehmen. */
public function renderingManagesRichFields(): void
{
foreach ($this->richFelder() as $name) {
$canonical = FormattedText::canonical((string) $this->{$name});
if (! array_key_exists($name, $this->richSeen) || $this->richSeen[$name] !== $canonical) {
$this->richPush($name);
}
}
}
/**
* Wert zum Schreiben in eine Spalte. Ist der Text inhaltlich der gespeicherte, bleibt der gespeicherte Wert, wie er
* ist: Klartext des Altbestands wird nicht allein durch das Öffnen im Editor zu HTML und erzeugt keine Änderung.
*/
protected function richStore(string $name, ?string $stored): ?string
{
if (FormattedText::same((string) $this->{$name}, $stored)) {
return ($stored === null || trim($stored) === '') ? null : $stored;
}
$value = $this->richWert($name);
return $value === '' ? null : $value;
}
/** Kanonischer Wert einer Eigenschaft für Speichern und Vergleichen. */
protected function richWert(string $name): string
{
return FormattedText::canonical((string) $this->{$name});
}
}
+12 -8
View File
@@ -6,6 +6,7 @@
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\DomainRuleException;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityProfile;
use App\Domain\Media\PresentationFile;
use App\Jobs\DeriveThumbnail;
@@ -35,7 +36,7 @@ public static function fields(bool $creating, ?ContentElement $element = null):
'document' => 'Dokument',
'text' => 'Text',
])->required()->live();
$fields[] = Textarea::make('body')->label('Text')->rows(8)
$fields[] = RichField::make('body', 'Text', live: false)
->visible(fn ($get): bool => $get('shape') === 'text')
->required(fn ($get): bool => $get('shape') === 'text');
$fields[] = self::fileField()
@@ -46,12 +47,12 @@ public static function fields(bool $creating, ?ContentElement $element = null):
->helperText('Bild, Film oder Hörstück ohne fachliche Inhaltsfassung, zum Beispiel ein Trailer, der ungeschützt auf der Website laufen soll. Der Film muss dafür MP4 (H.264) oder WebM sein. Er wird nicht lizenziert und erst nach „Für die Website freigeben“ öffentlich.')
->visible(fn ($get): bool => in_array($get('shape'), ['film', 'audio', 'bild'], true));
} elseif ($element?->output_class === 'text') {
$fields[] = Textarea::make('body')->label('Text')->rows(8)->required();
$fields[] = RichField::make('body', 'Text', live: false)->required();
}
return [
...$fields,
Textarea::make('description')->label('Beschreibung')->rows(4)
RichField::make('description', 'Beschreibung', live: false)
->helperText('Gilt für das Medium, nicht nur für diese eine Stelle.'),
Textarea::make('usage_note')->label('Hinweise für den Einsatz')->rows(3),
Textarea::make('license_note')->label('Interner Lizenzvermerk')->rows(3)
@@ -125,7 +126,7 @@ public static function create(array $data, bool $hold): ContentElement
self::remember($element, $data);
if ($output === 'text') {
$body = trim((string) ($data['body'] ?? ''));
$body = FormattedText::canonical((string) ($data['body'] ?? ''));
if ($body === '') {
throw new DomainRuleException('Der Text braucht einen Inhalt.');
@@ -164,7 +165,7 @@ public static function update(ContentElement $element, array $data): ?ContentEle
if ($element->output_class === 'text') {
$latest = $element->versions()->orderByDesc('number')->first();
$body = trim((string) ($data['body'] ?? ''));
$body = FormattedText::canonical((string) ($data['body'] ?? ''));
if ($latest instanceof ContentElementVersion && $body !== '') {
$revised = app(ContentService::class)->reviseElementContent($latest, $body);
@@ -185,11 +186,11 @@ public static function fill(ContentElement $element): array
return [
'working_title' => $element->working_title,
'description' => $element->description,
'description' => FormattedText::html($element->description),
'usage_note' => $element->usage_note,
'license_note' => $element->license_note,
'thumbnail_alt' => $element->thumbnail_alt,
'body' => $latest?->body,
'body' => FormattedText::html($latest?->body),
];
}
@@ -198,7 +199,10 @@ public static function fill(ContentElement $element): array
*/
public static function remember(ContentElement $element, array $data): void
{
app(ContentService::class)->describe($element, (string) $data['working_title'], $data['description'] ?? null);
$description = FormattedText::same((string) ($data['description'] ?? ''), $element->description)
? $element->description
: (FormattedText::canonical((string) ($data['description'] ?? '')) ?: null);
app(ContentService::class)->describe($element, (string) $data['working_title'], $description);
app(IdentityProfile::class)->fill($element, [
'usage_note' => $data['usage_note'] ?? null,
'license_note' => $data['license_note'] ?? null,
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Filament\Support;
use App\Domain\Catalog\FormattedText;
use Filament\Forms\Components\RichEditor;
/**
* Der eine Editor für formatierte Texte (ADR-50): immer dieselbe Symbolleiste, dasselbe Ergebnis (bereinigtes HTML).
* Neue formatierte Felder nutzen diesen Baustein und keinen eigenen Editor.
*/
final class RichField
{
/**
* @param ?string $label Mit Bezeichnung für Formulare und Dialoge; ohne bleibt sie dem Arbeitsplatz überlassen
* @param bool $live Arbeitsplätze gleichen beim Verlassen des Felds ab ({@see ManagesRichFields}); Dialoge nicht
*/
public static function make(string $name, ?string $label = null, bool $live = true): RichEditor
{
$field = RichEditor::make($name)->toolbarButtons(FormattedText::TOOLBAR);
if ($live) {
$field->live(onBlur: true);
}
return $label === null ? $field->hiddenLabel() : $field->label($label);
}
}
+11 -3
View File
@@ -12,6 +12,7 @@
use App\Domain\Catalog\ContentElementVersion;
use App\Domain\Catalog\EditorialProfileReader;
use App\Domain\Catalog\ExerciseGuide;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\ReleaseStatus;
use App\Domain\Catalog\StructureNode;
use App\Domain\Entitlement\DecideAccess;
@@ -125,7 +126,7 @@ public function index(User $user): array
'article' => $article,
'subject' => $subject,
'title' => $text['title'] ?? app(CourseOutline::class)->title($article),
'summary' => $text['summary'] ?? $element?->summary ?? $composition?->summary,
'summary' => $text['summary'] ?? FormattedText::plain($element?->summary ?? $composition?->summary) ?: null,
'kind' => app(CourseOutline::class)->kindLabel($article) ?? ($element === null ? null : $this->outputLabel($element->output_class)),
'coverage' => 'nutzbar',
'image' => $imageUrl === null ? null : ($element->thumbnail_alt ?: ($text['title'] ?? $element->working_title)),
@@ -170,6 +171,8 @@ public function program(User $user, Composition $composition): array
'title' => $text['title'],
'summary' => $text['summary'],
'description' => $text['description'],
'summary_html' => $text['summary_html'],
'description_html' => $text['description_html'],
'kind' => $composition->editorialContentKind?->label
?? ($composition->kind?->label()),
'is_module' => $composition->editorialContentKind?->slug === 'modul',
@@ -209,7 +212,7 @@ public function content(User $user, Composition $composition, int $elementVersio
$node = $found['node'];
$element = $node['element_id'] === null ? null : $this->element($node['element_id']);
$text = $element === null ? ['title' => $node['title'], 'summary' => null, 'description' => null] : $this->text($element);
$text = $element === null ? ['title' => $node['title'], 'summary' => null, 'description' => null, 'summary_html' => '', 'description_html' => ''] : $this->text($element);
$rootText = $this->text($composition);
$trail = [['label' => $rootText['title'], 'url' => route('member.program', $composition)]];
@@ -234,6 +237,8 @@ public function content(User $user, Composition $composition, int $elementVersio
'title' => $text['title'],
'summary' => $text['summary'],
'description' => $text['description'],
'summary_html' => $text['summary_html'],
'description_html' => $text['description_html'],
'trail' => $trail,
'back' => $trail[array_key_last($trail)],
'companions' => $companions,
@@ -245,7 +250,7 @@ public function content(User $user, Composition $composition, int $elementVersio
* Anzeigetitel und -texte für die Mitgliederbibliothek: Abweichung für „Mitgliederbibliothek“, sonst die zentrale Angabe,
* zuletzt die interne Bezeichnung. Nichts wird kopiert oder ergänzt.
*
* @return array{title: string, summary: ?string, description: ?string}
* @return array{title: string, summary: ?string, description: ?string, summary_html: string, description_html: string}
*/
public function text(Model $subject): array
{
@@ -261,6 +266,9 @@ public function text(Model $subject): array
'title' => $profile->value('display_title') ?? $profile->workingTitle ?? '',
'summary' => $profile->value('summary') ?? $profile->value('teaser'),
'description' => $profile->value('description'),
// Formatierte Fassung für Seiten, die sie zeigen; sonst gilt der Klartext oben.
'summary_html' => $profile->html('summary') ?: ($profile->value('teaser') !== null ? '<p>'.e($profile->value('teaser')).'</p>' : ''),
'description_html' => $profile->html('description'),
];
}
+24
View File
@@ -0,0 +1,24 @@
<?php
/**
* Nur die abweichenden Werte; alles andere gilt wie im Paket (`vendor/livewire/livewire/config/livewire.php`).
*/
return [
/*
|---------------------------------------------------------------------------
| Payload Guards
|---------------------------------------------------------------------------
|
| Der Editor für formatierte Texte hält sein Dokument als verschachtelte Daten. Eine Aufzählung liegt dort elf Ebenen
| tief (rich.feld.content.1.content.1.content.0.content.0.text), verschachtelte Listen noch tiefer. Die Vorgabe von 10
| Ebenen lehnt solche Texte ab (ADR-50). Die übrigen Grenzen bleiben wie im Paket.
|
*/
'payload' => [
'max_size' => 1024 * 1024,
'max_nesting_depth' => 30,
'max_calls' => 50,
'max_components' => 200,
],
];
@@ -706,3 +706,24 @@ ## ADR-49 – Übungsverwaltung: Übung als Komposition mit Varianten, Medienspe
**Folgen.** Alle Migrationen sind additiv; der Rückfall setzt nur den Code zurück. Nach einem Rückfall werden Übungen im vorherigen Stand nicht bearbeitet oder veröffentlicht. Der Rückfallschutz (Teil 0) muss auf `main` liegen, bevor auf Prod die erste Übung entsteht.
**Nachtrag (23.11.2026): Zugangsschlüssel in der Verwaltung hinterlegen und ersetzen.** Der Zugangsschlüssel der Shinkan-Anbindung lässt sich auf der Seite „Übungen aus Shinkan“ hinterlegen, ersetzen und prüfen (nur Katalogverwalter und Systemverwalter), damit ein Wechsel keine Änderung der Serverdatei und keinen neuen Container braucht. Die **Adresse bleibt je Umgebung vorgegeben** (`SHINKAN_DISTRIBUTION_URL`). Rangfolge beim Schlüssel: Ein Schlüssel aus der Umgebung des Servers (`SHINKAN_DISTRIBUTION_KEY`) hat Vorrang und bleibt die bestehende Anbindung; fehlt er dort, gilt der in der Verwaltung hinterlegte. Der hinterlegte Schlüssel liegt je Umgebung getrennt mit dem Anwendungsschlüssel verschlüsselt in `site_settings`, wird nie an den Browser zurückgegeben, nie angezeigt, nie protokolliert und steht in keiner Fehlermeldung oder Adresse. Die Redaktion sieht nur den Zustand („hinterlegt“, Herkunft) und arbeitet mit der Anbindung. **Das nimmt genau diesen Schlüssel von der Regel „Geheimnisse nur in den Env-Dateien der Server“ aus** (angepasst in `CLAUDE.md`, „Server und Umgebungen“). Folge: Wer `APP_KEY` wechselt, muss den Schlüssel neu hinterlegen; ein Rückfall des Codes lässt die Einstellung unberührt.
## ADR-50 – Formatierte Texte: bereinigtes HTML als einziges Format, ein Editor, eine kanonische Form
**Status:** umgesetzt, fachlich zu bestätigen. **Datum:** 23.11.2026. **Anlass:** Shinkan liefert Übungstexte jetzt als HTML (`text_format: html`); Lars verlangt für alle Textfelder Editoren mit Symbolleiste und visueller Darstellung.
**Entscheidung.**
- **Format.** Formatierte Texte werden als **bereinigtes HTML** aus einer festen Auswahl gespeichert: Absatz, Zwischenüberschrift (`h3`), fett, kursiv, Aufzählung, nummerierte Liste, Zitat, Link (http, https, mailto) und Zeilenumbruch. Alles andere fällt beim Speichern weg (Skripte, Ereignisattribute, andere Schemata, Bilder, Tabellen, Unterstreichung). Markdown wurde verworfen: Die Editoren arbeiten mit einem Dokumentmodell, das HTML-nah ist, die Quelle liefert HTML und das CMS speichert HTML bereits. Eine Umwandlung in beide Richtungen wäre verlustbehaftet.
- **Ein Baustein.** `App\Domain\Catalog\FormattedText` bereinigt, bringt Werte in die **kanonische Form**, wandelt Klartext des Altbestands und liefert Klartext, Auszug und Blöcke mit Auszeichnung (für das PDF). `App\Filament\Support\RichField` ist der eine Editor (Filament `RichEditor`, immer dieselbe Symbolleiste). Neue formatierte Felder nutzen ihn.
- **Kanonische Form.** Es wird nur in kanonischer Form verglichen, gehasht und gespeichert: Das Öffnen eines Felds im Editor, andere Schreibweise desselben Inhalts (`b`/`strong`, Zeilenumbrüche zwischen Blöcken, Listenpunkte mit oder ohne Absatz) und Klartext gegen HTML erzeugen weder „Geändert“-Markierungen noch neue Fassungen noch Scheinkonflikte beim Abgleich mit Shinkan. Lesbar und prüfbar ist das mit `FormattedText::same()`.
- **Erkennung statt Spalte.** Es gibt keine Formatspalte und keine Datenmigration. Ein Wert ist HTML, wenn er (nach Leerraum) mit einem Blockelement der Auswahl beginnt (`p`, `h3`, `ul`, `ol`, `blockquote`); gespeichertes HTML ist kanonisch und beginnt immer so. Klartext des Altbestands bleibt unverändert, bis jemand ihn ändert. Beim Anzeigen und Bearbeiten wird er nach den bekannten Konventionen (Leerzeile, „- “, „1. “, „## “) umgewandelt; Zeilenumbrüche an Stellen, die sie bisher zeigten, bleiben dort erhalten (`FormattedText::display`).
- **Arbeitsplätze.** Die Arbeitsplätze halten Texte als Zeichenketten; der Editor hält ein Dokument. `ManagesRichFields` verbindet beides: Die Zeichenkette ist maßgeblich, der Editor gleicht sich vor dem Rendern an, wenn der Server sie geändert hat, und schreibt beim Verlassen des Felds kanonisches HTML zurück. Beim Speichern einer Spalte bleibt ein inhaltlich unveränderter Altwert unverändert (`richStore`).
- **Formatiert sind:** Texte der Übungen und Textbausteine, Kurzbeschreibung und Beschreibung von Modulen, Programmen, Übungen, Medien und Lizenzartikeln, Lernziel und Ausstattung (Material) der Fassungen, Text einer Textfassung. **Klartext bleiben:** Titel, Teaser, Suchbegriffe, Variantenname und -beschreibung, interne Notizen, Lizenzvermerk, Änderungsnotizen, Voraussetzungen, Abweichungen je Zielgruppe.
- **Sichere Voreinstellung.** `EditorialProfile::value()` liefert für Kurzbeschreibung und Beschreibung **Klartext** (Karten, Listen, Suche, Zahlungsdienst, Meta-Angaben); wer formatiert zeigt, ruft `html()` auf. So gelangt keine Auszeichnung an eine Stelle, die kein HTML kennt.
- **Ausgabe.** Seiten geben das bereinigte HTML aus (nur nach `FormattedText::html()` oder `display()`, nie ungeprüft). Das PDF liest dieselben Blöcke und setzt fett und kursiv mit den Helvetica-Schnitten (neu: Oblique und Bold-Oblique, nur eingebunden, wenn das Dokument sie braucht; Belege bleiben byte-gleich). Links erscheinen auf Papier mit ausgeschriebener Adresse.
- **Shinkan.** Der Abruf wertet `text_format` aus. `html` gilt für Kurzbeschreibung, Lernziel, Durchführung, Vorbereitung, Trainerhinweise und die Abweichung der Durchführung einer Variante; ohne Angabe sind alle Texte Klartext wie bisher. Verweise auf Quellmedien im Text (`data-shinkan-exercise-media`) entfallen, weil keine Quellmedien übernommen werden. Vergleich und Dreiwegeabgleich arbeiten in kanonischer Form.
**Alternativen.** Markdown als Speicherformat (verworfen, siehe oben); Dokument-JSON des Editors (verworfen: Quelle und CMS liefern HTML, Hashes und Vergleiche wären an die Editorversion gebunden); Formatspalte je Feld (verworfen: Migration ohne Gewinn, die Erkennung ist eindeutig, weil gespeichertes HTML kanonisch ist).
**Folgen.** Keine Migration. Nach einem Code-Rückfall zeigt der vorherige Stand HTML-Texte mit sichtbaren Tags; für Übungen spielt das keine Rolle, solange auf Prod keine Übung liegt. Die erste Übernahme mit HTML zählt für jeden Textabschnitt als Änderung der Quelle (die Formatierung kommt hinzu); wo ein Abschnitt lokal bearbeitet wurde, fragt die Vorschau nach. Das CMS nutzt weiter `RichText` (eigene Auswahl); die Umstellung auf denselben Baustein ist ein späterer Schritt.
**Quelle.** Anfragen von Lars vom 23.11.2026 (Formatierung der Übungstexte, Editoren für alle Textfelder); Shinkan-Commit „Deliver stored exercise HTML on the catalog API“.
@@ -0,0 +1,28 @@
# Abnahme: formatierte Texte (ADR-50)
Stand: 23.11.2026. **Geprüft lokal im Browser** (Arbeitsbaum, SQLite, Playwright), **nicht auf luf-test**. Die Prüfung auf luf-test steht nach dem Deployment aus.
## Was geprüft ist
| Nachweis | Befund |
|---|---|
| `formatierte-texte/01-editor-kurzbeschreibung.png` | Der Editor erscheint im Feld „Kurzbeschreibung“ der Redaktion mit Symbolleiste: fett, kursiv, Link, Zwischenüberschrift, Liste, nummerierte Liste, Zitat, Rückgängig, Wiederholen. Der Klartext des Altbestands steht im Editor; das Öffnen setzt weder die Markierung „Geändert“ noch „Ungespeicherte Änderungen“. |
| `02-anzeige-mit-liste.png` | Nach „Fertig“ steht der Text formatiert (fett, Liste mit Punkten). „Geändert“ erscheint erst nach der Eingabe; „Redaktion speichern“ legt kanonisches HTML ab (`<p>…<strong>fett</strong>…</p><ul><li><p>…</p></li></ul>`). |
| `03-lernziel-ausstattung.png` | Lernziel und Ausstattung (Material) sind im Aufbau formatierbar. Der Entwurf speichert HTML; bei geöffnetem Altbestand meldet der Arbeitsplatz keine ungespeicherten Änderungen. |
| `04-neuer-text.png` | Ein neuer Text entsteht im Dialog mit dem Editor und wird als HTML gespeichert; die Quelle des Textes ist im Reiter „Quelle“ ebenfalls im Editor bearbeitbar. |
| `05-mitgliederansicht-prosa.png` | Darstellung im Mitgliederbereich mit dem gebauten Stylesheet (Abschnitt „Durchführung“, Lernziel und Ausstattung): Absatz, Zwischenüberschrift, Listen mit Punkten und Nummern, Zitat, Link, fett und kursiv. Die Seite wurde als statisches Beispiel mit den echten Klassen und dem echten CSS gerendert, nicht mit einem Mitgliedskonto. |
Automatisch (Gate): Bereinigung und kanonische Form (`FormattedTextTest`), Anbindung des Editors an die Arbeitsplätze und Altbestand ohne Änderungsmarkierung (`FormatierteTexteEditorTest`), Mitgliederansicht und PDF mit fett und kursiv (`UebungAusgabeTest`), Übernahme aus Shinkan als HTML (`ShinkanUebernahmeTest`).
## Gefundene und behobene Fehler
- Das Livewire-Limit für verschachtelte Pfade (10 Ebenen) lehnte Texte mit Aufzählung ab: `config/livewire.php` setzt 30. Der Test `test_a_list_and_a_nested_list_pass_the_payload_depth_guard` belegt es.
- Das Öffnen eines Altbestands meldete „Es gibt ungespeicherte Änderungen“, weil Klartext und HTML verglichen wurden. Der Vergleich arbeitet jetzt in kanonischer Form.
- Listenpunkte fehlten in der Anzeige (Stilrücksetzung), im Mitgliederbereich liefen Listen im Faktenblock inline. Die Stile stehen in `verwaltung/styles.blade.php` und `lf-member.css`.
## Offen
- Prüfung auf luf-test nach dem Deployment (breite und schmale Fenster, Tastatur im Editor).
- Echter Abruf aus Shinkan mit HTML, sobald die produktive Quelle `text_format: html` liefert (nicht geprüft).
- Mitgliederansicht und PDF mit einem Testkonto auf luf-test (siehe `uebungen.md`).
- Nicht umgestellt: CMS-Texte (eigene Auswahl `RichText`), Abweichungen je Zielgruppe, Variantenbeschreibung.
Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 155 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

+79
View File
@@ -1014,6 +1014,37 @@ .mb-facts svg {
height: 1.1rem;
}
/* Angaben einer Übung (Lernziel, Dauer, Ausstattung): Bezeichnung und formatierter Text untereinander */
.mb-exercise .mb-facts {
display: grid;
align-items: start;
gap: var(--space-3);
margin-block: var(--space-4);
font-size: var(--text-body);
font-weight: 400;
}
.mb-exercise .mb-facts > div {
display: grid;
gap: var(--space-1);
}
.mb-exercise .mb-facts dt {
font-size: var(--text-small);
font-weight: 700;
}
.mb-exercise .mb-facts dd {
margin: 0;
}
@media (min-width: 40rem) {
.mb-exercise .mb-facts > div {
grid-template-columns: 9rem minmax(0, 1fr);
gap: var(--space-3);
}
}
.mb-note {
padding: var(--space-2) var(--space-3);
border-left: 4px solid currentColor;
@@ -1100,6 +1131,54 @@ .mb-prose > :last-child {
margin-bottom: 0;
}
/* Formatierte Texte (ADR-50): Absatz, Zwischenüberschrift, Listen, Zitat, Link */
.mb-prose p {
margin: 0 0 var(--space-3);
}
.mb-prose h3 {
margin: var(--space-4) 0 var(--space-2);
font-size: var(--text-body);
}
.mb-prose ul,
.mb-prose ol {
margin: 0 0 var(--space-3);
padding-left: 1.4rem;
}
.mb-prose ul {
list-style: disc;
}
.mb-prose ol {
list-style: decimal;
}
.mb-prose li {
display: list-item;
}
.mb-prose li > p {
margin: 0 0 var(--space-1);
}
.mb-prose a {
color: var(--lf-green-deep);
text-decoration: underline;
text-underline-offset: 0.15em;
}
.mb-prose blockquote {
margin: 0 0 var(--space-3);
padding-left: var(--space-3);
border-left: 3px solid var(--color-accent);
}
.mb-prose blockquote > p {
margin-bottom: var(--space-2);
}
.mb-reading {
max-width: var(--measure);
padding: var(--pad-card);
+1 -1
View File
@@ -27,6 +27,6 @@
@if (filled($version->body))
<article class="prose">
{!! nl2br(e($version->body)) !!}
{!! \App\Domain\Catalog\FormattedText::display($version->body) !!}
</article>
@endif
@@ -145,9 +145,10 @@
<label class="vw-feldlabel">Titel
<input id="text-titel" class="vw-eingabe" type="text" wire:model="newTextTitle" required autofocus>
</label>
<label class="vw-feldlabel">Inhalt
<textarea id="text-inhalt" class="vw-eingabe" rows="8" wire:model="newTextBody" required></textarea>
</label>
<div class="vw-feldlabel" role="group" aria-labelledby="text-inhalt-neu-label">
<span id="text-inhalt-neu-label">Inhalt</span>
<div class="vw-rich-eingabe">{{ $this->richKomponente('newTextBody') }}</div>
</div>
</div>
<div class="vw-dialog-fuss">
<div class="vw-dialog-fuss-zeile">
@@ -34,22 +34,22 @@
@endif
<h1>{{ $title }}</h1>
@if (filled($summary))
<p>{{ $summary }}</p>
<div>{!! \App\Domain\Catalog\FormattedText::display($summary) !!}</div>
@endif
@if (filled($description ?? null))
<h2>Beschreibung</h2>
<p>{{ $description }}</p>
<div>{!! \App\Domain\Catalog\FormattedText::display($description) !!}</div>
@endif
@if (filled($learningGoal))
<h2>Lernziel</h2>
<p>{{ $learningGoal }}</p>
<div>{!! \App\Domain\Catalog\FormattedText::display($learningGoal) !!}</div>
@endif
@if ($durationMinutes)
<p>Zeit: {{ $durationMinutes }} Minuten</p>
@endif
@if (filled($materialNote))
<h2>Material</h2>
<p>{{ $materialNote }}</p>
<div>{!! \App\Domain\Catalog\FormattedText::display($materialNote) !!}</div>
@endif
<h2>Aufbau</h2>
@include('filament.editorial.preview-nodes', ['nodes' => $nodes])
@@ -177,8 +177,8 @@
<div class="vw-detail-inhalt">
@if ($canEditBody)
<label class="vw-feldlabel" for="fassung-text">Text der Fassung</label>
<textarea id="fassung-text" class="vw-eingabe" rows="14" wire:model.live.blur="bodyDraft"></textarea>
<span class="vw-feldlabel" id="fassung-text-label">Text der Fassung</span>
<div id="fassung-text" class="vw-rich-eingabe">{{ $this->richKomponente('bodyDraft') }}</div>
<p class="vw-feld-hilfe">
@if ($bodyCommitted)
Fassung {{ $shown->number }} ist freigegeben und wird verwendet. Sie bleibt unverändert, „Text speichern“ legt Fassung {{ $naechste }} an.
@@ -8,9 +8,10 @@
<section class="vw-medien-haupt" aria-labelledby="didaktik-titel">
<h2 id="didaktik-titel" class="vw-abschnitt-titel">Didaktik</h2>
<p class="vw-feld-hilfe">Lernziel, Zeit und Material gehören zum fachlichen Stand {{ $ort }}. Sie werden mit „Entwurf speichern“ gesichert und erst mit „Fassung freigeben“ Teil einer neuen Fassung.</p>
<label class="vw-feldlabel">Lernziel
<textarea class="vw-eingabe" rows="4" wire:model.live.blur="learningGoal"></textarea>
</label>
<div class="vw-feldlabel" role="group" aria-labelledby="lernziel-label">
<span id="lernziel-label">Lernziel</span>
<div class="vw-rich-eingabe">{{ $this->richKomponente('learningGoal') }}</div>
</div>
<div class="vw-raster-2">
<label class="vw-feldlabel">Zeitbedarf in Minuten
<input class="vw-eingabe" type="text" inputmode="numeric" wire:model.live.blur="durationMinutes">
@@ -19,9 +20,10 @@
<input class="vw-eingabe" type="text" wire:model.live.blur="revisionNote">
</label>
</div>
<label class="vw-feldlabel">{{ $this->isExercise() ? 'Ausstattung' : 'Materialbedarf' }}
<textarea class="vw-eingabe" rows="3" wire:model.live.blur="materialNote"></textarea>
</label>
<div class="vw-feldlabel" role="group" aria-labelledby="material-label">
<span id="material-label">{{ $this->isExercise() ? 'Ausstattung' : 'Materialbedarf' }}</span>
<div class="vw-rich-eingabe">{{ $this->richKomponente('materialNote') }}</div>
</div>
@if ($this->isExercise())
<div class="vw-raster-2">
<label class="vw-feldlabel">Zeitbedarf bis (Minuten)
@@ -147,9 +147,10 @@
<label class="vw-feldlabel">Titel
<input class="vw-eingabe" type="text" wire:model="partTitle">
</label>
<label class="vw-feldlabel">Inhalt
<textarea class="vw-eingabe" rows="8" wire:model="partBody"></textarea>
</label>
<div class="vw-feldlabel" role="group" aria-labelledby="text-inhalt-label">
<span id="text-inhalt-label">Inhalt</span>
<div class="vw-rich-eingabe">{{ $this->richKomponente('partBody') }}</div>
</div>
<p class="vw-feld-hilfe">
@if (! empty($gewaehlt['committed']))
Diese Fassung ist freigegeben und wird verwendet. Speichern legt eine neue Fassung an; die bisherige bleibt in den freigegebenen Aufbauten.
@@ -167,6 +167,18 @@
.vw-feld-kopf .vw-feld-aktion { margin-left: auto; }
.vw-feld-wert { white-space: pre-line; overflow-wrap: anywhere; }
.vw-feld-wert.is-uebernommen { color: var(--vw-quiet); }
/* Formatierte Texte (ADR-50): Anzeige und Editor */
.vw-feld-wert.vw-rich { white-space: normal; }
.vw-rich p { margin: 0 0 0.5rem; }
.vw-rich h3 { margin: 0.75rem 0 0.35rem; font-size: 1rem; }
.vw-rich ul, .vw-rich ol { margin: 0 0 0.5rem; padding-left: 1.4rem; }
.vw-rich ul { list-style: disc; }
.vw-rich ol { list-style: decimal; }
.vw-rich li > p { margin: 0 0 0.2rem; }
.vw-rich blockquote { margin: 0 0 0.5rem; padding-left: 0.8rem; border-left: 3px solid var(--vw-line, #d5ddd6); }
.vw-rich > :last-child { margin-bottom: 0; }
.vw-rich-eingabe { display: block; margin-top: 0.3rem; font-weight: 400; }
.vw-rich-eingabe .fi-fo-rich-editor { min-width: 0; }
.vw-feld-wert.is-leer { color: var(--vw-muted); font-style: italic; }
.vw-feld-wert.is-kurz:not(.is-voll) { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
.vw-feld-edit { display: grid; gap: 0.45rem; }
@@ -6,8 +6,9 @@
$uebernommen = $wert === '' && $quelleWert !== '';
$geaendert = $this->feldGeaendert($feld);
$fehler = $this->redaktionFehlerFeld === $model;
$lang = mb_strlen($uebernommen ? $quelleWert : $wert) > 220;
$kind = $feld['kind'] ?? 'text';
$rich = $kind === 'rich';
$lang = mb_strlen($rich ? \App\Domain\Catalog\FormattedText::plain($uebernommen ? $quelleWert : $wert) : ($uebernommen ? $quelleWert : $wert)) > 220;
$id = 'feld-'.$feld['id'];
@endphp
<section @class(['vw-feld', 'is-fehler' => $fehler]) wire:key="feld-{{ $feld['id'] }}" x-data="{ offen: @js($fehler), voll: false }">
@@ -35,7 +36,11 @@
@if ($wert === '' && ! $uebernommen)
<p class="vw-feld-wert is-leer">Keine Angabe</p>
@else
<p @class(['vw-feld-wert', 'is-uebernommen' => $uebernommen, 'is-kurz' => $lang]) x-bind:class="{ 'is-voll': voll }">{{ $uebernommen ? $quelleWert : $wert }}</p>
@if ($rich)
<div @class(['vw-feld-wert', 'vw-rich', 'is-uebernommen' => $uebernommen, 'is-kurz' => $lang]) x-bind:class="{ 'is-voll': voll }">{!! \App\Domain\Catalog\FormattedText::html($uebernommen ? $quelleWert : $wert) !!}</div>
@else
<p @class(['vw-feld-wert', 'is-uebernommen' => $uebernommen, 'is-kurz' => $lang]) x-bind:class="{ 'is-voll': voll }">{{ $uebernommen ? $quelleWert : $wert }}</p>
@endif
@if ($lang)
<button type="button" class="vw-link is-quiet" x-on:click="voll = ! voll" x-text="voll ? 'Weniger anzeigen' : 'Ganzen Text anzeigen'">Ganzen Text anzeigen</button>
@endif
@@ -45,7 +50,9 @@
@if ($editable)
<div class="vw-feld-edit" id="{{ $id }}" x-show="offen" x-cloak>
<label class="vw-sr" for="{{ $id }}-eingabe">{{ $feld['label'] }}</label>
@if ($kind === 'textarea')
@if ($rich)
<div id="{{ $id }}-eingabe" x-ref="eingabe" class="vw-rich-eingabe" x-on:keydown.escape.stop="offen = false">{{ $this->richKomponente($model) }}</div>
@elseif ($kind === 'textarea')
<textarea id="{{ $id }}-eingabe" x-ref="eingabe" rows="{{ $feld['rows'] ?? 4 }}" wire:model.live.blur="{{ $model }}" placeholder="{{ $uebernommen || $wert === '' ? ($quelleWert !== '' ? $quelleWert : ($feld['placeholder'] ?? '')) : ($feld['placeholder'] ?? '') }}" @if ($fehler) aria-invalid="true" aria-describedby="{{ $id }}-fehler" @endif x-on:keydown.escape.stop="offen = false"></textarea>
@else
<input id="{{ $id }}-eingabe" x-ref="eingabe" type="text" wire:model.live.blur="{{ $model }}" placeholder="{{ $uebernommen || $wert === '' ? ($quelleWert !== '' ? $quelleWert : ($feld['placeholder'] ?? '')) : ($feld['placeholder'] ?? '') }}" @if ($fehler) aria-invalid="true" aria-describedby="{{ $id }}-fehler" @endif x-on:keydown.escape.stop="offen = false" x-on:keydown.enter.prevent="$el.blur(); offen = false">
+1 -1
View File
@@ -60,7 +60,7 @@
@endif
@if (filled($entry['version']->body))
<article class="mb-prose">
{!! nl2br(e($entry['version']->body)) !!}
{!! \App\Domain\Catalog\FormattedText::display($entry['version']->body) !!}
</article>
@endif
</li>
+5 -5
View File
@@ -78,14 +78,14 @@
</div>
<aside class="mb-content-side">
@if (filled($summary) || filled($description))
@if (filled($summary_html) || filled($description_html))
<section class="mb-side-card" aria-labelledby="kurz">
<h2 id="kurz">Kurzbeschreibung</h2>
@if (filled($summary))
<p>{{ $summary }}</p>
@if (filled($summary_html))
<div class="mb-prose">{!! $summary_html !!}</div>
@endif
@if (filled($description))
<div class="mb-prose">{!! nl2br(e($description)) !!}</div>
@if (filled($description_html))
<div class="mb-prose">{!! $description_html !!}</div>
@endif
</section>
@endif
+5 -5
View File
@@ -13,8 +13,8 @@
<article class="mb-reading mb-exercise">
<header class="mb-content-head">
<h1 class="mb-title">{{ $guide['title'] }}</h1>
@if (filled($guide['summary']))
<p class="mb-lead">{{ $guide['summary'] }}</p>
@if (filled($guide['summary_html']))
<div class="mb-lead mb-prose">{!! $guide['summary_html'] !!}</div>
@endif
</header>
@@ -24,7 +24,7 @@
<dl class="mb-facts">
@if (filled($guide['learning_goal']))
<div><dt>Lernziel</dt><dd>{{ $guide['learning_goal'] }}</dd></div>
<div><dt>Lernziel</dt><dd class="mb-prose">{!! \App\Domain\Catalog\FormattedText::display($guide['learning_goal']) !!}</dd></div>
@endif
@if ($guide['duration_minutes'] !== null)
<div><dt>Dauer</dt><dd>{{ $guide['duration_minutes'] }}@if ($guide['duration_max'] !== null) bis {{ $guide['duration_max'] }}@endif Minuten</dd></div>
@@ -33,7 +33,7 @@
<div><dt>Voraussetzungen</dt><dd>{{ $guide['prerequisites'] }}</dd></div>
@endif
@if (filled($guide['material_note']))
<div><dt>Ausstattung</dt><dd>{{ $guide['material_note'] }}</dd></div>
<div><dt>Ausstattung</dt><dd class="mb-prose">{!! \App\Domain\Catalog\FormattedText::display($guide['material_note']) !!}</dd></div>
@endif
</dl>
@@ -71,7 +71,7 @@
@if ($entry['allowed'] && $entry['class'] === 'text')
<h2>{{ $entry['title'] }}</h2>
<div class="mb-prose">
@include('member.partials.guide-blocks', ['blocks' => $entry['blocks']])
{!! $entry['html'] !!}
</div>
@elseif ($entry['allowed'])
<h2>{{ $entry['title'] }}</h2>
@@ -1,23 +0,0 @@
@foreach ($blocks as $block)
@switch ($block['type'])
@case ('heading')
<h3>{{ $block['text'] }}</h3>
@break
@case ('bullets')
<ul>
@foreach ($block['items'] as $item)
<li>{{ $item }}</li>
@endforeach
</ul>
@break
@case ('numbered')
<ol>
@foreach ($block['items'] as $item)
<li>{{ $item }}</li>
@endforeach
</ol>
@break
@default
<p>{{ $block['text'] }}</p>
@endswitch
@endforeach
+8 -8
View File
@@ -10,7 +10,7 @@
--}}
@section('content')
@php
$hasOverview = filled($description) || filled($learning_goal);
$hasOverview = filled($description_html) || filled($learning_goal);
$hasUse = filled($material_note);
$facts = [];
if ($module_count > 0) {
@@ -40,8 +40,8 @@
<div class="mb-detail-copy">
<x-member.type :type="$is_module ? 'modul' : 'programm'" :label="$kind" />
<h1 class="mb-title">{{ $title }} <x-brand.underline class="mb-title-line" /></h1>
@if (filled($summary))
<p class="mb-lede">{{ $summary }}</p>
@if (filled($summary_html))
<div class="mb-lede mb-prose">{!! $summary_html !!}</div>
@endif
<ul class="mb-facts">
@foreach ($facts as $fact)
@@ -69,17 +69,17 @@
@endif
@if ($hasOverview)
<section class="mb-section mb-overview {{ filled($description) && filled($learning_goal) ? '' : 'mb-overview-single' }}" id="ueberblick" aria-label="Überblick">
@if (filled($description))
<section class="mb-section mb-overview {{ filled($description_html) && filled($learning_goal) ? '' : 'mb-overview-single' }}" id="ueberblick" aria-label="Überblick">
@if (filled($description_html))
<div class="mb-overview-text">
<h2 id="ueberblick-titel">Darum geht es</h2>
<div class="mb-prose">{!! nl2br(e($description)) !!}</div>
<div class="mb-prose">{!! $description_html !!}</div>
</div>
@endif
@if (filled($learning_goal))
<aside class="mb-goal" aria-labelledby="lernziel-titel">
<h3 id="lernziel-titel"><x-heroicon-o-check-circle aria-hidden="true" /> Lernziele</h3>
<div class="mb-prose">{!! nl2br(e($learning_goal)) !!}</div>
<div class="mb-prose">{!! \App\Domain\Catalog\FormattedText::display($learning_goal) !!}</div>
</aside>
@endif
</section>
@@ -104,7 +104,7 @@
<h2 id="einsatz-titel">Einsatz &amp; Vorbereitung</h2>
<div class="mb-note-card">
<h3>Material</h3>
<div class="mb-prose">{!! nl2br(e($material_note)) !!}</div>
<div class="mb-prose">{!! \App\Domain\Catalog\FormattedText::display($material_note) !!}</div>
</div>
</section>
@endif
+1 -1
View File
@@ -14,7 +14,7 @@
<p class="state state-hinweis">Lizenzkennzeichnung: {{ $license }}</p>
@endif
<div class="mb-prose">
{!! nl2br(e($version->body)) !!}
{!! \App\Domain\Catalog\FormattedText::display($version->body) !!}
</div>
</article>
@endsection
+2 -2
View File
@@ -6,10 +6,10 @@
<p><a href="{{ route('public.programs') }}">Programme</a></p>
<h1>{{ $composition->display_title ?: $composition->designation }}</h1>
@if (filled($composition->summary))
<p class="lede">{{ $composition->summary }}</p>
<div class="lede">{!! \App\Domain\Catalog\FormattedText::display($composition->summary) !!}</div>
@endif
@if (filled($version->learning_goal))
<p>Lernziel: {{ $version->learning_goal }}</p>
<div><strong>Lernziel:</strong> {!! \App\Domain\Catalog\FormattedText::display($version->learning_goal) !!}</div>
@endif
<ol class="course">
@foreach ($nodes as $node)
+2 -2
View File
@@ -273,7 +273,7 @@ public function test_a_license_article_overrides_only_its_own_presentation(): vo
$article->refresh();
$release->refresh();
$this->assertSame('Eigene Artikelbeschreibung', $article->summary);
$this->assertSame('<p>Eigene Artikelbeschreibung</p>', $article->summary);
$this->assertNull($article->teaser);
$again = app(EditorialProfileReader::class)->read($article, 'artikel');
$this->assertSame('eigen', $again->origin('summary'));
@@ -288,7 +288,7 @@ public function test_a_license_article_overrides_only_its_own_presentation(): vo
$cover = $this->pictureWithoutVersion('Artikelbild ohne Fassung');
Livewire::test(ViewLicenseArticle::class, ['record' => $article->getKey()])
->assertSet('summary', 'Eigene Artikelbeschreibung')
->assertSet('summary', '<p>Eigene Artikelbeschreibung</p>')
->call('openRedaktion')
->set('descriptionText', 'Nur dieser Artikel')
->call('openPresentationPicker', 'titelbild')
+12 -12
View File
@@ -84,7 +84,7 @@ public function test_display_data_does_not_create_a_version_and_a_module_works_w
$this->assertSame('Sichtbar ohne Film', $module->display_title);
$this->assertSame(1, $module->versions()->count());
$this->assertSame('Den Abstand erklären', $module->versions()->first()->learning_goal);
$this->assertSame('<p>Den Abstand erklären</p>', $module->versions()->first()->learning_goal);
$this->assertSame(1, $module->versions()->first()->members()->count());
}
@@ -259,18 +259,18 @@ public function test_saving_a_draft_ten_times_creates_one_version_only_when_rele
$module->refresh();
$this->assertSame(0, $module->versions()->count());
$this->assertSame('Durchgang 10', $module->working_draft['learning_goal']);
$this->assertSame('<p>Durchgang 10</p>', $module->working_draft['learning_goal']);
Livewire::actingAs($editor, 'staff')
->test(EditExercise::class, ['record' => $module->id])
->assertSet('learningGoal', 'Durchgang 10')
->assertSet('learningGoal', '<p>Durchgang 10</p>')
->set('releaseConsent', true)
->call('publishRevision')
->assertSet('feedback', 'Fassung 1 ist freigegeben. Der Entwurf ist geschlossen und die bisherige Fassung bleibt erhalten. Die Mitgliederbibliothek ändert sich dadurch nicht.');
$module->refresh();
$this->assertSame(1, $module->versions()->count());
$this->assertSame('Durchgang 10', $module->versions()->first()->learning_goal);
$this->assertSame('<p>Durchgang 10</p>', $module->versions()->first()->learning_goal);
$this->assertNull($module->working_draft);
Livewire::actingAs($editor, 'staff')
@@ -280,8 +280,8 @@ public function test_saving_a_draft_ten_times_creates_one_version_only_when_rele
$module->refresh();
$this->assertSame(1, $module->versions()->count());
$this->assertSame('Durchgang 10', $module->versions()->first()->fresh()->learning_goal);
$this->assertSame('Nur Entwurf', $module->working_draft['learning_goal']);
$this->assertSame('<p>Durchgang 10</p>', $module->versions()->first()->fresh()->learning_goal);
$this->assertSame('<p>Nur Entwurf</p>', $module->working_draft['learning_goal']);
}
public function test_the_picker_finds_a_film_by_title(): void
@@ -393,7 +393,7 @@ public function test_a_chosen_picture_and_description_do_not_create_a_version():
$this->assertSame(1, $composition->versions()->count());
$this->assertSame('vorschau/komposition-'.$composition->id.'.jpg', $composition->thumbnail_path);
$this->assertSame('element:'.$first->element->id, $composition->thumbnail_source);
$this->assertSame('Eine fachliche Beschreibung für die Bibliothek.', $composition->description);
$this->assertSame('<p>Eine fachliche Beschreibung für die Bibliothek.</p>', $composition->description);
Storage::disk('media_derived')->assertExists($composition->thumbnail_path);
$this->get('/medien/'.$composition->thumbnail_path)->assertNotFound();
}
@@ -429,7 +429,7 @@ public function test_texts_save_in_the_redaktion_and_the_dialog_keeps_didactics_
$composition = $version->composition->fresh();
$this->assertSame(1, $composition->versions()->count());
$this->assertSame('Ausführlicher Dialogtext', $composition->description);
$this->assertSame('<p>Ausführlicher Dialogtext</p>', $composition->description);
$this->assertNull($composition->working_draft);
Livewire::actingAs($editor, 'staff')
@@ -441,7 +441,7 @@ public function test_texts_save_in_the_redaktion_and_the_dialog_keeps_didactics_
$composition->refresh();
$this->assertSame(1, $composition->versions()->count());
$this->assertSame(ContentVersionStatus::Bereit, $composition->versions()->first()->status);
$this->assertSame('Nur im Entwurf', $composition->working_draft['learning_goal']);
$this->assertSame('<p>Nur im Entwurf</p>', $composition->working_draft['learning_goal']);
$this->assertSame(9, $composition->working_draft['duration_minutes']);
}
@@ -621,7 +621,7 @@ public function test_a_module_text_stays_editable_until_it_is_released_and_used(
$version = $element->versions()->sole();
$this->assertSame(ContentVersionStatus::Entwurf, $version->status);
$this->assertSame('Geänderter Wortlaut', $version->body);
$this->assertSame('<p>Geänderter Wortlaut</p>', $version->body);
$this->assertSame(1, $element->versions()->count());
$this->actingAs($editor, 'staff')
@@ -643,7 +643,7 @@ public function test_a_module_text_stays_editable_until_it_is_released_and_used(
->call('saveDraft');
$this->assertSame(2, $element->fresh()->versions()->count());
$this->assertSame('Geänderter Wortlaut', $version->fresh()->body);
$this->assertSame('<p>Geänderter Wortlaut</p>', $version->fresh()->body);
$this->assertSame($version->id, $module->fresh()->versions()->first()->members()->first()->content_element_version_id);
$this->assertSame('element:'.$element->versions()->orderByDesc('number')->first()->id, $module->fresh()->working_draft['members'][0]['target']);
}
@@ -685,7 +685,7 @@ public function test_a_file_can_be_created_inside_the_module(): void
$version = $element->versions()->sole();
$this->assertSame('document', $element->output_class);
$this->assertSame('Für die Gruppe', $element->description);
$this->assertSame('<p>Für die Gruppe</p>', $element->description);
$this->assertSame('Vorher lesen', $element->usage_note);
$this->assertSame(ContentVersionStatus::Entwurf, $version->status);
$this->assertSame('eigen', $element->fresh()->thumbnail_source);
@@ -0,0 +1,182 @@
<?php
namespace Tests\Feature;
use App\Domain\Catalog\CompositionKind;
use App\Domain\Catalog\ContentService;
use App\Domain\Catalog\FormattedText;
use App\Domain\Catalog\IdentityChange;
use App\Filament\Resources\ContentElements\Pages\ViewContentElement;
use App\Filament\Resources\Practices\Pages\EditPractice;
use App\Filament\Support\EditorialCatalog;
use App\Models\User;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\Support\BuildsExercises;
use Tests\TestCase;
/**
* Formatierte Textfelder im Arbeitsplatz (ADR-50): Der Editor schreibt kanonisches HTML in die Eigenschaft, Klartext des
* Altbestands erscheint formatiert, ohne dass das Öffnen etwas als geändert markiert.
*/
class FormatierteTexteEditorTest extends TestCase
{
use BuildsExercises;
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Filament::setCurrentPanel(Filament::getPanel('verwaltung'));
}
public function test_the_editor_state_reaches_the_property_as_canonical_html_and_back(): void
{
$practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise);
$component = Livewire::actingAs($this->editor(), 'staff')
->test(EditPractice::class, ['record' => $practice->getKey()])
->assertOk();
$component->set('rich.summary', [
'type' => 'doc',
'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => 'Fester ', 'marks' => []], ['type' => 'text', 'text' => 'Stand', 'marks' => [['type' => 'bold']]]]]],
]);
$this->assertSame('<p>Fester <strong>Stand</strong></p>', $component->get('summary'));
$component->set('summary', '<p>Vom Server</p>')->assertOk();
$this->assertSame('doc', $component->get('rich.summary.type'));
$this->assertSame('Vom Server', $component->get('rich.summary.content.0.content.0.text'));
}
public function test_legacy_plain_text_appears_formatted_but_opening_it_changes_nothing(): void
{
$practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise);
$practice->forceFill(['summary' => "Erste Zeile.\n\n- Punkt A\n- Punkt B"])->save();
$component = Livewire::actingAs($this->editor(), 'staff')
->test(EditPractice::class, ['record' => $practice->getKey()])
->assertOk();
$this->assertSame("Erste Zeile.\n\n- Punkt A\n- Punkt B", $component->get('summary'), 'Die Eigenschaft bleibt, was gespeichert ist.');
$this->assertSame('bulletList', $component->get('rich.summary.content.1.type'), 'Der Editor zeigt die Liste.');
$this->assertFalse($component->instance()->textFieldsChanged(), 'Öffnen markiert nichts als geändert.');
$this->assertSame("Erste Zeile.\n\n- Punkt A\n- Punkt B", $practice->fresh()->summary);
}
public function test_saving_stores_canonical_html_and_an_untouched_legacy_field_is_not_reported_as_changed(): void
{
$practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise);
$component = Livewire::actingAs($this->editor(), 'staff')
->test(EditPractice::class, ['record' => $practice->getKey()])
->set('summary', '<p>Kurz <b>fett</b></p>')
->set('description', '<p>Lang</p><script>x()</script>');
$this->assertTrue($component->instance()->textFieldsChanged());
$component->call('saveRedaktion');
$practice->refresh();
$this->assertSame(FormattedText::canonicalHtml('<p>Kurz <strong>fett</strong></p>'), $practice->summary);
$this->assertSame('<p>Lang</p>', $practice->description);
}
public function test_a_list_and_a_nested_list_pass_the_payload_depth_guard(): void
{
$practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise);
$item = fn (string $text, array $more = []): array => ['type' => 'listItem', 'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => $text]]], ...$more]];
$component = Livewire::actingAs($this->editor(), 'staff')
->test(EditPractice::class, ['record' => $practice->getKey()])
->set('rich.summary', ['type' => 'doc', 'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => 'Davor']]], ['type' => 'bulletList', 'content' => [$item('Eins', [['type' => 'bulletList', 'content' => [$item('Eins eins')]]]), $item('Zwei')]]]])
->assertHasNoErrors();
$this->assertSame('<p>Davor</p><ul><li><p>Eins</p><ul><li><p>Eins eins</p></li></ul></li><li><p>Zwei</p></li></ul>', $component->get('summary'));
$component->set('rich.summary.content.1.content.0.content.0.content.0.text', 'Geändert');
$this->assertStringContainsString('Geändert', $component->get('summary'));
}
public function test_opening_a_legacy_exercise_reports_no_unsaved_changes(): void
{
$exercise = $this->exercise('Altbestand');
$composition = $exercise['version']->composition;
$component = Livewire::actingAs($this->editor(), 'staff')
->test(EditPractice::class, ['record' => $composition->getKey()])
->assertOk();
$this->assertStringNotContainsString('ungespeicherte', $component->instance()->editorStatus());
$this->assertSame('Nein sagen und Abstand halten', $component->get('rich.learningGoal.content.0.content.0.text'), 'Das Lernziel steht im Editor.');
$this->assertFalse($component->instance()->textFieldsChanged());
}
public function test_an_untouched_legacy_exercise_creates_no_new_version_when_released_again(): void
{
$exercise = $this->exercise('Altbestand');
$composition = $exercise['version']->composition;
Livewire::actingAs($this->editor(), 'staff')
->test(EditPractice::class, ['record' => $composition->getKey()])
->call('saveDraft')
->call('armRelease')
->set('releaseConsent', true)
->call('publishRevision');
$this->assertSame(1, $composition->versions()->count());
$this->assertSame('Nein sagen und Abstand halten', $composition->versions()->first()->learning_goal, 'Der Altbestand bleibt Klartext.');
}
public function test_formatting_the_learning_goal_is_a_real_change_and_creates_a_version(): void
{
$exercise = $this->exercise('Altbestand');
$composition = $exercise['version']->composition;
Livewire::actingAs($this->editor(), 'staff')
->test(EditPractice::class, ['record' => $composition->getKey()])
->set('learningGoal', '<p>Nein sagen und <strong>Abstand</strong> halten</p>')
->call('saveDraft')
->call('armRelease')
->set('releaseConsent', true)
->call('publishRevision');
$this->assertSame(2, $composition->versions()->count());
$this->assertSame('<p>Nein sagen und <strong>Abstand</strong> halten</p>', $composition->versions()->orderByDesc('number')->first()->learning_goal);
$this->assertSame('Nein sagen und Abstand halten', $composition->versions()->orderBy('number')->first()->learning_goal, 'Die frühere Fassung bleibt unverändert.');
}
public function test_a_medium_keeps_its_plain_description_unless_it_is_edited_and_stores_edits_as_clean_html(): void
{
$content = app(ContentService::class);
$element = $content->createElement('text', 'text', 'Trainerunterlage');
$content->publishElementVersion($element, 'Der Wortlaut');
$content->describe($element, 'Trainerunterlage', 'Alt und schlicht.
- Punkt');
$before = IdentityChange::query()->count();
$component = Livewire::actingAs($this->editor(), 'staff')
->test(ViewContentElement::class, ['record' => $element->getKey()])
->call('openRedaktion')
->call('saveRedaktion');
$this->assertSame('Alt und schlicht.
- Punkt', $element->fresh()->description, 'Speichern ohne Änderung lässt den Altbestand, wie er ist.');
$this->assertSame($before, IdentityChange::query()->count());
$component->set('descriptionText', '<p>Neu <b>fett</b></p><script>x()</script>')->call('saveRedaktion');
$this->assertSame('<p>Neu <strong>fett</strong></p>', $element->fresh()->description);
}
private function editor(): User
{
$editor = User::factory()->redakteur()->create();
$editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP');
return $editor;
}
}
+3 -3
View File
@@ -61,7 +61,7 @@ public function test_a_medium_keeps_the_old_version_when_a_new_one_is_saved(): v
$this->assertCount(2, $versions);
$this->assertSame('Erste Fassung', $versions[0]->body);
$this->assertSame('Zweite Fassung', $versions[1]->body);
$this->assertSame('<p>Zweite Fassung</p>', $versions[1]->body);
$this->assertSame(ContentVersionStatus::Bereit, $versions[0]->status);
}
@@ -152,7 +152,7 @@ public function test_an_exercise_can_gain_and_drop_a_medium_without_losing_the_o
->call('publishRevision')
->assertSet('feedback', 'Fassung 3 ist freigegeben. Der Entwurf ist geschlossen und die bisherige Fassung bleibt erhalten. Die Mitgliederbibliothek ändert sich dadurch nicht.');
$this->assertSame('Den Abstand üben', $exercise->composition->versions()->orderByDesc('number')->first()->learning_goal);
$this->assertSame('<p>Den Abstand üben</p>', $exercise->composition->versions()->orderByDesc('number')->first()->learning_goal);
$this->assertSame(3, $exercise->composition->versions()->count());
}
@@ -232,7 +232,7 @@ public function test_a_description_does_not_create_a_version_and_an_older_versio
->assertSee('Es gibt keine neue Fassung.');
$this->assertSame(2, $element->versions()->count());
$this->assertSame('Für die Gruppe', $element->fresh()->description);
$this->assertSame('<p>Für die Gruppe</p>', $element->fresh()->description);
Livewire::test(ViewContentElement::class, ['record' => $element->getKey()])
->set('bereich', 'inhalt')
+2 -2
View File
@@ -49,7 +49,7 @@ public function test_editorial_text_is_saved_without_a_new_version_and_previewed
$this->assertSame(1, $element->versions()->count());
$this->assertSame($version->id, $element->versions()->first()->id);
$this->assertSame('Lara im Park, neu', $element->display_title);
$this->assertSame('Ein kurzer Teaser für die Karte', $element->summary);
$this->assertSame('<p>Ein kurzer Teaser für die Karte</p>', $element->summary);
$this->assertTrue(
IdentityChange::query()->where('subject_id', $element->id)->where('field', 'summary')->exists()
);
@@ -58,7 +58,7 @@ public function test_editorial_text_is_saved_without_a_new_version_and_previewed
'summary' => 'Noch nicht gespeichert',
]);
$this->assertSame('Noch nicht gespeichert', $draft->summary);
$this->assertSame('Ein kurzer Teaser für die Karte', $element->fresh()->summary);
$this->assertSame('<p>Ein kurzer Teaser für die Karte</p>', $element->fresh()->summary);
Livewire::test(ViewContentElement::class, ['record' => $element->getKey()])
->set('bereich', 'vorschau')
+54
View File
@@ -258,6 +258,60 @@ public function test_the_path_finds_the_place_even_when_the_exercise_sits_deeper
$this->assertNull($guide->pathTo($outer, 999999));
}
public function test_formatted_text_appears_formatted_in_the_guide_and_the_pdf_and_never_carries_markup_that_could_run(): void
{
$content = app(ContentService::class);
$text = $this->section('Formatiert', '<p>Erster Absatz mit <strong>fettem</strong> und <em>schrägem</em> Text.</p><h3>Ablauf</h3><ol><li><p>Erst <strong>aufwärmen</strong></p></li><li><p>Dann üben</p></li></ol><ul><li><p>Matten</p></li></ul><blockquote><p>Ein Zitat</p></blockquote><p><a href="https://example.org/regeln">Regeln</a><script>alert(1)</script></p>');
$composition = $this->exerciseComposition('Formatierte Übung');
$version = $content->publishComposition($composition, [['role' => 'Durchführung', 'target' => $text]], null, null, [
'learning_goal' => '<p>Das <strong>Ziel</strong>:</p><ul><li><p>Stand</p></li><li><p>Stimme</p></li></ul>',
'material_note' => '<p>Matten und <em>Pratzen</em></p>',
]);
$module = $this->moduleWith('Modul formatiert', $version);
$articles = app(ArticleService::class);
$article = $articles->create('formatiert');
$release = $articles->publishRelease($article, $module, 'Formatiert.');
$member = $this->grantTo($this->full(), [$article]);
$page = $this->actingAs($member)->get($this->page($article, $release));
$page->assertOk()
->assertSee('<strong>fettem</strong>', false)
->assertSee('<em>schrägem</em>', false)
->assertSee('<h3>Ablauf</h3>', false)
->assertSee('<li><p>Erst <strong>aufwärmen</strong></p></li>', false)
->assertSee('<blockquote>', false)
->assertSee('<strong>Ziel</strong>', false)
->assertSee('<em>Pratzen</em>', false)
->assertSee('rel="noopener noreferrer"', false)
->assertDontSee('alert(1)', false);
$response = $this->actingAs($member)->get($this->pdf($article, $release, null, $member));
$response->assertOk();
$pdf = $response->getContent();
$text = $this->pdfText($pdf);
$this->assertStringContainsString('/BaseFont /Helvetica-Oblique', $pdf, 'Kursiv braucht die schräge Schrift.');
$this->assertMatchesRegularExpression('/\/F2 [0-9.]+ Tf [0-9. ]+ Td \( ?fettem\)/', $pdf, 'Fettes Wort in fetter Schrift.');
$this->assertMatchesRegularExpression('/\/F3 [0-9.]+ Tf [0-9. ]+ Td \( ?schr\xE4gem\)/', $pdf, 'Kursives Wort in schräger Schrift.');
$this->assertStringContainsString('Ablauf', $text);
$this->assertStringContainsString('Erst', $text);
$this->assertStringContainsString('Ein Zitat', $text);
$this->assertStringContainsString('(https://example.org/regeln)', $text, 'Der Link erscheint auf Papier mit Adresse.');
$this->assertStringNotContainsString('alert(1)', $text);
$this->assertStringContainsString('Lernziel:', $text);
$this->assertStringContainsString('Ausstattung:', $text);
$this->assertStringNotContainsString('<strong>', $text, 'Im PDF steht keine Auszeichnung als Text.');
}
public function test_legacy_plain_text_reads_exactly_as_before(): void
{
$this->actingAs($this->member)
->get($this->page($this->moduleArticle, $this->moduleRelease))
->assertOk()
->assertSee('<ul><li><p>Sicher stehen</p></li><li><p>Deutlich sprechen</p></li></ul>', false)
->assertSee('Nein sagen und Abstand halten');
}
private function page(LicenseArticle $article, ArticleRelease $release): string
{
return route('member.exercise', ['article' => $article, 'release' => $release, 'path' => '1']);
+2 -2
View File
@@ -656,7 +656,7 @@ public function test_saving_a_released_text_selects_the_new_version(): void
->assertSee('Fassung 3 ist angelegt. Fassung 1 bleibt erhalten.');
$third = $text->versions()->where('number', 3)->firstOrFail();
$component->assertSet('fassung', $third->id)->assertSet('bodyDraft', 'Dritter Wortlaut');
$component->assertSet('fassung', $third->id)->assertSet('bodyDraft', '<p>Dritter Wortlaut</p>');
$this->assertSame('Erster Wortlaut', $first->fresh()->body);
}
@@ -739,7 +739,7 @@ public function test_a_new_version_from_the_dialog_is_shown_with_its_own_text():
$second = $text->versions()->where('number', 2)->firstOrFail();
$component->assertSet('fassung', $second->id)
->assertSet('bodyDraft', 'Neuer Wortlaut')
->assertSet('bodyDraft', '<p>Neuer Wortlaut</p>')
->assertDontSee('Text der Fassung nicht gespeichert');
}
+104
View File
@@ -0,0 +1,104 @@
<?php
namespace Tests\Unit;
use App\Domain\Catalog\FormattedText;
use Tests\TestCase;
class FormattedTextTest extends TestCase
{
public function test_unsafe_markup_is_removed_and_the_text_stays_readable(): void
{
$html = FormattedText::canonical('<p onclick="x()">Hallo <script>alert(1)</script><strong>Welt</strong></p><p><a href="javascript:alert(1)">Link</a> <a href="https://example.org/a?b=1&c=2">Gut</a> <a href="/intern">Relativ</a></p><iframe src="https://evil.example"></iframe><p><img src="x" onerror="y()">Bild</p>');
$this->assertStringNotContainsString('<script', $html);
$this->assertStringNotContainsString('onclick', $html);
$this->assertStringNotContainsString('onerror', $html);
$this->assertStringNotContainsString('javascript:', $html);
$this->assertStringNotContainsString('<iframe', $html);
$this->assertStringNotContainsString('<img', $html);
$this->assertStringContainsString('<strong>Welt</strong>', $html);
$this->assertStringContainsString('href="https://example.org/a?b=1&amp;c=2"', $html);
$this->assertStringContainsString('rel="noopener noreferrer"', $html);
$this->assertStringContainsString('Bild', $html);
}
public function test_canonical_form_is_stable_and_ignores_spelling_of_the_same_content(): void
{
$samples = [
'<p>Eins</p>'."\n\n".'<p>Zwei <b>fett</b> und <i>schräg</i></p>',
'<div>Lose <strong>Zeile</strong></div><ul><li>Punkt A</li><li><p>Punkt B</p></li></ul>',
'<h2>Titel</h2><ol><li>Erst</li><li>Dann</li></ol><blockquote>Zitat</blockquote>',
'Text <b>ohne</b> Block',
];
foreach ($samples as $sample) {
$once = FormattedText::canonicalHtml($sample);
$this->assertNotSame('', $once);
$this->assertSame($once, FormattedText::canonical($once), 'Zweimal kanonisch ändert nichts: '.$sample);
$this->assertTrue(FormattedText::isHtml($once));
}
$this->assertSame(
FormattedText::canonicalHtml('<p>A <b>B</b></p>'),
FormattedText::canonicalHtml("<p>A <strong>B</strong></p>\n"),
);
$this->assertTrue(FormattedText::same('<p>A</p>', "<p>A</p>\n\n"));
$this->assertSame('', FormattedText::canonical("<p></p>\n<p> </p>"));
$this->assertSame('', FormattedText::canonical(' '));
$this->assertSame('', FormattedText::canonical(null));
}
public function test_list_items_always_carry_their_text_in_a_paragraph_like_the_editor_writes_them(): void
{
$this->assertSame('<ul><li><p>A</p></li><li><p>B</p></li></ul>', FormattedText::canonicalHtml('<ul><li>A</li><li>B</li></ul>'));
$this->assertSame('<ul><li><p>A</p></li></ul>', FormattedText::canonicalHtml('<ul><li><p>A</p></li></ul>'));
}
public function test_legacy_plain_text_keeps_its_paragraphs_lists_and_headings(): void
{
$plain = "Einleitung mit < und & Zeichen.\n\n## Ablauf\n\n1. Stand einnehmen\n2. Arme nach vorn\n\n- Leise ermutigen\n- Laute anhalten\n\nSchluss.";
$this->assertFalse(FormattedText::isHtml($plain));
$html = FormattedText::canonical($plain);
$this->assertSame(
'<p>Einleitung mit &lt; und &amp; Zeichen.</p><h3>Ablauf</h3><ol><li><p>Stand einnehmen</p></li><li><p>Arme nach vorn</p></li></ol><ul><li><p>Leise ermutigen</p></li><li><p>Laute anhalten</p></li></ul><p>Schluss.</p>',
$html,
);
$this->assertSame($html, FormattedText::canonical($html));
$this->assertSame(FormattedText::html($plain), $html);
}
public function test_plain_text_that_only_looks_like_markup_stays_plain(): void
{
$this->assertFalse(FormattedText::isHtml('<3 Training & Spaß'));
$this->assertSame('<p>&lt;3 Training &amp; Spaß</p>', FormattedText::canonical('<3 Training & Spaß'));
$this->assertFalse(FormattedText::isHtml('Preis < 5 und > 3'));
}
public function test_plain_text_and_excerpt_drop_markup_but_keep_structure(): void
{
$html = '<p>Erster <strong>Absatz</strong><br>mit Umbruch</p><ul><li><p>Eins</p></li><li><p>Zwei</p></li></ul><ol><li><p>A</p></li><li><p>B</p></li></ol>';
$this->assertSame("Erster Absatz\nmit Umbruch\n\n- Eins\n- Zwei\n\n1. A\n2. B", FormattedText::plain($html));
$this->assertSame('Erster Absatz mit Umbruch - Eins - Zwei 1. A 2. B', FormattedText::excerpt($html, 200));
$this->assertSame('Erster Absatz…', FormattedText::excerpt($html, 14));
}
public function test_blocks_carry_the_emphasis_for_the_pdf(): void
{
$blocks = FormattedText::blocks('<h3>Titel</h3><p>Normal <strong>fett</strong> <em>schräg</em> <a href="https://example.org/">Link</a></p><ul><li><p>Eins <strong>fett</strong></p></li></ul>');
$this->assertSame('heading', $blocks[0]['type']);
$this->assertSame('Titel', $blocks[0]['runs'][0]['text']);
$this->assertSame('paragraph', $blocks[1]['type']);
$this->assertSame(
[['Normal ', false, false, null], ['fett', true, false, null], [' ', false, false, null], ['schräg', false, true, null], [' ', false, false, null], ['Link', false, false, 'https://example.org/']],
array_map(fn (array $run): array => [$run['text'], $run['bold'], $run['italic'], $run['href']], $blocks[1]['runs']),
);
$this->assertSame('bullets', $blocks[2]['type']);
$this->assertTrue($blocks[2]['items'][0][1]['bold']);
}
}