diff --git a/CLAUDE.md b/CLAUDE.md index 6d317e4..b1d14cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,5 +65,7 @@ ## 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 ``, 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. +- Filter mit Mehrfachauswahl in Bestandslisten (z. B. Medienmanager): Baustein `verwaltung/bestand-filterdialog` über den Eintrag `filterdialog` in `bestand()` (Filterknopf neben der Suche, Pillen je wirksamem Feld, Dialog mit Entwurf der Auswahl: „Anwenden“ übernimmt, „Abbrechen“ verwirft). Mehrere Werte eines Felds gelten als ODER, verschiedene Felder als UND. Die Häkchen sind per `wire:model` an eine Liste im Entwurf gebunden (nie `wire:click` mit `@checked`: nach einer Serverantwort stimmt sonst die Anzeige nicht). Persönliche Standardfilter je Konto liegen in `user_view_defaults` (`UserViewDefault`). Texte, die für eine Übung angelegt werden, erhalten über `ExerciseSections::mark` die Materialart „Übungsabschnitt“ und den Verweis auf ihre Übung. - 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`. diff --git a/app/Domain/Catalog/ContentElement.php b/app/Domain/Catalog/ContentElement.php index fc028cb..031f2cd 100644 --- a/app/Domain/Catalog/ContentElement.php +++ b/app/Domain/Catalog/ContentElement.php @@ -32,6 +32,7 @@ class ContentElement extends Model 'editorial_content_kind_id', 'archived_at', 'source_ref', + 'origin_composition_id', ]; protected function casts(): array @@ -47,6 +48,12 @@ public function editorialContentKind(): BelongsTo return $this->belongsTo(EditorialContentKind::class); } + /** Die Übung, für die dieser Textabschnitt angelegt wurde (nur bei Übungsabschnitten). */ + public function originComposition(): BelongsTo + { + return $this->belongsTo(Composition::class, 'origin_composition_id'); + } + public function versions(): HasMany { return $this->hasMany(ContentElementVersion::class); diff --git a/app/Domain/Catalog/EditorialContentKind.php b/app/Domain/Catalog/EditorialContentKind.php index 51dafc9..1fa989a 100644 --- a/app/Domain/Catalog/EditorialContentKind.php +++ b/app/Domain/Catalog/EditorialContentKind.php @@ -27,7 +27,13 @@ class EditorialContentKind extends Model * Modulen (programm, modul), Vertraulichkeit von Traineranleitungen (traineranleitung). Ihre Bezeichnung bleibt * pflegbar; deaktivieren, Kontexte ändern und löschen sind gesperrt. */ - public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung']; + public const SYSTEM_SLUGS = ['programm', 'modul', 'uebung', 'traineranleitung', self::EXERCISE_SECTION_SLUG]; + + /** + * Textabschnitte einer Übung. Die Materialart wird nur automatisch gesetzt (ExerciseSections) und hat deshalb + * keinen wählbaren Kontext. + */ + public const EXERCISE_SECTION_SLUG = 'uebungsabschnitt'; protected $fillable = [ 'slug', @@ -74,6 +80,12 @@ public function allows(string $context): bool return in_array($context, (array) ($this->contexts ?? []), true); } + /** Wird nie von Hand gewählt, sondern von der Übungsverwaltung gesetzt. */ + public function isAutomatic(): bool + { + return $this->slug === self::EXERCISE_SECTION_SLUG; + } + public function isSystem(): bool { return in_array($this->slug, self::SYSTEM_SLUGS, true); diff --git a/app/Domain/Catalog/EditorialProfile.php b/app/Domain/Catalog/EditorialProfile.php index a870b53..4bbf781 100644 --- a/app/Domain/Catalog/EditorialProfile.php +++ b/app/Domain/Catalog/EditorialProfile.php @@ -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; diff --git a/app/Domain/Catalog/EditorialVocabulary.php b/app/Domain/Catalog/EditorialVocabulary.php index ecde016..fea6138 100644 --- a/app/Domain/Catalog/EditorialVocabulary.php +++ b/app/Domain/Catalog/EditorialVocabulary.php @@ -124,10 +124,52 @@ public function kindFilterOptions(string $context, string $selected = ''): array public function kindLabel(EditorialContentKind $kind, string $context): string { + // Die automatische Art hat bewusst keinen wählbaren Kontext; das ist kein Mangel der Zuordnung. + if ($kind->isAutomatic() && $kind->is_active) { + return (string) $kind->label; + } + return (string) $kind->label .(! $kind->is_active ? self::INACTIVE_SUFFIX : (! $kind->allows($context) ? self::OUT_OF_CONTEXT_SUFFIX : '')); } + /** + * Materialarten für die Mehrfachauswahl im Medienmanager: im Kontext zulässige Arten, Arten, die bei Medien + * tatsächlich vorkommen, und die automatische Art „Übungsabschnitt“. Die Reihenfolge folgt der Pflege, die + * automatische Art steht zuletzt. „Ohne Materialart“ ergänzt der Medienmanager. + * + * @param list $selectedIds bereits gewählte Arten bleiben sichtbar + * @return list + */ + public function mediumKindChoices(array $selectedIds = []): array + { + $used = $this->usedKindIds('medium'); + $regular = []; + $automatic = []; + + foreach (EditorialContentKind::query()->orderBy('sort_order')->orderBy('id')->get() as $kind) { + $id = (int) $kind->id; + $show = $kind->isAutomatic() + || ($kind->allows('medium') && $kind->is_active) + || in_array($id, $used, true) + || in_array($id, $selectedIds, true); + + if (! $show) { + continue; + } + + $row = ['id' => $id, 'label' => $this->kindLabel($kind, 'medium'), 'automatic' => $kind->isAutomatic()]; + + if ($kind->isAutomatic()) { + $automatic[] = $row; + } else { + $regular[] = $row; + } + } + + return [...$regular, ...$automatic]; + } + /** * @return list */ diff --git a/app/Domain/Catalog/ExerciseGuide.php b/app/Domain/Catalog/ExerciseGuide.php index b0eb01a..27416d0 100644 --- a/app/Domain/Catalog/ExerciseGuide.php +++ b/app/Domain/Catalog/ExerciseGuide.php @@ -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, diff --git a/app/Domain/Catalog/ExercisePdf.php b/app/Domain/Catalog/ExercisePdf.php index f016211..f7c837b 100644 --- a/app/Domain/Catalog/ExercisePdf.php +++ b/app/Domain/Catalog/ExercisePdf.php @@ -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 $items + * Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat und Listen mit fett und kursiv. + * + * @param list> $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> $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 $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) { diff --git a/app/Domain/Catalog/ExerciseSections.php b/app/Domain/Catalog/ExerciseSections.php new file mode 100644 index 0000000..38f7020 --- /dev/null +++ b/app/Domain/Catalog/ExerciseSections.php @@ -0,0 +1,132 @@ +where('slug', self::KIND_SLUG)->value('id'); + + return $id === null ? null : (int) $id; + } + + /** + * Ordnet einen Abschnitt seiner Übung zu und gibt ihm die Materialart. Eine bereits gesetzte Materialart bleibt: + * Sie ist eine bewusste Einordnung der Redaktion. + */ + public function mark(ContentElement $element, Composition $exercise): void + { + $element->origin_composition_id = $exercise->getKey(); + + if ($element->editorial_content_kind_id === null) { + $element->editorial_content_kind_id = $this->kindId(); + } + + $element->save(); + } + + /** + * Ordnet vorhandene Texte nur dann zu, wenn ihre Herkunft belegt ist: + * + * - Ein Abschnitt aus der Übernahme aus Shinkan (`source_ref` = `shinkan::`) gehört zur lokalen + * Übung dieser Quelle. + * - Ein anderer Text gilt als Abschnitt, wenn er ohne Materialart ist, ausschließlich in genau einer Übung + * vorkommt und nirgends in einem Modul oder Programm direkt verwendet wird. + * + * Ein bereits gesetzter Materialtyp bleibt in jedem Fall erhalten, ebenso unklare Fälle. + * + * @return int Anzahl der Texte, die jetzt einer Übung zugeordnet sind + */ + public function backfill(): int + { + $kindId = $this->kindId(); + + if ($kindId === null) { + return 0; + } + + $assigned = 0; + + foreach ($this->fromSource() + $this->fromUse() as $elementId => $compositionId) { + DB::table('content_elements')->where('id', $elementId)->whereNull('origin_composition_id')->update(['origin_composition_id' => $compositionId]); + DB::table('content_elements')->where('id', $elementId)->whereNull('editorial_content_kind_id')->update(['editorial_content_kind_id' => $kindId]); + $assigned++; + } + + return $assigned; + } + + /** + * @return array Element-ID => Übung + */ + private function fromSource(): array + { + $byRef = []; + + foreach (DB::table('exercise_sources')->whereNotNull('composition_id')->get(['source_id', 'composition_id']) as $source) { + $byRef[(string) $source->source_id] = (int) $source->composition_id; + } + + $found = []; + + foreach (DB::table('content_elements')->where('output_class', 'text')->where('source_ref', 'like', 'shinkan:%')->get(['id', 'source_ref']) as $element) { + $parts = explode(':', (string) $element->source_ref); + + if (count($parts) === 3 && isset($byRef[$parts[1]])) { + $found[(int) $element->id] = $byRef[$parts[1]]; + } + } + + return $found; + } + + /** + * @return array Element-ID => Übung + */ + private function fromUse(): array + { + $exerciseKind = CompositionKind::Exercise->value; + $uses = DB::table('composition_members as m') + ->join('content_element_versions as v', 'v.id', '=', 'm.content_element_version_id') + ->join('content_elements as e', 'e.id', '=', 'v.content_element_id') + ->join('composition_versions as cv', 'cv.id', '=', 'm.composition_version_id') + ->join('compositions as c', 'c.id', '=', 'cv.composition_id') + ->where('e.output_class', 'text') + ->whereNull('e.editorial_content_kind_id') + ->whereNull('e.origin_composition_id') + ->select('e.id as element_id', 'c.id as composition_id', 'c.kind as composition_kind') + ->get(); + + $exercises = []; + $elsewhere = []; + + foreach ($uses as $use) { + if ($use->composition_kind === $exerciseKind) { + $exercises[(int) $use->element_id][(int) $use->composition_id] = true; + } else { + $elsewhere[(int) $use->element_id] = true; + } + } + + $found = []; + + foreach ($exercises as $elementId => $compositions) { + if (count($compositions) === 1 && ! isset($elsewhere[$elementId])) { + $found[$elementId] = array_key_first($compositions); + } + } + + return $found; + } +} diff --git a/app/Domain/Catalog/FormattedText.php b/app/Domain/Catalog/FormattedText.php new file mode 100644 index 0000000..1ff124e --- /dev/null +++ b/app/Domain/Catalog/FormattedText.php @@ -0,0 +1,375 @@ +\/]/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, items?: list>}> + */ + public static function blocks(?string $value): array + { + $html = self::canonical($value); + + if ($html === '') { + return []; + } + + $document = HTMLDocument::createFromString(''.$html.'', 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' => '

'.e($block['text']).'

', + 'bullets' => '
    '.implode('', array_map(fn (string $item): string => '
  • '.e($item).'

  • ', $block['items'])).'
', + 'numbered' => '
    '.implode('', array_map(fn (string $item): string => '
  1. '.e($item).'

  2. ', $block['items'])).'
', + default => '

'.e($block['text']).'

', + }; + } + + 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(''.$html.'', LIBXML_NOERROR); + $body = $document->body; + $out = ''; + $loose = ''; + + $flush = function () use (&$out, &$loose): void { + $loose = trim($loose); + + if ($loose !== '' && trim(strip_tags(str_replace(['
', '
', '
'], '', $loose))) !== '') { + $out .= '

'.$loose.'

'; + } + + $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, '

')) { + $inner = '

'.$inner.'

'; + } + + if (self::hasText($inner)) { + $items .= '
  • '.$inner.'
  • '; + } + } + + return $items === '' ? '' : '<'.$name.'>'.$items.''; + } + + $inner = self::inner($node); + + if ($name === 'blockquote' && ! str_contains($inner, '

    ')) { + $inner = '

    '.$inner.'

    '; + } + + return self::hasText($inner) ? '<'.$name.'>'.$inner.'' : ''; + } + + 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 + */ + 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 $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), + ); + } +} diff --git a/app/Domain/Catalog/ShinkanImport.php b/app/Domain/Catalog/ShinkanImport.php index d6569f2..99b5ded 100644 --- a/app/Domain/Catalog/ShinkanImport.php +++ b/app/Domain/Catalog/ShinkanImport.php @@ -33,6 +33,9 @@ class ShinkanImport 'trainer_notes' => 'Trainerhinweise', ]; + /** Felder, die Shinkan bei `text_format: html` als HTML liefert (ADR-50). Ohne diese Angabe sind alle Texte Klartext. */ + private const HTML_FIELDS = ['summary', 'goal', 'execution', 'preparation', 'trainer_notes']; + /** Änderungshinweis der Textfassungen, die die Übernahme angelegt hat. Alles andere ist eine lokale Bearbeitung. */ private const IMPORT_NOTE = 'Übernahme aus Shinkan'; @@ -212,8 +215,8 @@ public function preview(ExerciseSource $source): array $sections = []; foreach (self::SECTIONS as $field => $label) { - if (trim((string) ($document[$field] ?? '')) !== '') { - $sections[] = ['label' => $label, 'text' => mb_strimwidth(trim((string) $document[$field]), 0, 280, '…')]; + if ($this->value($document, $field) !== '') { + $sections[] = ['label' => $label, 'text' => FormattedText::excerpt($this->value($document, $field), 280)]; } } @@ -223,16 +226,16 @@ public function preview(ExerciseSource $source): array 'hash' => $snapshot?->content_hash, 'state' => $state, 'title' => (string) ($document['title'] ?? $source->title), - 'summary' => (string) ($document['summary'] ?? ''), - 'goal' => (string) ($document['goal'] ?? ''), + 'summary' => FormattedText::plain($this->value($document, 'summary')), + 'goal' => FormattedText::plain($this->value($document, 'goal')), 'duration' => $this->duration($document), - 'equipment' => (string) ($document['equipment'] ?? ''), + 'equipment' => FormattedText::plain($this->value($document, 'equipment')), 'sections' => $sections, 'variants' => array_map(fn (array $variant): array => [ 'key' => (string) ($variant['id'] ?? ''), 'name' => (string) ($variant['name'] ?? ''), 'description' => (string) ($variant['description'] ?? ''), - 'changes' => trim((string) ($variant['execution_changes'] ?? '')) !== '', + 'changes' => $this->variantChanges($document, $variant) !== '', ], array_values(array_filter((array) ($document['variants'] ?? []), 'is_array'))), 'media' => array_map(fn (array $media): string => ($media['title'] ?? 'Medium').' ('.($media['media_type'] ?? '').')', array_values(array_filter((array) ($document['media'] ?? []), 'is_array'))), 'changes' => $previous === null ? [] : $this->changes($previous->payload, $document, $source), @@ -260,7 +263,7 @@ public function changes(array $before, array $after, ?ExerciseSource $source = n ] + self::SECTIONS; foreach ($labels as $field => $label) { - if (trim((string) ($before[$field] ?? '')) !== trim((string) ($after[$field] ?? ''))) { + if (! $this->sameValue($field, $before, $after)) { $lines[] = $label.' geändert'; } } @@ -282,7 +285,7 @@ public function changes(array $before, array $after, ?ExerciseSource $source = n } if (trim((string) ($variant['description'] ?? '')) !== trim((string) ($old[$key]['description'] ?? '')) - || trim((string) ($variant['execution_changes'] ?? '')) !== trim((string) ($old[$key]['execution_changes'] ?? ''))) { + || ! FormattedText::same($this->variantChanges($after, $variant), $this->variantChanges($before, (array) $old[$key]))) { $lines[] = 'Variante „'.($variant['name'] ?? '').'“ geändert'; } } @@ -298,7 +301,7 @@ public function changes(array $before, array $after, ?ExerciseSource $source = n $lines[] = 'Der Titel wurde lokal geändert und bleibt unverändert'; } - if (($before['summary'] ?? '') !== ($after['summary'] ?? '') && filled($source->composition->summary) && $source->composition->summary !== ($before['summary'] ?? '')) { + if (! $this->sameValue('summary', $before, $after) && filled($source->composition->summary) && ! FormattedText::same($source->composition->summary, $this->value($before, 'summary'))) { $lines[] = 'Die Kurzbeschreibung wurde lokal geändert und bleibt unverändert'; } } @@ -367,7 +370,11 @@ public function textDecisions(ExerciseSource $source, array $document, string $w $latest = $source->composition->versions()->orderByDesc('number')->first(); foreach (self::FIELDS as $field => [$column, $label]) { - if ($latest !== null && $this->classifyField($latest->{$column}, $previousSource[$field] ?? null, $document[$field] ?? null) === $wanted) { + $isText = in_array($field, ['goal', 'equipment'], true); + $old = $isText ? ($this->value($previousSource, $field) ?: null) : ($previousSource[$field] ?? null); + $new = $isText ? ($this->value($document, $field) ?: null) : ($document[$field] ?? null); + + if ($latest !== null && $this->classifyField($latest->{$column}, $old, $new, $isText) === $wanted) { $result[] = ['key' => $field, 'label' => $label]; } } @@ -436,7 +443,7 @@ public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, arr $title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan'; $previousSnapshot = $this->lastAdopted($source); $previousSource = $previousSnapshot?->payload ?? []; - $composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? '')); + $composition = $source->composition ?? $this->createComposition($title, $this->value($document, 'summary')); if ($source->composition !== null && $previousSnapshot !== null) { $this->carryOverTexts($composition, $previousSource, $document); @@ -466,7 +473,7 @@ public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, arr } $keepLocal = $decision === 'keep_local' && $latest !== null; - $target = $keepLocal ? $latest : $this->sectionVersion($source, $item['field'], $item['title'], $item['text'], $latest); + $target = $keepLocal ? $latest : $this->sectionVersion($source, $composition, $item['field'], $item['title'], $item['text'], $latest); $members[] = array_filter([ 'role' => $item['role'], 'target' => $target, @@ -479,10 +486,11 @@ public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, arr $fields = []; foreach (self::FIELDS as $field => [$column, $label]) { - $value = $document[$field] ?? null; + $isText = in_array($field, ['goal', 'equipment'], true); + $value = $isText ? ($this->value($document, $field) ?: null) : ($document[$field] ?? null); if ($previous !== null && $previousSnapshot !== null) { - $decision = $this->classifyField($previous->{$column}, $previousSource[$field] ?? null, $value); + $decision = $this->classifyField($previous->{$column}, $isText ? ($this->value($previousSource, $field) ?: null) : ($previousSource[$field] ?? null), $value, $isText); if ($decision === 'conflict') { $decision = ($choices[$field] ?? null) === 'lokal' ? 'keep_local' : (($choices[$field] ?? null) === 'quelle' ? 'source' : 'conflict'); @@ -535,10 +543,10 @@ private function plan(ExerciseSource $source, array $document, array $previousSo $title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan'; foreach (self::SECTIONS as $field => $label) { - $text = trim((string) ($document[$field] ?? '')); + $text = $this->value($document, $field); if ($text !== '') { - $plan[] = $this->textItem($source, $field, $label, $title.' · '.$label, $label, $text, null, $previousSource[$field] ?? null); + $plan[] = $this->textItem($source, $field, $label, $title.' · '.$label, $label, $text, null, $this->value($previousSource, $field) ?: null); } } @@ -554,7 +562,7 @@ private function plan(ExerciseSource $source, array $document, array $previousSo 'kind' => 'variant', 'variant' => ['key' => $key, 'name' => $name, 'description' => (string) ($variant['description'] ?? ''), 'origin' => 'quelle'], ]; - $changes = trim((string) ($variant['execution_changes'] ?? '')); + $changes = $this->variantChanges($document, $variant); if ($changes !== '') { $before = collect((array) ($previousSource['variants'] ?? []))->firstWhere('id', $key); @@ -566,7 +574,7 @@ private function plan(ExerciseSource $source, array $document, array $previousSo 'Abweichung der Durchführung', $changes, $key, - is_array($before) ? ($before['execution_changes'] ?? null) : null, + is_array($before) ? ($this->variantChanges($previousSource, $before) ?: null) : null, 'variant_'.$key, ); } @@ -599,22 +607,68 @@ private function textItem(ExerciseSource $source, string $field, string $label, private function classifyText(?ContentElementVersion $latest, string $text, ?string $previousText): string { - if ($latest === null || trim((string) $latest->body) === $text || $latest->change_note === self::IMPORT_NOTE) { + if ($latest === null || FormattedText::same($latest->body, $text) || $latest->change_note === self::IMPORT_NOTE) { return 'source'; } - return $previousText === null || trim($previousText) !== $text ? 'conflict' : 'keep_local'; + return $previousText === null || ! FormattedText::same($previousText, $text) ? 'conflict' : 'keep_local'; } - private function classifyField(mixed $local, mixed $previousSource, mixed $new): string + private function classifyField(mixed $local, mixed $previousSource, mixed $new, bool $text = false): string { - $plain = fn (mixed $value): string => $value === null ? '' : trim((string) $value); + $same = $text + ? fn (mixed $a, mixed $b): bool => FormattedText::same($a === null ? null : (string) $a, $b === null ? null : (string) $b) + : fn (mixed $a, mixed $b): bool => ($a === null ? '' : trim((string) $a)) === ($b === null ? '' : trim((string) $b)); - if ($plain($local) === $plain($new) || $plain($local) === $plain($previousSource)) { + if ($same($local, $new) || $same($local, $previousSource)) { return 'source'; } - return $plain($previousSource) !== $plain($new) ? 'conflict' : 'keep_local'; + return ! $same($previousSource, $new) ? 'conflict' : 'keep_local'; + } + + /** + * Text eines Felds der Quelle in der Form, in der er übernommen wird: Bei `text_format: html` wird das HTML bereinigt + * und kanonisch, sonst bleibt der Klartext, wie er geliefert wird. + * + * @param array $document + */ + private function value(array $document, string $field): string + { + $raw = trim((string) ($document[$field] ?? '')); + + return ($document['text_format'] ?? null) === 'html' && in_array($field, self::HTML_FIELDS, true) + ? FormattedText::canonicalHtml($raw) + : $raw; + } + + /** + * Abweichung der Durchführung einer Variante, im Format des Dokuments. + * + * @param array $document + * @param array $variant + */ + private function variantChanges(array $document, array $variant): string + { + $raw = trim((string) ($variant['execution_changes'] ?? '')); + + return ($document['text_format'] ?? null) === 'html' ? FormattedText::canonicalHtml($raw) : $raw; + } + + /** + * Ist das Feld in beiden Quellständen inhaltlich gleich? Texte werden als kanonischer Text verglichen, alles andere + * ohne führenden und folgenden Leerraum. + * + * @param array $before + * @param array $after + */ + private function sameValue(string $field, array $before, array $after): bool + { + if (in_array($field, [...self::HTML_FIELDS, 'equipment'], true)) { + return FormattedText::same($this->value($before, $field), $this->value($after, $field)); + } + + return trim((string) ($before[$field] ?? '')) === trim((string) ($after[$field] ?? '')); } /** @@ -630,8 +684,8 @@ private function carryOverTexts(Composition $composition, array $before, array $ $composition->designation = trim((string) $after['title']); } - if (array_key_exists('summary', $after) && ((string) $composition->summary === '' || $composition->summary === ($before['summary'] ?? null))) { - $composition->summary = trim((string) $after['summary']) ?: null; + if (array_key_exists('summary', $after) && ((string) $composition->summary === '' || FormattedText::same($composition->summary, $this->value($before, 'summary')))) { + $composition->summary = $this->value($after, 'summary') ?: null; } $composition->save(); @@ -696,7 +750,7 @@ private function localAdditions(?CompositionVersion $previous, array $sourceVari /** * Die Textfassung eines Abschnitts der Quelle. Unveränderter Text bleibt dieselbe Fassung. */ - private function sectionVersion(ExerciseSource $source, string $field, string $title, string $text, ?ContentElementVersion $latest): ContentElementVersion + private function sectionVersion(ExerciseSource $source, Composition $composition, string $field, string $title, string $text, ?ContentElementVersion $latest): ContentElementVersion { $content = app(ContentService::class); $ref = 'shinkan:'.$source->source_id.':'.$field; @@ -708,7 +762,10 @@ private function sectionVersion(ExerciseSource $source, string $field, string $t $element->save(); } - return $latest !== null && trim((string) $latest->body) === $text + // Der Abschnitt gehört zu dieser Übung und liegt als „Übungsabschnitt“ im gemeinsamen Medienbestand. + app(ExerciseSections::class)->mark($element, $composition); + + return $latest !== null && FormattedText::same($latest->body, $text) ? $latest : $content->publishElementVersion($element, $text, [], self::IMPORT_NOTE); } diff --git a/app/Domain/Cms/Catalog/PublicCatalogReader.php b/app/Domain/Cms/Catalog/PublicCatalogReader.php index f1b18b9..bd964f6 100644 --- a/app/Domain/Cms/Catalog/PublicCatalogReader.php +++ b/app/Domain/Cms/Catalog/PublicCatalogReader.php @@ -8,6 +8,7 @@ use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\EditorialContentKind; use App\Domain\Catalog\EditorialProfileReader; +use App\Domain\Catalog\FormattedText; use App\Domain\Media\ThumbnailRef; use Illuminate\Support\Collection; @@ -166,7 +167,7 @@ public function entries(array $refs, bool $includeNonPublic): array $entries[] = new CatalogEntry( id: $composition->id, title: $this->title($composition), - summary: filled($composition->summary) ? (string) $composition->summary : null, + summary: FormattedText::plain($composition->summary) ?: null, kindLabel: (string) ($composition->editorialContentKind?->label ?? ''), url: $public ? route('public.program', $composition) : null, public: $public, @@ -264,7 +265,7 @@ public function subject(mixed $id, bool $includeNonPublic): ?CardSubject $kind = (string) ($composition->editorialContentKind?->label ?? ($program ? 'Programm' : 'Modul')); $profile = app(EditorialProfileReader::class)->read($composition, 'kachel'); $summary = $profile->value('teaser') ?: $profile->value('summary'); - $goal = filled($version?->learning_goal) ? trim((string) $version->learning_goal) : null; + $goal = FormattedText::plain($version?->learning_goal) ?: null; // Zentrale Texte, aus denen die Redaktion den Kartentext wählen kann (Zielgruppe „Öffentliche Kachel“). $texts = [ 'teaser' => $profile->value('teaser'), diff --git a/app/Domain/Cms/Catalog/PublicMaterialReader.php b/app/Domain/Cms/Catalog/PublicMaterialReader.php index 78557d7..66fa673 100644 --- a/app/Domain/Cms/Catalog/PublicMaterialReader.php +++ b/app/Domain/Cms/Catalog/PublicMaterialReader.php @@ -6,6 +6,7 @@ use App\Domain\Catalog\ContentElement; use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\EditorialProfileReader; +use App\Domain\Catalog\FormattedText; use App\Domain\Catalog\MaterialTag; use App\Domain\Catalog\StructureNode; use App\Domain\Media\ThumbnailRef; @@ -37,8 +38,8 @@ */ class PublicMaterialReader { - /** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen. */ - public const CONFIDENTIAL_KINDS = ['traineranleitung']; + /** Inhaltsarten, die nie öffentlich auf einer Karte erscheinen: Anleitungen für Trainer und die Textabschnitte der Übungen. */ + public const CONFIDENTIAL_KINDS = ['traineranleitung', 'uebungsabschnitt']; /** @var array|null Element-ID => erstes öffentliches Programm */ private ?array $publicIndex = null; @@ -175,7 +176,7 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ? $output = self::outputLabel((string) $shown->output_class); $film = $shown->output_class === 'film'; $editorialKind = $element->editorialContentKind?->label; - $summary = filled($shown->summary) ? trim((string) $shown->summary) : null; + $summary = FormattedText::plain($shown->summary) ?: null; $profile = app(EditorialProfileReader::class)->read($shown, 'bibliothek'); if (! array_key_exists('summary', $draft) && $profile->origin('summary') === 'variante') { @@ -187,7 +188,8 @@ public function subject(mixed $id, bool $includeNonPublic, array $draft = []): ? $texts = []; foreach (['teaser', 'summary', 'description'] as $field) { - $own = filled($shown->getAttribute($field)) ? trim((string) $shown->getAttribute($field)) : null; + $own = filled($shown->getAttribute($field)) ? trim(in_array($field, FormattedText::FIELDS, true) ? FormattedText::plain((string) $shown->getAttribute($field)) : (string) $shown->getAttribute($field)) : null; + $own = $own === '' ? null : $own; if (! array_key_exists($field, $draft) && $profile->origin($field) === 'variante') { $own = $profile->value($field); diff --git a/app/Domain/Cms/Widgets/Support/HeadingAccent.php b/app/Domain/Cms/Widgets/Support/HeadingAccent.php index ea15ca5..a97002b 100644 --- a/app/Domain/Cms/Widgets/Support/HeadingAccent.php +++ b/app/Domain/Cms/Widgets/Support/HeadingAccent.php @@ -36,6 +36,117 @@ final class HeadingAccent public const BRUSH_LABEL = ['Pinselstrich', 'Gelbe Unterstreichung unter der Überschrift (freigegebenes Motiv aus dem Brand-Kit). Vorgabe: ohne.']; + /** @var array */ + public const SIZE = [ + 'small' => 'Klein (2,5 rem), links neben dem ganzen Absatz', + 'medium' => 'Mittel (3,5 rem), links neben dem ganzen Absatz', + 'large' => 'Groß (5 rem), links neben dem ganzen Absatz', + 'xlarge' => 'Sehr groß (7 rem), links neben dem ganzen Absatz', + ]; + + /** + * Gemeinsame Größenstufen aller Widgets (Kantenlänge des Symbolquadrats): klein 2,5 rem, mittel 3,5 rem, groß 5 rem, + * sehr groß 7 rem. Die Werte stehen als --lf-symbol-… in tokens.css; Merkmalszeile, Karten und alle Überschriften- + * Widgets verwenden dieselben Schlüssel. + * + * @var array + */ + public const STEPS = ['small' => 'Klein', 'medium' => 'Mittel', 'large' => 'Groß', 'xlarge' => 'Sehr groß']; + + public const SIZE_LABEL = ['Größe des Symbols', 'Vorgabe: klein, vor der Überschrift in der Zeile. Klein bis Sehr groß stellen das Symbol links neben Überschrift und Text; bei wenig Platz steht es darüber. Wirkt nur, wenn ein Symbol gewählt ist.']; + + /** @var array */ + public const ALIGN = ['top' => 'Oben', 'center' => 'Mitte', 'bottom' => 'Unten']; + + public const ALIGN_LABEL = ['Ausrichtung des Symbols', 'Senkrechte Lage des Symbols neben dem Absatz. Vorgabe: oben. Wirkt nur bei Symbolen neben dem Absatz (Klein bis Sehr groß).']; + + /** + * Waagerechte Ausrichtung von Inhalten mit Symbol (Merkmalszeile, Karten): links ist die Vorgabe. + * + * @var array + */ + public const TEXT_ALIGN = ['left' => 'Linksbündig', 'center' => 'Zentriert', 'right' => 'Rechtsbündig']; + + /** @var array */ + public const LINK_STYLE = ['text' => 'Kleiner Textlink', 'pill' => 'Pille (Schaltfläche)']; + + public const LINK_STYLE_LABEL = ['Darstellung der Links', 'Wie die Links der Merkmale aussehen. Vorgabe: kleiner Textlink. Merkmale ohne Link zeigen nichts.']; + + /** + * Größenstufe eines Symbols links neben dem ganzen Absatz (small, medium, large, xlarge) oder null, wenn das Symbol + * klein vor der Überschrift steht. Nur mit gültigem Symbol. Ohne gültige Stufe gilt $default (null = in der Zeile). + * + * @param array $settings + */ + public static function sideSize(array $settings, ?string $default = null): ?string + { + if (self::symbol($settings) === null) { + return null; + } + + $size = $settings['symbol_size'] ?? null; + + return is_string($size) && array_key_exists($size, self::SIZE) ? $size : $default; + } + + /** + * Alles, was eine Ansicht für Symbol und Absatz braucht: das Symbol, die Stufe neben dem Absatz (oder null), die + * senkrechte Lage und die Einstellungen für das kleine Symbol in der Überschrift (leer, wenn das Symbol daneben steht, + * damit es nicht doppelt erscheint). + * + * @param array $settings + * @return array{symbol: ?string, side: ?string, align: string, inline: array} + */ + public static function lead(array $settings, ?string $defaultSide = null): array + { + $side = self::sideSize($settings, $defaultSide); + + return [ + 'symbol' => self::symbol($settings), + 'side' => $side, + 'align' => self::align($settings), + 'inline' => $side !== null ? [] : $settings, + ]; + } + + /** + * Senkrechte Ausrichtung des Symbols neben dem Absatz; ungültig oder leer ergibt oben. + * + * @param array $settings + */ + public static function align(array $settings): string + { + $align = $settings['symbol_align'] ?? null; + + return is_string($align) && array_key_exists($align, self::ALIGN) ? $align : 'top'; + } + + /** + * Ausrichtung und Symbolgröße für Inhalte mit Symbol über dem Text (Merkmalszeile, Karten). Ungültige oder fehlende + * Werte fallen auf die Vorgaben zurück: linksbündig und mittlere Symbole. + * + * @param array $settings + * @return array{align: string, size: string} + */ + public static function block(array $settings): array + { + $align = $settings['align'] ?? null; + $size = $settings['symbol_size'] ?? null; + + return [ + 'align' => is_string($align) && array_key_exists($align, self::TEXT_ALIGN) ? $align : 'left', + 'size' => is_string($size) && array_key_exists($size, self::STEPS) ? $size : 'medium', + ]; + } + + /** + * @param array $settings + */ + public static function linkStyle(array $settings): string + { + return ($settings['link_style'] ?? null) === 'pill' ? 'pill' : 'text'; + } + /** * Gültiger Symbolname aus den Einstellungen eines Widgets oder null. * diff --git a/app/Domain/Cms/Widgets/Types/CallToActionWidget.php b/app/Domain/Cms/Widgets/Types/CallToActionWidget.php index 01d06cd..c59ae99 100644 --- a/app/Domain/Cms/Widgets/Types/CallToActionWidget.php +++ b/app/Domain/Cms/Widgets/Types/CallToActionWidget.php @@ -93,17 +93,27 @@ public function dataFields(): array public function settings(): array { - return ['symbol' => HeadingAccent::SYMBOLS]; + return [ + 'symbol' => HeadingAccent::SYMBOLS, + 'symbol_size' => HeadingAccent::SIZE, + 'symbol_align' => HeadingAccent::ALIGN, + 'accent' => HeadingAccent::BRUSH, + ]; } public function settingGroups(): array { - return ['Aussehen' => ['symbol']]; + return ['Aussehen' => ['symbol', 'symbol_size', 'symbol_align', 'accent']]; } public function settingLabels(): array { - return ['symbol' => HeadingAccent::SYMBOL_LABEL]; + return [ + 'symbol' => HeadingAccent::SYMBOL_LABEL, + 'symbol_size' => HeadingAccent::SIZE_LABEL, + 'symbol_align' => HeadingAccent::ALIGN_LABEL, + 'accent' => HeadingAccent::BRUSH_LABEL, + ]; } public function clean(array $data, array $refs, WidgetErrors $errors): array diff --git a/app/Domain/Cms/Widgets/Types/CardsWidget.php b/app/Domain/Cms/Widgets/Types/CardsWidget.php index 0c54bea..c6a02e3 100644 --- a/app/Domain/Cms/Widgets/Types/CardsWidget.php +++ b/app/Domain/Cms/Widgets/Types/CardsWidget.php @@ -3,6 +3,7 @@ namespace App\Domain\Cms\Widgets\Types; use App\Domain\Cms\Widgets\RenderContext; +use App\Domain\Cms\Widgets\Support\HeadingAccent; use App\Domain\Cms\Widgets\Support\ImageRefFields; use App\Domain\Cms\Widgets\Support\PublicMedia; use App\Domain\Cms\Widgets\Support\SafeUrl; @@ -10,8 +11,10 @@ use App\Domain\Cms\Widgets\WidgetErrors; use App\Domain\Cms\Widgets\WidgetType; use Filament\Forms\Components\Repeater; +use Filament\Forms\Components\Select; use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; +use Illuminate\Validation\Rule; /** * Redaktionelle Karten. Die Einträge sind freie redaktionelle Verweise, keine Produkte oder Lizenzartikel. @@ -85,11 +88,33 @@ public function dataRules(): array 'items.*.title' => ['required', 'string', 'max:120'], 'items.*.text' => ['nullable', 'string', 'max:500'], 'items.*.url' => ['nullable', 'string', 'max:500'], + 'items.*.symbol' => ['nullable', 'string', Rule::in(array_keys(HeadingAccent::SYMBOLS))], 'items.*.image' => ['nullable'], 'items.*._upload' => ['nullable'], ]; } + public function settings(): array + { + return [ + 'symbol_size' => HeadingAccent::STEPS, + 'align' => HeadingAccent::TEXT_ALIGN, + ]; + } + + public function settingGroups(): array + { + return ['Aussehen' => ['symbol_size', 'align']]; + } + + public function settingLabels(): array + { + return [ + 'symbol_size' => ['Größe der Symbole', 'Kantenlänge der Symbole auf den Karten, die eins haben: Klein 2,5 rem, Mittel 3,5 rem, Groß 5 rem, Sehr groß 7 rem. Vorgabe: Mittel.'], + 'align' => ['Ausrichtung', 'Richtet Symbol, Titel und Text jeder Karte aus. Vorgabe: linksbündig.'], + ]; + } + public function dataFields(): array { [$image, $upload, $status] = ImageRefFields::fields('Bild (optional)'); @@ -99,6 +124,11 @@ public function dataFields(): array ->label('Karten') ->schema([ TextInput::make('title')->label('Titel')->required()->maxLength(120), + Select::make('symbol') + ->label('Symbol (optional)') + ->options(HeadingAccent::SYMBOLS) + ->placeholder('Kein Symbol') + ->helperText('Kleine Grafik aus dem Brand-Kit über dem Titel. Größe und Ausrichtung im Reiter „Darstellung“.'), Textarea::make('text')->label('Beschreibung')->rows(2)->maxLength(500), TextInput::make('url') ->label('Linkziel') @@ -128,10 +158,12 @@ public function clean(array $data, array $refs, WidgetErrors $errors): array $itemRefs = ImageRefFields::clean(['image' => $item['image'] ?? null, '_upload' => $item['_upload'] ?? null], $errors, errorKey: "data.items.$index.image"); + // Der Schlüssel symbol wird nur gespeichert, wenn ein Symbol gewählt ist: Karten ohne Symbol bleiben byteweise wie zuvor. $data['items'][$index] = [ 'title' => $item['title'], 'text' => filled($item['text'] ?? null) ? $item['text'] : null, 'url' => filled($item['url'] ?? null) ? $item['url'] : null, + ...(filled($item['symbol'] ?? null) ? ['symbol' => $item['symbol']] : []), 'image' => $itemRefs['image'], ]; } @@ -154,6 +186,7 @@ public function resolve(array $widget, RenderContext $context): array 'title' => $item['title'], 'text' => $item['text'] ?? null, 'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null, + 'symbol' => HeadingAccent::symbol(['symbol' => $item['symbol'] ?? null]), 'imageUrl' => $images->url($item['image'] ?? null, $context->preview), ]; @@ -162,7 +195,11 @@ public function resolve(array $widget, RenderContext $context): array } } - return ['items' => $items, 'imageNotice' => $notices === [] ? null : implode(' ', $notices)]; + return [ + 'items' => $items, + 'layout' => HeadingAccent::block($widget['settings'] ?? []), + 'imageNotice' => $notices === [] ? null : implode(' ', $notices), + ]; } public function mediaPaths(array $widget): array diff --git a/app/Domain/Cms/Widgets/Types/FaqWidget.php b/app/Domain/Cms/Widgets/Types/FaqWidget.php index ca92261..8ee9f5a 100644 --- a/app/Domain/Cms/Widgets/Types/FaqWidget.php +++ b/app/Domain/Cms/Widgets/Types/FaqWidget.php @@ -2,6 +2,7 @@ namespace App\Domain\Cms\Widgets\Types; +use App\Domain\Cms\Widgets\Support\HeadingAccent; use App\Domain\Cms\Widgets\WidgetType; use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Textarea; @@ -83,6 +84,29 @@ public function dataFields(): array ]; } + public function settings(): array + { + return [ + 'symbol' => HeadingAccent::SYMBOLS, + 'symbol_size' => HeadingAccent::SIZE, + 'symbol_align' => HeadingAccent::ALIGN, + ]; + } + + public function settingGroups(): array + { + return ['Aussehen' => ['symbol', 'symbol_size', 'symbol_align']]; + } + + public function settingLabels(): array + { + return [ + 'symbol' => ['Symbol neben den Fragen', 'Kleine Grafik aus dem Brand-Kit links neben allen Fragen. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'], + 'symbol_size' => ['Größe des Symbols', 'Vorgabe: Mittel. Bei wenig Platz steht das Symbol über den Fragen. Wirkt nur, wenn ein Symbol gewählt ist.'], + 'symbol_align' => HeadingAccent::ALIGN_LABEL, + ]; + } + public function summary(array $widget): string { $count = count($widget['data']['items'] ?? []); diff --git a/app/Domain/Cms/Widgets/Types/FeaturesWidget.php b/app/Domain/Cms/Widgets/Types/FeaturesWidget.php index 2a1fda2..511fd2e 100644 --- a/app/Domain/Cms/Widgets/Types/FeaturesWidget.php +++ b/app/Domain/Cms/Widgets/Types/FeaturesWidget.php @@ -4,6 +4,7 @@ use App\Domain\Cms\Widgets\RenderContext; use App\Domain\Cms\Widgets\Support\HeadingAccent; +use App\Domain\Cms\Widgets\Support\SafeUrl; use App\Domain\Cms\Widgets\WidgetErrors; use App\Domain\Cms\Widgets\WidgetType; use Filament\Forms\Components\Repeater; @@ -13,13 +14,40 @@ use Illuminate\Validation\Rule; /** - * Merkmalszeile nach den Entwürfen des Brand-Kits (04_visuelle_entwuerfe): zwei bis vier Merkmale nebeneinander, - * je mit Symbol, Kurztitel und einem Satz. Die Anzahl der Einträge bestimmt die Spaltenzahl; es gibt keine + * Merkmalszeile nach den Entwürfen des Brand-Kits (04_visuelle_entwuerfe): ein bis zwölf Merkmale nebeneinander, + * je mit Symbol, Kurztitel und einem Satz. Die Spaltenzahl folgt der Anzahl der Einträge und der Breite; es gibt keine * zweite Einstellung dafür. Das Symbol stammt aus der festen Auswahl (HeadingAccent::SYMBOLS), nie aus einem * freien Dateinamen. */ class FeaturesWidget extends WidgetType { + private const DEFAULT_LINK_LABEL = 'Mehr erfahren'; + + /** @var array */ + public const ALIGN = HeadingAccent::TEXT_ALIGN; + + /** + * Größenstufen der Symbole, überall dieselben (HeadingAccent::STEPS): klein 2,5 rem, mittel 3,5 rem (Vorgabe), groß + * 5 rem, sehr groß 7 rem. + * + * @var array + */ + public const SYMBOL_SIZE = HeadingAccent::STEPS; + + /** @var array */ + public const DIVIDER = ['line' => 'Feiner Strich zwischen den Merkmalen']; + + /** + * Gültige Layout-Einstellungen mit Vorgaben (links, mittel, ohne Strich); alles andere fällt auf die Vorgabe zurück. + * + * @param array $settings + * @return array{align: string, size: string, divider: bool} + */ + public static function layout(array $settings): array + { + return HeadingAccent::block($settings) + ['divider' => ($settings['divider'] ?? null) === 'line']; + } + public function key(): string { return 'features'; @@ -32,12 +60,12 @@ public function label(): string public function description(): string { - return 'Zwei bis vier Merkmale nebeneinander, je mit Symbol, Kurztitel und einem Satz.'; + return 'Ein bis zwölf Merkmale nebeneinander (bei wenig Platz untereinander), je mit Symbol, Kurztitel, einem Satz und optionalem Link.'; } public function supportedUnits(): array { - return [2, 3, 4]; + return [1, 2, 3, 4]; } public function narrowBehavior(): string @@ -71,10 +99,37 @@ public function schematic(): array public function dataRules(): array { return [ - 'items' => ['required', 'array', 'min:2', 'max:4'], + 'items' => ['required', 'array', 'min:1', 'max:12'], 'items.*.symbol' => ['required', 'string', Rule::in(array_keys(HeadingAccent::SYMBOLS))], 'items.*.title' => ['required', 'string', 'max:60'], 'items.*.text' => ['nullable', 'string', 'max:200'], + 'items.*.url' => ['nullable', 'string', 'max:500'], + 'items.*.link_label' => ['nullable', 'string', 'max:60'], + ]; + } + + public function settings(): array + { + return [ + 'align' => self::ALIGN, + 'symbol_size' => self::SYMBOL_SIZE, + 'divider' => self::DIVIDER, + 'link_style' => HeadingAccent::LINK_STYLE, + ]; + } + + public function settingGroups(): array + { + return ['Aussehen' => ['align', 'symbol_size', 'divider', 'link_style']]; + } + + public function settingLabels(): array + { + return [ + 'align' => ['Ausrichtung', 'Richtet Symbol, Titel, Satz und Link jedes Merkmals aus. Vorgabe: linksbündig.'], + 'symbol_size' => ['Größe der Symbole', 'Kantenlänge der Symbole: Klein 2,5 rem, Mittel 3,5 rem, Groß 5 rem, Sehr groß 7 rem. Vorgabe: Mittel.'], + 'divider' => ['Trennstrich', 'Ein feiner Strich zwischen den Merkmalen: senkrecht zwischen Spalten, waagerecht zwischen Zeilen und bei untereinander stehenden Merkmalen. Vorgabe: ohne.'], + 'link_style' => HeadingAccent::LINK_STYLE_LABEL, ]; } @@ -87,24 +142,43 @@ public function dataFields(): array Select::make('symbol')->label('Symbol')->options(HeadingAccent::SYMBOLS)->required(), TextInput::make('title')->label('Kurztitel')->required()->maxLength(60), Textarea::make('text')->label('Satz')->rows(2)->maxLength(200), + TextInput::make('url') + ->label('Linkziel (optional)') + ->maxLength(500) + ->rule(SafeUrl::rule()) + ->helperText('Seitenpfad wie /materialien oder eine http(s)-Adresse. Leer lassen für ein Merkmal ohne Link.'), + TextInput::make('link_label') + ->label('Linktext') + ->maxLength(60) + ->placeholder(self::DEFAULT_LINK_LABEL) + ->helperText('Nur mit Linkziel. Leer: „'.self::DEFAULT_LINK_LABEL.'“.'), ]) - ->minItems(2) - ->maxItems(4) + ->minItems(1) + ->maxItems(12) ->reorderableWithButtons() ->collapsible() ->itemLabel(fn (array $state): ?string => $state['title'] ?? null) ->addActionLabel('Merkmal hinzufügen') - ->helperText('Die Anzahl der Merkmale bestimmt die Spalten: zwei, drei oder vier.'), + ->helperText('Ein bis zwölf Merkmale. Sie stehen nebeneinander, solange jedes mindestens 12 rem breit bleibt, und brechen sonst um.'), ]; } public function clean(array $data, array $refs, WidgetErrors $errors): array { foreach ($data['items'] as $index => $item) { + $hasUrl = filled($item['url'] ?? null); + + if ($hasUrl && ! SafeUrl::isSafe($item['url'])) { + $errors->add("data.items.$index.url", SafeUrl::message()); + } + $data['items'][$index] = [ 'symbol' => $item['symbol'], 'title' => $item['title'], 'text' => filled($item['text'] ?? null) ? $item['text'] : null, + 'url' => $hasUrl ? $item['url'] : null, + // Ein Linktext ohne Linkziel wird verworfen, damit nichts Verstecktes gespeichert bleibt. + 'link_label' => $hasUrl && filled($item['link_label'] ?? null) ? $item['link_label'] : null, ]; } @@ -124,10 +198,14 @@ public function resolve(array $widget, RenderContext $context): array 'symbol' => HeadingAccent::symbol(['symbol' => $item['symbol'] ?? null]), 'title' => $item['title'], 'text' => $item['text'] ?? null, + 'url' => SafeUrl::isSafe($item['url'] ?? null) ? $item['url'] : null, + 'linkLabel' => filled($item['link_label'] ?? null) ? $item['link_label'] : self::DEFAULT_LINK_LABEL, ]; } - return ['items' => $items]; + $settings = $widget['settings'] ?? []; + + return ['items' => $items, 'linkStyle' => HeadingAccent::linkStyle($settings), 'layout' => self::layout($settings)]; } public function summary(array $widget): string diff --git a/app/Domain/Cms/Widgets/Types/HeadingWidget.php b/app/Domain/Cms/Widgets/Types/HeadingWidget.php index d1c7b0b..3c3b885 100644 --- a/app/Domain/Cms/Widgets/Types/HeadingWidget.php +++ b/app/Domain/Cms/Widgets/Types/HeadingWidget.php @@ -76,19 +76,23 @@ public function settings(): array { return [ 'symbol' => HeadingAccent::SYMBOLS, + 'symbol_size' => HeadingAccent::SIZE, + 'symbol_align' => HeadingAccent::ALIGN, 'accent' => HeadingAccent::BRUSH, ]; } public function settingGroups(): array { - return ['Aussehen' => ['symbol', 'accent']]; + return ['Aussehen' => ['symbol', 'symbol_size', 'symbol_align', 'accent']]; } public function settingLabels(): array { return [ 'symbol' => HeadingAccent::SYMBOL_LABEL, + 'symbol_size' => HeadingAccent::SIZE_LABEL, + 'symbol_align' => HeadingAccent::ALIGN_LABEL, 'accent' => HeadingAccent::BRUSH_LABEL, ]; } diff --git a/app/Domain/Cms/Widgets/Types/HeroWidget.php b/app/Domain/Cms/Widgets/Types/HeroWidget.php index 0950636..80c113d 100644 --- a/app/Domain/Cms/Widgets/Types/HeroWidget.php +++ b/app/Domain/Cms/Widgets/Types/HeroWidget.php @@ -114,13 +114,15 @@ public function settings(): array 'heading_level' => PremiumFields::HEADING_LEVELS, 'accent' => ['underline' => 'Gelbe Unterstreichung', 'rays' => 'Unterstreichung und Signalstrahlen', 'none' => 'Ohne Akzent'], 'symbol' => HeadingAccent::SYMBOLS, + 'symbol_size' => HeadingAccent::SIZE, + 'symbol_align' => HeadingAccent::ALIGN, ]; } public function settingGroups(): array { return [ - 'Aussehen' => ['accent', 'symbol'], + 'Aussehen' => ['accent', 'symbol', 'symbol_size', 'symbol_align'], 'Seitenstruktur' => ['heading_level'], ]; } @@ -131,6 +133,8 @@ public function settingLabels(): array 'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Der erste Einstieg einer Seite ist immer die Hauptüberschrift (H1).'], 'accent' => ['Markenakzent', 'Freigegebene Akzente aus dem Brand-UI-Kit. Vorgabe: gelbe Unterstreichung.'], 'symbol' => HeadingAccent::SYMBOL_LABEL, + 'symbol_size' => HeadingAccent::SIZE_LABEL, + 'symbol_align' => HeadingAccent::ALIGN_LABEL, ]; } diff --git a/app/Domain/Cms/Widgets/Types/ImageTextWidget.php b/app/Domain/Cms/Widgets/Types/ImageTextWidget.php index 6d9dead..5c697cd 100644 --- a/app/Domain/Cms/Widgets/Types/ImageTextWidget.php +++ b/app/Domain/Cms/Widgets/Types/ImageTextWidget.php @@ -116,13 +116,15 @@ public function settings(): array 'surface' => ['cream' => 'Creme (Markenfläche)', 'clear' => 'Ohne eigene Fläche', 'navy' => 'Navy (dunkel)'], 'heading_level' => PremiumFields::HEADING_LEVELS, 'symbol' => HeadingAccent::SYMBOLS, + 'symbol_size' => HeadingAccent::SIZE, + 'symbol_align' => HeadingAccent::ALIGN, ]; } public function settingGroups(): array { return [ - 'Aussehen' => ['surface', 'symbol'], + 'Aussehen' => ['surface', 'symbol', 'symbol_size', 'symbol_align'], 'Seitenstruktur' => ['heading_level'], ]; } @@ -132,6 +134,8 @@ public function settingLabels(): array return [ 'surface' => ['Hintergrund des Widgets', 'Unabhängig vom Abschnittshintergrund. „Ohne eigene Fläche“ übernimmt den Abschnitt.'], 'symbol' => HeadingAccent::SYMBOL_LABEL, + 'symbol_size' => HeadingAccent::SIZE_LABEL, + 'symbol_align' => HeadingAccent::ALIGN_LABEL, 'heading_level' => ['Überschriftenebene', 'Betrifft nur die Gliederung für Suchmaschinen und Hilfstechnik, nicht das Aussehen. Steht das Widget als erstes auf der Seite, ist die Überschrift immer H1.'], ]; } diff --git a/app/Domain/Cms/Widgets/Types/ProseWidget.php b/app/Domain/Cms/Widgets/Types/ProseWidget.php index d62a15c..0f73c79 100644 --- a/app/Domain/Cms/Widgets/Types/ProseWidget.php +++ b/app/Domain/Cms/Widgets/Types/ProseWidget.php @@ -2,6 +2,7 @@ namespace App\Domain\Cms\Widgets\Types; +use App\Domain\Cms\Widgets\Support\HeadingAccent; use App\Domain\Cms\Widgets\Support\RichText; use App\Domain\Cms\Widgets\WidgetType; use Filament\Forms\Components\Textarea; @@ -69,6 +70,29 @@ public function dataFields(): array ]; } + public function settings(): array + { + return [ + 'symbol' => HeadingAccent::SYMBOLS, + 'symbol_size' => HeadingAccent::SIZE, + 'symbol_align' => HeadingAccent::ALIGN, + ]; + } + + public function settingGroups(): array + { + return ['Aussehen' => ['symbol', 'symbol_size', 'symbol_align']]; + } + + public function settingLabels(): array + { + return [ + 'symbol' => ['Symbol neben dem Text', 'Kleine Grafik aus dem Brand-Kit links neben dem ganzen Text. Sie ist reine Zierde und wird von Hilfstechnik nicht vorgelesen. Vorgabe: kein Symbol.'], + 'symbol_size' => ['Größe des Symbols', 'Vorgabe: Mittel. Bei wenig Platz steht das Symbol über dem Text. Wirkt nur, wenn ein Symbol gewählt ist.'], + 'symbol_align' => HeadingAccent::ALIGN_LABEL, + ]; + } + public function summary(array $widget): string { return RichText::excerpt(e((string) ($widget['data']['body'] ?? ''))); diff --git a/app/Domain/Commerce/Receipt/PdfDocument.php b/app/Domain/Commerce/Receipt/PdfDocument.php index dabcfd2..fb73e0e 100644 --- a/app/Domain/Commerce/Receipt/PdfDocument.php +++ b/app/Domain/Commerce/Receipt/PdfDocument.php @@ -17,14 +17,44 @@ final class PdfDocument /** @var list */ 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 >>'; diff --git a/app/Filament/Resources/Compositions/Pages/EditComposition.php b/app/Filament/Resources/Compositions/Pages/EditComposition.php index 4b705a1..7934111 100644 --- a/app/Filament/Resources/Compositions/Pages/EditComposition.php +++ b/app/Filament/Resources/Compositions/Pages/EditComposition.php @@ -15,7 +15,9 @@ use App\Domain\Catalog\DomainRuleException; use App\Domain\Catalog\EditorialVocabulary; use App\Domain\Catalog\EditorialWorkingDraft; +use App\Domain\Catalog\ExerciseSections; 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 +28,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 +51,7 @@ abstract class EditComposition extends EditRecord { use AssignsPillars; use ManagesEditorialSurface; + use ManagesRichFields; use WithFileUploads; protected string $view = 'filament.editorial.edit'; @@ -382,6 +386,21 @@ public function redaktionTitel(): string return $title !== '' ? $title : $this->hostLabel(); } + /** + * @return array + */ + protected function richFelder(): array + { + return [ + 'summary' => 'Kurzbeschreibung', + 'description' => 'Ausführliche Beschreibung', + 'learningGoal' => 'Lernziel', + 'materialNote' => $this->isExercise() ? 'Ausstattung' : 'Materialbedarf', + 'partBody' => 'Inhalt des Textes', + 'newTextBody' => 'Inhalt des neuen Textes', + ]; + } + /** * @return list> */ @@ -395,8 +414,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 +1267,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.'; @@ -1260,6 +1279,11 @@ public function addText(): void $service = app(ContentService::class); $element = $service->createElement('text', 'text', $title); $version = $service->draftElementVersion($element, $body); + + // Ein Abschnitt, der im Übungseditor entsteht, gehört zu dieser Übung (Materialart „Übungsabschnitt“). + if ($this->isExercise()) { + app(ExerciseSections::class)->mark($element, $this->getRecord()); + } } catch (DomainRuleException $exception) { $this->feedback = $exception->getMessage(); @@ -1578,7 +1602,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 +1622,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 +1779,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 +2103,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 +2128,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 +2170,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 +2323,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 +2424,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'] ?? []), diff --git a/app/Filament/Resources/ContentElements/Pages/EditContentElement.php b/app/Filament/Resources/ContentElements/Pages/EditContentElement.php index d062061..815f998 100644 --- a/app/Filament/Resources/ContentElements/Pages/EditContentElement.php +++ b/app/Filament/Resources/ContentElements/Pages/EditContentElement.php @@ -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)) { diff --git a/app/Filament/Resources/ContentElements/Pages/ListContentElements.php b/app/Filament/Resources/ContentElements/Pages/ListContentElements.php index a2d0056..071048c 100644 --- a/app/Filament/Resources/ContentElements/Pages/ListContentElements.php +++ b/app/Filament/Resources/ContentElements/Pages/ListContentElements.php @@ -6,11 +6,15 @@ use App\Domain\Catalog\PillarFilterCompat; use App\Filament\Resources\ContentElements\ContentElementResource; use App\Filament\Support\Bestand; +use App\Filament\Support\MaterialKindSelection; use App\Filament\Support\MediaLibrary; use App\Filament\Support\MediumForm; use App\Filament\Support\ReportsDomainRules; use App\Filament\Support\ShowsBestand; +use App\Models\UserViewDefault; use Filament\Actions\Action; +use Filament\Facades\Filament; +use Filament\Notifications\Notification; use Filament\Resources\Pages\ListRecords; use Filament\Schemas\Components\RenderHook; use Filament\Schemas\Components\View; @@ -55,9 +59,34 @@ class ListContentElements extends ListRecords #[Url(as: 'saeule', except: '')] public string $saeule = ''; + /** Frühere Adresse mit einer einzelnen Materialart (zum Beispiel aus den Stammdaten); wird zu `arten`. */ #[Url(as: 'inhaltsart', except: '')] public string $inhaltsart = ''; + /** + * Mehrfachauswahl der fachlichen Materialarten (MaterialKindSelection). Leer heißt: allgemeine Startansicht, also + * alle Materialarten und Medien ohne Materialart, aber ohne Übungsabschnitte. + */ + #[Url(as: 'arten', except: '')] + public string $arten = ''; + + /** Der Filterdialog ist offen. */ + public bool $filterOffen = false; + + /** Das Filterfeld, bei dem der Dialog beginnt (leer: beim ersten Feld). */ + public string $filterFokus = ''; + + /** + * Arbeitsstand des Dialogs: die Auswahl seit dem Öffnen. Erst „Anwenden“ übernimmt sie in die Filter der Liste, + * „Abbrechen“ verwirft sie. + * + * @var array + */ + public array $filterDraft = []; + + /** Filterfelder mit mehreren Werten (ODER); verschiedene Felder gelten zusammen (UND). */ + private const MULTI_FIELDS = ['art', 'freigabe', 'nutzung']; + #[Url(as: 'einordnung', except: '')] public string $einordnung = ''; @@ -67,6 +96,27 @@ class ListContentElements extends ListRecords #[Url(as: 'archiv', except: 'aktiv')] public string $archiv = 'aktiv'; + /** Eigenschaften, die der persönliche Standard festhält. Die Suche gehört nicht dazu: Sie ist Teil der Arbeit, kein Zustand der Ansicht. */ + private const DEFAULT_FILTERS = ['arten', 'art', 'freigabe', 'schutz', 'entwurf', 'fassung', 'nutzung', 'saeule', 'einordnung', 'verarbeitung', 'archiv', 'ansicht']; + + public function mount(): void + { + parent::mount(); + + if ($this->inhaltsart !== '' && $this->arten === '') { + $this->arten = ctype_digit($this->inhaltsart) ? MaterialKindSelection::encode([MaterialKindSelection::key((int) $this->inhaltsart)]) : ''; + } + + $this->inhaltsart = ''; + + // Ohne eigene Vorgaben in der Adresse startet der Medienmanager mit dem persönlichen Standard. + $given = array_intersect(array_keys(request()->query()), ['suche', 'ansicht', 'art', 'arten', 'inhaltsart', 'freigabe', 'schutz', 'entwurf', 'fassung', 'nutzung', 'saeule', 'einordnung', 'verarbeitung', 'archiv']); + + if ($given === [] && ($saved = $this->savedDefault()) !== null) { + $this->applyFilters($saved); + } + } + public function getSubheading(): string|Htmlable|null { return 'Die Dateien und Texte. Ein Modul oder ein Programm verweist auf eine Fassung; die Datei wird nicht für jede Verwendung neu hochgeladen.'; @@ -88,7 +138,7 @@ public function content(Schema $schema): Schema protected function bestandFilterEigenschaften(): array { - return ['suche', 'art', 'schutz', 'freigabe', 'entwurf', 'fassung', 'nutzung', 'saeule', 'inhaltsart', 'einordnung', 'verarbeitung', 'archiv']; + return ['suche', 'art', 'arten', 'schutz', 'freigabe', 'entwurf', 'fassung', 'nutzung', 'saeule', 'inhaltsart', 'einordnung', 'verarbeitung', 'archiv']; } public function showingList(): bool @@ -128,14 +178,6 @@ public function classificationOptions(): array return app(MediaLibrary::class)->classifications(ctype_digit($this->einordnung) ? [(int) $this->einordnung] : []); } - /** - * @return array - */ - public function contentKindOptions(): array - { - return app(EditorialVocabulary::class)->kindFilterOptions('medium', $this->inhaltsart); - } - public function filtersActive(): bool { return trim($this->suche) !== '' @@ -147,7 +189,7 @@ public function filtersActive(): bool || $this->nutzung !== '' || $this->saeule !== '' || $this->einordnung !== '' - || $this->inhaltsart !== '' + || $this->arten !== '' || $this->verarbeitung !== '' || $this->archiv !== 'aktiv'; } @@ -164,13 +206,346 @@ public function resetFilters(): void $this->saeule = ''; $this->einordnung = ''; $this->inhaltsart = ''; + $this->arten = ''; $this->verarbeitung = ''; $this->archiv = 'aktiv'; $this->bestandGrenze = Bestand::SCHRITT; } + // ---------------------------------------------------------------- Materialarten und persönlicher Standard + /** - * Gemeinsame Bestandsliste: Suche und häufige Filter sichtbar, die übrigen unter „Weitere Filter“. + * Die wählbaren Materialarten mit Schlüssel: die Arten der redaktionellen Stammdaten, „Übungsabschnitt“ und „Ohne + * Materialart“. + * + * @return array + */ + public function artChoices(): array + { + $chosen = array_map( + fn (string $key): int => (int) substr($key, 1), + array_filter(MaterialKindSelection::decode($this->arten) ?? [], fn (string $key): bool => $key !== MaterialKindSelection::WITHOUT), + ); + $choices = []; + + foreach (app(EditorialVocabulary::class)->mediumKindChoices(array_values($chosen)) as $kind) { + $choices[MaterialKindSelection::key($kind['id'])] = ['label' => $kind['label'], 'automatic' => $kind['automatic']]; + } + + $choices[MaterialKindSelection::WITHOUT] = ['label' => 'Ohne Materialart', 'automatic' => false]; + + return $choices; + } + + /** + * Allgemeine Startansicht: alle Materialarten und Medien ohne Materialart, ohne Übungsabschnitte. + * + * @return list + */ + private function defaultArten(): array + { + return array_keys(array_filter($this->artChoices(), fn (array $choice): bool => ! $choice['automatic'])); + } + + /** + * @return list die gerade gewählten Schlüssel + */ + public function selectedArten(): array + { + return MaterialKindSelection::decode($this->arten) ?? $this->defaultArten(); + } + + /** + * @param list $keys + */ + private function storeArten(array $keys): void + { + $default = $this->defaultArten(); + sort($keys); + sort($default); + + // Die allgemeine Startansicht bleibt ohne Eintrag in der Adresse. + $this->arten = $keys === $default ? '' : MaterialKindSelection::encode($keys); + $this->bestandGrenze = Bestand::SCHRITT; + } + + private function userId(): ?int + { + $id = Filament::auth()->id(); + + return $id === null ? null : (int) $id; + } + + /** + * @return array|null + */ + private function savedDefault(): ?array + { + return UserViewDefault::filtersFor($this->userId(), UserViewDefault::MEDIA); + } + + public function hasSavedDefault(): bool + { + return $this->savedDefault() !== null; + } + + /** + * Die aktuellen Filter (ohne Suche) als persönlicher Standard dieses Kontos. + */ + public function saveDefault(): void + { + $userId = $this->userId(); + + if ($userId === null) { + return; + } + + $filters = []; + + foreach (self::DEFAULT_FILTERS as $name) { + $filters[$name] = (string) $this->{$name}; + } + + UserViewDefault::remember($userId, UserViewDefault::MEDIA, $filters); + $this->filterOffen = false; + Notification::make()->title('Standard gespeichert')->body('Der Medienmanager startet für dich mit diesen Filtern.')->success()->send(); + } + + public function restoreDefault(): void + { + $saved = $this->savedDefault(); + + if ($saved === null) { + Notification::make()->title('Kein persönlicher Standard gespeichert')->warning()->send(); + + return; + } + + $this->suche = ''; + $this->applyFilters($saved); + $this->filterOffen = false; + Notification::make()->title('Dein Standard ist geladen')->success()->send(); + } + + public function deleteDefault(): void + { + $userId = $this->userId(); + + if ($userId !== null) { + UserViewDefault::forget($userId, UserViewDefault::MEDIA); + } + + $this->resetFilters(); + $this->ansicht = 'liste'; + $this->filterOffen = false; + Notification::make()->title('Persönlicher Standard gelöscht')->body('Der Medienmanager startet wieder mit der allgemeinen Auswahl.')->success()->send(); + } + + /** + * @param array $filters + */ + private function applyFilters(array $filters): void + { + foreach (self::DEFAULT_FILTERS as $name) { + if (array_key_exists($name, $filters)) { + $this->{$name} = (string) $filters[$name]; + } + } + + $this->ansicht = $this->ansicht === 'kacheln' ? 'kacheln' : 'liste'; + $this->archiv = in_array($this->archiv, ['aktiv', 'archiviert', 'alle'], true) ? $this->archiv : 'aktiv'; + $this->bestandGrenze = Bestand::SCHRITT; + } + + // ---------------------------------------------------------------- Filterdialog + + /** + * Filterfelder mit Checkboxen (Mehrfachauswahl). Mehrere Werte eines Felds gelten als ODER. + * + * @return array}> + */ + private function multiFields(): array + { + $arten = array_map(fn (array $choice): string => $choice['label'], $this->artChoices()); + + return [ + 'arten' => ['label' => 'Fachliche Materialart', 'kurz' => 'Materialart', 'optionen' => $arten], + 'art' => ['label' => 'Technische Art', 'kurz' => 'Technische Art', 'optionen' => collect($this->typeOptions())->mapWithKeys(fn (array $type): array => [$type['value'] => $type['label']])->all()], + 'freigabe' => ['label' => 'Freigabe', 'kurz' => 'Freigabe', 'optionen' => ['freigegeben' => 'Freigegebene Fassung', 'entwurf' => 'Nur offener Entwurf', 'ohne' => 'Keine freigegebene Fassung']], + 'nutzung' => ['label' => 'Verwendung', 'kurz' => 'Verwendung', 'optionen' => ['verwendet' => 'Verwendet', 'unbenutzt' => 'Nicht verwendet']], + ]; + } + + /** + * Weitere Kriterien mit einem Wert je Feld, unter „Weitere Filter“ im Dialog. + * + * @return array}> + */ + private function singleFields(): array + { + $optionen = fn (array $liste, string $wert, string $label): array => collect($liste) + ->mapWithKeys(fn (array $eintrag): array => [(string) $eintrag[$wert] => $eintrag[$label]]) + ->all(); + $fields = [ + 'schutz' => ['label' => 'Schutz', 'vorgabe' => '', 'alle' => 'Alle Medien', 'optionen' => ['geschuetzt' => 'Geschützte Medien', 'oeffentlich' => 'Öffentliche Medien', 'website' => 'Auf der Website frei']], + 'entwurf' => ['label' => 'Entwurf', 'vorgabe' => '', 'alle' => 'Entwurf egal', 'optionen' => ['offen' => 'Offener Entwurf', 'keiner' => 'Kein offener Entwurf']], + 'fassung' => ['label' => 'Deaktivierte Fassungen', 'vorgabe' => '', 'alle' => 'Regulärer Bestand', 'optionen' => ['mit' => 'Mit deaktivierter Fassung', 'nur' => 'Nur deaktivierte Fassungen']], + ]; + + if (($pillars = $this->pillarOptions()) !== []) { + $fields['saeule'] = ['label' => 'Fachliche Säule', 'vorgabe' => '', 'alle' => 'Alle Säulen', 'optionen' => $optionen($pillars, 'id', 'name')]; + } + + if (($classes = $this->classificationOptions()) !== []) { + $fields['einordnung'] = ['label' => 'Einordnung', 'vorgabe' => '', 'alle' => 'Alle Einordnungen', 'optionen' => $optionen($classes, 'id', 'label')]; + } + + $fields['verarbeitung'] = ['label' => 'Verarbeitung', 'vorgabe' => '', 'alle' => 'Verarbeitung egal', 'optionen' => ['fehler' => 'Verarbeitungsfehler', 'uebernahme' => 'Datei wird übernommen']]; + $fields['archiv'] = ['label' => 'Archiv', 'vorgabe' => 'aktiv', 'alle' => null, 'optionen' => ['aktiv' => 'Aktive Medien', 'archiviert' => 'Archivierte Medien', 'alle' => 'Auch archivierte']]; + + return $fields; + } + + /** + * @return list + */ + private function appliedList(string $field): array + { + $value = trim((string) $this->{$field}); + + return $value === '' ? [] : array_values(array_filter(array_map('trim', explode(',', $value)), fn (string $part): bool => $part !== '')); + } + + /** + * Die Auswahl der Liste als Arbeitsstand des Dialogs. + * + * @return array + */ + private function draftFromApplied(): array + { + $draft = ['arten' => $this->selectedArten()]; + + foreach (self::MULTI_FIELDS as $field) { + $draft[$field] = $this->appliedList($field); + } + + foreach (array_keys($this->singleFields()) as $field) { + $draft[$field] = (string) $this->{$field}; + } + + return $draft; + } + + public function openFilter(string $field = ''): void + { + $this->filterDraft = $this->draftFromApplied(); + $this->filterFokus = $field; + $this->filterOffen = true; + } + + /** Verwirft die Auswahl seit dem Öffnen. */ + public function cancelFilter(): void + { + $this->filterOffen = false; + $this->filterDraft = []; + $this->filterFokus = ''; + } + + /** Alle Materialarten im Dialog ankreuzen, auch Übungsabschnitte und „Ohne Materialart“. */ + public function draftAlleArten(): void + { + $this->filterDraft['arten'] = array_keys($this->artChoices()); + } + + /** Übernimmt die Auswahl des Dialogs in die Liste. */ + public function applyFilter(): void + { + $this->applyDraft(); + $this->filterOffen = false; + $this->filterDraft = []; + $this->filterFokus = ''; + } + + /** Übernimmt die Auswahl des Dialogs und merkt sie als persönlichen Standard. */ + public function saveDefaultFromDialog(): void + { + $this->applyDraft(); + $this->filterDraft = []; + $this->filterFokus = ''; + $this->saveDefault(); + } + + private function applyDraft(): void + { + $draft = $this->filterDraft; + $known = array_keys($this->artChoices()); + $this->storeArten(array_values(array_intersect($known, array_map('strval', (array) ($draft['arten'] ?? []))))); + $options = $this->multiFields(); + + foreach (self::MULTI_FIELDS as $field) { + $allowed = array_keys($options[$field]['optionen']); + $chosen = array_values(array_intersect($allowed, array_map('strval', (array) ($draft[$field] ?? [])))); + // Alle Werte angekreuzt heißt: keine Einschränkung. + $this->{$field} = count($chosen) === count($allowed) ? '' : implode(',', $chosen); + } + + foreach ($this->singleFields() as $field => $definition) { + $value = (string) ($draft[$field] ?? $definition['vorgabe']); + $this->{$field} = array_key_exists($value, $definition['optionen']) ? $value : $definition['vorgabe']; + } + + $this->bestandGrenze = Bestand::SCHRITT; + } + + /** + * Die wirksamen Filter als Pillen unter der Suche. Ein Klick öffnet den Dialog beim Filterfeld. In der allgemeinen + * Startansicht erklärt eine Pille, warum Übungsabschnitte fehlen. + * + * @return list + */ + private function filterPills(): array + { + $pills = []; + $short = function (array $labels): string { + $joined = implode(', ', $labels); + + return count($labels) <= 3 && mb_strlen($joined) <= 40 ? $joined : count($labels).' gewählt'; + }; + $multi = $this->multiFields(); + + if ($this->arten === '') { + $pills[] = ['feld' => 'arten', 'label' => 'Übungsabschnitte ausgeblendet', 'info' => true]; + } else { + $selected = $this->selectedArten(); + + if ($selected === []) { + $pills[] = ['feld' => 'arten', 'label' => 'Materialart · keine gewählt', 'info' => false]; + } elseif (count($selected) < count($multi['arten']['optionen'])) { + $pills[] = ['feld' => 'arten', 'label' => 'Materialart · '.$short(array_map(fn (string $key): string => $multi['arten']['optionen'][$key] ?? $key, $selected)), 'info' => false]; + } + } + + foreach (self::MULTI_FIELDS as $field) { + $values = $this->appliedList($field); + + if ($values !== []) { + $pills[] = ['feld' => $field, 'label' => $multi[$field]['kurz'].' · '.$short(array_map(fn (string $value): string => $multi[$field]['optionen'][$value] ?? $value, $values)), 'info' => false]; + } + } + + foreach ($this->singleFields() as $field => $definition) { + $value = (string) $this->{$field}; + + if ($value !== $definition['vorgabe']) { + $pills[] = ['feld' => $field, 'label' => $definition['label'].' · '.($definition['optionen'][$value] ?? $value), 'info' => false]; + } + } + + return $pills; + } + + /** + * Gemeinsame Bestandsliste: Suche mit Filterknopf, wirksame Filter als Pillen, alle Kriterien im Filterdialog. * * @return array */ @@ -181,38 +556,27 @@ public function bestand(): array [$this->saeule, $this->einordnung] = [(string) $pillar, '']; } - $optionen = fn (array $liste, string $wert, string $label): array => collect($liste) - ->mapWithKeys(fn (array $eintrag): array => [(string) $eintrag[$wert] => $eintrag[$label]]) - ->all(); - $weitere = [ - ['eigenschaft' => 'inhaltsart', 'label' => 'Fachliche Materialart', 'vorgabe' => '', 'alle' => 'Alle Materialarten', 'optionen' => $this->contentKindOptions()], - ['eigenschaft' => 'entwurf', 'label' => 'Entwurf', 'vorgabe' => '', 'alle' => 'Entwurf egal', 'optionen' => ['offen' => 'Offener Entwurf', 'keiner' => 'Kein offener Entwurf']], - ['eigenschaft' => 'fassung', 'label' => 'Deaktivierte Fassungen', 'vorgabe' => '', 'alle' => 'Regulärer Bestand', 'optionen' => ['mit' => 'Mit deaktivierter Fassung', 'nur' => 'Nur deaktivierte Fassungen']], + $pills = $this->filterPills(); + $keine = $this->selectedArten() === []; + $gespeichert = $this->hasSavedDefault(); + $dialog = [ + 'offen' => $this->filterOffen, + 'fokus' => $this->filterFokus, + 'pillen' => $pills, + 'anzahl' => count(array_filter($pills, fn (array $pill): bool => ! $pill['info'])), + 'felder' => $this->multiFields(), + 'weitere' => $this->singleFields(), + 'entwurf' => 'filterDraft', + 'gespeichert' => $gespeichert, + 'hinweis' => 'Mehrere Werte eines Felds zeigen Medien, auf die einer davon zutrifft. Verschiedene Felder gelten zusammen. Freigabe meint die Fassung des Mediums, nicht die Website und keinen Zugriff. Geschützte Medien haben eine Inhaltsfassung und laufen über Lizenzen. Öffentliche Medien sind eigenständige Präsentationsmedien ohne Fassung für die Website. Materialart und Einordnung sind die redaktionelle Klassifikation; Verwendung zeigt, wo das Medium tatsächlich eingebunden ist. Übungsabschnitte, die Texte der Übungen, erscheinen erst, wenn du sie unter Materialart ankreuzt. „Als Standard speichern“ merkt die Filter für dein Konto, ohne die Suche.', ]; - if (($pillars = $this->pillarOptions()) !== []) { - $weitere[] = ['eigenschaft' => 'saeule', 'label' => 'Fachliche Säule', 'vorgabe' => '', 'alle' => 'Alle Säulen', 'optionen' => $optionen($pillars, 'id', 'name')]; - } - - if (($classes = $this->classificationOptions()) !== []) { - $weitere[] = ['eigenschaft' => 'einordnung', 'label' => 'Einordnung', 'vorgabe' => '', 'alle' => 'Alle Einordnungen', 'optionen' => $optionen($classes, 'id', 'label')]; - } - - $weitere[] = ['eigenschaft' => 'verarbeitung', 'label' => 'Verarbeitung', 'vorgabe' => '', 'alle' => 'Verarbeitung egal', 'optionen' => ['fehler' => 'Verarbeitungsfehler', 'uebernahme' => 'Datei wird übernommen']]; - $weitere[] = ['eigenschaft' => 'archiv', 'label' => 'Archiv', 'vorgabe' => 'aktiv', 'optionen' => ['aktiv' => 'Aktive Medien', 'archiviert' => 'Archivierte Medien', 'alle' => 'Auch archivierte']]; - return [ 'suche' => ['eigenschaft' => 'suche', 'label' => 'Suche', 'platzhalter' => 'Titel, Beschreibung oder Suchbegriff'], - 'filter' => [ - ['eigenschaft' => 'art', 'label' => 'Technische Art', 'vorgabe' => '', 'alle' => 'Alle Arten', 'optionen' => $optionen($this->typeOptions(), 'value', 'label')], - ['eigenschaft' => 'schutz', 'label' => 'Schutz', 'vorgabe' => '', 'alle' => 'Alle Medien', 'optionen' => ['geschuetzt' => 'Geschützte Medien', 'oeffentlich' => 'Öffentliche Medien', 'website' => 'Auf der Website frei']], - ['eigenschaft' => 'freigabe', 'label' => 'Freigabe', 'vorgabe' => '', 'alle' => 'Alle Freigaben', 'optionen' => ['freigegeben' => 'Freigegebene Fassung', 'entwurf' => 'Nur offener Entwurf', 'ohne' => 'Keine freigegebene Fassung']], - ['eigenschaft' => 'nutzung', 'label' => 'Verwendung', 'vorgabe' => '', 'alle' => 'Verwendung egal', 'optionen' => ['verwendet' => 'Verwendet', 'unbenutzt' => 'Nicht verwendet']], - ], - 'weitere' => $weitere, - 'hinweis' => 'Freigabe meint die Fassung des Mediums, nicht die Website und keinen Zugriff. Geschützte Medien haben eine Inhaltsfassung und laufen über Lizenzen. Öffentliche Medien sind eigenständige Präsentationsmedien ohne Fassung für die Website; ob sie freigegeben sind, zeigt die Kennzeichnung an der Zeile. Materialart und Einordnung sind die redaktionelle Klassifikation; Verwendung zeigt, wo das Medium tatsächlich eingebunden ist. Deaktivierte und archivierte Medien bleiben über „Weitere Filter“ auffindbar.', + 'filterdialog' => $dialog, 'zeilen' => array_map($this->zeile(...), $this->cards()), 'einheit' => ['Medium', 'Medien'], + 'leerHinweis' => $keine ? 'Öffne den Filter und wähle mindestens eine Materialart aus, um Medien zu sehen. „Alle auswählen“ zeigt alles, auch die Übungsabschnitte.' : null, 'leer' => ['titel' => 'Noch keine Medien', 'text' => 'Mit „Medium anlegen“ oben lädst du eine Datei hoch oder schreibst einen Text.'], 'ansicht' => 'ansicht', ]; @@ -250,7 +614,7 @@ private function zeile(array $card): array return [ 'schluessel' => 'm'.$card['id'], 'titel' => $card['title'], - 'meta' => $card['type'].(filled($card['editorialKind'] ?? null) ? ' · '.$card['editorialKind'] : ''), + 'meta' => $card['type'].(filled($card['editorialKind'] ?? null) ? ' · '.$card['editorialKind'] : '').($card['exercise'] !== null ? ' · Übung: '.$card['exercise']['title'] : ''), 'text' => $card['description'], 'bild' => $card['image'], 'bildAlt' => $card['imageAlt'], @@ -271,6 +635,7 @@ private function zeile(array $card): array 'aktionen' => array_values(array_filter([ ['label' => 'Ansehen', 'href' => $card['url'], 'icon' => 'auge'], $card['editUrl'] ? ['label' => 'Redaktion', 'href' => $card['editUrl'], 'icon' => 'stift'] : null, + ($card['exercise']['url'] ?? null) ? ['label' => 'Zur Übung', 'href' => $card['exercise']['url'], 'icon' => 'stift'] : null, ])), ]; } @@ -291,6 +656,7 @@ private function libraryFilters(): array 'saeule' => $this->saeule, 'einordnung' => $this->einordnung, 'inhaltsart' => $this->inhaltsart, + 'arten' => $this->arten === '' ? MaterialKindSelection::encode($this->defaultArten()) : $this->arten, 'verarbeitung' => $this->verarbeitung, 'archiv' => $this->archiv, ]; diff --git a/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php b/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php index 6656743..b41a36d 100644 --- a/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php +++ b/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php @@ -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 array + */ + protected function richFelder(): array + { + return ['summary' => 'Kurzbeschreibung', 'descriptionText' => 'Ausführliche Beschreibung', 'bodyDraft' => 'Text der Fassung']; + } + /** * @return list> */ @@ -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, diff --git a/app/Filament/Resources/LicenseArticles/Pages/ViewLicenseArticle.php b/app/Filament/Resources/LicenseArticles/Pages/ViewLicenseArticle.php index ae4f7ab..04dbe8a 100644 --- a/app/Filament/Resources/LicenseArticles/Pages/ViewLicenseArticle.php +++ b/app/Filament/Resources/LicenseArticles/Pages/ViewLicenseArticle.php @@ -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 array + */ + protected function richFelder(): array + { + return ['summary' => 'Kurzbeschreibung', 'descriptionText' => 'Beschreibung']; + } + /** * @return list> */ @@ -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')], ]; } diff --git a/app/Filament/Support/EditorialCatalog.php b/app/Filament/Support/EditorialCatalog.php index 70cd2b8..865cb22 100644 --- a/app/Filament/Support/EditorialCatalog.php +++ b/app/Filament/Support/EditorialCatalog.php @@ -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), diff --git a/app/Filament/Support/ElementRevision.php b/app/Filament/Support/ElementRevision.php index c253142..fa3fcd1 100644 --- a/app/Filament/Support/ElementRevision.php +++ b/app/Filament/Support/ElementRevision.php @@ -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') diff --git a/app/Filament/Support/ListsCompositions.php b/app/Filament/Support/ListsCompositions.php index 143ee51..c22dc83 100644 --- a/app/Filament/Support/ListsCompositions.php +++ b/app/Filament/Support/ListsCompositions.php @@ -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; diff --git a/app/Filament/Support/ManagesEditorialSurface.php b/app/Filament/Support/ManagesEditorialSurface.php index 5746522..801b383 100644 --- a/app/Filament/Support/ManagesEditorialSurface.php +++ b/app/Filament/Support/ManagesEditorialSurface.php @@ -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'] ?? '')); } diff --git a/app/Filament/Support/ManagesRichFields.php b/app/Filament/Support/ManagesRichFields.php new file mode 100644 index 0000000..643d228 --- /dev/null +++ b/app/Filament/Support/ManagesRichFields.php @@ -0,0 +1,132 @@ +`). 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 Zustand der Editoren (Dokumente) je Eigenschaft */ + public array $rich = []; + + /** @var array Prüfsumme des zuletzt abgeglichenen kanonischen Werts je Eigenschaft */ + public array $richSeen = []; + + /** + * Eigenschaften dieser Seite, die mit dem Editor bearbeitet werden, mit ihrer Bezeichnung (Name für Hilfstechnik). + * + * @return array + */ + protected function richFelder(): array + { + return []; + } + + /** @return list */ + protected function richNamen(): array + { + return array_keys($this->richFelder()); + } + + public function richTextSchema(Schema $schema): Schema + { + return $schema + ->statePath('rich') + ->components(array_map(fn (string $name, string $label): RichEditor => RichField::make($name, $label, hideLabel: true), $this->richNamen(), $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->richNamen(), 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] = md5($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] = md5($canonical); + } + + /** Vor dem Rendern: Eigenschaften, die der Server geändert hat, in den Editor übernehmen. */ + public function renderingManagesRichFields(): void + { + foreach ($this->richNamen() as $name) { + $canonical = FormattedText::canonical((string) $this->{$name}); + + if (! array_key_exists($name, $this->richSeen) || $this->richSeen[$name] !== md5($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}); + } +} diff --git a/app/Filament/Support/MaterialKindSelection.php b/app/Filament/Support/MaterialKindSelection.php new file mode 100644 index 0000000..c0d341d --- /dev/null +++ b/app/Filament/Support/MaterialKindSelection.php @@ -0,0 +1,58 @@ +` für eine Materialart oder `ohne` für Medien ohne Materialart. + * + * - Leer: keine Einschränkung (so rufen andere Stellen die Medienbibliothek auf). + * - `keine`: ausdrücklich nichts ausgewählt, die Liste ist dann leer. + * - sonst: die Schlüssel, durch Komma getrennt. + */ +final class MaterialKindSelection +{ + public const WITHOUT = 'ohne'; + + public const NONE = 'keine'; + + public static function key(?int $kindId): string + { + return $kindId === null ? self::WITHOUT : 'k'.$kindId; + } + + /** + * @param list $keys + */ + public static function encode(array $keys): string + { + $keys = self::clean($keys); + + return $keys === [] ? self::NONE : implode(',', $keys); + } + + /** + * @return list|null null = keine Einschränkung + */ + public static function decode(string $value): ?array + { + $value = trim($value); + + if ($value === '') { + return null; + } + + return $value === self::NONE ? [] : self::clean(explode(',', $value)); + } + + /** + * @param list $keys + * @return list + */ + private static function clean(array $keys): array + { + $keys = array_filter(array_map('trim', $keys), fn (string $key): bool => $key === self::WITHOUT || preg_match('/^k\d+$/', $key) === 1); + + return array_values(array_unique($keys)); + } +} diff --git a/app/Filament/Support/MediaLibrary.php b/app/Filament/Support/MediaLibrary.php index 73b3240..8e401a3 100644 --- a/app/Filament/Support/MediaLibrary.php +++ b/app/Filament/Support/MediaLibrary.php @@ -9,12 +9,14 @@ use App\Domain\Catalog\ContentElementVersion; use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\EditorialVocabulary; +use App\Domain\Catalog\FormattedText; use App\Domain\Catalog\IdentityDimensionValue; use App\Domain\Catalog\Pillar; use App\Domain\Catalog\PillarFilterCompat; use App\Domain\Catalog\ReleaseContent; use App\Domain\Media\ThumbnailRef; use App\Filament\Resources\ContentElements\ContentElementResource; +use App\Filament\Resources\Practices\PracticeResource; use Illuminate\Support\Collection; use Illuminate\Support\Str; @@ -77,7 +79,7 @@ public function classifications(array $selectedIds = []): array */ public function cardFor(ContentElement $element, bool $canEdit): array { - $element->loadMissing(['versions', 'pillars', 'editorialContentKind']); + $element->loadMissing(['versions', 'pillars', 'editorialContentKind', 'originComposition']); $versionIds = $element->versions->pluck('id')->all(); return $this->card( @@ -97,7 +99,7 @@ public function cards(array $filters, bool $canEdit): array { $filters = $this->normalize($filters); $elements = ContentElement::query() - ->with(['versions', 'pillars', 'editorialContentKind']) + ->with(['versions', 'pillars', 'editorialContentKind', 'originComposition']) ->orderBy('working_title') ->get(); $versionIds = $elements->flatMap(fn (ContentElement $element) => $element->versions->pluck('id'))->all(); @@ -142,20 +144,34 @@ private function normalize(array $filters): array return [ 'suche' => trim($filters['suche'] ?? ''), - 'art' => $this->choice($filters['art'] ?? '', ['film', 'text', 'document', 'bild', 'audio']), - 'freigabe' => $this->choice($filters['freigabe'] ?? '', ['freigegeben', 'entwurf', 'ohne']), + 'art' => $this->choices($filters['art'] ?? '', ['film', 'text', 'document', 'bild', 'audio']), + 'freigabe' => $this->choices($filters['freigabe'] ?? '', ['freigegeben', 'entwurf', 'ohne']), 'schutz' => $this->choice($filters['schutz'] ?? '', ['geschuetzt', 'oeffentlich', 'website']), 'entwurf' => $this->choice($filters['entwurf'] ?? '', ['offen', 'keiner']), 'fassung' => $this->choice($filters['fassung'] ?? '', ['mit', 'nur']), - 'nutzung' => $this->choice($filters['nutzung'] ?? '', ['verwendet', 'unbenutzt']), + 'nutzung' => $this->choices($filters['nutzung'] ?? '', ['verwendet', 'unbenutzt']), 'saeule' => $saeule, 'einordnung' => $einordnung, 'inhaltsart' => ctype_digit($filters['inhaltsart'] ?? '') ? $filters['inhaltsart'] : '', + // Mehrfachauswahl der Materialarten (MaterialKindSelection); leer = keine Einschränkung. + 'arten' => trim((string) ($filters['arten'] ?? '')), 'verarbeitung' => $this->choice($filters['verarbeitung'] ?? '', ['fehler', 'uebernahme']), 'archiv' => $this->choice($filters['archiv'] ?? '', ['aktiv', 'archiviert', 'alle'], 'aktiv'), ]; } + /** + * Mehrere Werte eines Filterfelds, durch Komma getrennt. Sie gelten als ODER; leer heißt keine Einschränkung. + * Ein einzelner Wert, wie ihn ältere Adressen und gespeicherte Standards enthalten, ist ein gültiger Sonderfall. + * + * @param list $allowed + * @return list + */ + private function choices(string $value, array $allowed): array + { + return array_values(array_intersect($allowed, array_map('trim', explode(',', $value)))); + } + /** * @param list $allowed */ @@ -357,7 +373,7 @@ private function processing(Collection $versions): ?string /** * @param array $portrait * @param list> $uses - * @param array $filters + * @param array $filters * @param array> $classified */ private function matches(ContentElement $element, array $portrait, array $uses, array $filters, string $needle, array $classified): bool @@ -366,7 +382,7 @@ private function matches(ContentElement $element, array $portrait, array $uses, return false; } - if (! $this->matchesArt($element, $filters['art'])) { + if ($filters['art'] !== [] && ! $this->matchesAnyArt($element, $filters['art'])) { return false; } @@ -398,16 +414,16 @@ private function matches(ContentElement $element, array $portrait, array $uses, return false; } - if ($filters['freigabe'] === 'freigegeben' && $portrait['ready'] === null) { - return false; - } + if ($filters['freigabe'] !== []) { + $passes = [ + 'freigegeben' => $portrait['ready'] !== null, + 'entwurf' => $portrait['draft'] !== null && $portrait['ready'] === null, + 'ohne' => $portrait['ready'] === null, + ]; - if ($filters['freigabe'] === 'entwurf' && ($portrait['draft'] === null || $portrait['ready'] !== null)) { - return false; - } - - if ($filters['freigabe'] === 'ohne' && $portrait['ready'] !== null) { - return false; + if (! in_array(true, array_intersect_key($passes, array_flip($filters['freigabe'])), true)) { + return false; + } } if ($filters['entwurf'] === 'offen' && $portrait['draft'] === null) { @@ -428,11 +444,7 @@ private function matches(ContentElement $element, array $portrait, array $uses, $used = $this->usageCount($uses) > 0; - if ($filters['nutzung'] === 'verwendet' && ! $used) { - return false; - } - - if ($filters['nutzung'] === 'unbenutzt' && $used) { + if ($filters['nutzung'] !== [] && ! in_array($used ? 'verwendet' : 'unbenutzt', $filters['nutzung'], true)) { return false; } @@ -448,6 +460,14 @@ private function matches(ContentElement $element, array $portrait, array $uses, return false; } + if ($filters['arten'] !== '') { + $keys = MaterialKindSelection::decode($filters['arten']) ?? []; + + if (! in_array(MaterialKindSelection::key($element->editorial_content_kind_id === null ? null : (int) $element->editorial_content_kind_id), $keys, true)) { + return false; + } + } + if ($filters['verarbeitung'] === 'fehler' && $portrait['processing'] !== 'Verarbeitungsfehler') { return false; } @@ -468,6 +488,20 @@ private function isPresentationMedium(ContentElement $element, int $versionCount return $versionCount === 0 && in_array($element->output_class, ['bild', 'film', 'audio'], true); } + /** + * @param list $arts + */ + private function matchesAnyArt(ContentElement $element, array $arts): bool + { + foreach ($arts as $art) { + if ($this->matchesArt($element, $art)) { + return true; + } + } + + return false; + } + private function matchesArt(ContentElement $element, string $art): bool { if ($art === '') { @@ -488,8 +522,8 @@ private function haystack(ContentElement $element): string return mb_strtolower(implode("\n", array_filter([ $element->working_title, $element->display_title, - $element->description, - $element->summary, + FormattedText::plain($element->description), + FormattedText::plain($element->summary), $element->teaser, $element->search_terms, $element->usage_note, @@ -504,7 +538,7 @@ private function haystack(ContentElement $element): string */ private function card(ContentElement $element, array $portrait, array $uses, array $codes, bool $canEdit): array { - $description = trim((string) ($element->description ?: $element->summary ?: '')); + $description = FormattedText::plain((string) ($element->description ?: $element->summary ?: '')); $usageNote = trim((string) $element->usage_note); $licenseNote = trim((string) $element->license_note); $typeKey = $this->typeKey((string) $element->output_class); @@ -515,6 +549,7 @@ private function card(ContentElement $element, array $portrait, array $uses, arr 'title' => $element->working_title, 'type' => $this->catalog->outputLabel((string) $element->output_class), 'editorialKind' => $element->editorialContentKind?->label, + 'exercise' => $this->exerciseOf($element, $canEdit), 'typeKey' => $typeKey, 'description' => $description === '' ? null : $description, 'usageNote' => $usageNote === '' ? null : $usageNote, @@ -543,6 +578,25 @@ private function card(ContentElement $element, array $portrait, array $uses, arr ]; } + /** + * Die Übung, für die ein Textabschnitt angelegt wurde: Titel und, für die Redaktion, der Weg zum Übungseditor. + * + * @return array{title: string, url: string|null}|null + */ + private function exerciseOf(ContentElement $element, bool $canEdit): ?array + { + $exercise = $element->originComposition; + + if (! $exercise instanceof Composition) { + return null; + } + + return [ + 'title' => (string) ($exercise->display_title ?: $exercise->designation), + 'url' => $canEdit ? PracticeResource::getUrl('edit', ['record' => $exercise]) : null, + ]; + } + /** * @param list> $uses */ diff --git a/app/Filament/Support/MediumForm.php b/app/Filament/Support/MediumForm.php index 6032be8..e84a941 100644 --- a/app/Filament/Support/MediumForm.php +++ b/app/Filament/Support/MediumForm.php @@ -6,6 +6,8 @@ use App\Domain\Catalog\ContentElementVersion; use App\Domain\Catalog\ContentService; use App\Domain\Catalog\DomainRuleException; +use App\Domain\Catalog\EditorialVocabulary; +use App\Domain\Catalog\FormattedText; use App\Domain\Catalog\IdentityProfile; use App\Domain\Media\PresentationFile; use App\Jobs\DeriveThumbnail; @@ -28,14 +30,19 @@ public static function fields(bool $creating, ?ContentElement $element = null): ]; if ($creating) { - $fields[] = Select::make('shape')->label('Was ist das?')->options([ + $fields[] = Select::make('editorial_content_kind_id') + ->label('Fachliche Materialart') + ->options(fn (): array => app(EditorialVocabulary::class)->kindOptions('medium')) + ->required() + ->helperText('Die redaktionelle Einordnung, zum Beispiel Merkblatt. Sie steht in der Medienliste und lässt sich dort filtern. Die technische Art wählst du darunter.'); + $fields[] = Select::make('shape')->label('Technische Art')->options([ 'film' => 'Film', 'audio' => 'Hörstück', 'bild' => 'Bild', '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 +53,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) @@ -94,6 +101,7 @@ public static function create(array $data, bool $hold): ContentElement { $service = app(ContentService::class); [$kind, $output] = self::shape($data['shape'] ?? null); + $kindId = self::contentKindId($data); $incoming = null; if ($output !== 'text') { @@ -122,10 +130,12 @@ public static function create(array $data, bool $hold): ContentElement } $element = $service->createElement($kind, $output, (string) $data['working_title']); + $element->editorial_content_kind_id = $kindId; + $element->save(); 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.'); @@ -154,6 +164,28 @@ public static function create(array $data, bool $hold): ContentElement return $element->fresh() ?? $element; } + /** + * Die fachliche Materialart ist beim Anlegen Pflicht und muss für Medien zulässig und aktiv sein. + * + * @param array $data + */ + private static function contentKindId(array $data): int + { + $id = $data['editorial_content_kind_id'] ?? null; + + if (! filled($id) || ! ctype_digit((string) $id)) { + throw new DomainRuleException('Die fachliche Materialart fehlt.'); + } + + $error = app(EditorialVocabulary::class)->kindError('medium', (int) $id, null); + + if ($error !== null) { + throw new DomainRuleException($error); + } + + return (int) $id; + } + /** * @param array $data */ @@ -164,7 +196,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 +217,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 +230,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, diff --git a/app/Filament/Support/RichField.php b/app/Filament/Support/RichField.php new file mode 100644 index 0000000..3cd8bb8 --- /dev/null +++ b/app/Filament/Support/RichField.php @@ -0,0 +1,33 @@ +toolbarButtons(FormattedText::TOOLBAR); + + if ($live) { + $field->live(onBlur: true); + } + + if ($label !== null) { + $field->label($label); + } + + return $label === null || $hideLabel ? $field->hiddenLabel() : $field; + } +} diff --git a/app/Http/Controllers/ShopController.php b/app/Http/Controllers/ShopController.php index 92901f6..29a9dc6 100644 --- a/app/Http/Controllers/ShopController.php +++ b/app/Http/Controllers/ShopController.php @@ -4,6 +4,7 @@ use App\Domain\Catalog\Bundle; use App\Domain\Catalog\Composition; +use App\Domain\Catalog\FormattedText; use App\Domain\Cms\Catalog\PublicCatalogReader; use App\Domain\Commerce\Money; use App\Domain\Commerce\ProductOptions; @@ -30,7 +31,7 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR } $title = (string) ($composition->display_title ?: $composition->designation); - $haystack = mb_strtolower($title.' '.$composition->teaser.' '.$composition->summary.' '.$composition->search_terms); + $haystack = mb_strtolower($title.' '.$composition->teaser.' '.FormattedText::plain($composition->summary).' '.$composition->search_terms); if ($term !== '' && ! str_contains($haystack, mb_strtolower($term))) { continue; @@ -40,7 +41,7 @@ public function index(Request $request, ProductOptions $products, PublicCatalogR $cards[] = [ 'url' => route('public.program', $composition), 'title' => $title, - 'teaser' => (string) ($composition->teaser ?: $composition->summary), + 'teaser' => (string) ($composition->teaser ?: FormattedText::plain($composition->summary)), 'from' => Money::format($summary['from_cents']), 'count' => $summary['count'], ]; diff --git a/app/Http/LibraryCatalog.php b/app/Http/LibraryCatalog.php index d715389..2e40ed6 100644 --- a/app/Http/LibraryCatalog.php +++ b/app/Http/LibraryCatalog.php @@ -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 ? '

    '.e($profile->value('teaser')).'

    ' : ''), + 'description_html' => $profile->html('description'), ]; } diff --git a/app/Models/UserViewDefault.php b/app/Models/UserViewDefault.php new file mode 100644 index 0000000..5dea407 --- /dev/null +++ b/app/Models/UserViewDefault.php @@ -0,0 +1,54 @@ + 'array']; + } + + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + /** + * @return array|null + */ + public static function filtersFor(?int $userId, string $view): ?array + { + if ($userId === null) { + return null; + } + + $row = static::query()->where('user_id', $userId)->where('view', $view)->first(); + + return $row === null ? null : array_map('strval', (array) $row->filters); + } + + /** + * @param array $filters + */ + public static function remember(int $userId, string $view, array $filters): void + { + static::query()->updateOrCreate(['user_id' => $userId, 'view' => $view], ['filters' => $filters]); + } + + public static function forget(int $userId, string $view): void + { + static::query()->where('user_id', $userId)->where('view', $view)->delete(); + } +} diff --git a/app/Support/Brand/Symbols.php b/app/Support/Brand/Symbols.php index af63267..3c80d35 100644 --- a/app/Support/Brand/Symbols.php +++ b/app/Support/Brand/Symbols.php @@ -25,6 +25,9 @@ final class Symbols /** @var array */ private static array $cache = []; + /** @var array>|null */ + private static ?array $bounds = null; + /** * @return list */ @@ -56,20 +59,51 @@ private static function render(string $set, string $name, string $attributes): H throw new InvalidArgumentException("Unbekanntes Markensymbol „{$name}“ im Satz „{$set}“."); } - $svg = self::$cache["$set/$name"] ??= self::clean((string) file_get_contents(self::directory($set)."/$name.svg")); + $svg = self::$cache["$set/$name"] ??= self::clean((string) file_get_contents(self::directory($set)."/$name.svg"), $set === self::SET_SYMBOLS ? self::bounds($name) : null); $extra = trim($attributes) === '' ? '' : ' '.trim($attributes); return new HtmlString(preg_replace('/^