forked from OpenZeppelin/docs.openzeppelin.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07-copy-code.js
37 lines (32 loc) · 1.15 KB
/
07-copy-code.js
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
(function () {
const codeElementSelector = '[data-lang]';
const shellAliases = ['console', 'shell', 'sh', 'bash'];
function onDOMContentLoaded(callback) {
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', callback);
} else {
callback();
}
}
function copyClick(e) {
let code = e.target.parentElement.innerText;
const codeParentElement = e.target.parentElement;
const codeElement = codeParentElement.querySelector(codeElementSelector);
const codeLanguage = codeElement?.dataset?.lang;
const isShellLanguage = shellAliases.includes(codeLanguage);
if (isShellLanguage) {
code = code.replace(/\$ /gm, '');
}
navigator.clipboard.writeText(code);
}
onDOMContentLoaded(() => {
for (const elem of document.querySelectorAll('.listingblock')) {
const btn = document.createElement('button');
btn.classList.add('btn-icon', 'btn-copy', 'hljs');
btn.setAttribute('aria-label', 'Copy');
btn.innerHTML = '<svg class="icon"><use href="#copy-icon"/></svg>';
btn.addEventListener('click', copyClick);
elem.prepend(btn);
}
});
})();