47 lines
1.4 KiB
PHP
47 lines
1.4 KiB
PHP
<?php
|
|
|
|
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('/<h3>/', $this->bodyBlocks()->toBlocks());
|
|
},
|
|
|
|
/**
|
|
* Retourne les items de la TOC
|
|
*/
|
|
'tocItems' => function(): array {
|
|
if (!$this->bodyBlocks()?->isNotEmpty()) {
|
|
return [];
|
|
}
|
|
preg_match_all('/<h3>(.*?)<\/h3>/', $this->bodyBlocks()->toBlocks(), $matches);
|
|
|
|
return array_map(fn($title) => [
|
|
'title' => $title,
|
|
'slug' => Str::slug($title)
|
|
], $matches[1]);
|
|
},
|
|
|
|
/**
|
|
* Retourne le contenu avec les ancres ajoutées aux h3
|
|
*/
|
|
'bodyWithAnchors' => function(): string {
|
|
if (!$this->bodyBlocks()?->isNotEmpty()) {
|
|
return '';
|
|
}
|
|
return preg_replace_callback(
|
|
'/<h3>(.*?)<\/h3>/',
|
|
fn($m) => '<h3 id="' . Str::slug($m[1]) . '">' . $m[1] . '</h3>',
|
|
$this->bodyBlocks()->toBlocks()
|
|
);
|
|
}
|
|
]
|
|
]);
|