site.lyte.dev/static/global.mjs

86 lines
2.6 KiB
JavaScript

import { Theme } from "./theme.mjs";
document.querySelectorAll(".js-only").forEach((a) =>
a.classList.remove("js-only")
);
document.querySelectorAll(".js-disabled-only").forEach((a) => a.remove());
const theme = new Theme();
document.querySelectorAll(".theme-toggler").forEach((a) =>
a.addEventListener("click", () => theme.cycle())
);
const initAlign = () => {
const cur = localStorage.getItem("align");
const prev = cur == "center" ? "left" : "center";
document.body.classList.add("align-" + cur);
document.body.classList.remove("align-" + prev);
};
if (localStorage.getItem("align") === null) {
localStorage.setItem("align", "center");
}
initAlign();
const toggleAlign = (ev) => {
localStorage.setItem(
"align",
localStorage.getItem("align") == "center" ? "left" : "center",
);
initAlign();
if (!!ev.target) ev.preventDefault();
return false;
};
document.querySelectorAll(".align-toggler").forEach((a) =>
a.addEventListener("click", toggleAlign)
);
window.addEventListener("load", (_ev) => {
const selector = [1, 2, 3, 4, 5, 6].map((n) => `h${n}[id]`).join(",");
document.querySelectorAll(selector).forEach((el) => {
const anchorLink = document.createElement("a");
anchorLink.classList.add("anchor-link");
anchorLink.textContent = "§";
anchorLink.href = `#${el.id}`;
el.appendChild(anchorLink);
});
});
function initCodeCopyButtons() {
const codeBlocks = document.querySelectorAll("pre.chroma");
codeBlocks.forEach((block) => {
const code = block.querySelectorAll("code")[0];
const buttonContainer = document.createElement("p");
buttonContainer.classList.add("copy-code-button-container");
const button = document.createElement("button");
buttonContainer.appendChild(button);
button.classList.add("copy-code-button");
block.parentNode.parentNode.insertBefore(buttonContainer, block.parentNode);
button.textContent = "Copy";
button.addEventListener("click", (_ev) => {
button.disabled = true;
navigator.clipboard.writeText(code.textContent).catch(() => {
const lastText = button.textContent;
button.textContent = "Error Copying";
setTimeout(() => {
button.disabled = false;
button.textContent = lastText;
}, 500);
}).then(() => {
const lastText = button.textContent;
button.textContent = "Copied to clipbooard!";
setTimeout(() => {
button.disabled = false;
button.textContent = lastText;
}, 3000);
});
});
});
}
window.addEventListener("load", (_ev) => {
initCodeCopyButtons();
});