generated from spatie/package-skeleton-php
-
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathCodeBlockShiki.php
More file actions
67 lines (57 loc) · 1.76 KB
/
CodeBlockShiki.php
File metadata and controls
67 lines (57 loc) · 1.76 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
59
60
61
62
63
64
65
66
67
<?php
namespace Tiptap\Nodes;
use DomainException;
use Exception;
use Highlight\Highlighter;
use Spatie\ShikiPhp\Shiki;
use Tiptap\Utils\HTML;
class CodeBlockShiki extends CodeBlock
{
public function addOptions()
{
return [
'languageClassPrefix' => 'language-',
'HTMLAttributes' => [],
'defaultLanguage' => 'html',
'theme' => 'nord',
'guessLanguage' => true,
];
}
public function renderHTML($node, $HTMLAttributes = [])
{
$code = $node->content[0]->text ?? '';
// Language is set
if ($node->attrs->language === null) {
$language = $node->attrs->language;
}
// Auto-detect the language
elseif ($this->options['guessLanguage']) {
try {
$highlighter = new Highlighter();
$result = $highlighter->highlightAuto($code);
$language = $result->language;
} catch (Exception $exception) {
//
}
}
// Use the default language
if (! isset($language)) {
$language = $this->options['defaultLanguage'];
}
try {
$content = Shiki::highlight($code, $language, $this->options['theme']);
} catch (DomainException $exception) {
$mergedAttributes = HTML::mergeAttributes(
$this->options['HTMLAttributes'],
$HTMLAttributes,
);
$renderedAttributes = HTML::renderAttributes($mergedAttributes);
$content = "<pre><code" . $renderedAttributes . ">";
$content .= htmlentities($code);
$content .= "</code></pre>";
}
return [
'content' => $content,
];
}
}