actuel-inactuel/site/plugins/toc/index.php
isUnknown 4e5440a7ae toc plugin : refactor and fix for grid/linear templates
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 19:12:14 +01:00

54 lines
1.4 KiB
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', [
'pageMethods' => [
'hasToc' => function(): bool {
return count($this->tocItems()) > 0;
},
'tocItems' => function(): array {
$content = getTocContent($this);
if (!$content) return [];
preg_match_all(H3_PATTERN, $content, $matches);
return array_map(fn($title) => [
'title' => $title,
'slug' => Str::slug($title)
], $matches[1]);
},
'bodyWithAnchors' => function(): string {
$content = getTocContent($this);
if (!$content) return '';
return preg_replace_callback(
H3_PATTERN,
fn($m) => '<h3 id="' . Str::slug($m[1]) . '">' . $m[1] . '</h3>',
$content
);
}
]
]);