80 lines
2.4 KiB
JavaScript
80 lines
2.4 KiB
JavaScript
/*
|
|
* Copyright (C) 2022 Aravinth Manivannan <realaravinth@batsense.net>
|
|
*
|
|
* This program is free software: you can redistribute it and/or modify
|
|
* it under the terms of the GNU Affero General Public License as
|
|
* published by the Free Software Foundation, either version 3 of the
|
|
* License, or (at your option) any later version.
|
|
*
|
|
* This program is distributed in the hope that it will be useful,
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
* GNU Affero General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU Affero General Public License
|
|
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
const check_dataset = (id, property) => {
|
|
let elem = document.getElementById(id);
|
|
if (elem === undefined || elem == null) {
|
|
console.warn(`${id} not found`);
|
|
return false;
|
|
}
|
|
if (!elem.dataset.hasOwnProperty(property)) {
|
|
console.warn(`${id} component doesn't have ${property} dataset attribute`);
|
|
return false;
|
|
}
|
|
|
|
return elem;
|
|
};
|
|
|
|
const init_clipboard = () => {
|
|
const CHECK_COMPONENT = check_dataset("check-icon", "check");
|
|
if (CHECK_COMPONENT == false) {
|
|
return;
|
|
}
|
|
const CHECK_ICON = CHECK_COMPONENT.dataset.check;
|
|
|
|
const CLIPBOARD_COMPONET = check_dataset("clipboard-icon", "clipboard");
|
|
if (CLIPBOARD_COMPONET == false) {
|
|
return;
|
|
}
|
|
const CLIPBOARD_ICON = CLIPBOARD_COMPONET.dataset.clipboard;
|
|
|
|
const copy_code = async (event) => {
|
|
const switch_clipboard_icon = async (event) => {
|
|
event.target.src = CHECK_ICON;
|
|
setTimeout(() => {
|
|
event.target.src = CLIPBOARD_ICON;
|
|
}, 1200);
|
|
};
|
|
|
|
let elem = event.target;
|
|
let codes = Array.from(elem.parentElement.getElementsByTagName("span"));
|
|
let content = "";
|
|
codes.forEach((span) => {
|
|
content = `${content} ${span.innerText}`;
|
|
});
|
|
|
|
await navigator.clipboard.writeText(content);
|
|
await switch_clipboard_icon(event);
|
|
};
|
|
|
|
const new_clipboard = () => {
|
|
let clipboard = document.createElement("img");
|
|
clipboard.src = CLIPBOARD_ICON;
|
|
clipboard.classList = ["copy-code"];
|
|
clipboard.addEventListener("click", copy_code);
|
|
return clipboard;
|
|
};
|
|
|
|
document.querySelectorAll("code").forEach((code) => {
|
|
if (code.parentElement.tagName == "PRE") {
|
|
code.parentElement.appendChild(new_clipboard());
|
|
}
|
|
});
|
|
};
|
|
|
|
init_clipboard();
|