UNPKG

1.54 kBJavaScriptView Raw
1(function(){
2 if (typeof self === 'undefined' || !self.Prism || !self.document) {
3 return;
4 }
5
6 if (!Prism.plugins.toolbar) {
7 console.warn('Copy to Clipboard plugin loaded before Toolbar plugin.');
8
9 return;
10 }
11
12 var ClipboardJS = window.ClipboardJS || undefined;
13
14 if (!ClipboardJS && typeof require === 'function') {
15 ClipboardJS = require('clipboard');
16 }
17
18 var callbacks = [];
19
20 if (!ClipboardJS) {
21 var script = document.createElement('script');
22 var head = document.querySelector('head');
23
24 script.onload = function() {
25 ClipboardJS = window.ClipboardJS;
26
27 if (ClipboardJS) {
28 while (callbacks.length) {
29 callbacks.pop()();
30 }
31 }
32 };
33
34 script.src = 'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js';
35 head.appendChild(script);
36 }
37
38 Prism.plugins.toolbar.registerButton('copy-to-clipboard', function (env) {
39 var linkCopy = document.createElement('button');
40 linkCopy.textContent = 'Copy';
41
42 if (!ClipboardJS) {
43 callbacks.push(registerClipboard);
44 } else {
45 registerClipboard();
46 }
47
48 return linkCopy;
49
50 function registerClipboard() {
51 var clip = new ClipboardJS(linkCopy, {
52 'text': function () {
53 return env.code;
54 }
55 });
56
57 clip.on('success', function() {
58 linkCopy.textContent = 'Copied!';
59
60 resetText();
61 });
62 clip.on('error', function () {
63 linkCopy.textContent = 'Press Ctrl+C to copy';
64
65 resetText();
66 });
67 }
68
69 function resetText() {
70 setTimeout(function () {
71 linkCopy.textContent = 'Copy';
72 }, 5000);
73 }
74 });
75})();