Skip to content

Commit 3d44d5d

Browse files
authored
Merge pull request #73 from clue-labs/heading-anchors
Fix heading anchors after GitHub changed its markdown output
2 parents c248286 + 374030e commit 3d44d5d

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

‎src/berti.php‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,8 @@ function github_markdown_filter(
129129
$assetCollection
130130
);
131131

132+
$html = github_heading_rewriter($html);
133+
132134
$map = [];
133135

134136
foreach ($documentCollection as $doc) {
@@ -185,3 +187,21 @@ function ($component) {
185187

186188
return $html;
187189
}
190+
191+
/**
192+
* Moves GitHub's heading anchors back into the headings themselves.
193+
*
194+
* Since early 2024, GitHub renders headings like
195+
* `<div class="markdown-heading"><h2 class="heading-element">Title</h2>`
196+
* followed by `<a id="title" class="anchor" ...>...</a></div>`, while our
197+
* theme expects the previous format with the anchor as the first child of the
198+
* heading like `<h2><a id="title" class="anchor" ...>...</a>Title</h2>`.
199+
*/
200+
function github_heading_rewriter(string $html): string
201+
{
202+
return preg_replace(
203+
'/<div class="markdown-heading"[^>]*><(h[1-6])[^>]*>(.*?)<\/\1>(<a [^>]*class="anchor".*?<\/a>)<\/div>/',
204+
'<$1>$3$2</$1>',
205+
$html
206+
);
207+
}

0 commit comments

Comments
 (0)