anchors.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace Grav\Plugin;
  3. use \Grav\Common\Plugin;
  4. use \Grav\Common\Grav;
  5. use \Grav\Common\Page\Page;
  6. class AnchorsPlugin extends Plugin
  7. {
  8. /**
  9. * @return array
  10. */
  11. public static function getSubscribedEvents()
  12. {
  13. return [
  14. 'onPluginsInitialized' => ['onPluginsInitialized', 0]
  15. ];
  16. }
  17. /**
  18. * Initialize configuration
  19. */
  20. public function onPluginsInitialized()
  21. {
  22. if ($this->isAdmin()) {
  23. $this->active = false;
  24. } else {
  25. $this->enable([
  26. 'onPageInitialized' => ['onPageInitialized', 0],
  27. 'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
  28. ]);
  29. }
  30. }
  31. /**
  32. * Initialize configuration
  33. */
  34. public function onPageInitialized()
  35. {
  36. $defaults = (array) $this->config->get('plugins.anchors');
  37. /** @var Page $page */
  38. $page = $this->grav['page'];
  39. if (isset($page->header()->anchors)) {
  40. $this->config->set('plugins.anchors', array_merge($defaults, $page->header()->anchors));
  41. }
  42. }
  43. /**
  44. * if enabled on this page, load the JS + CSS and set the selectors.
  45. */
  46. public function onTwigSiteVariables()
  47. {
  48. if ($this->config->get('plugins.anchors.active')) {
  49. $selectors = $this->config->get('plugins.anchors.selectors', 'h1,h2,h3,h4');
  50. $visible = "visible: '{$this->config->get('plugins.anchors.visible', 'hover')}',";
  51. $placement = "placement: '{$this->config->get('plugins.anchors.placement', 'right')}',";
  52. $icon = $this->config->get('plugins.anchors.icon') ? "icon: '{$this->config->get('plugins.anchors.icon')}'," : '';
  53. $class = $this->config->get('plugins.anchors.class') ? "class: '{$this->config->get('plugins.anchors.class')}'," : '';
  54. $truncate = "truncate: {$this->config->get('plugins.anchors.truncate', 64)}";
  55. $this->grav['assets']->addJs('plugin://anchors/js/anchor.min.js');
  56. $anchors_init = "$(document).ready(function() {
  57. anchors.options = {
  58. $visible
  59. $placement
  60. $icon
  61. $class
  62. $truncate
  63. };
  64. anchors.add('$selectors');
  65. });";
  66. $this->grav['assets']->addInlineJs($anchors_init);
  67. }
  68. }
  69. }