2026-02-17 18:10:04 +01:00
|
|
|
<?php
|
|
|
|
|
|
2026-03-27 19:12:14 +01:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-17 18:10:04 +01:00
|
|
|
Kirby::plugin('actuel-inactuel/toc', [
|
|
|
|
|
'pageMethods' => [
|
|
|
|
|
'hasToc' => function(): bool {
|
2026-03-27 19:12:14 +01:00
|
|
|
return count($this->tocItems()) > 0;
|
2026-02-17 18:10:04 +01:00
|
|
|
},
|
|
|
|
|
|
|
|
|
|
'tocItems' => function(): array {
|
2026-03-27 19:12:14 +01:00
|
|
|
$content = getTocContent($this);
|
|
|
|
|
|
|
|
|
|
if (!$content) return [];
|
|
|
|
|
|
|
|
|
|
preg_match_all(H3_PATTERN, $content, $matches);
|
2026-02-17 18:10:04 +01:00
|
|
|
|
|
|
|
|
return array_map(fn($title) => [
|
|
|
|
|
'title' => $title,
|
|
|
|
|
'slug' => Str::slug($title)
|
|
|
|
|
], $matches[1]);
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
'bodyWithAnchors' => function(): string {
|
2026-03-27 19:12:14 +01:00
|
|
|
$content = getTocContent($this);
|
|
|
|
|
if (!$content) return '';
|
|
|
|
|
|
2026-02-17 18:10:04 +01:00
|
|
|
return preg_replace_callback(
|
2026-03-27 19:12:14 +01:00
|
|
|
H3_PATTERN,
|
2026-02-17 18:10:04 +01:00
|
|
|
fn($m) => '<h3 id="' . Str::slug($m[1]) . '">' . $m[1] . '</h3>',
|
2026-03-27 19:12:14 +01:00
|
|
|
$content
|
2026-02-17 18:10:04 +01:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
]);
|