Welcome to mirror list, hosted at ThFree Co, Russian Federation.

codeblock.ts « ts « assets - github.com/CaiJimmy/hugo-theme-stack.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 08c3328755f0394b6d87aa63fa73d3b3dabb0d74 (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
/**
 * Copy button for code blocks
*/
export default () => {
    const copyButtons = document.querySelectorAll('.codeblock-copy');
    copyButtons.forEach(button => {
        const codeblockID = button.getAttribute('data-id'),
            copyText = button.textContent,
            copiedText = button.getAttribute('data-copied-text');
        if (!codeblockID) return;
        button.addEventListener('click', (e) => {
            e.preventDefault();
            const codeblock = document.getElementById(codeblockID) as HTMLElement;
            if (!codeblockID) return;
            navigator.clipboard.writeText(codeblock.textContent)
                .then(() => {
                    button.textContent = copiedText;
                    setTimeout(() => {
                        button.textContent = copyText;
                    }, 1000);
                })
                .catch(err => {
                    alert(err)
                    console.log('Something went wrong', err);
                });
        }, false);
    });
}