aboutsummaryrefslogtreecommitdiffstats
path: root/web_src/js/features/clipboard.js
diff options
context:
space:
mode:
Diffstat (limited to 'web_src/js/features/clipboard.js')
-rw-r--r--web_src/js/features/clipboard.js39
1 files changed, 22 insertions, 17 deletions
diff --git a/web_src/js/features/clipboard.js b/web_src/js/features/clipboard.js
index 12486a208d..4781f8d6ff 100644
--- a/web_src/js/features/clipboard.js
+++ b/web_src/js/features/clipboard.js
@@ -1,4 +1,4 @@
-const selector = '[data-clipboard-target], [data-clipboard-text]';
+// For all DOM elements with [data-clipboard-target] or [data-clipboard-text], this copy-to-clipboard will work for them
// TODO: replace these with toast-style notifications
function onSuccess(btn) {
@@ -16,23 +16,28 @@ function onError(btn) {
btn.dataset.content = btn.dataset.original;
}
-export default async function initClipboard() {
- for (const btn of document.querySelectorAll(selector) || []) {
- btn.addEventListener('click', async () => {
+export default function initGlobalCopyToClipboardListener() {
+ document.addEventListener('click', async (e) => {
+ let target = e.target;
+ // in case <button data-clipboard-text><svg></button>, so we just search up to 3 levels for performance.
+ for (let i = 0; i < 3 && target; i++) {
let text;
- if (btn.dataset.clipboardText) {
- text = btn.dataset.clipboardText;
- } else if (btn.dataset.clipboardTarget) {
- text = document.querySelector(btn.dataset.clipboardTarget)?.value;
+ if (target.dataset.clipboardText) {
+ text = target.dataset.clipboardText;
+ } else if (target.dataset.clipboardTarget) {
+ text = document.querySelector(target.dataset.clipboardTarget)?.value;
}
- if (!text) return;
-
- try {
- await navigator.clipboard.writeText(text);
- onSuccess(btn);
- } catch {
- onError(btn);
+ if (text) {
+ e.preventDefault();
+ try {
+ await navigator.clipboard.writeText(text);
+ onSuccess(target);
+ } catch {
+ onError(target);
+ }
+ break;
}
- });
- }
+ target = target.parentElement;
+ }
+ });
}