-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
prism-copy-to-clipboard.js
78 lines (60 loc) · 1.58 KB
/
prism-copy-to-clipboard.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
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
68
69
70
71
72
73
74
75
76
77
78
(function(){
if (typeof self === 'undefined' || !self.Prism || !self.document) {
return;
}
if (!Prism.plugins.toolbar) {
console.warn('Copy to Clipboard plugin loaded before Toolbar plugin.');
return;
}
var ClipboardJS = window.ClipboardJS || undefined;
if (!ClipboardJS && typeof require === 'function') {
ClipboardJS = require('clipboard');
}
var callbacks = [];
if (!ClipboardJS) {
var script = document.createElement('script');
var head = document.querySelector('head');
script.onload = function() {
ClipboardJS = window.ClipboardJS;
if (ClipboardJS) {
while (callbacks.length) {
callbacks.pop()();
}
}
};
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js';
head.appendChild(script);
}
Prism.plugins.toolbar.registerButton('copy-to-clipboard', function (env) {
var linkCopy = document.createElement('button');
linkCopy.textContent = 'Copy';
linkCopy.setAttribute('type', 'button');
var element = env.element;
if (!ClipboardJS) {
callbacks.push(registerClipboard);
} else {
registerClipboard();
}
return linkCopy;
function registerClipboard() {
var clip = new ClipboardJS(linkCopy, {
'text': function () {
return element.textContent;
}
});
clip.on('success', function() {
linkCopy.textContent = 'Copied!';
resetText();
});
clip.on('error', function () {
linkCopy.textContent = 'Press Ctrl+C to copy';
resetText();
});
}
function resetText() {
setTimeout(function () {
linkCopy.textContent = 'Copy';
}, 5000);
}
});
})();