From 2c4c1b9a7a45d527a876474af4c692bdeec1b502 Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Tue, 19 Apr 2022 21:50:40 +0200 Subject: [PATCH] Add the table of contents generation --- src/Actions/GeneratesTableOfContents.php | 53 ++++++++++++++++++++++++ src/Models/DocumentationPage.php | 9 ++++ src/Models/HasTableOfContents.php | 20 +++++++++ 3 files changed, 82 insertions(+) create mode 100644 src/Actions/GeneratesTableOfContents.php create mode 100644 src/Models/HasTableOfContents.php diff --git a/src/Actions/GeneratesTableOfContents.php b/src/Actions/GeneratesTableOfContents.php new file mode 100644 index 00000000..98ea5235 --- /dev/null +++ b/src/Actions/GeneratesTableOfContents.php @@ -0,0 +1,53 @@ +markdown = $markdown; + } + + public static int $minHeadingLevel = 2; + public static int $maxHeadingLevel = 4; + + public function execute(): string + { + $config = [ + 'table_of_contents' => [ + 'html_class' => 'table-of-contents', + 'position' => 'top', + 'style' => 'bullet', + 'min_heading_level' => static::$minHeadingLevel, + 'max_heading_level' => static::$maxHeadingLevel, + 'normalize' => 'relative', + ], + 'heading_permalink' => [ + 'fragment_prefix' => '', + ], + ]; + + $environment = new Environment($config); + $environment->addExtension(new CommonMarkCoreExtension()); + $environment->addExtension(new HeadingPermalinkExtension()); + $environment->addExtension(new TableOfContentsExtension()); + + $converter = new MarkdownConverter($environment); + $html = $converter->convert("[[END_TOC]]\n" . $this->markdown)->getContent(); + + return substr($html, 0, strpos($html, '[[END_TOC]]') - 9); + } +} diff --git a/src/Models/DocumentationPage.php b/src/Models/DocumentationPage.php index 76c20a6b..61905b45 100644 --- a/src/Models/DocumentationPage.php +++ b/src/Models/DocumentationPage.php @@ -6,6 +6,15 @@ class DocumentationPage extends MarkdownDocument { + use HasTableOfContents; + public static string $sourceDirectory = '_docs'; public static string $parserClass = DocumentationPageParser::class; + + public function __construct(array $matter, string $body, string $title = '', string $slug = '') + { + parent::__construct($matter, $body, $title, $slug); + + $this->constructTableOfContents(); + } } diff --git a/src/Models/HasTableOfContents.php b/src/Models/HasTableOfContents.php new file mode 100644 index 00000000..7c2bc3da --- /dev/null +++ b/src/Models/HasTableOfContents.php @@ -0,0 +1,20 @@ +tableOfContents = (new GeneratesTableOfContents($this->body))->execute(); + } +} \ No newline at end of file