summaryrefslogtreecommitdiffstats
path: root/web_src/js/features/clipboard.js
blob: 12486a208d5a3632269e22bafedded02ddb15c2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const selector = '[data-clipboard-target], [data-clipboard-text]';

// TODO: replace these with toast-style notifications
function onSuccess(btn) {
  if (!btn.dataset.content) return;
  $(btn).popup('destroy');
  btn.dataset.content = btn.dataset.success;
  $(btn).popup('show');
  btn.dataset.content = btn.dataset.original;
}
function onError(btn) {
  if (!btn.dataset.content) return;
  $(btn).popup('destroy');
  btn.dataset.content = btn.dataset.error;
  $(btn).popup('show');
  btn.dataset.content = btn.dataset.original;
}

export default async function initClipboard() {
  for (const btn of document.querySelectorAll(selector) || []) {
    btn.addEventListener('click', async () => {
      let text;
      if (btn.dataset.clipboardText) {
        text = btn.dataset.clipboardText;
      } else if (btn.dataset.clipboardTarget) {
        text = document.querySelector(btn.dataset.clipboardTarget)?.value;
      }
      if (!text) return;

      try {
        await navigator.clipboard.writeText(text);
        onSuccess(btn);
      } catch {
        onError(btn);
      }
    });
  }
}