public-web/assets/main.js
ondrej 937b5a4893
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
Fix & chore
2023-08-30 21:30:27 +02:00

58 lines
2.2 KiB
JavaScript

/* Tooltips */
document.querySelectorAll("[data-tooltip]").forEach((el) => {
tippy(el, { content: el.dataset.tooltip });
});
/* Copy button component */
async function initCopyButtons() {
const copyIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="w-4"><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" class="w-4"><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);
try {
const permission = await navigator.permissions.query({
name: "clipboard-write",
});
if (permission.state == "denied") {
return;
}
} catch (error) {
// This query throws on some browsers which don't know "clipboard-write" permission.
// We ignore this error and then try to access clipboard anyway.
}
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
);
});
}
window.addEventListener("turbo:load", () => {
initCopyButtons();
});