highlight.php
1.9 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
<?php
namespace Grav\Plugin;
use \Grav\Common\Plugin;
use \Grav\Common\Grav;
use \Grav\Common\Page\Page;
class HighlightPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPageInitialized' => ['onPageInitialized', 0]
];
}
/**
* Initialize configuration
*/
public function onPageInitialized()
{
if ($this->isAdmin()) {
$this->active = false;
return;
}
$defaults = (array) $this->config->get('plugins.highlight');
/** @var Page $page */
$page = $this->grav['page'];
if (isset($page->header()->highlight)) {
$this->config->set('plugins.highlight', array_merge($defaults, $page->header()->highlight));
}
if ($this->config->get('plugins.highlight.enabled')) {
$this->enable([
'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
]);
}
}
/**
* if enabled on this page, load the JS + CSS theme.
*/
public function onTwigSiteVariables()
{
$init = "$(document).ready(function() {\n";
$init .= "$('pre code').each(function(i, block) {\n";
$init .= "hljs.highlightBlock(block);\n";
if ($this->config->get('plugins.highlight.lines')) {
$init .= "hljs.initLineNumbersOnLoad();\n";
}
$init .= "});\n";
$init .= "});\n";
$theme = $this->config->get('plugins.highlight.theme') ?: 'default';
$this->grav['assets']->addCss('plugin://highlight/css/'.$theme.'.css');
$this->grav['assets']->addJs('plugin://highlight/js/highlight.pack.js');
if ($this->config->get('plugins.highlight.lines')) {
$this->grav['assets']->addJs('plugin://highlight/js/highlightjs-line-numbers.min.js');
}
$this->grav['assets']->addInlineJs($init);
}
}