From c57a506f854873513c4a55878b1f20ce723192cd Mon Sep 17 00:00:00 2001 From: Lars Date: Tue, 24 Nov 2026 11:31:03 +0100 Subject: [PATCH] Biete Tabellen und Bilder im gemeinsamen Texteditor an und setze sie in Ansicht und PDF MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tabellen und Bilder gehören zur festen Auswahl von FormattedText. Ein Bild ist ein Verweis auf eine freigegebene Bildfassung und kommt per Picker aus dem Medienbestand; der Stand schreibt die Bildfassung mit fest, die Rechte entscheidet DecideAccess. Der PDF-Satz (PdfFlow) ist für Übung und kommende Dokumente gemeinsam; PdfDocument kann zusätzlich Bilder, Flächen, Verweise und Lesezeichen, Belege bleiben byte-gleich. Co-Authored-By: Claude Sonnet 5.5 --- app/Domain/Catalog/ContentResolver.php | 34 +- app/Domain/Catalog/ContentService.php | 38 ++ app/Domain/Catalog/EmbeddedImages.php | 123 ++++ app/Domain/Catalog/ExerciseGuide.php | 3 +- app/Domain/Catalog/ExercisePdf.php | 203 +----- app/Domain/Catalog/FormattedText.php | 279 ++++++++- app/Domain/Catalog/PdfFlow.php | 587 ++++++++++++++++++ app/Domain/Catalog/PdfImages.php | 49 ++ app/Domain/Commerce/Receipt/PdfDocument.php | 173 +++++- app/Domain/Media/PdfImage.php | 56 ++ .../Compositions/Pages/EditComposition.php | 10 + .../Pages/EditContentElement.php | 3 +- .../Pages/ViewContentElement.php | 8 + app/Filament/Support/ChoosesMedia.php | 8 +- app/Filament/Support/ElementRevision.php | 3 +- .../Support/ManagesEditorialSurface.php | 70 ++- app/Filament/Support/ManagesRichFields.php | 15 +- app/Filament/Support/MediumForm.php | 3 +- app/Filament/Support/RichField.php | 24 +- .../Controllers/Member/ExerciseController.php | 8 + .../Controllers/Member/LibraryController.php | 3 + resources/css/components/lf-member.css | 42 ++ resources/views/content/player.blade.php | 2 +- resources/views/member/article.blade.php | 2 +- resources/views/member/read.blade.php | 2 +- tests/Feature/TextEditorWerkzeugeTest.php | 147 +++++ tests/Unit/FormattedTextTest.php | 53 ++ 27 files changed, 1729 insertions(+), 219 deletions(-) create mode 100644 app/Domain/Catalog/EmbeddedImages.php create mode 100644 app/Domain/Catalog/PdfFlow.php create mode 100644 app/Domain/Catalog/PdfImages.php create mode 100644 app/Domain/Media/PdfImage.php create mode 100644 tests/Feature/TextEditorWerkzeugeTest.php diff --git a/app/Domain/Catalog/ContentResolver.php b/app/Domain/Catalog/ContentResolver.php index 54098ba..6988819 100644 --- a/app/Domain/Catalog/ContentResolver.php +++ b/app/Domain/Catalog/ContentResolver.php @@ -23,7 +23,7 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p 'path' => $path !== '' ? $path : $node->element->working_title, 'requirement' => CompositionMember::REQUIRED, 'variant' => null, - ]]; + ], ...$this->embeddedImages($node, $path !== '' ? $path : $node->element->working_title, null)]; } if (in_array($node->composition_id, $stack, true)) { @@ -51,6 +51,10 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p 'variant' => $variantKey, ]; + foreach ($this->embeddedImages($member->contentElementVersion, $segment, $variantKey) as $image) { + $rows[] = $image; + } + continue; } @@ -79,6 +83,34 @@ public function expand(ContentElementVersion|CompositionVersion $node, string $p return $rows; } + /** + * Bilder, auf die ein Text verweist, gehören zum Inhalt des Stands: Nur was im Stand steht, darf ein Mitglied sehen + * (`DecideAccess`), und eine Sperre des Bildes wirkt über denselben Weg. Ein fehlendes Bild macht den Text nicht + * unbrauchbar, daher „ergänzend“. + * + * @return list + */ + private function embeddedImages(?ContentElementVersion $text, string $path, ?string $variantKey): array + { + if ($text === null || trim((string) $text->body) === '' || ! str_contains((string) $text->body, 'img')) { + return []; + } + + $rows = []; + + foreach (FormattedText::imageIds($text->body) as $id) { + $rows[] = [ + 'version_id' => $id, + 'role' => 'Bild', + 'path' => $path.' / Bild', + 'requirement' => CompositionMember::SUPPLEMENTARY, + 'variant' => $variantKey, + ]; + } + + return $rows; + } + public function resolvedHash(ContentElementVersion|CompositionVersion $node): string { $ids = array_values(array_unique(array_column($this->expand($node), 'version_id'))); diff --git a/app/Domain/Catalog/ContentService.php b/app/Domain/Catalog/ContentService.php index fba9675..f7bfd77 100644 --- a/app/Domain/Catalog/ContentService.php +++ b/app/Domain/Catalog/ContentService.php @@ -190,6 +190,44 @@ public function elementReleaseProblem(ContentElementVersion $version): ?string return 'Der Text braucht einen Inhalt.'; } + if ($version->element?->output_class === 'text') { + return $this->imageProblem((string) $version->body); + } + + return null; + } + + /** + * Ein Text verweist auf Bildfassungen des Medienbestands. Festgeschrieben werden kann er nur, wenn jede davon + * vorhanden, ein Bild und freigegeben ist; sonst wäre die Ausgabe der Fassung nicht festgelegt. + */ + public function imageProblem(?string $body): ?string + { + $ids = FormattedText::imageIds($body); + + if ($ids === []) { + return null; + } + + $versions = ContentElementVersion::query()->with('element')->whereKey($ids)->get()->keyBy('id'); + + foreach ($ids as $id) { + $image = $versions->get($id); + $title = $image?->element === null ? 'Bild' : (string) ($image->element->display_title ?: $image->element->working_title); + + if ($image === null || $image->element === null || $image->element->output_class !== 'bild') { + return 'Der Text verweist auf ein Bild, das es nicht mehr gibt.'; + } + + if ($image->status === ContentVersionStatus::Gesperrt) { + return 'Das Bild „'.$title.'“ ist deaktiviert und kann nicht festgeschrieben werden.'; + } + + if ($image->status !== ContentVersionStatus::Bereit) { + return 'Das Bild „'.$title.'“ ist noch nicht freigegeben.'; + } + } + return null; } diff --git a/app/Domain/Catalog/EmbeddedImages.php b/app/Domain/Catalog/EmbeddedImages.php new file mode 100644 index 0000000..9b468bb --- /dev/null +++ b/app/Domain/Catalog/EmbeddedImages.php @@ -0,0 +1,123 @@ + ['src' => self::staffSource($id)]; + } + + /** Adresse einer Bildfassung für den Editor und die Vorschau der Verwaltung. */ + public static function staffSource(int $id): string + { + return route('content.file', ['version' => $id], false); + } + + /** Text für einen Editor der Verwaltung: Bilder tragen ihre Adresse, damit der Editor sie zeigt. */ + public static function forEditor(?string $value): string + { + return FormattedText::forEditor(FormattedText::canonical($value), fn (int $id): string => self::staffSource($id)); + } + + /** + * Auflösung für {@see FormattedText::html()}. + * + * @return Closure(int): ?array{src?: string, alt?: string, note?: string} + */ + public function forView(User $user, LicenseArticle $article, ArticleRelease $release): Closure + { + return function (int $id) use ($user, $article, $release): ?array { + $decision = $this->decide($user, $article, $release, $id, 'ansehen'); + + if ($decision === null) { + return ['note' => 'Dieses Bild gibt es nicht mehr.']; + } + + if (! $decision['allowed']) { + return ['note' => 'Dieses Bild ist derzeit nicht verfügbar.']; + } + + return ['src' => SignedLink::temporary('member.media', now()->addMinutes(10), [ + 'article' => $article->id, + 'release' => $release->id, + 'version' => $id, + 'action' => 'ansehen', + 'reader' => $user->id, + ])]; + }; + } + + /** + * Auflösung für das PDF. Die Bilder, die tatsächlich im PDF stehen, sammelt {@see PdfImages::used()} für den + * Ausgabenachweis. + */ + public function forPdf(User $user, LicenseArticle $article, ArticleRelease $release): PdfImages + { + return new PdfImages(function (int $id) use ($user, $article, $release): ?array { + $decision = $this->decide($user, $article, $release, $id, 'laden'); + + if ($decision === null) { + return ['note' => 'Bild nicht mehr vorhanden', 'grant' => null, 'version' => null]; + } + + if (! $decision['allowed']) { + return ['note' => 'Bild nicht verfügbar', 'grant' => null, 'version' => null]; + } + + $file = $decision['version']->metadata['file'] ?? null; + $disk = Storage::disk('media_derived'); + $prepared = is_string($file) && $file !== '' && ! str_contains($file, '..') && $disk->exists($file) + ? PdfImage::fromBytes((string) $disk->get($file)) + : null; + + if ($prepared === null) { + return ['note' => 'Bild kann nicht gedruckt werden', 'grant' => null, 'version' => null]; + } + + return $prepared + ['grant' => $decision['grant'], 'version' => $decision['version']]; + }); + } + + /** + * @return array{allowed: bool, version: ContentElementVersion, grant: ?Grant}|null + */ + private function decide(User $user, LicenseArticle $article, ArticleRelease $release, int $id, string $action): ?array + { + $version = ContentElementVersion::query()->with('element')->find($id); + + if (! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') { + return null; + } + + $decision = ($this->access)($user, $article, $release, $version, $action); + + return ['allowed' => $decision->allowed, 'version' => $version, 'grant' => $decision->grant]; + } +} diff --git a/app/Domain/Catalog/ExerciseGuide.php b/app/Domain/Catalog/ExerciseGuide.php index 27416d0..81408be 100644 --- a/app/Domain/Catalog/ExerciseGuide.php +++ b/app/Domain/Catalog/ExerciseGuide.php @@ -114,6 +114,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea { $exercise->loadMissing(['composition', 'variants', 'members.variant', 'members.contentElementVersion.element']); $library = app(LibraryCatalog::class); + $images = app(EmbeddedImages::class)->forView($user, $article, $release); $offered = $exercise->variants->filter(fn (CompositionVersionVariant $variant): bool => $selection === null || in_array($variant->key, $selection, true))->values(); $chosen = $offered->firstWhere('key', $variantKey) ?? $offered->first(); $entries = []; @@ -146,7 +147,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea 'download_grant' => $download?->grant, 'state' => $decision->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'), 'blocks' => $decision->allowed && $class === 'text' ? FormattedText::blocks($version->body) : null, - 'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body) : null, + 'html' => $decision->allowed && $class === 'text' ? FormattedText::html($version->body, $images) : null, ]; } diff --git a/app/Domain/Catalog/ExercisePdf.php b/app/Domain/Catalog/ExercisePdf.php index f7c837b..00ac074 100644 --- a/app/Domain/Catalog/ExercisePdf.php +++ b/app/Domain/Catalog/ExercisePdf.php @@ -3,6 +3,7 @@ namespace App\Domain\Catalog; use App\Domain\Commerce\Receipt\PdfDocument; +use Closure; use Transliterator; /** @@ -23,7 +24,7 @@ class ExercisePdf private PdfDocument $pdf; - private float $y = self::TOP; + private PdfFlow $flow; private int $page = 0; @@ -64,32 +65,36 @@ public function sections(array $guide): ?array * @param array $guide * @param list> $sections */ - public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl): string + public function render(array $guide, array $sections, string $licensee, string $copyId, string $variantName, string $guideUrl, ?PdfImages $images = null): string { $this->pdf = new PdfDocument; $this->page = 0; $this->footer = self::printable('Lizenziert für '.$licensee.' · Lizenzkopie '.$copyId); + $this->flow = new PdfFlow($this->pdf, self::LEFT, self::RIGHT, self::TOP, self::BOTTOM, function (): void { + $this->closePage(); + $this->newPage(); + }, $images === null ? null : Closure::fromCallable($images)); $this->newPage(); - $this->write(self::printable((string) $guide['title']), 18, true, 8); + $this->flow->write(self::printable((string) $guide['title']), 18, true, 8); if ($variantName !== '') { - $this->write(self::printable('Variante: '.$variantName), 11, true, 6); + $this->flow->write(self::printable('Variante: '.$variantName), 11, true, 6); } $this->fact('Lernziel', $guide['learning_goal']); 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); + $this->flow->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->flow->write(self::printable('Voraussetzungen: '.$guide['prerequisites']), 10.5, false, 4); } $this->fact('Ausstattung', $guide['material_note']); - $this->y -= 6; + $this->flow->y -= 6; foreach ($sections as $section) { $this->section($section, $guideUrl); @@ -108,16 +113,7 @@ public function render(array $guide, array $sections, string $licensee, string $ */ public static function printable(string $text): string { - $text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']); - $latin = Transliterator::create('Any-Latin; Latin-ASCII'); - $out = ''; - - foreach (mb_str_split($text) as $char) { - $encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8'); - $out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char; - } - - return $out; + return PdfFlow::printable($text); } /** @@ -131,16 +127,16 @@ private function section(array $section, string $guideUrl): void $label = in_array($section['class'], ['film', 'audio'], true) ? 'Film: '.$title.' - online abrufbar im Mitgliederbereich (geschützte Wiedergabe): '.$guideUrl : 'Material: '.$title.' - im Mitgliederbereich abrufbar: '.$guideUrl; - $this->write(self::printable($label), 10, false, 6); + $this->flow->write(self::printable($label), 10, false, 6); return; } - $this->write($title, 12.5, true, 5); + $this->flow->write($title, 12.5, true, 5, keep: 40); - $this->formatted($section['blocks'] ?? []); + $this->flow->formatted($section['blocks'] ?? []); - $this->y -= 4; + $this->flow->y -= 4; } /** Angabe mit Bezeichnung; formatierte Angaben stehen unter der Bezeichnung, einfache dahinter. */ @@ -153,177 +149,20 @@ private function fact(string $label, ?string $value): void } 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); + $this->flow->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); - } - - /** - * Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat und Listen mit fett und kursiv. - * - * @param list> $blocks - */ - 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) { - $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) { - $this->room($size + 4); - $this->pdf->text(self::LEFT, $this->y, $line, $size, $bold); - $this->y -= $size + 4; - } - - $this->y -= $after; - } - - private function room(float $needed): void - { - if ($this->y - $needed < self::BOTTOM) { - $this->closePage(); - $this->newPage(); - } + $this->flow->write(self::printable($label.':'), 10.5, true, 2); + $this->flow->formatted($blocks); } private function newPage(): void { $this->pdf->addPage(); $this->page++; - $this->y = self::TOP; + $this->flow->restart(); } private function closePage(): void diff --git a/app/Domain/Catalog/FormattedText.php b/app/Domain/Catalog/FormattedText.php index 1ff124e..708d6ce 100644 --- a/app/Domain/Catalog/FormattedText.php +++ b/app/Domain/Catalog/FormattedText.php @@ -8,11 +8,15 @@ use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig; /** - * Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50). + * Formatierter Text in der Verwaltung und im Mitgliederbereich (ADR-50, ADR-51). * * Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschrift (h3), fett, kursiv, Aufzählung, - * nummerierte Liste, Zitat, Link und Zeilenumbruch. Alles andere fällt beim Speichern weg, auch Skripte, Ereignis­attribute - * und Links auf andere Schemata als http, https und mailto. + * nummerierte Liste, Zitat, Link, Zeilenumbruch, Tabelle und Bild. Alles andere fällt beim Speichern weg, auch Skripte, + * Ereignis­attribute und Links auf andere Schemata als http, https und mailto. + * + * Ein Bild ist nie eine Adresse, sondern ein Verweis auf eine Bildfassung des Medienbestands (`…`). + * Die Adresse entsteht erst bei der Ausgabe, je nach Leser (Verwaltung, Mitglied mit Berechtigung, PDF). Ohne Auflösung + * zeigt die Ausgabe kein Bild. * * Klartext aus dem Altbestand bleibt unverändert in der Datenbank. Er wird erst beim Anzeigen oder Bearbeiten in dieselbe * Form gebracht ({@see self::html()}) und erst beim Speichern als HTML abgelegt. Erkannt wird HTML an einer Regel: Der @@ -25,7 +29,7 @@ final class FormattedText { /** Blockelemente, mit denen gespeichertes HTML beginnt. */ - private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote']; + private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote', 'table', 'img']; /** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */ public const FIELDS = ['summary', 'description']; @@ -33,7 +37,13 @@ final class FormattedText private static ?HtmlSanitizer $sanitizer = null; /** Symbolleiste der Editoren; muss zur Auswahl oben passen. */ - public const TOOLBAR = [['bold', 'italic', 'link'], ['h3'], ['bulletList', 'orderedList', 'blockquote'], ['undo', 'redo']]; + public const TOOLBAR = [ + ['bold', 'italic', 'link'], + ['h3'], + ['bulletList', 'orderedList', 'blockquote'], + ['table', 'tableAddRowAfter', 'tableAddColumnAfter', 'tableDeleteRow', 'tableDeleteColumn', 'tableToggleHeaderRow', 'tableDelete'], + ['undo', 'redo'], + ]; /** Wird der Wert als HTML gelesen (sonst als Klartext des Altbestands)? */ public static function isHtml(?string $value): bool @@ -66,21 +76,121 @@ public static function canonicalHtml(?string $html): string return $html === '' ? '' : self::normalize($html); } - /** Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt. */ - public static function html(?string $value): string + /** + * Sicheres HTML zur Ausgabe (für `{!! !!}`); Klartext des Altbestands wird dabei umgewandelt. + * + * Bilder erscheinen nur, wenn `$images` sie auflöst: Die Funktion bekommt die Kennung der Bildfassung und liefert + * `['src' => Adresse, 'alt' => Text]` (Bild), `['note' => Text]` (Hinweis an der Stelle des Bilds) oder null (Bild + * entfällt). Ohne Funktion entfallen alle Bilder; so zeigt keine Ausgabe versehentlich ein Bild ohne Rechteprüfung. + * + * @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images + */ + public static function html(?string $value, ?callable $images = null): string { - return self::canonical($value); + return self::renderImages(self::canonical($value), $images); } /** * 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). + * + * @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images */ - public static function display(?string $value): string + public static function display(?string $value, ?callable $images = null): string { $value = (string) $value; - return self::isHtml($value) ? self::canonical($value) : nl2br(e($value)); + return self::isHtml($value) ? self::renderImages(self::canonical($value), $images) : nl2br(e($value)); + } + + /** + * Die Bildfassungen, auf die ein Text verweist, in der Reihenfolge ihres Auftretens (ohne Wiederholung). + * + * @return list + */ + public static function imageIds(?string $value): array + { + $html = self::canonical($value); + + if ($html === '' || ! str_contains($html, ''.$html.'', LIBXML_NOERROR); + + foreach ($document->querySelectorAll('img[data-id]') as $image) { + $id = (int) $image->getAttribute('data-id'); + + if ($id > 0 && ! in_array($id, $ids, true)) { + $ids[] = $id; + } + } + + return $ids; + } + + /** + * Fügt die Adresse an jedes Bild, damit der Editor es zeigt. Die Adresse gehört nicht zum gespeicherten Wert: Die + * Bereinigung entfernt sie beim Übernehmen aus dem Editor wieder. + * + * @param callable(int): ?string $source + */ + public static function forEditor(string $html, callable $source): string + { + if (! str_contains($html, ''.$html.'', LIBXML_NOERROR); + + foreach ($document->querySelectorAll('img[data-id]') as $image) { + $src = $source((int) $image->getAttribute('data-id')); + + if ($src !== null) { + $image->setAttribute('src', $src); + } + } + + return trim($document->body->innerHTML); + } + + /** + * @param (callable(int): ?array{src?: string, alt?: string, note?: string})|null $images + */ + private static function renderImages(string $html, ?callable $images): string + { + if ($html === '' || ! str_contains($html, ''.$html.'', LIBXML_NOERROR); + + foreach (iterator_to_array($document->querySelectorAll('img')) as $image) { + $found = $images === null ? null : $images((int) $image->getAttribute('data-id')); + + if (isset($found['src'])) { + $image->removeAttribute('data-id'); + $image->setAttribute('src', (string) $found['src']); + $image->setAttribute('alt', (string) ($found['alt'] ?? $image->getAttribute('alt'))); + $image->setAttribute('loading', 'lazy'); + + continue; + } + + if (isset($found['note'])) { + $note = $document->createElement('p'); + $note->setAttribute('class', 'mb-bildhinweis'); + $note->textContent = (string) $found['note']; + $image->replaceWith($note); + + continue; + } + + $image->remove(); + } + + return trim($document->body->innerHTML); } public static function isBlank(?string $value): bool @@ -103,16 +213,37 @@ 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']), - }; + $text = self::plainBlock($block); + + if ($text !== '') { + $out[] = $text; + } } return trim(implode("\n\n", $out)); } + /** + * @param array $block + */ + private static function plainBlock(array $block): string + { + return 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']))), + 'table' => implode("\n", array_map( + fn (array $row): string => implode(' | ', array_map( + fn (array $cell): string => trim((string) preg_replace('/\s+/u', ' ', implode(' ', array_filter(array_map(fn (array $inner): string => self::plainBlock($inner), $cell['blocks']))))), + $row, + )), + $block['rows'], + )), + // Ein Bild hat im Klartext keinen Platz (Listen, Auszüge, Meta-Beschreibung). + 'image' => '', + default => self::runsText($block['runs']), + }; + } + /** Kurzer Text für Listen und Karten. */ public static function excerpt(?string $value, int $length = 120): string { @@ -123,9 +254,10 @@ public static function excerpt(?string $value, int $length = 120): string /** * Zerlegung in Blöcke mit Textabschnitten für das PDF. Ein Textabschnitt (Run) trägt `text`, `bold`, `italic` und - * `href`. + * `href`. Eine Tabelle besteht aus Zeilen mit Zellen (`header`, `colspan`, `rowspan`, `blocks`); ein Bild trägt die + * Kennung seiner Bildfassung (`id`) und den Alternativtext. * - * @return list, items?: list>}> + * @return list> */ public static function blocks(?string $value): array { @@ -136,9 +268,18 @@ public static function blocks(?string $value): array } $document = HTMLDocument::createFromString(''.$html.'', LIBXML_NOERROR); + + return self::extractBlocks($document->body); + } + + /** + * @return list> + */ + private static function extractBlocks(Node $parent): array + { $blocks = []; - foreach ($document->body->childNodes as $node) { + foreach ($parent->childNodes as $node) { if ($node->nodeType !== XML_ELEMENT_NODE) { continue; } @@ -159,6 +300,41 @@ public static function blocks(?string $value): array continue; } + if ($name === 'img') { + $blocks[] = ['type' => 'image', 'id' => (int) $node->getAttribute('data-id'), 'alt' => (string) $node->getAttribute('alt')]; + + continue; + } + + if ($name === 'table') { + $rows = []; + + foreach ($node->querySelectorAll('tr') as $row) { + $cells = []; + + foreach ($row->childNodes as $cell) { + if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) { + continue; + } + + $cells[] = [ + 'header' => strtolower($cell->nodeName) === 'th', + 'colspan' => max(1, (int) $cell->getAttribute('colspan')), + 'rowspan' => max(1, (int) $cell->getAttribute('rowspan')), + 'blocks' => self::extractBlocks($cell), + ]; + } + + if ($cells !== []) { + $rows[] = $cells; + } + } + + $blocks[] = ['type' => 'table', 'rows' => $rows]; + + continue; + } + $blocks[] = [ 'type' => match ($name) { 'h3' => 'heading', @@ -203,6 +379,14 @@ private static function normalize(string $html): string $document = HTMLDocument::createFromString(''.$html.'', LIBXML_NOERROR); $body = $document->body; + + // Ein Bild steht zwischen den Absätzen (der Editor setzt es als Block) und braucht seine Bildfassung. + foreach (iterator_to_array($document->querySelectorAll('img')) as $image) { + if ($image->parentNode !== $body || (int) $image->getAttribute('data-id') < 1) { + $image->remove(); + } + } + $out = ''; $loose = ''; @@ -229,7 +413,7 @@ private static function normalize(string $html): string $flush(); - return self::hasText($out) ? $out : ''; + return self::hasText($out) || str_contains($out, 'nodeName); + if ($name === 'img') { + $id = (int) $node->getAttribute('data-id'); + + return $id > 0 ? ''.e(trim((string) $node->getAttribute('alt'))).'' : ''; + } + + if ($name === 'table') { + return self::table($node); + } + if (in_array($name, ['ul', 'ol'], true)) { $items = ''; @@ -268,6 +462,45 @@ private static function block(Node $node): string return self::hasText($inner) ? '<'.$name.'>'.$inner.'' : ''; } + /** + * Eine Tabelle in der festen Form des Editors: Zeilen mit Kopf- (`th`) und Datenzellen (`td`), Zellen mit Absätzen, + * Verbindungen nur als `colspan` und `rowspan` über 1. Breiten, Gestaltung und Zwischenebenen entfallen. + */ + private static function table(Node $table): string + { + $rows = ''; + + foreach ($table->querySelectorAll('tr') as $row) { + $cells = ''; + + foreach ($row->childNodes as $cell) { + if ($cell->nodeType !== XML_ELEMENT_NODE || ! in_array(strtolower($cell->nodeName), ['th', 'td'], true)) { + continue; + } + + $name = strtolower($cell->nodeName); + $attributes = ''; + + foreach (['colspan', 'rowspan'] as $span) { + $value = (int) $cell->getAttribute($span); + + if ($value > 1) { + $attributes .= ' '.$span.'="'.min($value, 50).'"'; + } + } + + $inner = self::inner($cell); + $cells .= '<'.$name.$attributes.'>'.($inner === '' ? '

' : (preg_match('/^<(?:p|ul|ol|blockquote|h3)[\s>]/', $inner) === 1 ? $inner : '

'.$inner.'

')).''; + } + + if ($cells !== '') { + $rows .= ''.$cells.''; + } + } + + return $rows !== '' && self::hasText($rows) ? ''.$rows.'
' : ''; + } + private static function inner(Node $node): string { $html = ''; @@ -365,6 +598,14 @@ private static function sanitizer(): HtmlSanitizer ->allowElement('ol') ->allowElement('li') ->allowElement('blockquote') + ->allowElement('table') + ->allowElement('thead') + ->allowElement('tbody') + ->allowElement('tfoot') + ->allowElement('tr') + ->allowElement('th', ['colspan', 'rowspan']) + ->allowElement('td', ['colspan', 'rowspan']) + ->allowElement('img', ['data-id', 'alt']) ->allowElement('a', ['href']) ->allowLinkSchemes(['http', 'https', 'mailto']) ->allowRelativeLinks(false) diff --git a/app/Domain/Catalog/PdfFlow.php b/app/Domain/Catalog/PdfFlow.php new file mode 100644 index 0000000..17d76f3 --- /dev/null +++ b/app/Domain/Catalog/PdfFlow.php @@ -0,0 +1,587 @@ +y = $top; + } + + /** + * Zeichen außerhalb von Windows-1252 werden, wo möglich, lesbar ersetzt (Pfeil, Ungleichheitszeichen, andere + * lateinische Buchstaben); sonst bleibt „?“. + */ + public static function printable(string $text): string + { + $text = strtr($text, ['→' => '->', '←' => '<-', '≥' => '>=', '≤' => '<=', '✓' => '+', '✗' => 'x', '≠' => '!=', '≈' => '~']); + $latin = Transliterator::create('Any-Latin; Latin-ASCII'); + $out = ''; + + foreach (mb_str_split($text) as $char) { + $encoded = mb_convert_encoding($char, 'Windows-1252', 'UTF-8'); + $out .= $encoded === '?' && $char !== '?' ? ($latin?->transliterate($char) ?: '?') : $char; + } + + return $out; + } + + /** Beginn einer neuen Seite: der Satz steht wieder am oberen Rand. */ + public function restart(): void + { + $this->y = $this->top; + } + + public function room(float $needed): void + { + if ($this->y - $needed < $this->bottom) { + ($this->breakPage)(); + $this->y = $this->top; + } + } + + /** Eine Überschrift oder ein kurzer Text in Zeilen nach {@see PdfDocument::wrap()}. `$keep` hält Platz für folgenden Text frei. */ + public function write(string $text, float $size, bool $bold, float $after, float $keep = 0, ?float $x = null): void + { + $x ??= $this->left; + $lines = PdfDocument::wrap($text, $this->right - $x, $size, $bold); + + if ($keep > 0 && $lines !== []) { + $this->room(count($lines) * ($size + 4) + $keep); + } + + foreach ($lines as $line) { + $this->room($size + 4); + $this->pdf->text($x, $this->y, $line, $size, $bold); + $this->y -= $size + 4; + } + + $this->y -= $after; + } + + /** + * Blöcke aus {@see FormattedText::blocks()}: Absatz, Zwischenüberschrift, Zitat, Listen, Tabelle und Bild. + * + * @param list> $blocks + */ + public function formatted(array $blocks, ?float $x = null, float $size = 10.5): void + { + $x ??= $this->left; + + foreach ($blocks as $block) { + match ($block['type']) { + 'heading' => $this->headingBlock($block, $x, $size), + 'quote' => $this->runs($block['runs'], $x + 14, $size, italic: true, after: 5), + 'bullets' => $this->listItems($block['items'], fn (int $n): string => '•', $x, $size), + 'numbered' => $this->listItems($block['items'], fn (int $n): string => $n.'.', $x, $size), + 'table' => $this->table($block['rows'], $x), + 'image' => $this->image($block, $x), + default => $this->runs($block['runs'] ?? [], $x, $size, after: 5), + }; + } + } + + /** + * @param array $block + */ + private function headingBlock(array $block, float $x, float $size): void + { + // Eine Zwischenüberschrift bleibt bei ihrem Text: mindestens zwei Zeilen müssen mit auf die Seite. + $this->room(($size + 0.5) + 4 + 2 * ($size + 4)); + $this->runs($block['runs'], $x, $size + 0.5, bold: true, after: 4); + } + + /** + * @param list> $items + * @param callable(int): string $marker + */ + public function listItems(array $items, callable $marker, ?float $x = null, float $size = 10.5): void + { + $x ??= $this->left; + + foreach ($items as $index => $item) { + $this->room(14); + $this->pdf->text($x + 4, $this->y, $marker($index + 1), $size); + $this->runs($item, $x + 18, $size, after: 1); + } + + $this->y -= 3; + } + + /** + * Setzt Textabschnitte mit fett und kursiv in Zeilen um und zeichnet sie. Links erscheinen mit ausgeschriebener + * Adresse, weil sie auf Papier sonst verloren gehen. + * + * @param list $runs + */ + public function runs(array $runs, float $x, float $size, bool $bold = false, bool $italic = false, float $after = 0): void + { + foreach ($this->lines($runs, $this->right - $x, $size, $bold, $italic) 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; + } + + /** + * Zeilen aus Textabschnitten für eine Breite. Die Breite kommt aus den Schriftbreiten der Helvetica + * ({@see PdfDocument::exactWidth()}), damit verschiedene Schnitte in einer Zeile ohne Lücken aneinanderstoßen. + * + * @param list $runs + * @return list> + */ + public function lines(array $runs, float $maxWidth, float $size, bool $bold = false, bool $italic = false): array + { + $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(); + + return $lines; + } + + /** + * Ein Bild in Breite der Spalte, höchstens 320 Punkt hoch. Ein Bild lässt sich nicht teilen: Es steht ganz auf einer + * Seite. Kann das Bild nicht gezeigt werden, steht an seiner Stelle der Hinweis. + * + * @param array $block + */ + private function image(array $block, float $x): void + { + $found = $this->images === null ? null : ($this->images)((int) $block['id']); + + if ($found === null) { + return; + } + + if (! isset($found['jpeg'])) { + $this->runs([['text' => '['.($found['note'] ?? 'Bild nicht verfügbar').']', 'bold' => false, 'italic' => true, 'href' => null]], $x, 9.5, after: 5); + + return; + } + + $available = $this->right - $x; + $scale = min(1.0, $available / max(1, $found['width']), 320.0 / max(1, $found['height'])); + $width = max(1.0, $found['width'] * $scale); + $height = max(1.0, $found['height'] * $scale); + + $this->room($height + 8); + $this->pdf->image($x, $this->y - $height, $width, $height, $found['jpeg'], $found['width'], $found['height']); + $this->y -= $height + 8; + } + + /** + * Eine Tabelle mit Rahmen. Die Spaltenbreiten folgen dem Inhalt (Spalten mit kurzem Text bleiben schmal), Verbindungen + * über Spalten und Zeilen werden gesetzt. Eine Zeile bleibt zusammen; auf jeder Folgeseite stehen die Kopfzeilen + * erneut. Ist eine einzelne Zeile höher als eine Seite, erscheint ihr Inhalt als Fließtext. + * + * @param list>> $rows + */ + private function table(array $rows, float $x): void + { + if ($this->depth > 0 || $rows === []) { + // Tabellen in Tabellen kennt der Editor nicht; sicherheitshalber als Fließtext. + foreach ($rows as $row) { + foreach ($row as $cell) { + $this->formatted($cell['blocks'], $x); + } + } + + return; + } + + $size = 9.5; + $pad = 3.5; + $lineHeight = $size + 3; + $grid = $this->grid($rows); + $columns = $grid['columns']; + $widths = $this->columnWidths($grid['cells'], $columns, $this->right - $x, $size, $pad); + $headRows = 0; + + foreach ($rows as $row) { + if ($row !== [] && count(array_filter($row, fn (array $cell): bool => $cell['header'])) === count($row)) { + $headRows++; + + continue; + } + + break; + } + + $headRows = $headRows === count($rows) ? 0 : $headRows; + $prepared = []; + + foreach ($grid['cells'] as $cell) { + $inner = array_sum(array_slice($widths, $cell['column'], $cell['colspan'])) - 2 * $pad; + $this->depth++; + $cell['lines'] = $this->cellLines($cell['blocks'], max(10.0, $inner), $size, $cell['header']); + $this->depth--; + $cell['height'] = max(1, count($cell['lines'])) * $lineHeight + 2 * $pad; + $prepared[] = $cell; + } + + $rowCount = count($rows); + $heights = array_fill(0, $rowCount, $lineHeight + 2 * $pad); + + foreach ($prepared as $cell) { + if ($cell['rowspan'] === 1) { + $heights[$cell['row']] = max($heights[$cell['row']], $cell['height']); + } + } + + foreach ($prepared as $cell) { + if ($cell['rowspan'] > 1) { + $last = min($rowCount - 1, $cell['row'] + $cell['rowspan'] - 1); + $have = array_sum(array_slice($heights, $cell['row'], $last - $cell['row'] + 1)); + $heights[$last] += max(0.0, $cell['height'] - $have); + } + } + + $pageHeight = $this->top - $this->bottom; + + if (max($heights) > $pageHeight - 8) { + foreach ($rows as $row) { + foreach ($row as $cell) { + $this->formatted($cell['blocks'], $x); + } + } + + return; + } + + $drawRows = function (int $from, int $to) use ($prepared, $widths, $heights, $x, $size, $pad, $lineHeight): void { + $y = $this->y; + + for ($r = $from; $r <= $to; $r++) { + foreach ($prepared as $cell) { + if ($cell['row'] !== $r) { + continue; + } + + $cellLeft = $x + array_sum(array_slice($widths, 0, $cell['column'])); + $cellWidth = array_sum(array_slice($widths, $cell['column'], $cell['colspan'])); + $cellHeight = array_sum(array_slice($heights, $r, $cell['rowspan'])); + $this->frame($cellLeft, $y - $cellHeight, $cellWidth, $cellHeight, $cell['header']); + $textY = $y - $pad - $size; + + foreach ($cell['lines'] as $line) { + if ($line['marker'] !== null) { + $this->pdf->text($cellLeft + $pad + $line['indent'] - 12, $textY, $line['marker'], $size, $cell['header']); + } + + $cursor = $cellLeft + $pad + $line['indent']; + + foreach ($line['segments'] as [$text, $isBold, $isItalic]) { + $this->pdf->text($cursor, $textY, $text, $size, $isBold || $cell['header'], $isItalic); + $cursor += PdfDocument::exactWidth($text, $size, $isBold || $cell['header']); + } + + $textY -= $lineHeight; + } + } + + $y -= $heights[$r]; + } + + $this->y = $y; + }; + + $this->room($heights[0] + ($rowCount > 1 ? min($heights[1], 40.0) : 0)); + + for ($r = 0; $r < $rowCount; $r++) { + // Zeilen, die eine Verbindung über Zeilen zusammenhält, werden gemeinsam gesetzt. + $end = $r; + + do { + $before = $end; + + foreach ($prepared as $cell) { + if ($cell['row'] <= $end && $end < $cell['row'] + $cell['rowspan'] - 1) { + $end = min($rowCount - 1, $cell['row'] + $cell['rowspan'] - 1); + } + } + } while ($end !== $before); + + $span = $end - $r + 1; + $need = array_sum(array_slice($heights, $r, $span)); + + if ($this->y - $need < $this->bottom) { + ($this->breakPage)(); + $this->y = $this->top; + + if ($headRows > 0 && $r >= $headRows) { + $drawRows(0, $headRows - 1); + } + } + + $drawRows($r, $r + $span - 1); + $r += $span - 1; + } + + $this->y -= 8; + } + + private function frame(float $x, float $y, float $w, float $h, bool $header): void + { + if ($header) { + $this->pdf->fillRect($x, $y, $w, $h, 0.92); + } + + $this->pdf->line($x, $y, $x + $w, $y, 0.4); + $this->pdf->line($x, $y + $h, $x + $w, $y + $h, 0.4); + $this->pdf->line($x, $y, $x, $y + $h, 0.4); + $this->pdf->line($x + $w, $y, $x + $w, $y + $h, 0.4); + } + + /** + * Weist jeder Zelle ihre Spalte zu; Verbindungen über Zeilen belegen die Spalte in den Folgezeilen mit. + * + * @param list>> $rows + * @return array{columns: int, cells: list>} + */ + private function grid(array $rows): array + { + $occupied = []; + $cells = []; + $columns = 0; + + foreach ($rows as $r => $row) { + $column = 0; + + foreach ($row as $cell) { + while (isset($occupied[$r][$column])) { + $column++; + } + + $colspan = max(1, (int) $cell['colspan']); + $rowspan = max(1, (int) $cell['rowspan']); + + for ($dr = 0; $dr < $rowspan; $dr++) { + for ($dc = 0; $dc < $colspan; $dc++) { + $occupied[$r + $dr][$column + $dc] = true; + } + } + + $cells[] = $cell + ['row' => $r, 'column' => $column] + ['colspan' => $colspan, 'rowspan' => $rowspan]; + $column += $colspan; + $columns = max($columns, $column); + } + } + + return ['columns' => max(1, $columns), 'cells' => $cells]; + } + + /** + * Spaltenbreiten nach Inhalt: Jede Spalte braucht mindestens ihr längstes Wort und wünscht sich die Breite ihres + * längsten Zelltexts. Reicht der Platz, wird der Rest gleichmäßig verteilt; sonst teilt sich der Mangel nach Wunsch auf. + * + * @param list> $cells + * @return list + */ + private function columnWidths(array $cells, int $columns, float $available, float $size, float $pad): array + { + $min = array_fill(0, $columns, 24.0); + $want = array_fill(0, $columns, 24.0); + + foreach ($cells as $cell) { + if ($cell['colspan'] !== 1) { + continue; + } + + $text = self::printable($this->cellText($cell['blocks'])); + $widest = 0.0; + + foreach (preg_split('/\s+/u', $text) ?: [] as $word) { + $widest = max($widest, PdfDocument::exactWidth($word, $size, (bool) $cell['header'])); + } + + $c = $cell['column']; + $min[$c] = max($min[$c], $widest + 2 * $pad + 1); + $want[$c] = max($want[$c], PdfDocument::exactWidth($text, $size, (bool) $cell['header']) + 2 * $pad + 1); + } + + $want = array_map(fn (float $w, float $m): float => max($w, $m), $want, $min); + + if (array_sum($min) >= $available) { + $scale = $available / array_sum($min); + + return array_map(fn (float $w): float => $w * $scale, $min); + } + + if (array_sum($want) <= $available) { + $extra = ($available - array_sum($want)) / $columns; + + return array_map(fn (float $w): float => $w + $extra, $want); + } + + $room = $available - array_sum($min); + $wishes = array_sum($want) - array_sum($min); + + return array_map(fn (float $m, float $w): float => $m + $room * (($w - $m) / max(1.0, $wishes)), $min, $want); + } + + /** + * @param list> $blocks + */ + private function cellText(array $blocks): string + { + $out = []; + + foreach ($blocks as $block) { + $out[] = match ($block['type']) { + 'bullets', 'numbered' => implode(' ', array_map(fn (array $item): string => implode('', array_column($item, 'text')), $block['items'])), + 'table', 'image' => '', + default => implode('', array_column($block['runs'] ?? [], 'text')), + }; + } + + return trim((string) preg_replace('/\s+/u', ' ', implode(' ', $out))); + } + + /** + * Zeilen einer Tabellenzelle: Absätze, Aufzählungen und Zwischenüberschriften; ein Bild in der Zelle entfällt. + * + * @param list> $blocks + * @return list, indent: float, marker: ?string}> + */ + private function cellLines(array $blocks, float $width, float $size, bool $header): array + { + $out = []; + + foreach ($blocks as $block) { + if (in_array($block['type'], ['bullets', 'numbered'], true)) { + foreach ($block['items'] as $index => $item) { + foreach ($this->lines($item, $width - 12, $size, $header) as $i => $segments) { + $out[] = ['segments' => $segments, 'indent' => 12.0, 'marker' => $i === 0 ? ($block['type'] === 'bullets' ? '•' : ($index + 1).'.') : null]; + } + } + + continue; + } + + if (! isset($block['runs'])) { + continue; + } + + foreach ($this->lines($block['runs'], $width, $size, $header || $block['type'] === 'heading', $block['type'] === 'quote') as $segments) { + $out[] = ['segments' => $segments, 'indent' => 0.0, 'marker' => null]; + } + } + + return $out; + } +} diff --git a/app/Domain/Catalog/PdfImages.php b/app/Domain/Catalog/PdfImages.php new file mode 100644 index 0000000..536e2f6 --- /dev/null +++ b/app/Domain/Catalog/PdfImages.php @@ -0,0 +1,49 @@ + */ + private array $resolved = []; + + /** + * @param Closure(int): ?array{jpeg?: string, width?: int, height?: int, note?: string, grant: ?Grant, version: ?ContentElementVersion} $resolve + */ + public function __construct(private readonly Closure $resolve) {} + + /** + * @return array{jpeg?: string, width?: int, height?: int, note?: string}|null + */ + public function __invoke(int $id): ?array + { + if (! array_key_exists($id, $this->resolved)) { + $this->resolved[$id] = ($this->resolve)($id); + } + + return $this->resolved[$id]; + } + + /** + * @return list + */ + public function used(): array + { + $used = []; + + foreach ($this->resolved as $found) { + if ($found !== null && isset($found['jpeg']) && $found['version'] instanceof ContentElementVersion && $found['grant'] instanceof Grant) { + $used[] = ['version' => $found['version'], 'grant' => $found['grant']]; + } + } + + return $used; + } +} diff --git a/app/Domain/Commerce/Receipt/PdfDocument.php b/app/Domain/Commerce/Receipt/PdfDocument.php index fb73e0e..ba4e4c4 100644 --- a/app/Domain/Commerce/Receipt/PdfDocument.php +++ b/app/Domain/Commerce/Receipt/PdfDocument.php @@ -7,6 +7,10 @@ * WinAnsi). Absichtlich ohne Abhängigkeit: Ein Zahlungsbeleg ist ein Text mit Linien. Der Inhalt ist unkomprimiert und * enthält keinen Zeitstempel, damit dasselbe Dokument bei jedem Abruf byte-gleich ist und Tests den Text prüfen können. * Zeichen außerhalb von Windows-1252 werden durch „?“ ersetzt (das Minuszeichen U+2212 durch „-“). + * + * Für längere Dokumente (Handbuch) kann der Schreiber zusätzlich Flächen, JPEG-Bilder, Verweise innerhalb des Dokuments + * (Inhaltsverzeichnis) und Lesezeichen setzen. Wer sie nicht nutzt, erhält dieselben Bytes wie zuvor: Die zusätzlichen + * Objekte entstehen nur bei Bedarf und nach allen bisherigen. */ final class PdfDocument { @@ -20,6 +24,21 @@ final class PdfDocument /** Schräge Schnitte werden nur eingebunden, wenn das Dokument sie braucht (Belege bleiben unverändert). */ private bool $usesItalic = false; + /** @var list */ + private array $images = []; + + /** @var array Prüfsumme der Bilddatei => Index in {@see self::$images} */ + private array $imageIndex = []; + + /** @var array> Seite => Bilder, die sie zeigt */ + private array $pageImages = []; + + /** @var array> */ + private array $links = []; + + /** @var list */ + private array $outline = []; + /** 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]; @@ -31,6 +50,60 @@ public function addPage(): void $this->pages[] = ''; } + /** Anzahl der bisher angelegten Seiten. */ + public function pageCount(): int + { + return count($this->pages); + } + + /** Gefüllte Fläche in einem Grauwert (0 schwarz, 1 weiß), zum Beispiel für Tabellenköpfe. */ + public function fillRect(float $x, float $y, float $w, float $h, float $gray): void + { + $this->append(sprintf("q %s g %s %s %s %s re f Q\n", $this->n($gray), $this->n($x), $this->n($y), $this->n($w), $this->n($h))); + } + + /** + * Setzt ein JPEG (RGB, aus `imagejpeg`) mit seiner linken unteren Ecke bei `$x`/`$y`. Dasselbe Bild wird nur einmal + * im Dokument abgelegt. + */ + public function image(float $x, float $y, float $w, float $h, string $jpeg, int $pixelWidth, int $pixelHeight): void + { + $key = md5($jpeg); + + if (! isset($this->imageIndex[$key])) { + $this->imageIndex[$key] = count($this->images); + $this->images[] = ['bytes' => $jpeg, 'width' => $pixelWidth, 'height' => $pixelHeight]; + } + + $index = $this->imageIndex[$key]; + + if ($this->pages === []) { + $this->addPage(); + } + + $this->pageImages[array_key_last($this->pages)][$index] = true; + $this->append(sprintf("q %s 0 0 %s %s %s cm /Im%d Do Q\n", $this->n($w), $this->n($h), $this->n($x), $this->n($y), $index + 1)); + } + + /** + * Anklickbarer Bereich auf der aktuellen Seite, der zu einer Stelle im Dokument springt (Seitenindex ab 0, `$top` ist + * die Höhe des Ziels auf der Zielseite). + */ + public function link(float $x, float $y, float $w, float $h, int $page, float $top): void + { + if ($this->pages === []) { + $this->addPage(); + } + + $this->links[array_key_last($this->pages)][] = ['x' => $x, 'y' => $y, 'w' => $w, 'h' => $h, 'page' => $page, 'top' => $top]; + } + + /** Lesezeichen (Ebene 1 oder 2) für die Gliederung in PDF-Betrachtern. */ + public function bookmark(string $title, int $page, float $top, int $level = 1): void + { + $this->outline[] = ['title' => $title, 'page' => $page, 'top' => $top, 'level' => $level >= 2 ? 2 : 1]; + } + public function text(float $x, float $y, string $text, float $size = 10, bool $bold = false, bool $italic = false): void { $font = $italic ? ($bold ? 'F4' : 'F3') : ($bold ? 'F2' : 'F1'); @@ -145,9 +218,39 @@ public function output(string $title, ?string $keywords = null): string $kids = []; $next = 6; - foreach ($pages as $stream) { + // Nummern der zusätzlichen Objekte: nach den Seiten und Schriften, in fester Reihenfolge (Verweise, Bilder, Gliederung). + $cursor = 6 + 2 * count($pages) + ($this->usesItalic ? 2 : 0); + $annotations = []; + + foreach ($this->links as $pageIndex => $links) { + foreach ($links as $link) { + $annotations[$pageIndex][] = ['number' => $cursor++] + $link; + } + } + + $imageNumbers = []; + + foreach (array_keys($this->images) as $index) { + $imageNumbers[$index] = $cursor++; + } + + $outlineRoot = $this->outline === [] ? null : $cursor++; + $outlineNumbers = []; + + foreach (array_keys($this->outline) as $index) { + $outlineNumbers[$index] = $cursor++; + } + + foreach ($pages as $pageIndex => $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'.($this->usesItalic ? ' /F3 %ITALIC% 0 R /F4 %BOLDITALIC% 0 R' : '').' >> >> /Contents '.($next + 1).' 0 R >>'; + $xobjects = ''; + + foreach (array_keys($this->pageImages[$pageIndex] ?? []) as $index) { + $xobjects .= ' /Im'.($index + 1).' '.$imageNumbers[$index].' 0 R'; + } + + $annots = isset($annotations[$pageIndex]) ? ' /Annots ['.implode(' ', array_map(fn (array $link): string => $link['number'].' 0 R', $annotations[$pageIndex])).']' : ''; + $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' : '').' >>'.($xobjects === '' ? '' : ' /XObject <<'.$xobjects.' >>').' >> /Contents '.($next + 1).' 0 R'.$annots.' >>'; $objects[$next + 1] = '<< /Length '.strlen($stream)." >>\nstream\n".$stream.'endstream'; $next += 2; } @@ -161,6 +264,32 @@ public function output(string $title, ?string $keywords = null): string } } + foreach ($annotations as $links) { + foreach ($links as $link) { + $objects[$link['number']] = sprintf( + '<< /Type /Annot /Subtype /Link /Rect [%s %s %s %s] /Border [0 0 0] /Dest [%d 0 R /XYZ 0 %s null] >>', + $this->n($link['x']), + $this->n($link['y']), + $this->n($link['x'] + $link['w']), + $this->n($link['y'] + $link['h']), + 6 + 2 * min($link['page'], count($pages) - 1), + $this->n($link['top']), + ); + } + } + + foreach ($this->images as $index => $image) { + $objects[$imageNumbers[$index]] = '<< /Type /XObject /Subtype /Image /Width '.$image['width'].' /Height '.$image['height'].' /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length '.strlen($image['bytes'])." >>\nstream\n".$image['bytes']."\nendstream"; + } + + if ($outlineRoot !== null) { + $objects[1] = '<< /Type /Catalog /Pages 2 0 R /Outlines '.$outlineRoot.' 0 R /PageMode /UseOutlines >>'; + + foreach ($this->outlineObjects($outlineRoot, $outlineNumbers, count($pages)) as $number => $body) { + $objects[$number] = $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 >>'; @@ -186,6 +315,46 @@ public function output(string $title, ?string $keywords = null): string return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1).' /Root 1 0 R /Info 5 0 R >>'."\nstartxref\n".$xref."\n%%EOF\n"; } + /** + * Gliederung (Lesezeichen): Ebene 1 unter der Wurzel, Ebene 2 unter dem vorangehenden Eintrag der Ebene 1. + * + * @param array $numbers Objektnummer je Eintrag + * @return array + */ + private function outlineObjects(int $root, array $numbers, int $pageCount): array + { + $parentOf = []; + $childrenOf = []; + $lastTop = null; + + foreach ($this->outline as $index => $item) { + if ($item['level'] === 1 || $lastTop === null) { + $parentOf[$index] = null; + $lastTop = $index; + } else { + $parentOf[$index] = $lastTop; + } + + $childrenOf[$parentOf[$index] ?? -1][] = $index; + } + + $top = $childrenOf[-1]; + $objects = [$root => '<< /Type /Outlines /First '.$numbers[$top[0]].' 0 R /Last '.$numbers[$top[array_key_last($top)]].' 0 R /Count '.count($this->outline).' >>']; + + foreach ($this->outline as $index => $item) { + $siblings = $childrenOf[$parentOf[$index] ?? -1]; + $position = (int) array_search($index, $siblings, true); + $kids = $childrenOf[$index] ?? []; + $objects[$numbers[$index]] = '<< /Title ('.self::escape($item['title']).') /Parent '.($parentOf[$index] === null ? $root : $numbers[$parentOf[$index]]).' 0 R' + .($position > 0 ? ' /Prev '.$numbers[$siblings[$position - 1]].' 0 R' : '') + .($position < count($siblings) - 1 ? ' /Next '.$numbers[$siblings[$position + 1]].' 0 R' : '') + .($kids === [] ? '' : ' /First '.$numbers[$kids[0]].' 0 R /Last '.$numbers[$kids[array_key_last($kids)]].' 0 R /Count '.count($kids)) + .' /Dest ['.(6 + 2 * min($item['page'], $pageCount - 1)).' 0 R /XYZ 0 '.$this->n($item['top']).' null] >>'; + } + + return $objects; + } + private function append(string $operators): void { if ($this->pages === []) { diff --git a/app/Domain/Media/PdfImage.php b/app/Domain/Media/PdfImage.php new file mode 100644 index 0000000..61b8e4f --- /dev/null +++ b/app/Domain/Media/PdfImage.php @@ -0,0 +1,56 @@ + $jpeg, 'width' => $targetWidth, 'height' => $targetHeight] : null; + } +} diff --git a/app/Filament/Resources/Compositions/Pages/EditComposition.php b/app/Filament/Resources/Compositions/Pages/EditComposition.php index 7934111..6268d48 100644 --- a/app/Filament/Resources/Compositions/Pages/EditComposition.php +++ b/app/Filament/Resources/Compositions/Pages/EditComposition.php @@ -401,6 +401,16 @@ protected function richFelder(): array ]; } + /** + * Texte dürfen Bilder aus dem Medienbestand enthalten (gemeinsamer Picker); Kurzangaben nicht. + * + * @return list + */ + protected function richBilder(): array + { + return ['partBody', 'newTextBody']; + } + /** * @return list> */ diff --git a/app/Filament/Resources/ContentElements/Pages/EditContentElement.php b/app/Filament/Resources/ContentElements/Pages/EditContentElement.php index 815f998..5f6e298 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\EmbeddedImages; use App\Domain\Catalog\FormattedText; use App\Domain\Catalog\IdentityDimension; use App\Domain\Catalog\IdentityDimensionValue; @@ -195,7 +196,7 @@ protected function mutateFormDataBeforeFill(array $data): array return [ 'working_title' => $this->getRecord()->working_title, 'thumbnail_alt' => $this->getRecord()->thumbnail_alt, - 'body' => FormattedText::html($this->getRecord()->versions()->orderByDesc('number')->first()?->body), + 'body' => EmbeddedImages::forEditor($this->getRecord()->versions()->orderByDesc('number')->first()?->body), 'display_title' => $this->getRecord()->display_title, 'description' => FormattedText::html($this->getRecord()->description), 'usage_note' => $this->getRecord()->usage_note, diff --git a/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php b/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php index b41a36d..c733a5c 100644 --- a/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php +++ b/app/Filament/Resources/ContentElements/Pages/ViewContentElement.php @@ -791,6 +791,14 @@ protected function richFelder(): array return ['summary' => 'Kurzbeschreibung', 'descriptionText' => 'Ausführliche Beschreibung', 'bodyDraft' => 'Text der Fassung']; } + /** + * @return list + */ + protected function richBilder(): array + { + return ['bodyDraft']; + } + /** * @return list> */ diff --git a/app/Filament/Support/ChoosesMedia.php b/app/Filament/Support/ChoosesMedia.php index 47bd4d2..f3f5daf 100644 --- a/app/Filament/Support/ChoosesMedia.php +++ b/app/Filament/Support/ChoosesMedia.php @@ -106,13 +106,15 @@ public function pickerResult(): array return ['items' => [], 'more' => false]; } - if ($this->pickerPurpose === 'aufbau') { + if (in_array($this->pickerPurpose, ['aufbau', 'textbild'], true)) { + $image = $this->pickerPurpose === 'textbild'; + return $this->filterByMaterialart(app(EditorialCatalog::class)->browse( $this->pickerQuery, - $this->pickerKind, + $image ? 'bild' : $this->pickerKind, $this->pickerDimension, $this->pickerExceptId(), - false, + $image, ctype_digit($this->pickerSaeule) ? (int) $this->pickerSaeule : 0, )); } diff --git a/app/Filament/Support/ElementRevision.php b/app/Filament/Support/ElementRevision.php index fa3fcd1..2c255f7 100644 --- a/app/Filament/Support/ElementRevision.php +++ b/app/Filament/Support/ElementRevision.php @@ -6,6 +6,7 @@ use App\Domain\Catalog\ContentElementVersion; use App\Domain\Catalog\ContentService; use App\Domain\Catalog\DomainRuleException; +use App\Domain\Catalog\EmbeddedImages; use App\Domain\Catalog\FormattedText; use App\Filament\Resources\ContentElements\Pages\EditContentElement; use Filament\Forms\Components\Component; @@ -71,7 +72,7 @@ public static function fields(ContentElement $element): array $latest = $element->versions()->orderByDesc('number')->first(); return [ - RichField::make('body', 'Text', live: false)->default(FormattedText::html($latest?->body)), + RichField::make('body', 'Text', live: false)->default(EmbeddedImages::forEditor($latest?->body)), EditContentElement::uploadField(), Toggle::make('drop_file') ->label('Datei in der neuen Fassung nicht mehr verwenden') diff --git a/app/Filament/Support/ManagesEditorialSurface.php b/app/Filament/Support/ManagesEditorialSurface.php index 801b383..af94bdd 100644 --- a/app/Filament/Support/ManagesEditorialSurface.php +++ b/app/Filament/Support/ManagesEditorialSurface.php @@ -15,6 +15,7 @@ use App\Domain\Media\WebsiteRelease; use App\Filament\Resources\ContentElements\ContentElementResource; use App\Models\User; +use Filament\Forms\Components\RichEditor\EditorCommand; use Illuminate\Database\Eloquent\Model; use Livewire\Attributes\Url; @@ -66,6 +67,12 @@ trait ManagesEditorialSurface public bool $ausgabeOpen = false; + /** Der Editor, in den das gewählte Bild eingefügt wird (Eigenschaft der Seite), und seine Cursorstelle. */ + public string $textImageField = ''; + + /** @var array */ + public array $textImageSelection = []; + /** @var array{aktion: string, argument: int|string|null, titel: string, text: string, label: string, gefahr: bool}|null */ public ?array $bestaetigung = null; @@ -596,6 +603,57 @@ public function closePicker(): void } } + /** + * Öffnet den gemeinsamen Picker für ein Bild im Text. Der Editor ruft das mit seinem Namen und der Cursorstelle auf + * ({@see RichField}). Gewählt wird eine freigegebene Bildfassung des Medienbestands; eine Adresse speichert der Text nie. + * + * @param array $selection + */ + public function openTextImagePicker(string $field, array $selection = []): void + { + if (! method_exists($this, 'richKomponente') || $this->richKomponente($field) === null) { + return; + } + + $this->textImageField = $field; + $this->textImageSelection = $selection; + $this->resetPicker('textbild'); + $this->pickerKind = 'bild'; + } + + /** + * Fügt die gewählte Bildfassung an der Cursorstelle ein. Nur freigegebene Fassungen: Der Text verweist auf genau + * diese Fassung, und eine Dokumentfassung kann später nur freigegebene Bilder festschreiben. + */ + protected function insertTextImage(string $target): void + { + $component = method_exists($this, 'richKomponente') ? $this->richKomponente($this->textImageField) : null; + $version = preg_match('/^element:(\d+)$/', $target, $match) === 1 + ? ContentElementVersion::query()->with('element')->find($match[1]) + : null; + + if ($component === null || ! $version instanceof ContentElementVersion || $version->element === null || $version->element->output_class !== 'bild') { + $this->feedback('Dieses Bild lässt sich nicht einfügen.', true); + + return; + } + + if ($version->status !== ContentVersionStatus::Bereit) { + $this->feedback('„'.($version->element->display_title ?: $version->element->working_title).'“ ist noch nicht freigegeben. Gib das Bild im Medienbestand frei, dann lässt es sich einfügen.', true); + + return; + } + + $alt = trim((string) ($version->element->website_alt ?: $version->element->display_title ?: $version->element->working_title)); + $component->runCommands([ + EditorCommand::make('insertContent', arguments: [[ + 'type' => 'image', + 'attrs' => ['alt' => $alt, 'id' => (string) $version->id, 'src' => route('content.file', ['version' => $version->id], false)], + ]]), + ], editorSelection: $this->textImageSelection === [] ? null : $this->textImageSelection); + $this->feedback('„'.($version->element->display_title ?: $version->element->working_title).'“ ist im Text eingefügt. Gespeichert wird mit dem Text.'); + } + public function pickerAllowsMany(): bool { return $this->pickerPurpose === 'praesentation' && $this->roleAllowsMany($this->presentationRole); @@ -625,6 +683,14 @@ public function confirmPicker(): void return; } + if ($this->pickerPurpose === 'textbild') { + $target = $marked[0]; + $this->closePicker(); + $this->insertTextImage($target); + + return; + } + $this->guardEditorial(); if ($this->pickerPurpose === 'austausch' || ($this->pickerPurpose === 'praesentation' && $this->replacingKey !== null)) { @@ -684,7 +750,7 @@ public function assignFromPicker(string $target): void */ public function pickerKinds(): array { - if ($this->pickerPurpose === 'vorschaubild') { + if (in_array($this->pickerPurpose, ['vorschaubild', 'textbild'], true)) { return ['bild' => 'Bilder']; } @@ -709,6 +775,7 @@ public function pickerTitle(): string 'aufbau' => 'Bestandteil auswählen', 'austausch' => 'Medium austauschen', 'vorschaubild' => 'Vorschaubild aus dem Bestand', + 'textbild' => 'Bild in den Text einfügen', default => 'Medien auswählen', }; } @@ -725,6 +792,7 @@ public function pickerConfirmLabel(): string 'aufbau' => 'In den Aufbau übernehmen', 'austausch' => 'Austauschen', 'vorschaubild' => 'Als Vorschaubild übernehmen', + 'textbild' => 'Bild einfügen', default => $count === 1 ? '1 Medium übernehmen' : ($count === 0 ? 'Medien übernehmen' : $count.' Medien übernehmen'), }; } diff --git a/app/Filament/Support/ManagesRichFields.php b/app/Filament/Support/ManagesRichFields.php index 643d228..8403826 100644 --- a/app/Filament/Support/ManagesRichFields.php +++ b/app/Filament/Support/ManagesRichFields.php @@ -2,6 +2,7 @@ namespace App\Filament\Support; +use App\Domain\Catalog\EmbeddedImages; use App\Domain\Catalog\FormattedText; use Filament\Forms\Components\RichEditor; use Filament\Schemas\Components\Component; @@ -41,6 +42,16 @@ protected function richFelder(): array return []; } + /** + * Eigenschaften, deren Editor Bilder aus dem Medienbestand einfügen darf (Textinhalte, nicht Kurzangaben). + * + * @return list + */ + protected function richBilder(): array + { + return []; + } + /** @return list */ protected function richNamen(): array { @@ -51,7 +62,7 @@ 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())); + ->components(array_map(fn (string $name, string $label): RichEditor => RichField::make($name, $label, hideLabel: true, images: in_array($name, $this->richBilder(), true) && method_exists($this, 'openTextImagePicker')), $this->richNamen(), $this->richFelder())); } public function richKomponente(string $name): ?Component @@ -93,7 +104,7 @@ protected function richPush(string $name): void } $canonical = FormattedText::canonical((string) $this->{$name}); - $component->state($canonical === '' ? null : $canonical); + $component->state($canonical === '' ? null : FormattedText::forEditor($canonical, fn (int $id): string => EmbeddedImages::staffSource($id))); $this->richSeen[$name] = md5($canonical); } diff --git a/app/Filament/Support/MediumForm.php b/app/Filament/Support/MediumForm.php index e84a941..f25d001 100644 --- a/app/Filament/Support/MediumForm.php +++ b/app/Filament/Support/MediumForm.php @@ -7,6 +7,7 @@ use App\Domain\Catalog\ContentService; use App\Domain\Catalog\DomainRuleException; use App\Domain\Catalog\EditorialVocabulary; +use App\Domain\Catalog\EmbeddedImages; use App\Domain\Catalog\FormattedText; use App\Domain\Catalog\IdentityProfile; use App\Domain\Media\PresentationFile; @@ -221,7 +222,7 @@ public static function fill(ContentElement $element): array 'usage_note' => $element->usage_note, 'license_note' => $element->license_note, 'thumbnail_alt' => $element->thumbnail_alt, - 'body' => FormattedText::html($latest?->body), + 'body' => EmbeddedImages::forEditor($latest?->body), ]; } diff --git a/app/Filament/Support/RichField.php b/app/Filament/Support/RichField.php index 3cd8bb8..b3ee3a9 100644 --- a/app/Filament/Support/RichField.php +++ b/app/Filament/Support/RichField.php @@ -4,6 +4,9 @@ use App\Domain\Catalog\FormattedText; use Filament\Forms\Components\RichEditor; +use Filament\Forms\Components\RichEditor\RichEditorTool; +use Filament\Support\Icons\Heroicon; +use Illuminate\Support\Js; /** * Der eine Editor für formatierte Texte (ADR-50): immer dieselbe Symbolleiste, dasselbe Ergebnis (bereinigtes HTML). @@ -15,10 +18,27 @@ final class RichField * @param ?string $label Bezeichnung des Felds; sie ist auch der Name für Hilfstechnik * @param bool $live Arbeitsplätze gleichen beim Verlassen des Felds ab ({@see ManagesRichFields}); Dialoge nicht * @param bool $hideLabel Die Bezeichnung zeigt der Arbeitsplatz selbst + * @param bool $images Bilder aus dem Medienbestand einfügen; nur auf Seiten mit dem gemeinsamen Picker + * ({@see ManagesEditorialSurface::openTextImagePicker()}) */ - public static function make(string $name, ?string $label = null, bool $live = true, bool $hideLabel = false): RichEditor + public static function make(string $name, ?string $label = null, bool $live = true, bool $hideLabel = false, bool $images = false): RichEditor { - $field = RichEditor::make($name)->toolbarButtons(FormattedText::TOOLBAR); + $toolbar = FormattedText::TOOLBAR; + + if ($images) { + array_splice($toolbar, count($toolbar) - 1, 0, [['bild']]); + } + + $field = RichEditor::make($name)->toolbarButtons($toolbar); + + if ($images) { + $field->tools([ + RichEditorTool::make('bild') + ->label('Bild aus dem Medienbestand einfügen') + ->icon(Heroicon::Photo) + ->jsHandler('$wire.openTextImagePicker('.Js::from($name).', editorSelection)'), + ]); + } if ($live) { $field->live(onBlur: true); diff --git a/app/Http/Controllers/Member/ExerciseController.php b/app/Http/Controllers/Member/ExerciseController.php index 91b53b1..df18ef2 100644 --- a/app/Http/Controllers/Member/ExerciseController.php +++ b/app/Http/Controllers/Member/ExerciseController.php @@ -4,6 +4,7 @@ use App\Domain\Catalog\ArticleRelease; use App\Domain\Catalog\CompositionVersion; +use App\Domain\Catalog\EmbeddedImages; use App\Domain\Catalog\ExerciseGuide; use App\Domain\Catalog\ExercisePdf; use App\Domain\Catalog\LicenseArticle; @@ -76,6 +77,7 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r $copy = DeliveryLog::newCopyId(); $variant = collect($guide['variants'])->firstWhere('key', $guide['chosen']); + $images = app(EmbeddedImages::class)->forPdf($request->user(), $article, $release); $content = $pdf->render( $guide, $sections, @@ -83,6 +85,7 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r $copy, (string) ($variant['name'] ?? ''), route('member.exercise', ['article' => $article, 'release' => $release, 'path' => $path, 'variante' => $guide['chosen']]), + $images, ); $checksum = hash('sha256', $content); @@ -94,6 +97,11 @@ public function pdf(Request $request, LicenseArticle $article, ArticleRelease $r } } + // Bilder im Text sind eigene Fassungen: Auch sie stehen im Ausgabenachweis dieses PDF. + foreach ($images->used() as $image) { + app(DeliveryLog::class)->write($image['grant'], $article, $release, $image['version'], 'laden', 'pdf', $checksum, 'k2', $copy, $located['version']->id); + } + $name = str($guide['title'])->slug()->value() ?: 'uebung'; return response($content, 200, [ diff --git a/app/Http/Controllers/Member/LibraryController.php b/app/Http/Controllers/Member/LibraryController.php index 1de6b95..4452c27 100644 --- a/app/Http/Controllers/Member/LibraryController.php +++ b/app/Http/Controllers/Member/LibraryController.php @@ -8,6 +8,7 @@ use App\Domain\Catalog\ContentElementVersion; use App\Domain\Catalog\ContentVersionStatus; use App\Domain\Catalog\EditorialVocabulary; +use App\Domain\Catalog\EmbeddedImages; use App\Domain\Catalog\IdentityDimension; use App\Domain\Catalog\LicenseArticle; use App\Domain\Catalog\Pillar; @@ -278,6 +279,7 @@ public function show(Request $request, LicenseArticle $article): View 'entries' => $entries, 'title' => app(CourseOutline::class)->title($article), 'kind' => app(CourseOutline::class)->kindLabel($article), + 'images' => $release === null ? null : app(EmbeddedImages::class)->forView($request->user(), $article, $release), ]); } @@ -319,6 +321,7 @@ public function media( 'article' => $article, 'version' => $version, 'license' => $decision->grant->rights_snapshot['purpose'] ?? null, + 'images' => app(EmbeddedImages::class)->forView($request->user(), $article, $release), 'reader' => $request->user()->name, 'copy' => $delivery->copy_id, ]); diff --git a/resources/css/components/lf-member.css b/resources/css/components/lf-member.css index 6599221..b5884fc 100644 --- a/resources/css/components/lf-member.css +++ b/resources/css/components/lf-member.css @@ -1179,6 +1179,48 @@ .mb-prose blockquote > p { margin-bottom: var(--space-2); } +/* Tabellen und Bilder in formatierten Texten (ADR-51) */ +.mb-prose table { + display: block; + max-width: 100%; + margin: 0 0 var(--space-3); + overflow-x: auto; + border-collapse: collapse; + font-size: var(--text-small, 0.95rem); +} + +.mb-prose th, +.mb-prose td { + min-width: 6rem; + padding: var(--space-2) var(--space-3); + border: 1px solid var(--color-border-strong); + text-align: left; + vertical-align: top; +} + +.mb-prose th { + background: var(--color-surface-subtle); + font-weight: 700; +} + +.mb-prose td > p, +.mb-prose th > p { + margin: 0 0 var(--space-1); +} + +.mb-prose img { + display: block; + max-width: 100%; + height: auto; + margin: 0 0 var(--space-3); + border-radius: var(--radius-card); +} + +.mb-prose .mb-bildhinweis { + color: var(--color-text-muted, inherit); + font-style: italic; +} + .mb-reading { max-width: var(--measure); padding: var(--pad-card); diff --git a/resources/views/content/player.blade.php b/resources/views/content/player.blade.php index fbe7786..5697bff 100644 --- a/resources/views/content/player.blade.php +++ b/resources/views/content/player.blade.php @@ -27,6 +27,6 @@ @if (filled($version->body))
- {!! \App\Domain\Catalog\FormattedText::display($version->body) !!} + {!! \App\Domain\Catalog\FormattedText::display($version->body, \App\Domain\Catalog\EmbeddedImages::staff()) !!}
@endif diff --git a/resources/views/member/article.blade.php b/resources/views/member/article.blade.php index 94a8e45..c82dd87 100644 --- a/resources/views/member/article.blade.php +++ b/resources/views/member/article.blade.php @@ -60,7 +60,7 @@ @endif @if (filled($entry['version']->body))
- {!! \App\Domain\Catalog\FormattedText::display($entry['version']->body) !!} + {!! \App\Domain\Catalog\FormattedText::display($entry['version']->body, $images ?? null) !!}
@endif diff --git a/resources/views/member/read.blade.php b/resources/views/member/read.blade.php index c290f80..e3a2767 100644 --- a/resources/views/member/read.blade.php +++ b/resources/views/member/read.blade.php @@ -14,7 +14,7 @@

Lizenzkennzeichnung: {{ $license }}

@endif
- {!! \App\Domain\Catalog\FormattedText::display($version->body) !!} + {!! \App\Domain\Catalog\FormattedText::display($version->body, $images ?? null) !!}
@endsection diff --git a/tests/Feature/TextEditorWerkzeugeTest.php b/tests/Feature/TextEditorWerkzeugeTest.php new file mode 100644 index 0000000..b96930f --- /dev/null +++ b/tests/Feature/TextEditorWerkzeugeTest.php @@ -0,0 +1,147 @@ +create('Stopp sagen', CompositionKind::Exercise); + $cell = fn (string $type, string $text, array $attrs = []): array => ['type' => $type, 'attrs' => $attrs + ['colspan' => 1, 'rowspan' => 1, 'colwidth' => null], 'content' => [['type' => 'paragraph', 'content' => [['type' => 'text', 'text' => $text]]]]]; + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPractice::class, ['record' => $practice->getKey()]) + ->set('rich.partBody', ['type' => 'doc', 'content' => [ + ['type' => 'table', 'content' => [ + ['type' => 'tableRow', 'content' => [$cell('tableHeader', 'Zeit'), $cell('tableHeader', 'Inhalt')]], + ['type' => 'tableRow', 'content' => [$cell('tableCell', '10 Min.'), $cell('tableCell', 'Begrüßung')]], + ]], + ]]); + + $stored = '

Zeit

Inhalt

10 Min.

Begrüßung

'; + $this->assertSame($stored, $component->get('partBody')); + + // Zurück in den Editor und wieder heraus: kein Verlust, keine Scheinänderung. + $component->set('partBody', $stored)->assertOk(); + $this->assertSame('table', $component->get('rich.partBody.content.0.type')); + $this->assertSame('Begrüßung', $component->get('rich.partBody.content.0.content.1.content.1.content.0.content.0.text')); + $this->assertSame($stored, FormattedText::canonical($component->get('partBody'))); + } + + public function test_an_image_stays_a_reference_to_its_version_and_the_editor_gets_a_staff_address(): void + { + $image = $this->image('Stellung'); + $practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise); + $stored = '

Davor

Stellung

Danach

'; + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPractice::class, ['record' => $practice->getKey()]) + ->set('partBody', $stored) + ->assertOk(); + + $node = $component->get('rich.partBody.content.1'); + $this->assertSame('image', $node['type']); + $this->assertSame((string) $image->id, (string) $node['attrs']['id']); + $this->assertSame(route('content.file', ['version' => $image->id], false), $node['attrs']['src']); + + // Der Editor gibt die Adresse mit zurück; gespeichert wird sie nie. + $component->set('rich.partBody', ['type' => 'doc', 'content' => [$node]]); + $this->assertSame('Stellung', $component->get('partBody')); + } + + public function test_the_image_tool_exists_only_in_text_editors_with_the_picker(): void + { + $practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise); + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPractice::class, ['record' => $practice->getKey()]); + $page = $component->instance(); + + $this->assertContains('bild', collect($page->richKomponente('partBody')->getToolbarButtons())->flatten()->all()); + $this->assertContains('bild', collect($page->richKomponente('newTextBody')->getToolbarButtons())->flatten()->all()); + $this->assertNotContains('bild', collect($page->richKomponente('summary')->getToolbarButtons())->flatten()->all(), 'Kurzangaben nehmen keine Bilder auf.'); + + foreach (['partBody', 'summary', 'learningGoal'] as $field) { + $this->assertContains('table', collect($page->richKomponente($field)->getToolbarButtons())->flatten()->all(), $field.' hat dieselben Tabellenwerkzeuge.'); + } + } + + public function test_the_picker_offers_released_images_and_inserts_the_chosen_version_at_the_cursor(): void + { + $image = $this->image('Stellung'); + $draft = app(ContentService::class)->draftElementVersion(app(ContentService::class)->createElement('bild', 'bild', 'Entwurfsbild'), null, ['file' => 'inhalte/entwurf.jpg']); + $practice = app(EditorialCatalog::class)->create('Stopp sagen', CompositionKind::Exercise); + + $component = Livewire::actingAs($this->editor(), 'staff') + ->test(EditPractice::class, ['record' => $practice->getKey()]) + ->call('openTextImagePicker', 'partBody', ['type' => 'text', 'anchor' => 1, 'head' => 1]) + ->assertSet('pickerOpen', true) + ->assertSet('pickerPurpose', 'textbild'); + + $this->assertSame('Bild einfügen', $component->instance()->pickerConfirmLabel()); + $this->assertSame(['bild' => 'Bilder'], $component->instance()->pickerKinds()); + + $component->call('markPicker', 'element:'.$image->id, true)->call('confirmPicker'); + $component->assertSet('pickerOpen', false)->assertDispatched('run-rich-editor-commands'); + + // Eine noch nicht freigegebene Fassung lässt sich nicht in einen Text einfügen. + $component->call('openTextImagePicker', 'partBody', [])->call('markPicker', 'element:'.$draft->id, true)->call('confirmPicker'); + $this->assertStringContainsString('noch nicht freigegeben', (string) $component->get('deskFeedback')); + } + + public function test_a_text_with_an_unreleased_image_cannot_be_frozen(): void + { + $content = app(ContentService::class); + $draftImage = $content->draftElementVersion($content->createElement('bild', 'bild', 'Entwurfsbild'), null, ['file' => 'inhalte/entwurf.jpg']); + $text = $content->draftElementVersion($content->createElement('text', 'text', 'Kapitel'), '

Text

'); + + $this->assertStringContainsString('noch nicht freigegeben', (string) $content->elementReleaseProblem($text)); + + $released = $content->releaseElementVersion($draftImage); + $this->assertNull($content->elementReleaseProblem($text->refresh())); + $this->assertSame($released->id, $draftImage->id); + + $content->block($released, 'Rechte'); + $this->assertStringContainsString('deaktiviert', (string) $content->imageProblem($text->body)); + } + + private function image(string $title) + { + $content = app(ContentService::class); + + return $content->publishElementVersion($content->createElement('bild', 'bild', $title), null, ['file' => 'inhalte/'.str($title)->slug().'.jpg']); + } + + private function editor(): User + { + $editor = User::factory()->redakteur()->create(); + $editor->saveAppAuthenticationSecret('JBSWY3DPEHPK3PXP'); + + return $editor; + } +} diff --git a/tests/Unit/FormattedTextTest.php b/tests/Unit/FormattedTextTest.php index 5b24619..ebdd5a3 100644 --- a/tests/Unit/FormattedTextTest.php +++ b/tests/Unit/FormattedTextTest.php @@ -101,4 +101,57 @@ public function test_blocks_carry_the_emphasis_for_the_pdf(): void $this->assertSame('bullets', $blocks[2]['type']); $this->assertTrue($blocks[2]['items'][0][1]['bold']); } + + public function test_a_table_keeps_its_structure_and_loses_widths_and_styling(): void + { + $html = FormattedText::canonical('

Kopf

a

b x
  • eins
'); + + $this->assertSame('

Kopf

a

b x

  • eins

', $html); + $this->assertSame($html, FormattedText::canonical($html), 'Die kanonische Form ist stabil.'); + $this->assertTrue(FormattedText::isHtml($html), 'Ein Text, der mit einer Tabelle beginnt, bleibt HTML und wird nicht als Klartext maskiert.'); + } + + public function test_a_table_reaches_the_pdf_as_rows_and_plain_text_as_lines(): void + { + $html = '

Zeit

Inhalt

10 Min.

Begrüßung

'; + $blocks = FormattedText::blocks($html); + + $this->assertSame('table', $blocks[0]['type']); + $this->assertCount(2, $blocks[0]['rows']); + $this->assertTrue($blocks[0]['rows'][0][0]['header']); + $this->assertSame('Begrüßung', $blocks[0]['rows'][1][1]['blocks'][0]['runs'][0]['text']); + $this->assertSame("Zeit | Inhalt\n10 Min. | Begrüßung", FormattedText::plain($html)); + } + + public function test_an_image_is_a_reference_to_an_image_version_and_never_an_address(): void + { + $html = FormattedText::canonical('

Davor

Ein Bild

Danach

Eingebettet x im Absatz

'); + + $this->assertSame('

Davor

Ein Bild

Danach

Eingebettet im Absatz

', $html); + $this->assertSame([12], FormattedText::imageIds($html)); + $this->assertSame($html, FormattedText::canonical($html)); + $this->assertSame('', FormattedText::canonical(''), 'Ein Text nur aus einem Bild ist nicht leer.'); + } + + public function test_images_appear_only_where_the_reader_resolves_them(): void + { + $html = '

Davor

Ein BildAnderes

Danach

'; + + $this->assertSame('

Davor

Danach

', FormattedText::html($html), 'Ohne Auflösung zeigt die Ausgabe kein Bild.'); + $shown = FormattedText::html($html, fn (int $id): ?array => $id === 12 ? ['src' => '/b/12?sig=1'] : ['note' => 'Dieses Bild ist derzeit nicht verfügbar.']); + + $this->assertStringContainsString('Ein Bild', $shown); + $this->assertStringNotContainsString('data-id', $shown); + $this->assertStringContainsString('

Dieses Bild ist derzeit nicht verfügbar.

', $shown); + $this->assertSame('Davor'."\n\n".'Danach', FormattedText::plain($html), 'Im Klartext hat ein Bild keinen Platz.'); + } + + public function test_the_editor_gets_an_address_for_every_image_and_loses_it_again_on_the_way_back(): void + { + $stored = FormattedText::canonical('

Text

Ein Bild'); + $forEditor = FormattedText::forEditor($stored, fn (int $id): string => "/redaktion/inhalt/{$id}/datei"); + + $this->assertStringContainsString('src="/redaktion/inhalt/12/datei"', $forEditor); + $this->assertSame($stored, FormattedText::canonicalHtml($forEditor)); + } }