-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeBlockTitleRenderer.php
More file actions
58 lines (47 loc) · 1.64 KB
/
Copy pathCodeBlockTitleRenderer.php
File metadata and controls
58 lines (47 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
declare(strict_types=1);
/*
* This file is part of the ALTO Commonmark package.
*
* © 2025-Present Simon André
*
* For full copyright and license information, please see
* the LICENSE file distributed with this source code.
*/
namespace Alto\CommonMark\Extension\CodeBlockTitle;
use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode;
use League\CommonMark\Node\Node;
use League\CommonMark\Renderer\ChildNodeRendererInterface;
use League\CommonMark\Renderer\NodeRendererInterface;
use League\CommonMark\Util\HtmlElement;
use League\CommonMark\Util\Xml;
final readonly class CodeBlockTitleRenderer implements NodeRendererInterface
{
public function __construct(
private NodeRendererInterface $base,
) {
}
/**
* @return \Stringable|string|null
*/
public function render(Node $node, ChildNodeRendererInterface $childRenderer)
{
if (!$node instanceof FencedCode) {
return $this->base->render($node, $childRenderer);
}
$info = InfoStringParser::parse($node->getInfo() ?? '');
$title = $info['attrs']['title'] ?? $info['attrs']['filename'] ?? null;
// Let the default renderer build <pre><code ...>…</code></pre>
$inner = $this->base->render($node, $childRenderer);
if (null === $title) {
return $inner;
}
$escapedTitle = Xml::escape($title);
$caption = new HtmlElement('figcaption', ['class' => 'code-title'], $escapedTitle);
return new HtmlElement(
'figure',
['class' => 'code-block has-title', 'data-title' => $title],
$caption.$inner
);
}
}