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 | linkCopy.setAttribute('type', 'button');
|
42 |
|
43 | var element = env.element;
|
44 |
|
45 | if (!ClipboardJS) {
|
46 | callbacks.push(registerClipboard);
|
47 | } else {
|
48 | registerClipboard();
|
49 | }
|
50 |
|
51 | return linkCopy;
|
52 |
|
53 | function registerClipboard() {
|
54 | var clip = new ClipboardJS(linkCopy, {
|
55 | 'text': function () {
|
56 | return element.textContent;
|
57 | }
|
58 | });
|
59 |
|
60 | clip.on('success', function() {
|
61 | linkCopy.textContent = 'Copied!';
|
62 |
|
63 | resetText();
|
64 | });
|
65 | clip.on('error', function () {
|
66 | linkCopy.textContent = 'Press Ctrl+C to copy';
|
67 |
|
68 | resetText();
|
69 | });
|
70 | }
|
71 |
|
72 | function resetText() {
|
73 | setTimeout(function () {
|
74 | linkCopy.textContent = 'Copy';
|
75 | }, 5000);
|
76 | }
|
77 | });
|
78 | })();
|