Skip to content

Commit d8f7780

Browse files
committed
Add custom renderer option
1 parent 69007a1 commit d8f7780

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Changelog
22

3+
## 0.3.2 - 2021-07-31
4+
5+
### Added
6+
- Ability to register a custom block renderer. Needed for Ibis client.
7+
8+
39
## 0.3.1 - 2021-06-17
410

511
### Added

src/TorchlightExtension.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ class TorchlightExtension implements ExtensionInterface, BlockRendererInterface
1919
{
2020
public static $torchlightBlocks = [];
2121

22+
protected $customBlockRenderer;
23+
2224
public function register(ConfigurableEnvironmentInterface $environment)
2325
{
2426
// We start by walking the document immediately after it's parsed
@@ -66,10 +68,21 @@ public function render(AbstractBlock $block, ElementRendererInterface $htmlRende
6668
$hash = $this->makeTorchlightBlock($block)->hash();
6769

6870
if (array_key_exists($hash, static::$torchlightBlocks)) {
71+
if ($this->customBlockRenderer) {
72+
return call_user_func($this->customBlockRenderer, static::$torchlightBlocks[$hash]);
73+
}
74+
6975
return static::$torchlightBlocks[$hash]->wrapped;
7076
}
7177
}
7278

79+
public function registerCustomBlockRenderer($callback)
80+
{
81+
$this->customBlockRenderer = $callback;
82+
83+
return $this;
84+
}
85+
7386
protected function makeTorchlightBlock($node)
7487
{
7588
return Block::make()

tests/CodeRendererTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,50 @@ public function it_highlights_code_blocks()
7575
$this->assertEquals($expected, $html);
7676
}
7777

78+
/** @test */
79+
public function it_can_set_a_custom_renderer()
80+
{
81+
$markdown = <<<'EOT'
82+
```html
83+
<div>html</div>
84+
```
85+
EOT;
86+
87+
$response = [
88+
'blocks' => [[
89+
'id' => 'block_id_1',
90+
'wrapped' => '<pre><code>highlighted</code></pre>',
91+
]]
92+
];
93+
94+
Http::fake([
95+
'api.torchlight.dev/*' => Http::response($response, 200),
96+
]);
97+
98+
$extension = new TorchlightExtension;
99+
$extension->registerCustomBlockRenderer(function(Block $block) {
100+
return 'foo_bar';
101+
});
102+
103+
$environment = Environment::createCommonMarkEnvironment();
104+
$environment->addExtension($extension);
105+
106+
$parser = new DocParser($environment);
107+
$htmlRenderer = new HtmlRenderer($environment);
108+
109+
$document = $parser->parse($markdown);
110+
111+
$html = $htmlRenderer->renderBlock($document);
112+
113+
$expected = <<<EOT
114+
foo_bar
115+
116+
EOT;
117+
118+
$this->assertEquals($expected, $html);
119+
}
120+
121+
78122
/** @test */
79123
public function gets_language_and_contents()
80124
{

0 commit comments

Comments
 (0)