Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/Rules/HeadingRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ final class HeadingRule implements Rule, ProvidesFirstChar
{
public string $firstChar = '#';

public function __construct(
/**
* Whether a heading without an explicit id gets one slugged from its
* content. An id written as `## Title ## id` is kept either way.
*/
public bool $generateIds = true,
) {}

public function shouldParse(Parser $parser): bool
{
return $parser->comesNext('#', 1);
Expand All @@ -37,14 +45,16 @@ public function parse(Parser $parser): Token
|> trim(...);
$buffer = substr(string: $buffer, offset: 0, length: $idSeparator)
|> trim(...);
} else {
} elseif ($this->generateIds) {
// No id is specified, we'll slug the heading
$id = $buffer
|> mb_strtolower(...)
|> (fn (string $x) => trim(
preg_replace('/[^\p{L}\p{N}]+/u', '-', $x) ?? '',
'-',
));
} else {
$id = null;
}

return new HeadingToken(
Expand Down
31 changes: 31 additions & 0 deletions tests/Rules/HeadingRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,35 @@ public function test_slug_cannot_break_out_of_the_id_attribute(): void
$html,
);
}

#[Test]
public function lex_generates_an_id_by_default(): void
{
$html =
(string) new Parser(highlighter: null, rules: [new HeadingRule()])->parse(
'## A heading',
);

$this->assertSame('<h2 id="a-heading">A heading</h2>', $html);
}

#[Test]
public function lex_without_generated_ids(): void
{
$html = (string) new Parser(highlighter: null, rules: [
new HeadingRule(generateIds: false),
])->parse('## A heading');

$this->assertSame('<h2>A heading</h2>', $html);
}

#[Test]
public function lex_keeps_an_explicit_id_without_generated_ids(): void
{
$html = (string) new Parser(highlighter: null, rules: [
new HeadingRule(generateIds: false),
])->parse('## A heading ## custom-id');

$this->assertSame('<h2 id="custom-id">A heading</h2>', $html);
}
}
Loading