public-web/assets/main.js

51 lines
1.9 KiB
JavaScript

import Alpine from "alpinejs";
import persist from "@alpinejs/persist";
window.Alpine = Alpine;
Alpine.plugin(persist);
Alpine.start();
/* Copy button component */
const copyIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill="none" d="M0 0h24v24H0z"/><path d="M7 4V2h10v2h3.007c.548 0 .993.445.993.993v16.014a.994.994 0 0 1-.993.993H3.993A.994.994 0 0 1 3 21.007V4.993C3 4.445 3.445 4 3.993 4H7zm0 2H5v14h14V6h-2v2H7V6zm2-2v2h6V4H9z"/></svg>`;
const checkIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill="none" d="M0 0h24v24H0z"/><path d="M10 15.172l9.192-9.193 1.415 1.414L10 18l-6.364-6.364 1.414-1.414z"/></svg>`;
const defaultButtonLabel = `Zkopírovat text do schránky`;
const copiedButtonLabel = `Text zkopírován`;
const revertTimeout = 5_000;
const accessibleLabel = (text) => `<span class="sr-only">${text}</span>`;
const defaultButtonContent = copyIcon + accessibleLabel(defaultButtonLabel);
const copiedButtonContent = checkIcon + accessibleLabel(copiedButtonLabel);
navigator.permissions
.query({
name: "clipboard-read",
})
.then((permission) => {
if (permission.state == "denied") {
return;
}
document
.querySelectorAll(".prose pre code, .code-block")
.forEach((codeBlock) => {
const button = document.createElement("button");
button.innerHTML = defaultButtonContent;
button.className = "button absolute top-3 right-3 bg-white";
button.addEventListener("click", () => {
navigator.clipboard.writeText(codeBlock.innerHTML).then(() => {
button.innerHTML = copiedButtonContent;
setTimeout(() => {
button.innerHTML = defaultButtonContent;
}, revertTimeout);
});
});
codeBlock.parentElement.insertBefore(
button,
codeBlock.nextElementSibling
);
});
});