38 lines
974 B
JavaScript
38 lines
974 B
JavaScript
// retoor <retoor@molodetz.nl>
|
|
import hljs from "../../vendor/highlight.es.min.js";
|
|
import { Component } from "./Component.js";
|
|
import { Toast } from "../utils/Toast.js";
|
|
|
|
export class Code extends Component {
|
|
static tag = "dp-code";
|
|
|
|
setup() {
|
|
requestAnimationFrame(() => this.enhance());
|
|
}
|
|
|
|
enhance() {
|
|
const code = this.querySelector("pre > code");
|
|
if (!code) {
|
|
return;
|
|
}
|
|
try {
|
|
hljs.highlightElement(code);
|
|
} catch (error) {
|
|
console.debug("highlight failed", error);
|
|
}
|
|
const button = document.createElement("button");
|
|
button.type = "button";
|
|
button.className = "copy-button";
|
|
button.textContent = "Copy";
|
|
button.addEventListener("click", async () => {
|
|
try {
|
|
await navigator.clipboard.writeText(code.textContent);
|
|
Toast.flash(button, "Copied", 1500, "Copy");
|
|
} catch {
|
|
Toast.flash(button, "Failed", 1500, "Copy");
|
|
}
|
|
});
|
|
this.prepend(button);
|
|
}
|
|
}
|