Add generated anchors for h2 headings

This commit is contained in:
Pavel Zet 2018-05-26 23:08:58 -03:00
parent a0f24f42d9
commit 93b6fb6774
5 changed files with 79 additions and 1 deletions

44
_js/behaviors/anchors.js Normal file
View File

@ -0,0 +1,44 @@
import onmount from 'onmount'
import prepend from 'dom101/prepend'
const DEFAULTS = {
// select elements to put anchor on
rule: 'h2[id]',
// class name for anchor
cls: 'local-anchor',
// text of anchor
text: '#',
// append before or after innerText?
shouldAppend: false,
}
/*
* Behavior: Add local anchors
*/
onmount('[data-js-anchors]', function () {
const data = JSON.parse(this.getAttribute('data-js-anchors') || '{}')
const rules = Array.isArray(data)
? (data.length ? data : [DEFAULTS])
: [Object.assign({}, DEFAULTS, data)]
for (const { rule, cls, text, shouldAppend } of rules) {
for (const el of this.querySelectorAll(rule)) {
if (!el.hasAttribute('id')) {
continue
}
const id = el.getAttribute('id')
const anchor = document.createElement('a')
anchor.setAttribute('href', `#${id}`)
anchor.setAttribute('class', cls)
anchor.innerText = String(text || DEFAULTS.text)
if (shouldAppend) {
el.appendChild(anchor)
} else {
prepend(el, anchor)
}
}
}
})

View File

@ -52,7 +52,7 @@
</div>
{% endif %}
<main class='post-content MarkdownBody' data-js-main-body role='main'>
<main class='post-content MarkdownBody' data-js-main-body data-js-anchors role='main'>
{{ content }}
</main>
</div>

View File

@ -9,6 +9,10 @@
font-weight: 200;
font-family: $heading-font;
margin-top: 0;
&:target {
color: $base-a;
}
}
.MarkdownBody h3 {

View File

@ -0,0 +1,29 @@
.local-anchor {
& {
margin-left: -.9em;
margin-right: .1em;
padding: 0 .1em;
}
// Decoration
.MarkdownBody &,
.MarkdownBody &:visited {
color: $base-mute;
text-decoration: inherit;
opacity: .5;
}
.MarkdownBody &:target,
.MarkdownBody :target > & {
color: $base-a;
opacity: 1;
}
.MarkdownBody &:hover,
.MarkdownBody &:focus {
color: white;
background: $base-a;
opacity: 1;
text-decoration: inherit;
}
}

View File

@ -14,6 +14,7 @@
@import './markdown/a-em';
@import './markdown/code';
@import './markdown/headings';
@import './markdown/local-anchor';
@import './markdown/p';
@import './markdown/table';
@import './markdown/ul';