PageSourceSearch

https://cascade-prod.static.wm.edu/_shared/static/js/_js-imports/code_block_copy.js

js wm.edu collected 2026-10-01 08:37:44 UTC 2,214 bytes, 75 lines download raw bytes

1// this file includes exported copy_code_block() function 
2
3/* =============================================================
4FUNCTION copy_code_block()
5
6- Adds copy button to <code> tags with spans (to differentiate between block in inline code)
7- Copy code in code blocks made in the WYSIWYG
8
9================================================================= */
10
11export function copy_code_block() {
12
13    const preArray = Array.from(document.querySelectorAll('pre.code-block'));
14    if (preArray.length === 0)
15        return;
16
17    preArray.forEach( (pre) => {
18
19        const codeBlockWrapper = document.createElement('div');
20        codeBlockWrapper.className = 'code-block-wrapper';
21        
22        pre.parentNode.insertBefore(codeBlockWrapper, pre);
23        codeBlockWrapper.appendChild(pre);
24        
25        const copyBtn = document.createElement('button');
26        copyBtn.className = 'code__copy-btn';
27        copyBtn.innerText = "Copy";
28        codeBlockWrapper.appendChild(copyBtn);
29
30        copyBtn.addEventListener('click', async (event) => {
31            copyCodeText(event);
32        });
33
34        copyBtn.addEventListener('keydown', async (event) => {
35            if (event.key !== 'Enter')
36                return;
37            event.preventDefault();
38            copyCodeText(event);
39        });
40
41    });
42}
43
44async function copyCodeText(event) {
45    const btn = event.target;
46    const btnParent = btn.parentElement;
47    const codeText = btnParent.querySelector('.code-block').innerText;
48
49    if (!codeText)
50        return;
51
52    const res = await copyToClipboard(codeText);
53    
54    if (res) {
55        btn.classList.add('-clicked');
56        btn.innerText = 'Copied';
57        setTimeout( () => {
58            btn.classList.remove('-clicked');
59            btn.innerText = 'Copy';
60        }
61        , 3000);
62    } else {
63        console.log('Copy failed');
64    }
65}
66
67async function copyToClipboard(text) {
68    try {
69        await navigator.clipboard.writeText(text.trim());
70        console.log('Text copied to clipboard: ' + text.trim());
71        return true;
72    } catch (err) {
73        console.error('Failed to copy: ', err);
74    }
75}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.