site.lyte.dev/static/global.mjs
2023-07-10 11:15:32 -05:00

92 lines
2.7 KiB
JavaScript

import { Theme } from "./theme.mjs";
// import "./preload.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");
}
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) => `main > 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");
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);
});
});
block.parentNode.appendChild(button);
});
}
window.addEventListener("load", initAlign);
window.addEventListener("load", initCodeCopyButtons);
window.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll(".nojs").forEach(e => {
e.classList.remove("nojs")
})
})