blob: cd8ae9573b2b39e237f0f6405800cf655b3f4d02 (
plain) (
tree)
|
|
class CopyButtonPlugin {
constructor(options = {}) {
self.hook = options.hook;
self.callback = options.callback
}
"after:highlightElement"({
el,
text
}) {
let button = Object.assign(document.createElement("button"), {
innerHTML: "Copy",
className: "hljs-copy-button"
});
button.dataset.copied = false;
el.parentElement.classList.add("hljs-copy-wrapper");
el.parentElement.appendChild(button);
el.parentElement.style.setProperty("--hljs-theme-background", window.getComputedStyle(el).backgroundColor);
button.onclick = async () => {
let newText = text;
if (hook && typeof hook === "function") {
newText = hook(text, el) || text
}
try {
if (!navigator.clipboard) {
throw new Error("navigator.clipboard: Clipboard API unavailable.");
}
await navigator.clipboard.writeText(newText);
} catch (e) {
console.error(e);
console.error("Clipboard API writeText() failed! Fallback to document.exec(\"copy\")...");
fallback_clipboard(newText);
}
button.innerHTML = "Copied!";
button.dataset.copied = true;
let alert = Object.assign(document.createElement("div"), {
role: "status",
className: "hljs-copy-alert",
innerHTML: "Copied to clipboard"
});
el.parentElement.appendChild(alert);
setTimeout(() => {
button.innerHTML = "Copy";
button.dataset.copied = false;
el.parentElement.removeChild(alert);
alert = null
}, 2e3)
}
if (typeof callback === "function") return callback(newText, el);
}
}
|