aboutsummaryrefslogtreecommitdiff
path: root/plugins/base/src/main/resources/dokka/scripts/clipboard.js
blob: 7a4f33c598cdcf301db580e3d9dfb2a9c54328ae (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
50
51
52
53
54
55
56
/*
 * Copyright 2014-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

window.addEventListener('load', () => {
    document.querySelectorAll('span.copy-icon').forEach(element => {
        element.addEventListener('click', (el) => copyElementsContentToClipboard(element));
    })

    document.querySelectorAll('span.anchor-icon').forEach(element => {
        element.addEventListener('click', (el) => {
            if(element.hasAttribute('pointing-to')){
                const location = hrefWithoutCurrentlyUsedAnchor() + '#' + element.getAttribute('pointing-to')
                copyTextToClipboard(element, location)
            }
        });
    })
})

const copyElementsContentToClipboard = (element) => {
    const selection = window.getSelection();
    const range = document.createRange();
    range.selectNodeContents(element.parentNode.parentNode);
    selection.removeAllRanges();
    selection.addRange(range);

    copyAndShowPopup(element,  () => selection.removeAllRanges())
}

const copyTextToClipboard = (element, text) => {
    var textarea = document.createElement("textarea");
    textarea.textContent = text;
    textarea.style.position = "fixed";
    document.body.appendChild(textarea);
    textarea.select();

    copyAndShowPopup(element, () => document.body.removeChild(textarea))
}

const copyAndShowPopup = (element, after) => {
    try {
        document.execCommand('copy');
        element.nextElementSibling.classList.add('active-popup');
        setTimeout(() => {
            element.nextElementSibling.classList.remove('active-popup');
        }, 1200);
    } catch (e) {
        console.error('Failed to write to clipboard:', e)
    }
    finally {
        if(after) after()
    }
}

const hrefWithoutCurrentlyUsedAnchor = () => window.location.href.split('#')[0]