toc plugin : refactor and fix for grid/linear templates

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
isUnknown 2026-03-27 19:12:14 +01:00
parent 25d63346c6
commit 4e5440a7ae

View file

@ -1,28 +1,38 @@
<?php <?php
const H3_PATTERN = '/<h3>(.*?)<\/h3>/';
function getContent($page) {
if ($page->intendedTemplate() == 'grid') return $page->body()->toBlocks();
if ($page->intendedTemplate() == 'linear') {
if ($page->isBlockMode()->isTrue()) return $page->bodyBlocks()->toBlocks();
if ($page->isBlockMode()->isFalse()) return $page->body();
}
return null;
}
function getTocContent($page) {
if (!$page->parent()?->parent()?->is('textes')) return null;
$content = (string) getContent($page);
return $content ?: null;
}
Kirby::plugin('actuel-inactuel/toc', [ Kirby::plugin('actuel-inactuel/toc', [
'pageMethods' => [ 'pageMethods' => [
/**
* Vérifie si la page doit afficher une TOC
*/
'hasToc' => function(): bool { 'hasToc' => function(): bool {
if (!$this->parent()?->parent()?->is('textes')) { return count($this->tocItems()) > 0;
return false;
}
if (!$this->bodyBlocks()?->isNotEmpty()) {
return false;
}
return (bool) preg_match('/<h3>/', $this->bodyBlocks()->toBlocks());
}, },
/**
* Retourne les items de la TOC
*/
'tocItems' => function(): array { 'tocItems' => function(): array {
if (!$this->bodyBlocks()?->isNotEmpty()) { $content = getTocContent($this);
return [];
} if (!$content) return [];
preg_match_all('/<h3>(.*?)<\/h3>/', $this->bodyBlocks()->toBlocks(), $matches);
preg_match_all(H3_PATTERN, $content, $matches);
return array_map(fn($title) => [ return array_map(fn($title) => [
'title' => $title, 'title' => $title,
@ -30,17 +40,14 @@ Kirby::plugin('actuel-inactuel/toc', [
], $matches[1]); ], $matches[1]);
}, },
/**
* Retourne le contenu avec les ancres ajoutées aux h3
*/
'bodyWithAnchors' => function(): string { 'bodyWithAnchors' => function(): string {
if (!$this->bodyBlocks()?->isNotEmpty()) { $content = getTocContent($this);
return ''; if (!$content) return '';
}
return preg_replace_callback( return preg_replace_callback(
'/<h3>(.*?)<\/h3>/', H3_PATTERN,
fn($m) => '<h3 id="' . Str::slug($m[1]) . '">' . $m[1] . '</h3>', fn($m) => '<h3 id="' . Str::slug($m[1]) . '">' . $m[1] . '</h3>',
$this->bodyBlocks()->toBlocks() $content
); );
} }
] ]