49 lines
1.9 KiB
JavaScript
49 lines
1.9 KiB
JavaScript
import Alpine from "alpinejs";
|
|
|
|
window.Alpine = Alpine;
|
|
|
|
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 fill="currentColor" 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 fill="currentColor" 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 button--opaque absolute top-3 right-3";
|
|
|
|
button.addEventListener("click", () => {
|
|
navigator.clipboard.writeText(codeBlock.innerHTML).then(() => {
|
|
button.innerHTML = copiedButtonContent;
|
|
setTimeout(() => {
|
|
button.innerHTML = defaultButtonContent;
|
|
}, revertTimeout);
|
|
});
|
|
});
|
|
|
|
codeBlock.parentElement.insertBefore(
|
|
button,
|
|
codeBlock.nextElementSibling
|
|
);
|
|
});
|
|
});
|