var tocGen = {};
tocGen.headings = function() {
var md = document.querySelector('.markdown');
if (!md) {
return [];
}
return Array.prototype.slice.call(
md.querySelectorAll('h1, h2, h3, h4, h5, h6')
);
};
tocGen.contentsHeading = function(headings) {
return headings.filter(function(el) {
return el.innerText === 'Contents';
})[0];
};
tocGen.slugify = function(s) {
return s.toLowerCase().match(/\w+/g).join('-');
};
tocGen.createLiA = function(href, text) {
var li = document.createElement('li');
var a = document.createElement('a');
a.href = href;
a.innerText = text;
li.appendChild(a);
return li;
};
tocGen.createToC = function(headings, skipH1sInSlug) {
var prevLevel = 0;
var stack = [null, null, null, null, null, null];
var f = function(heading) {
var level = +heading.tagName[1];
var i, ul;
for (i = prevLevel; i < level; i++) {
ul = document.createElement('ul');
if (level > 1) {
var li = document.createElement('li');
li.style.listStyle = 'none';
li.appendChild(ul);
stack[i - 1].list.appendChild(li);
}
stack[i] = {'list': ul, 'text': ''};
}
stack[level - 1].text = heading.innerText;
var slug = stack.slice(1 * skipH1sInSlug, level).map(function(x) {
return tocGen.slugify(x.text);
}).join('--');
heading.id = slug;
var liA = tocGen.createLiA(
location.href.split('#')[0] + '#' + slug,
heading.innerText
);
stack[level - 1].list.appendChild(liA);
prevLevel = level;
};
headings.forEach(f);
return stack[0].list;
};
tocGen.insertAfter = function(ref, el) {
ref.parentNode.insertBefore(el, ref.nextSibling);
}
tocGen.addToC = function(skipH1sInSlug) {
var headings = tocGen.headings();
var contentsHeading = tocGen.contentsHeading(headings);
if (!contentsHeading) return;
headings = headings.filter(function (heading) {
return heading !== contentsHeading;
});
var toc = tocGen.createToC(headings, skipH1sInSlug);
if (toc.childNodes.length === 2) {
toc = toc.childNodes[1].childNodes[0];
};
tocGen.insertAfter(contentsHeading, toc);
};
tocGen.linkifyTagList = function (tagPageHref) {
var tagPageLinks = document.querySelectorAll(
'a[href$="' + tagPageHref + '"]'
);
if (tagPageLinks.length === 0) return;
var tagPageLink = tagPageLinks[tagPageLinks.length - 1];
var p = tagPageLink.parentNode;
var tagListNode = p.childNodes[1];
var tags = tagListNode
.textContent
.replace(/^:\s*/, '')
.replace(/\s*\.$/, '')
.split(/,\s*/);
var links = tags.map(function(tag) {
var a = document.createElement('a');
var slug = tocGen.slugify(tag);
a.href = tagPageHref + '#tags--' + slug;
a.appendChild(document.createTextNode(tag));
return a;
});
links.forEach(function(link, i) {
p.appendChild(link);
p.appendChild(document.createTextNode(
i === links.length - 1 ? '. ' : ', '
));
});
tagListNode.textContent = 'Tags: ';
p.removeChild(tagPageLink);
};