Repository navigation
Expand file tree
/
Copy pathcopy.js
More file actions
52 lines (52 loc) · 1.79 KB
/
Copy pathcopy.js
File metadata and controls
52 lines (52 loc) · 1.79 KB
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
/* Copy buttons: <button class="copy-btn" data-copy="#id"> copies that element's text.
The button turns green with a check for a moment on success. The Clipboard API needs a
secure context (https or localhost); elsewhere it falls back to a hidden textarea. */
(() => {
const fallback = (text) => {
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.cssText = 'position:fixed;top:-1000px;opacity:0';
document.body.appendChild(ta);
ta.select();
let ok = false;
try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
ta.remove();
return ok;
};
document.querySelectorAll('.copy-btn[data-copy]').forEach((btn) => {
const label = btn.querySelector('.copy-label');
let timer = 0;
const show = (cls, text) => {
clearTimeout(timer);
btn.classList.remove('copied', 'failed');
btn.classList.add(cls);
if (label) label.textContent = text;
timer = setTimeout(() => {
btn.classList.remove(cls);
if (label) label.textContent = 'Copy';
}, 1800);
};
btn.addEventListener('click', async () => {
const src = document.querySelector(btn.dataset.copy);
if (!src) return;
const text = src.textContent;
let ok = false;
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
ok = true;
}
} catch (e) { ok = false; }
if (!ok) ok = fallback(text);
show(ok ? 'copied' : 'failed', ok ? 'Copied' : 'Press ⌘C');
if (!ok) {
const r = document.createRange();
r.selectNodeContents(src);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(r);
}
});
});
})();