1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the league/commonmark package. |
7
|
|
|
* |
8
|
|
|
* (c) Colin O'Dell <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace League\CommonMark\Extension\HeadingPermalink; |
15
|
|
|
|
16
|
|
|
use League\CommonMark\Node\Node; |
17
|
|
|
use League\CommonMark\Renderer\ChildNodeRendererInterface; |
18
|
|
|
use League\CommonMark\Renderer\NodeRendererInterface; |
19
|
|
|
use League\CommonMark\Util\HtmlElement; |
20
|
|
|
use League\Config\ConfigurationAwareInterface; |
21
|
|
|
use League\Config\ConfigurationInterface; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Renders the HeadingPermalink elements |
25
|
|
|
*/ |
26
|
|
|
final class HeadingPermalinkRenderer implements NodeRendererInterface, ConfigurationAwareInterface |
27
|
|
|
{ |
28
|
|
|
public const DEFAULT_SYMBOL = '¶'; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var ConfigurationInterface |
32
|
|
|
* |
33
|
|
|
* @psalm-readonly-allow-private-mutation |
34
|
|
|
*/ |
35
|
|
|
private $config; |
36
|
|
|
|
37
|
75 |
|
public function setConfiguration(ConfigurationInterface $configuration): void |
38
|
|
|
{ |
39
|
75 |
|
$this->config = $configuration; |
40
|
75 |
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param HeadingPermalink $node |
44
|
|
|
* |
45
|
|
|
* {@inheritdoc} |
46
|
|
|
* |
47
|
|
|
* @psalm-suppress MoreSpecificImplementedParamType |
48
|
|
|
*/ |
49
|
72 |
|
public function render(Node $node, ChildNodeRendererInterface $childRenderer) |
50
|
|
|
{ |
51
|
72 |
|
if (! $node instanceof HeadingPermalink) { |
52
|
|
|
throw new \InvalidArgumentException('Incompatible node type: ' . \get_class($node)); |
53
|
|
|
} |
54
|
|
|
|
55
|
72 |
|
$slug = $node->getSlug(); |
56
|
|
|
|
57
|
72 |
|
$idPrefix = (string) $this->config->get('heading_permalink/id_prefix'); |
58
|
72 |
|
if ($idPrefix !== '') { |
59
|
69 |
|
$idPrefix .= '-'; |
60
|
|
|
} |
61
|
|
|
|
62
|
72 |
|
$attrs = $node->data->getData('attributes'); |
63
|
72 |
|
$attrs->set('id', $idPrefix . $slug); |
64
|
72 |
|
$attrs->set('href', '#' . $slug); |
65
|
72 |
|
$attrs->set('name', $slug); |
66
|
72 |
|
$attrs->append('class', $this->config->get('heading_permalink/html_class')); |
67
|
72 |
|
$attrs->set('aria-hidden', 'true'); |
68
|
72 |
|
$attrs->set('title', $this->config->get('heading_permalink/title')); |
69
|
|
|
|
70
|
72 |
|
$symbol = $this->config->get('heading_permalink/symbol'); |
71
|
|
|
\assert(\is_string($symbol)); |
72
|
|
|
|
73
|
72 |
|
return new HtmlElement('a', $attrs->export(), \htmlspecialchars($symbol), false); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|