Biete Überschriften h3 bis h6 an und nimm sie ins Inhaltsverzeichnis auf
Ein Dokument gliedert sich vor allem durch Kapitel der ersten Ebene und Überschriften im Text. Der Editor bietet h3 bis h6; h1 und h2 aus eingefügtem Text werden h3. Alle Überschriften des Kapiteltexts stehen automatisch im Inhaltsverzeichnis der Seite und des PDF (eingerückt, ohne Nummer), mit Sprungmarken, im PDF mit Seitenzahl, Verweis und verschachtelten Lesezeichen. Die PDF-Gliederung kennt jetzt bis zu sechs Ebenen und zählt alle Nachkommen. Unter einem Unterkapitel rücken die Überschriften eine Stufe tiefer (höchstens h6). Der bestehende Test erwartete h4 für eine Zwischenüberschrift im Kapitel; das gilt bewusst nicht mehr (h3 bleibt h3 und trägt eine Sprungmarke). Keine Migration, der Änderungsnachweis bleibt unverändert. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
58b68b768c
commit
b942b5331a
16 files changed
+421
-51
No files matched your search
@@ -34,7 +34,7 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
$view = ($this->access)($user, $article, $release, $version, 'ansehen');
|
||||
$download = ($this->access)($user, $article, $release, $version, 'laden');
|
||||
|
||||
$chapters[] = [
|
||||
$entry = [
|
||||
'number' => $chapter['number'],
|
||||
'level' => $chapter['level'],
|
||||
'anchor' => $chapter['anchor'],
|
||||
@@ -45,9 +45,11 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
'may_download' => $download->allowed,
|
||||
'download_grant' => $download->grant,
|
||||
'state' => $view->allowed ? 'ok' : ($version->status === ContentVersionStatus::Gesperrt ? 'gesperrt' : 'nicht_lizenziert'),
|
||||
'html' => $view->allowed ? $this->shiftHeadings(FormattedText::html($version->body, $embedded->forView($user, $article, $release, $version))) : null,
|
||||
'html' => null,
|
||||
'blocks' => $view->allowed ? FormattedText::blocks($version->body) : null,
|
||||
];
|
||||
$entry['html'] = $view->allowed ? self::anchoredHtml($entry, FormattedText::html($version->body, $embedded->forView($user, $article, $release, $version))) : null;
|
||||
$chapters[] = self::withHeadings($entry);
|
||||
}
|
||||
|
||||
$text = $library->text($document->composition);
|
||||
@@ -63,12 +65,54 @@ public function build(User $user, LicenseArticle $article, ArticleRelease $relea
|
||||
}
|
||||
|
||||
/**
|
||||
* Zwischenüberschriften im Kapiteltext stehen eine Ebene unter dem Kapiteltitel (h3 wird h4), damit die
|
||||
* Überschriftenfolge der Seite stimmt: Dokument h1, Kapitel h2, Unterkapitel h3, Zwischenüberschrift h4.
|
||||
* Um wie viele Stufen die Zwischenüberschriften eines Kapitels nach unten rücken: Im Kapitel (h2) bleiben h3 bis h6 wie
|
||||
* geschrieben, unter einem Unterkapitel (h3) rücken sie eine Stufe tiefer (höchstens h6). So steht nie eine Überschrift
|
||||
* des Texts auf der Stufe des Kapitels oder Unterkapitels, zu dem sie gehört.
|
||||
*/
|
||||
public static function shiftHeadings(string $html): string
|
||||
public static function headingShift(int $chapterLevel): int
|
||||
{
|
||||
return (string) preg_replace('/<(\/?)h3(?=[\s>])/i', '<$1h4', $html);
|
||||
return $chapterLevel >= 2 ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Das HTML eines Kapitels mit Sprungmarken an den Zwischenüberschriften und der Stufe, die zum Kapitel passt.
|
||||
*
|
||||
* @param array<string, mixed> $chapter
|
||||
*/
|
||||
public static function anchoredHtml(array $chapter, string $html): string
|
||||
{
|
||||
return FormattedText::anchorHeadings($html, (string) $chapter['anchor'], self::headingShift((int) $chapter['level']))['html'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ergänzt ein Kapitel um seine Zwischenüberschriften (`headings`: Stufe, Text, Sprungmarke) für das Inhaltsverzeichnis und
|
||||
* legt Stufe und Sprungmarke in die Überschriftenblöcke des PDF. Ansicht und PDF zählen gleich; sie lesen beide diese Liste.
|
||||
*
|
||||
* @param array<string, mixed> $chapter
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function withHeadings(array $chapter): array
|
||||
{
|
||||
$shift = self::headingShift((int) $chapter['level']);
|
||||
$headings = [];
|
||||
$blocks = $chapter['blocks'] ?? null;
|
||||
|
||||
foreach (is_array($blocks) ? $blocks : [] as $index => $block) {
|
||||
if ($block['type'] !== 'heading' || trim((string) ($block['text'] ?? '')) === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$level = min(6, (int) $block['level'] + $shift);
|
||||
$anchor = $chapter['anchor'].'-u'.(count($headings) + 1);
|
||||
$blocks[$index]['level'] = $level;
|
||||
$blocks[$index]['anchor'] = $anchor;
|
||||
$headings[] = ['level' => $level, 'text' => (string) $block['text'], 'anchor' => $anchor];
|
||||
}
|
||||
|
||||
$chapter['blocks'] = is_array($blocks) ? $blocks : null;
|
||||
$chapter['headings'] = $headings;
|
||||
|
||||
return $chapter;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -138,6 +138,10 @@ private function pass(array $guide, ?PdfTemplate $template, string $licensee, st
|
||||
$this->closePage();
|
||||
$this->newPage();
|
||||
}, $images === null ? null : Closure::fromCallable($images));
|
||||
$this->flow->onHeading = function (array $block, float $top): void {
|
||||
$this->starts[$block['anchor']] = ['page' => $this->page, 'top' => $top];
|
||||
$this->pdf->bookmark((string) $block['text'], $this->page - 1, $top, (int) $block['level'] - 1);
|
||||
};
|
||||
$this->total = $total;
|
||||
$withCover = $template !== null && $template->show_cover;
|
||||
|
||||
@@ -155,8 +159,8 @@ private function pass(array $guide, ?PdfTemplate $template, string $licensee, st
|
||||
|
||||
$this->flow->write('Inhaltsverzeichnis', 14, true, 8, keep: 40);
|
||||
|
||||
foreach ($guide['chapters'] as $chapter) {
|
||||
$this->contentsLine($chapter, $known[$chapter['anchor']] ?? ['page' => 1, 'top' => $this->top]);
|
||||
foreach ($this->contents($guide) as $entry) {
|
||||
$this->contentsLine($entry, $known[$entry['anchor']] ?? ['page' => 1, 'top' => $this->top]);
|
||||
}
|
||||
|
||||
foreach ($guide['chapters'] as $chapter) {
|
||||
@@ -231,29 +235,57 @@ private function coverText(string $text, float $size, bool $bold, float &$y, flo
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Zeile des Inhaltsverzeichnisses: Nummer und Titel, Punktlinie, Seitenzahl; die ganze Zeile springt zum Kapitel.
|
||||
* Die Einträge des Inhaltsverzeichnisses in der Reihenfolge des Dokuments: Kapitel und Unterkapitel mit Nummer, darunter
|
||||
* ihre Zwischenüberschriften (h3 bis h6), eingerückt nach Stufe.
|
||||
*
|
||||
* @param array<string, mixed> $chapter
|
||||
* @param array<string, mixed> $guide
|
||||
* @return list<array{anchor: string, label: string, size: float, indent: float, bold: bool}>
|
||||
*/
|
||||
private function contents(array $guide): array
|
||||
{
|
||||
$entries = [];
|
||||
|
||||
foreach ($guide['chapters'] as $chapter) {
|
||||
$entries[] = [
|
||||
'anchor' => $chapter['anchor'],
|
||||
'label' => $chapter['number'].' '.$chapter['title'],
|
||||
'size' => $chapter['level'] === 1 ? 11.0 : 10.0,
|
||||
'indent' => $chapter['level'] === 1 ? 0.0 : 18.0,
|
||||
'bold' => $chapter['level'] === 1,
|
||||
];
|
||||
|
||||
foreach ($chapter['headings'] ?? [] as $heading) {
|
||||
$entries[] = ['anchor' => $heading['anchor'], 'label' => $heading['text'], 'size' => 9.5, 'indent' => 18.0 + ($heading['level'] - 3) * 12.0, 'bold' => false];
|
||||
}
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Eine Zeile des Inhaltsverzeichnisses: Titel, Punktlinie, Seitenzahl; die ganze Zeile springt zum Eintrag.
|
||||
*
|
||||
* @param array{anchor: string, label: string, size: float, indent: float, bold: bool} $entry
|
||||
* @param array{page: int, top: float} $target
|
||||
*/
|
||||
private function contentsLine(array $chapter, array $target): void
|
||||
private function contentsLine(array $entry, array $target): void
|
||||
{
|
||||
$level = $chapter['level'];
|
||||
$size = $level === 1 ? 11.0 : 10.0;
|
||||
$indent = $level === 1 ? 0.0 : 18.0;
|
||||
$label = PdfFlow::printable($chapter['number'].' '.$chapter['title']);
|
||||
$size = $entry['size'];
|
||||
$indent = $entry['indent'];
|
||||
$bold = $entry['bold'];
|
||||
$label = PdfFlow::printable($entry['label']);
|
||||
$pageText = (string) $target['page'];
|
||||
$numberWidth = PdfDocument::exactWidth($pageText, $size, false);
|
||||
$lines = PdfDocument::wrap($label, self::RIGHT - self::LEFT - $indent - $numberWidth - 14, $size, $level === 1);
|
||||
$lines = PdfDocument::wrap($label, self::RIGHT - self::LEFT - $indent - $numberWidth - 14, $size, $bold);
|
||||
$x = self::LEFT + $indent;
|
||||
$this->flow->room(count($lines) * ($size + 4) + 2);
|
||||
$top = $this->flow->y;
|
||||
|
||||
foreach ($lines as $index => $line) {
|
||||
$this->pdf->text($x, $this->flow->y, $line, $size, $level === 1);
|
||||
$this->pdf->text($x, $this->flow->y, $line, $size, $bold);
|
||||
|
||||
if ($index === count($lines) - 1) {
|
||||
$used = PdfDocument::exactWidth($line, $size, $level === 1) + 4;
|
||||
$used = PdfDocument::exactWidth($line, $size, $bold) + 4;
|
||||
$room = self::RIGHT - $numberWidth - 4 - ($x + $used);
|
||||
$dots = (int) floor($room / PdfDocument::exactWidth('.', 8, false));
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
/**
|
||||
* 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,
|
||||
* Gespeichert wird bereinigtes HTML aus einer festen Auswahl: Absatz, Zwischenüberschriften (h3 bis h6), fett, kursiv, Aufzählung,
|
||||
* nummerierte Liste, Zitat, Link, Zeilenumbruch, Tabelle und Bild. Alles andere fällt beim Speichern weg, auch Skripte,
|
||||
* Ereignisattribute und Links auf andere Schemata als http, https und mailto.
|
||||
*
|
||||
@@ -29,7 +29,7 @@
|
||||
final class FormattedText
|
||||
{
|
||||
/** Blockelemente, mit denen gespeichertes HTML beginnt. */
|
||||
private const BLOCKS = ['p', 'h3', 'ul', 'ol', 'blockquote', 'table', 'img'];
|
||||
private const BLOCKS = ['p', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'blockquote', 'table', 'img'];
|
||||
|
||||
/** Angaben der Redaktion, die formatiert gespeichert werden. Suchbegriffe, Titel und Teaser bleiben Klartext. */
|
||||
public const FIELDS = ['summary', 'description'];
|
||||
@@ -39,7 +39,7 @@ final class FormattedText
|
||||
/** Symbolleiste der Editoren; muss zur Auswahl oben passen. */
|
||||
public const TOOLBAR = [
|
||||
['bold', 'italic', 'link'],
|
||||
['h3'],
|
||||
['h3', 'h4', 'h5', 'h6'],
|
||||
['bulletList', 'orderedList', 'blockquote'],
|
||||
['table', 'tableAddRowAfter', 'tableAddColumnAfter', 'tableDeleteRow', 'tableDeleteColumn', 'tableToggleHeaderRow', 'tableDelete'],
|
||||
['undo', 'redo'],
|
||||
@@ -130,6 +130,49 @@ public static function imageIds(?string $value): array
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Versieht die Zwischenüberschriften (h3 bis h6, auf oberster Ebene des Texts) mit Sprungmarken `<Präfix>-u<n>` und
|
||||
* verschiebt ihre Stufe um `$shift` (höchstens h6). Die Marken zählen die nicht leeren Überschriften in ihrer Reihenfolge;
|
||||
* {@see self::blocks()} zählt dieselben.
|
||||
*
|
||||
* @return array{html: string, headings: list<array{level: int, text: string, anchor: string}>}
|
||||
*/
|
||||
public static function anchorHeadings(string $html, string $prefix, int $shift = 0): array
|
||||
{
|
||||
if (preg_match('/<h[3-6][\s>]/i', $html) !== 1) {
|
||||
return ['html' => $html, 'headings' => []];
|
||||
}
|
||||
|
||||
$document = HTMLDocument::createFromString('<body>'.$html.'</body>', LIBXML_NOERROR);
|
||||
$headings = [];
|
||||
|
||||
foreach (iterator_to_array($document->body->childNodes) as $node) {
|
||||
if ($node->nodeType !== XML_ELEMENT_NODE || preg_match('/^h([3-6])$/', strtolower($node->nodeName), $match) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$text = trim((string) preg_replace('/\s+/u', ' ', (string) $node->textContent));
|
||||
|
||||
if ($text === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$level = min(6, (int) $match[1] + $shift);
|
||||
$anchor = $prefix.'-u'.(count($headings) + 1);
|
||||
$replacement = $document->createElement('h'.$level);
|
||||
$replacement->setAttribute('id', $anchor);
|
||||
|
||||
while ($node->firstChild !== null) {
|
||||
$replacement->appendChild($node->firstChild);
|
||||
}
|
||||
|
||||
$node->replaceWith($replacement);
|
||||
$headings[] = ['level' => $level, 'text' => $text, 'anchor' => $anchor];
|
||||
}
|
||||
|
||||
return ['html' => trim($document->body->innerHTML), 'headings' => $headings];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -335,9 +378,10 @@ private static function extractBlocks(Node $parent): array
|
||||
continue;
|
||||
}
|
||||
|
||||
$type = match ($name) {
|
||||
'h3' => 'heading',
|
||||
'blockquote' => 'quote',
|
||||
$level = preg_match('/^h([3-6])$/', $name, $heading) === 1 ? (int) $heading[1] : 0;
|
||||
$type = match (true) {
|
||||
$level > 0 => 'heading',
|
||||
$name === 'blockquote' => 'quote',
|
||||
default => 'paragraph',
|
||||
};
|
||||
|
||||
@@ -345,7 +389,7 @@ private static function extractBlocks(Node $parent): array
|
||||
$images = $node->querySelectorAll('img');
|
||||
|
||||
if (count($images) === 0) {
|
||||
$blocks[] = ['type' => $type, 'runs' => self::runs($node)];
|
||||
$blocks[] = self::textBlock($type, $level, self::runs($node));
|
||||
|
||||
continue;
|
||||
}
|
||||
@@ -355,7 +399,7 @@ private static function extractBlocks(Node $parent): array
|
||||
foreach ($node->childNodes as $child) {
|
||||
if ($child->nodeType === XML_ELEMENT_NODE && strtolower($child->nodeName) === 'img') {
|
||||
if (trim(self::runsText($pending)) !== '') {
|
||||
$blocks[] = ['type' => $type, 'runs' => $pending];
|
||||
$blocks[] = self::textBlock($type, $level, $pending);
|
||||
}
|
||||
|
||||
$pending = [];
|
||||
@@ -370,13 +414,26 @@ private static function extractBlocks(Node $parent): array
|
||||
}
|
||||
|
||||
if (trim(self::runsText($pending)) !== '') {
|
||||
$blocks[] = ['type' => $type, 'runs' => $pending];
|
||||
$blocks[] = self::textBlock($type, $level, $pending);
|
||||
}
|
||||
}
|
||||
|
||||
return $blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ein Textblock; eine Überschrift trägt zusätzlich ihre Stufe (3 bis 6) und ihren Text ohne Auszeichnung.
|
||||
*
|
||||
* @param list<array{text: string, bold: bool, italic: bool, href: ?string}> $runs
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function textBlock(string $type, int $level, array $runs): array
|
||||
{
|
||||
return $type === 'heading'
|
||||
? ['type' => $type, 'level' => $level, 'text' => self::runsText($runs), 'runs' => $runs]
|
||||
: ['type' => $type, 'runs' => $runs];
|
||||
}
|
||||
|
||||
/**
|
||||
* Klartext des Altbestands als HTML: Absätze an Leerzeilen, Listen mit „- “, „• “ oder „1. “, Zwischenüberschriften
|
||||
* mit „## “. Dieselben Konventionen wie {@see GuideText}.
|
||||
@@ -520,7 +577,7 @@ private static function table(Node $table): string
|
||||
}
|
||||
|
||||
$inner = self::inner($cell);
|
||||
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h3|img)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
|
||||
$cells .= '<'.$name.$attributes.'>'.($inner === '' ? '<p></p>' : (preg_match('/^<(?:p|ul|ol|blockquote|h[3-6]|img)[\s>]/', $inner) === 1 ? $inner : '<p>'.$inner.'</p>')).'</'.$name.'>';
|
||||
}
|
||||
|
||||
if ($cells !== '') {
|
||||
@@ -575,12 +632,12 @@ 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. */
|
||||
/** b, i und die Überschriftsstufen 1 und 2 der Quelle werden auf die feste Auswahl abgebildet (h1 und h2 gehören dem Dokument und dem Kapitel); 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);
|
||||
$html = (string) preg_replace('/<(\/?)h[12](?=[\s>\/])/i', '<$1h3', $html);
|
||||
|
||||
return (string) preg_replace('/<(\/?)div(?=[\s>\/])/i', '<$1p', $html);
|
||||
}
|
||||
@@ -644,6 +701,9 @@ private static function sanitizer(): HtmlSanitizer
|
||||
->allowElement('p')
|
||||
->allowElement('br')
|
||||
->allowElement('h3')
|
||||
->allowElement('h4')
|
||||
->allowElement('h5')
|
||||
->allowElement('h6')
|
||||
->allowElement('strong')
|
||||
->allowElement('em')
|
||||
->allowElement('ul')
|
||||
|
||||
@@ -18,6 +18,13 @@ final class PdfFlow
|
||||
{
|
||||
public float $y;
|
||||
|
||||
/**
|
||||
* Wird für jede Zwischenüberschrift mit Sprungmarke aufgerufen, bevor sie gesetzt wird: Block und obere Kante.
|
||||
*
|
||||
* @var (Closure(array<string, mixed>, float): void)|null
|
||||
*/
|
||||
public ?Closure $onHeading = null;
|
||||
|
||||
/** Schachtelungstiefe beim Setzen einer Tabelle (Zelleninhalt setzt nie wieder eine Tabelle). */
|
||||
private int $depth = 0;
|
||||
|
||||
@@ -116,9 +123,20 @@ public function formatted(array $blocks, ?float $x = null, float $size = 10.5):
|
||||
*/
|
||||
private function headingBlock(array $block, float $x, float $size): void
|
||||
{
|
||||
// Stufe 3 ist die größte Zwischenüberschrift, Stufe 6 hat Textgröße (und steht kursiv).
|
||||
$level = max(3, min(6, (int) ($block['level'] ?? 3)));
|
||||
$heading = $size + [3 => 2.0, 4 => 1.0, 5 => 0.5, 6 => 0.0][$level];
|
||||
$gap = [3 => 6.0, 4 => 4.0, 5 => 3.0, 6 => 2.0][$level];
|
||||
|
||||
// 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);
|
||||
$this->room($gap + $heading + 4 + 2 * ($size + 4));
|
||||
$this->y -= $gap;
|
||||
|
||||
if ($this->onHeading !== null && isset($block['anchor'])) {
|
||||
($this->onHeading)($block, $this->y + $heading);
|
||||
}
|
||||
|
||||
$this->runs($block['runs'], $x, $heading, bold: true, italic: $level === 6, after: 4);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user