anchors.php
2.5 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
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace Grav\Plugin;
use \Grav\Common\Plugin;
use \Grav\Common\Grav;
use \Grav\Common\Page\Page;
class AnchorsPlugin extends Plugin
{
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0]
];
}
/**
* Initialize configuration
*/
public function onPluginsInitialized()
{
if ($this->isAdmin()) {
$this->active = false;
} else {
$this->enable([
'onPageInitialized' => ['onPageInitialized', 0],
'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
]);
}
}
/**
* Initialize configuration
*/
public function onPageInitialized()
{
$defaults = (array) $this->config->get('plugins.anchors');
/** @var Page $page */
$page = $this->grav['page'];
if (isset($page->header()->anchors)) {
$this->config->set('plugins.anchors', array_merge($defaults, $page->header()->anchors));
}
}
/**
* if enabled on this page, load the JS + CSS and set the selectors.
*/
public function onTwigSiteVariables()
{
if ($this->config->get('plugins.anchors.active')) {
$selectors = $this->config->get('plugins.anchors.selectors', 'h1,h2,h3,h4');
$visible = "visible: '{$this->config->get('plugins.anchors.visible', 'hover')}',";
$placement = "placement: '{$this->config->get('plugins.anchors.placement', 'right')}',";
$icon = $this->config->get('plugins.anchors.icon') ? "icon: '{$this->config->get('plugins.anchors.icon')}'," : '';
$class = $this->config->get('plugins.anchors.class') ? "class: '{$this->config->get('plugins.anchors.class')}'," : '';
$truncate = "truncate: {$this->config->get('plugins.anchors.truncate', 64)}";
$this->grav['assets']->addJs('plugin://anchors/js/anchor.min.js');
$anchors_init = "$(document).ready(function() {
anchors.options = {
$visible
$placement
$icon
$class
$truncate
};
anchors.add('$selectors');
});";
$this->grav['assets']->addInlineJs($anchors_init);
}
}
}