summaryrefslogtreecommitdiffstats
path: root/asset/js/widget/CopyToClipboard.js
blob: e3b348c136e35eb3df2e24664d27131a18b62c89 (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
39
40
41
42
43
44
45
46
47
48
49
define(["../notjQuery"], function ($) {

    "use strict";

    class CopyToClipboard {
        constructor(button)
        {
            button.classList.add('active');
            button.removeAttribute('tabindex');
            $(button).on('click', null, this.onClick, this);
        }

        onClick(event)
        {
            let button = event.currentTarget;
            let clipboardSource = button.parentElement.querySelector("[data-clipboard-source]");
            let copyText;

            if (clipboardSource) {
                copyText = clipboardSource.innerText;
            } else {
                throw new Error('Clipboard source is required but not provided');
            }

            if (navigator.clipboard) {
                navigator.clipboard.writeText(copyText).then(() => {
                    let previousHtml = button.innerHTML;
                    button.innerText = button.dataset.copiedLabel;
                    button.classList.add('copied');

                    setTimeout(() => {
                        // after 4 second, reset it.
                        button.classList.remove('copied');
                        button.innerHTML = previousHtml;
                    }, 4000);
                }).catch((err) => {
                    console.error('Failed to copy: ', err);
                });
            } else {
                throw new Error('Copy to clipboard requires HTTPS connection');
            }

            event.stopPropagation();
            event.preventDefault();
        }
    }

    return CopyToClipboard;
});