|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Laravelsu\Highlight\CommonMark; |
| 4 | + |
| 5 | +use InvalidArgumentException; |
| 6 | +use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; |
| 7 | +use League\CommonMark\Node\Node; |
| 8 | +use League\CommonMark\Renderer\ChildNodeRendererInterface; |
| 9 | +use League\CommonMark\Renderer\NodeRendererInterface; |
| 10 | +use Tempest\Highlight\Highlighter; |
| 11 | +use Tempest\Highlight\WebTheme; |
| 12 | + |
| 13 | +final class CodeBlockRenderer implements NodeRendererInterface |
| 14 | +{ |
| 15 | + public function __construct( |
| 16 | + private Highlighter $highlighter, |
| 17 | + private string $defaultLanguage = 'php' |
| 18 | + ) {} |
| 19 | + |
| 20 | + public function render(Node $node, ChildNodeRendererInterface $childRenderer) |
| 21 | + { |
| 22 | + if (! $node instanceof FencedCode) { |
| 23 | + throw new InvalidArgumentException('Block must be instance of '.FencedCode::class); |
| 24 | + } |
| 25 | + |
| 26 | + preg_match('/^(?<language>[\w]+)(\{(?<startAt>[\d]+)\})?/', $node->getInfoWords()[0] ?? 'txt', $matches); |
| 27 | + |
| 28 | + $highlighter = $this->highlighter; |
| 29 | + |
| 30 | + if ($startAt = ($matches['startAt']) ?? null) { |
| 31 | + $highlighter = $highlighter->withGutter((int) $startAt); |
| 32 | + } |
| 33 | + |
| 34 | + $language = $matches['language'] ?? $this->defaultLanguage; |
| 35 | + |
| 36 | + $parsed = $highlighter->parse($node->getLiteral(), $language); |
| 37 | + |
| 38 | + $theme = $highlighter->getTheme(); |
| 39 | + |
| 40 | + if ($theme instanceof WebTheme) { |
| 41 | + return $theme->preBefore($highlighter).$parsed.$theme->preAfter($highlighter); |
| 42 | + } |
| 43 | + |
| 44 | + return sprintf( |
| 45 | + '<pre><code data-lang="%s" class="notranslate">%s</code></pre>', |
| 46 | + $language, |
| 47 | + $parsed |
| 48 | + ); |
| 49 | + } |
| 50 | +} |
0 commit comments