lbry.tech/app/components/glossary-toc.js

58 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2018-07-20 00:36:48 +02:00
"use strict";
2018-11-30 21:46:22 +01:00
// U T I L S
2018-08-30 23:53:52 +02:00
const idRegex = /(".*")/g;
const numberRegex = /^[0-9]/g;
2018-08-30 23:53:52 +02:00
const renderedHeaderRegex = /(<h\d\sid.*h\d>)/g;
const titleRegex = /(>.*<)/g;
2018-07-20 00:36:48 +02:00
// E X P O R T
2018-11-30 21:46:22 +01:00
export default (state, emit, markdown) => {
2018-07-20 00:36:48 +02:00
const collectionOfTocElements = [];
2018-08-30 23:53:52 +02:00
const tocElements = markdown.match(renderedHeaderRegex);
2018-07-20 00:36:48 +02:00
2018-08-30 23:53:52 +02:00
for (const item of tocElements) {
const id = item.match(idRegex)[0].replace(/"/g, "");
const title = item.match(titleRegex)[0].replace(">", "").replace("<", "");
collectionOfTocElements.push(`
2018-12-12 18:15:27 +01:00
<li>
<a href="${slugify(id)}" title="Go to '${title}'">${title}</a>
</li>
2018-08-30 23:53:52 +02:00
`);
}
2018-07-20 00:36:48 +02:00
return `
<ul class="component--glossary-toc">
${collectionOfTocElements.join("")}
</ul>
`;
};
// H E L P E R
function slugify(stringToSlugify) {
let finalString = stringToSlugify
2018-07-20 00:36:48 +02:00
.toLowerCase()
.replace(/###\s/g, "")
.replace(/\s\/\s/g, "-")
2018-07-20 00:36:48 +02:00
.replace(/\s/g, "-")
.replace(/%/g, "")
2018-07-20 00:36:48 +02:00
.replace(/\(/g, "")
.replace(/\)/g, "")
.replace(/,/g, "");
2019-04-12 21:08:35 +02:00
if (finalString.match(numberRegex))
finalString = `_${finalString}`;
return `#${finalString}`;
2018-07-20 00:36:48 +02:00
}