Skip to content

Instantly share code, notes, and snippets.

@AWtnb
Last active December 1, 2021 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AWtnb/9085b2a74b77bad4399d399f0ae34925 to your computer and use it in GitHub Desktop.
Save AWtnb/9085b2a74b77bad4399d399f0ae34925 to your computer and use it in GitHub Desktop.
javascript for formatting markdown-compiled html
// ------------------------------------------------------------
// format markdown-compiled html with js
// ------------------------------------------------------------
const getElems = (query) => {
return Array.from(document.querySelectorAll(query));
};
const insertFilename = (elm) => {
const filename = elm.className.replace(/^language-/, "");
if (filename) {
elm.classList.remove(elm.className);
elm.classList.add("content");
const pre = elm.parentElement;
pre.setAttribute("data-lang", filename);
pre.classList.add("codeblock-header");
}
}
const convertToCheckBox = (elm) => {
const s = elm.innerHTML;
elm.innerHTML = s.replace(/\[ *\]/g, "<input type=\"checkbox\" >").replace(/\[x\]/g, "<input type=\"checkbox\" checked>");
}
const adjustIndex = (elm) => {
const startIdx = elm.getAttribute("startIdx") || 1;
let counter = Number(startIdx);
Array.from(elm.children).filter(elm => elm.tagName == "OL").forEach(elm => {
elm.start = counter;
const lis = Array.from(elm.children).filter(c => c.tagName == "LI");
counter += lis.length;
});
}
const adjustSpacing = (elm) => {
const t = elm.innerText;
if (t.length >= 2 && t.length <= 4) {
elm.classList.add(`spacing-${t.length}`);
}
}
const newlineToBr = (elm) => {
if (elm.innerHTML.match(/\r?\n/)) {
elm.innerHTML = (elm.innerHTML).replace(/\r?\n/g, "<br>");
}
};
const insertTOC = () => {
const output = document.querySelector(".toc");
if(!output) {
return;
}
const hs = getElems("h2, h3, h4, h5, h6");
if (hs.length) {
const markup = hs.map(elem => {
return `<li class="toc-${elem.localName}"><a target="_self" href="#${elem.id}">${elem.innerText}</a></li>`;
}).join("");
output.innerHTML = `<ul>${markup}</ul>`
}
};
/*
called when page is loaded
*/
document.addEventListener("DOMContentLoaded", () => {
getElems("code").filter(elm => elm.className).forEach(insertFilename);
getElems("p > img").forEach(elm => {
elm.parentElement.classList.add("imgContainer");
});
getElems("body > p").forEach(newlineToBr);
getElems("blockquote p").forEach(newlineToBr);
getElems("table td").forEach(convertToCheckBox);
getElems(".forceOrder, .force-order").forEach(adjustIndex);
getElems("h2,h3,h4,h5").forEach(adjustSpacing);
insertTOC();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment