|
|
@ -0,0 +1,56 @@ |
|
|
|
/* |
|
|
|
* original from Amber Wilson - no license information available. |
|
|
|
* original file: https://github.com/ambrwlsn/website/blob/da2056c316fa45fa58b443b07be1ac4c5080912e/helpers/markdown-anchor-wat.js#L1
|
|
|
|
* more info: https://amberwilson.co.uk/blog/are-your-anchor-links-accessible/
|
|
|
|
* file has been modified!! |
|
|
|
*/ |
|
|
|
|
|
|
|
const slugify = (s) => |
|
|
|
encodeURIComponent( |
|
|
|
String(s) |
|
|
|
.trim() |
|
|
|
.toLowerCase() |
|
|
|
.replace(/\s+/g, '-') |
|
|
|
); |
|
|
|
|
|
|
|
const defaultOptions = { |
|
|
|
divClass: 'heading-wrapper', |
|
|
|
anchorClass: 'anchor-link', |
|
|
|
linkIcon: '#', |
|
|
|
}; |
|
|
|
|
|
|
|
const targets = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; |
|
|
|
|
|
|
|
const anchor = (md, options) => { |
|
|
|
options = Object.assign({}, defaultOptions, options); |
|
|
|
|
|
|
|
md.renderer.rules.heading_open = function(tokens, index) { |
|
|
|
const contentToken = tokens[index + 1]; |
|
|
|
const slug = slugify(contentToken.content); |
|
|
|
|
|
|
|
if (targets.indexOf(tokens[index].tag) > -1) { |
|
|
|
return `
|
|
|
|
<div class="${options.divClass}"> |
|
|
|
<${tokens[index].tag} id="${slug}">`;
|
|
|
|
} |
|
|
|
return `<${tokens[index].tag}>`; |
|
|
|
}; |
|
|
|
|
|
|
|
md.renderer.rules.heading_close = function(tokens, index) { |
|
|
|
const contentToken = tokens[index - 1]; |
|
|
|
const slug = slugify(contentToken.content); |
|
|
|
|
|
|
|
if (targets.indexOf(tokens[index].tag) > -1 ) { |
|
|
|
return `
|
|
|
|
</${tokens[index].tag}> |
|
|
|
<a class="${options.anchorClass}" href="#${slug}"> |
|
|
|
<span aria-hidden="true">${options.linkIcon}</span> |
|
|
|
<span class="hidden">Section titled ${contentToken.content}</span> |
|
|
|
</a> |
|
|
|
</div>`; |
|
|
|
} |
|
|
|
return `</${tokens[index].tag}>`; |
|
|
|
}; |
|
|
|
}; |
|
|
|
|
|
|
|
module.exports = anchor; |