-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpage.js
More file actions
67 lines (58 loc) · 1.99 KB
/
Copy pathpage.js
File metadata and controls
67 lines (58 loc) · 1.99 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* Shared behaviour for .at-page documents.
*
* One delegated listener, so a page adds a copy button by writing the markup
* and nothing else. No per-page handler, no onclick attribute.
*/
(function () {
'use strict';
var RESET_MS = 1400;
function flash(button, label, failed) {
var original = button.getAttribute('data-label') || button.textContent;
button.setAttribute('data-label', original);
button.textContent = label;
button.classList.add(failed ? 'failed' : 'copied');
window.setTimeout(function () {
button.textContent = original;
button.classList.remove('copied', 'failed');
}, RESET_MS);
}
// Clipboard API needs a secure context and, in some browsers, a real user
// gesture. Selecting an offscreen textarea still works where it does not.
function copyBySelection(text) {
var area = document.createElement('textarea');
area.value = text;
area.setAttribute('readonly', '');
area.style.position = 'fixed';
area.style.top = '0';
area.style.opacity = '0';
document.body.appendChild(area);
area.select();
var ok = false;
try { ok = document.execCommand('copy'); } catch (err) { ok = false; }
document.body.removeChild(area);
return ok;
}
document.addEventListener('click', function (event) {
var button = event.target.closest ? event.target.closest('.copy') : null;
if (!button) return;
var block = button.closest('.code');
var pre = block && block.querySelector('pre');
if (!pre) return;
var text = pre.innerText;
var fallback = function () {
if (copyBySelection(text)) {
flash(button, 'COPIED');
} else {
// Never leave the button silent: say so rather than imply success.
flash(button, 'SELECT AND COPY', true);
}
};
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(function () {
flash(button, 'COPIED');
}, fallback);
return;
}
fallback();
});
})();