From 4e5440a7aec3e01845f8ed0f764d7ee4b1bb1836 Mon Sep 17 00:00:00 2001 From: isUnknown Date: Fri, 27 Mar 2026 19:12:14 +0100 Subject: [PATCH] toc plugin : refactor and fix for grid/linear templates Co-Authored-By: Claude Opus 4.6 --- site/plugins/toc/index.php | 57 +++++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/site/plugins/toc/index.php b/site/plugins/toc/index.php index 5a6e97d..c3edad0 100644 --- a/site/plugins/toc/index.php +++ b/site/plugins/toc/index.php @@ -1,28 +1,38 @@ (.*?)<\/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', [ 'pageMethods' => [ - /** - * Vérifie si la page doit afficher une TOC - */ 'hasToc' => function(): bool { - if (!$this->parent()?->parent()?->is('textes')) { - return false; - } - if (!$this->bodyBlocks()?->isNotEmpty()) { - return false; - } - return (bool) preg_match('/

/', $this->bodyBlocks()->toBlocks()); + return count($this->tocItems()) > 0; }, - /** - * Retourne les items de la TOC - */ 'tocItems' => function(): array { - if (!$this->bodyBlocks()?->isNotEmpty()) { - return []; - } - preg_match_all('/

(.*?)<\/h3>/', $this->bodyBlocks()->toBlocks(), $matches); + $content = getTocContent($this); + + if (!$content) return []; + + preg_match_all(H3_PATTERN, $content, $matches); return array_map(fn($title) => [ 'title' => $title, @@ -30,17 +40,14 @@ Kirby::plugin('actuel-inactuel/toc', [ ], $matches[1]); }, - /** - * Retourne le contenu avec les ancres ajoutées aux h3 - */ 'bodyWithAnchors' => function(): string { - if (!$this->bodyBlocks()?->isNotEmpty()) { - return ''; - } + $content = getTocContent($this); + if (!$content) return ''; + return preg_replace_callback( - '/

(.*?)<\/h3>/', + H3_PATTERN, fn($m) => '

' . $m[1] . '

', - $this->bodyBlocks()->toBlocks() + $content ); } ]