|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Hyde\Framework\Actions; |
|
6
|
|
|
|
|
7
|
|
|
use Hyde\Facades\Config; |
|
8
|
|
|
use Hyde\Markdown\Models\Markdown; |
|
9
|
|
|
use League\CommonMark\Environment\Environment; |
|
10
|
|
|
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; |
|
11
|
|
|
use League\CommonMark\Extension\HeadingPermalink\HeadingPermalinkExtension; |
|
12
|
|
|
use League\CommonMark\Extension\TableOfContents\TableOfContentsExtension; |
|
13
|
|
|
use League\CommonMark\MarkdownConverter; |
|
14
|
|
|
use function strpos; |
|
15
|
|
|
use function substr; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Generates a table of contents for the Markdown document, most commonly used for the sidebar. |
|
19
|
|
|
* |
|
20
|
|
|
* @see \Hyde\Framework\Testing\Feature\Actions\GeneratesSidebarTableOfContentsTest |
|
21
|
|
|
*/ |
|
22
|
|
|
class GeneratesTableOfContents |
|
23
|
|
|
{ |
|
24
|
|
|
protected string $markdown; |
|
25
|
|
|
|
|
26
|
|
|
public function __construct(Markdown|string $markdown) |
|
27
|
|
|
{ |
|
28
|
|
|
$this->markdown = (string) $markdown; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function execute(): string |
|
32
|
|
|
{ |
|
33
|
|
|
$config = [ |
|
34
|
|
|
'table_of_contents' => [ |
|
35
|
|
|
'html_class' => 'table-of-contents', |
|
36
|
|
|
'position' => 'top', |
|
37
|
|
|
'style' => 'bullet', |
|
38
|
|
|
'min_heading_level' => Config::getInt('docs.table_of_contents.min_heading_level', 2), |
|
39
|
|
|
'max_heading_level' => Config::getInt('docs.table_of_contents.max_heading_level', 4), |
|
40
|
|
|
'normalize' => 'relative', |
|
41
|
|
|
], |
|
42
|
|
|
'heading_permalink' => [ |
|
43
|
|
|
'fragment_prefix' => '', |
|
44
|
|
|
], |
|
45
|
|
|
]; |
|
46
|
|
|
|
|
47
|
|
|
$environment = new Environment($config); |
|
48
|
|
|
$environment->addExtension(new CommonMarkCoreExtension()); |
|
49
|
|
|
$environment->addExtension(new HeadingPermalinkExtension()); |
|
50
|
|
|
$environment->addExtension(new TableOfContentsExtension()); |
|
51
|
|
|
|
|
52
|
|
|
$converter = new MarkdownConverter($environment); |
|
53
|
|
|
$html = $converter->convert("[[END_TOC]]\n".$this->markdown)->getContent(); |
|
54
|
|
|
|
|
55
|
|
|
// Return everything before the [[END_TOC]] marker. |
|
56
|
|
|
return substr($html, 0, strpos($html, '<p>[[END_TOC]]')); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|