prism-copy-to-clipboard.js 1.5 KB

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