-
Notifications
You must be signed in to change notification settings - Fork 561
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
627ca99
commit 69c1e23
Showing
3 changed files
with
61 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
<?php | ||
|
||
namespace App\Markdown; | ||
|
||
use League\CommonMark\Event\DocumentParsedEvent; | ||
use League\CommonMark\Extension\CommonMark\Node\Block\Heading; | ||
use League\CommonMark\Extension\CommonMark\Node\Inline\HtmlInline; | ||
use League\CommonMark\Node\Block\Paragraph; | ||
|
||
class ConfigureHeadingLinks | ||
{ | ||
public function __invoke(DocumentParsedEvent $event): void | ||
{ | ||
$walker = $event->getDocument()->walker(); | ||
|
||
while ($event = $walker->next()) { | ||
[$paragraph, $heading, $linkOpener, $linkCloser] = [ | ||
$event->getNode(), | ||
$event->getNode()->next(), | ||
$event->getNode()->firstChild(), | ||
$event->getNode()->lastChild(), | ||
]; | ||
|
||
if ( | ||
! $heading instanceof Heading || | ||
! $paragraph instanceof Paragraph || | ||
count($paragraph->children()) !== 2 || | ||
! $linkOpener instanceof HtmlInline || | ||
! $linkCloser instanceof HtmlInline || | ||
! str_starts_with($linkOpener->getLiteral(), '<a name="') || | ||
! str_ends_with($linkOpener->getLiteral(), '">') || | ||
substr_count($linkOpener->getLiteral(), '"') !== 2 || | ||
$paragraph->firstChild()->next() !== $paragraph->lastChild() || | ||
! str_starts_with($linkCloser->getLiteral(), '</a>') | ||
) { | ||
continue; | ||
} | ||
|
||
$link = str($linkOpener->getLiteral())->after('<a name="')->beforeLast('">')->toString(); | ||
|
||
$heading->data->set('attributes.id', $link); | ||
$heading->prependChild(new HtmlInline('<a href="#'.$link.'">')); | ||
$heading->appendChild(new HtmlInline('</a>')); | ||
|
||
$paragraph->detach(); | ||
|
||
$walker->resumeAt($heading->next()); | ||
} | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters