Commit cd5ae7fb authored by Administrator's avatar Administrator 💬

Add the anchors plugin.

parent 763526be
# v1.5.2
## 09/28/2016
1. [](#improved)
* Updated `anchors.js` to version 4.1.0
# v1.5.1
## 07/14/2016
1. [](#improved)
* Translate some blueprint options
# v1.5.0
## 01/06/2016
1. [](#improved)
* Disable anchors in Admin
# v1.4.0
## 08/25/2015
1. [](#improved)
* Added blueprints for Grav Admin plugin
# v1.3.0
## 07/20/2015
1. [](#new)
* Updated `anchors.js` to version 1.2.1
* Added new options such as 'placement', 'visible', 'icon' and 'class'
# v1.2.0
## 03/01/2015
1. [](#new)
* Updated `anchors.js` to version 0.3.0
# v1.1.0
## 11/30/2014
1. [](#new)
* ChangeLog started...
The MIT License (MIT)
Copyright (c) 2014 Grav
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# Grav Anchors Plugin
`anchors` is a [Grav](http://github.com/getgrav/grav) plugin that provides automatic header anchors via the [anchorjs](http://bryanbraun.github.io/anchorjs) jQuery plugin.
# Installation
## GPM Installation (Preferred)
The simplest way to install this plugin is via the [Grav Package Manager (GPM)](http://learn.getgrav.org/advanced/grav-gpm). From the root of your Grav install type:
bin/gpm install anchors
## Manual Installation
If for some reason you can't use GPM you can manually install this plugin. Download the zip version of this repository and unzip it under `/your/site/grav/user/plugins`. Then, rename the folder to `anchors`.
You should now have all the plugin files under
/your/site/grav/user/plugins/anchors
# Usage
To best understand how Anchors works, you should read through the original [project documentation](https://github.com/bryanbraun/anchorjs).
## Show Menu of Anchors
If you want to use the generated links to also generate a menu from these anchors, just put the function below in the template file twig:
`anchors(content, tag, terms)`
The function accepts 3 parameters:
content: this parameter is the content of the page in which the function will search for all content and separate only the tags and their contents defined by the second parameter. Ex: page.content
tag: this parameter will be the string of the tag used to make the menu. Ex: 'h2'
terms: this parameter is to exclude terms that you do not wish to include in the menu formation that is between the tag passed in the second parameter. The value passed is a string separated by vírgurla to identify each term. Ex: 'title 01, title 02'
When rendered the function will return a formed HTML with `<ul>` and the links of the anchors in each `<li>`.
## Configuration:
Simply copy the `user/plugins/breadcrumbs/anchors.yaml` into `user/config/plugins/anchors.yaml` and make your modifications.
enabled: true # enable or disable the plugin
active: true # active by default, if false then you must activate per-page
selectors: 'h1,h2,h3,h4' # css elements to activate on. Uses jQuery style selectors
placement: right # either "left" or "right"
visible: hover # Active on "hover" or "always" visible
icon: # default link or a specific character like: #, ¶, ❡, and §.
class: # adds the provided class to the anchor html
truncate: 64 # truncates the generated ID to the specified character length
You can override any default settings from the page headers:
eg:
---
title: Sample Code With Custom Theme
anchors:
active: true
selectors: .blog h1, .blog h2
---
# Header
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas accumsan porta diam,
nec sagittis odio euismod nec. Etiam eu rutrum eros.
## Sub Header
Proin commodo lobortis elementum.
Integer vel ultrices massa, nec ornare urna. Phasellus tincidunt rutrum dolor, vestibulum
faucibus ligula laoreet id. Donec hendrerit arcu vitae lacus mattis facilisis. Praesent
tortor nibh, pulvinar nec orci ac, rhoncus pharetra nunc.
You can also disable anchors for a particular page if causes issues:
---
title: Sample Code with Highlight disabled
anchors:
active: false
---
# Header
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas accumsan porta diam,
nec sagittis odio euismod nec. Etiam eu rutrum eros.
## Sub Header
Proin commodo lobortis elementum.
Integer vel ultrices massa, nec ornare urna. Phasellus tincidunt rutrum dolor, vestibulum
faucibus ligula laoreet id. Donec hendrerit arcu vitae lacus mattis facilisis. Praesent
tortor nibh, pulvinar nec orci ac, rhoncus pharetra nunc.
> Note: If you want to see this plugin in action, have a look at [Grav Learn Site](http://learn.getgrav.org)
<?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],
'onTwigExtensions' => ['onTwigExtensions', 0]
]);
}
}
public function onTwigExtensions()
{
$config = $this->config->get('plugins.anchors.selectors');
require_once(__DIR__ . '/twig/AnchorsTwigExtension.php');
$this->grav['twig']->twig->addExtension(new AnchorsTwigExtension($config));
}
/**
* 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);
}
}
}
enabled: true # enable or disable the plugin
active: true # active by default, if false then you must activate per-page
selectors: 'h1,h2,h3,h4' # css elements to activate on. Uses jQuery style selectors
placement: right # either "left" or "right"
visible: hover # Active on "hover" or "always" visible
icon: # default link or a specific character like: #, ¶, ❡, and §.
class: # adds the provided class to the anchor html
truncate: 64 # truncates the generated ID to the specified character length
name: Anchors
version: 1.5.2
description: "This plugin provides automatic header anchors via the [anchorjs](http://bryanbraun.github.io/anchorjs) jQuery plugin."
icon: anchor
author:
name: Team Grav
email: devs@getgrav.org
url: http://getgrav.org
homepage: https://github.com/getgrav/grav-plugin-anchors
demo: http://learn.getgrav.org
keywords: anchor, header, plugin, code
bugs: https://github.com/getgrav/grav-plugin-anchors/issues
license: MIT
form:
validation: strict
fields:
enabled:
type: toggle
label: PLUGIN_ADMIN.PLUGIN_STATUS
highlight: 1
default: 0
options:
1: PLUGIN_ADMIN.ENABLED
0: PLUGIN_ADMIN.DISABLED
validate:
type: bool
active:
type: toggle
label: Active
highlight: 1
default: 1
options:
1: PLUGIN_ADMIN.ENABLED
0: PLUGIN_ADMIN.DISABLED
validate:
type: bool
help: Activate for all pages. If disabled then you must activate per-page
selectors:
type: text
label: Selectors
size: large
default: 'h1,h2,h3,h4'
placeholder: "Anchor Selectors"
help: Comma separated list of header selectors to activate on
placement:
type: select
label: Placement
classes: fancy
help: "Either `left` or `right`"
default: 'right'
options:
'left': 'left'
'right': 'right'
visible:
type: select
label: Visible
classes: fancy
help: "Hover activates on `hover` else will always display"
default: 'hover'
options:
'hover': 'hover'
'always': 'always'
icon:
type: text
label: Icon
size: medium
default: ''
help: "Replace the default link icon with the character(s) provided, e.g. #, ¶, or §"
class:
type: text
label: Class
size: medium
default: ''
help: "Adds the provided class to the anchor html"
truncate:
type: text
size: x-small
label: Truncate
help: "Truncates the generated ID to the specified character length"
default: 64
validate:
type: number
min: 0
\ No newline at end of file
{
"project":"grav-plugin-anchors",
"platforms":{
"grav":{
"nodes":{
"plugin":[
{
"source":"/",
"destination":"/user/plugins/anchors"
}
]
}
}
}
}
/**
* AnchorJS - v4.1.0 - 2017-09-20
* https://github.com/bryanbraun/anchorjs
* Copyright (c) 2017 Bryan Braun; Licensed MIT
*/
!function(A,e){"use strict";"function"==typeof define&&define.amd?define([],e):"object"==typeof module&&module.exports?module.exports=e():(A.AnchorJS=e(),A.anchors=new A.AnchorJS)}(this,function(){"use strict";return function(A){function e(A){A.icon=A.hasOwnProperty("icon")?A.icon:"",A.visible=A.hasOwnProperty("visible")?A.visible:"hover",A.placement=A.hasOwnProperty("placement")?A.placement:"right",A.ariaLabel=A.hasOwnProperty("ariaLabel")?A.ariaLabel:"Anchor",A.class=A.hasOwnProperty("class")?A.class:"",A.truncate=A.hasOwnProperty("truncate")?Math.floor(A.truncate):64}function t(A){var e;if("string"==typeof A||A instanceof String)e=[].slice.call(document.querySelectorAll(A));else{if(!(Array.isArray(A)||A instanceof NodeList))throw new Error("The selector provided to AnchorJS was invalid.");e=[].slice.call(A)}return e}function i(){if(null===document.head.querySelector("style.anchorjs")){var A,e=document.createElement("style");e.className="anchorjs",e.appendChild(document.createTextNode("")),void 0===(A=document.head.querySelector('[rel="stylesheet"], style'))?document.head.appendChild(e):document.head.insertBefore(e,A),e.sheet.insertRule(" .anchorjs-link { opacity: 0; text-decoration: none; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }",e.sheet.cssRules.length),e.sheet.insertRule(" *:hover > .anchorjs-link, .anchorjs-link:focus { opacity: 1; }",e.sheet.cssRules.length),e.sheet.insertRule(" [data-anchorjs-icon]::after { content: attr(data-anchorjs-icon); }",e.sheet.cssRules.length),e.sheet.insertRule(' @font-face { font-family: "anchorjs-icons"; src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype"); }',e.sheet.cssRules.length)}}this.options=A||{},this.elements=[],e(this.options),this.isTouchDevice=function(){return!!("ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch)},this.add=function(A){var n,o,s,a,r,c,h,l,u,d,f,p=[];if(e(this.options),"touch"===(f=this.options.visible)&&(f=this.isTouchDevice()?"always":"hover"),A||(A="h2, h3, h4, h5, h6"),0===(n=t(A)).length)return this;for(i(),o=document.querySelectorAll("[id]"),s=[].map.call(o,function(A){return A.id}),r=0;r<n.length;r++)if(this.hasAnchorJSLink(n[r]))p.push(r);else{if(n[r].hasAttribute("id"))a=n[r].getAttribute("id");else if(n[r].hasAttribute("data-anchor-id"))a=n[r].getAttribute("data-anchor-id");else{u=l=this.urlify(n[r].textContent),h=0;do{void 0!==c&&(u=l+"-"+h),c=s.indexOf(u),h+=1}while(-1!==c);c=void 0,s.push(u),n[r].setAttribute("id",u),a=u}a.replace(/-/g," "),(d=document.createElement("a")).className="anchorjs-link "+this.options.class,d.href="#"+a,d.setAttribute("aria-label",this.options.ariaLabel),d.setAttribute("data-anchorjs-icon",this.options.icon),"always"===f&&(d.style.opacity="1"),""===this.options.icon&&(d.style.font="1em/1 anchorjs-icons","left"===this.options.placement&&(d.style.lineHeight="inherit")),"left"===this.options.placement?(d.style.position="absolute",d.style.marginLeft="-1em",d.style.paddingRight="0.5em",n[r].insertBefore(d,n[r].firstChild)):(d.style.paddingLeft="0.375em",n[r].appendChild(d))}for(r=0;r<p.length;r++)n.splice(p[r]-r,1);return this.elements=this.elements.concat(n),this},this.remove=function(A){for(var e,i,n=t(A),o=0;o<n.length;o++)(i=n[o].querySelector(".anchorjs-link"))&&(-1!==(e=this.elements.indexOf(n[o]))&&this.elements.splice(e,1),n[o].removeChild(i));return this},this.removeAll=function(){this.remove(this.elements)},this.urlify=function(A){var t=/[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\]/g;return this.options.truncate||e(this.options),A.trim().replace(/\'/gi,"").replace(t,"-").replace(/-{2,}/g,"-").substring(0,this.options.truncate).replace(/^-+|-+$/gm,"").toLowerCase()},this.hasAnchorJSLink=function(A){var e=A.firstChild&&(" "+A.firstChild.className+" ").indexOf(" anchorjs-link ")>-1,t=A.lastChild&&(" "+A.lastChild.className+" ").indexOf(" anchorjs-link ")>-1;return e||t||!1}}});
\ No newline at end of file
<?php
namespace Grav\Plugin;
class AnchorsTwigExtension extends \Twig_Extension
{
private $config;
public function __construct($config)
{
$this->config = $config;
}
public function getName()
{
return 'AnchorsTwigExtension';
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('anchors', [$this, 'anchorsFunction'])
];
}
/**
* Get a list of anchors link
*
* @param $content
* @param $tag
* @return string
*/
public function anchorsFunction($content, $tag = 'h2', $terms)
{
$configTags = array_map('trim', explode(',',$this->config));
if (in_array($tag, $configTags)){
$textMenu = [];
$rx = '/<'.$tag.'>(.*)<\/'.$tag.'>/';
preg_match_all($rx, $content, $group);
if (!empty($group[1])){
if (!empty($terms)){
$termsArray = array_map('trim', explode(',',$terms));
$elements = array_diff($group[1],$termsArray);
}else{
$elements = $group[1];
}
foreach($elements as $element){
$textMenu[] = $element;
}
$html = $this->getHtmlTag($textMenu);
}else{
$html = '';
}
}else{
$tag = current($configTags);
$html = $this->anchorsFunction($tag, $content);
}
return $html;
}
/**
* Mount the html of anchors link
*
* @param $itens
* @return string
*/
private function getHtmlTag($itens)
{
$html = '';
$html .= '<ul class="items-menus-page">';
foreach($itens as $item){
$html .= '<li><a href="#'.$this->getUrl($item).'">'.$this->textLimit($item, 50, false).'</a></li>';
}
$html .= '</ul>';
return $html;
}
/**
* Get url whithout special characters
*
* @param $text
* @return string
*/
private function getUrl($text)
{
$rx1 = array('ä','ã','à','á','â','ê','ë','è','é','ï','ì','í','ö','õ','ò','ó','ô','ü','ù','ú','û','À','Á','Â','Ã','É','Ê','Ô','Í','Ó','Õ','Ú','ñ','Ñ','ç','Ç');
$rx2 = '/\'/';
$rx3 = '/[& \+\$,:;=\?@"#\{\}\|\^~\[`%!\'<>\]\.\/\(\)\*ºª]/';
$rx4 = '/-{2,}/';
$rx5 = '/\^-+|-+$/';
$urlAnchor1 = str_replace('–', '-', str_replace($rx1, '', $text));
$urlAnchor2 = preg_replace($rx2, '', $urlAnchor1);
$urlAnchor3 = preg_replace($rx3, '-', $urlAnchor2);
$urlAnchor4 = $this->textLimit(preg_replace($rx4, '-', $urlAnchor3), 64);
$urlAnchor5 = preg_replace($rx5, '', $urlAnchor4);
$urlAnchorFinal = strtolower($urlAnchor5);
return $urlAnchorFinal;
}
/**
* It limit characters total in exit
*
* @param $text
* @param $limit
* @param bool|true $url //verify if type content is url or title
* @return string
*/
private function textLimit($text, $limit, $url = true)
{
$count = strlen($text);
if ( $count >= $limit ) {
if ($url){
$text = substr($text, 0, $limit);
return $text;
}else {
$text = substr($text, 0, strrpos(substr($text, 0, $limit), ' ')) . '...';
return $text;
}
}
else{
return $text;
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment