prism-copy-to-clipboard.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. (function () {
  2. if (typeof Prism === 'undefined' || typeof document === 'undefined') {
  3. return;
  4. }
  5. if (!Prism.plugins.toolbar) {
  6. console.warn('Copy to Clipboard plugin loaded before Toolbar plugin.');
  7. return;
  8. }
  9. /**
  10. * When the given elements is clicked by the user, the given text will be copied to clipboard.
  11. *
  12. * @param {HTMLElement} element
  13. * @param {CopyInfo} copyInfo
  14. *
  15. * @typedef CopyInfo
  16. * @property {() => string} getText
  17. * @property {() => void} success
  18. * @property {(reason: unknown) => void} error
  19. */
  20. function registerClipboard(element, copyInfo) {
  21. element.addEventListener('click', function () {
  22. copyTextToClipboard(copyInfo);
  23. });
  24. }
  25. // https://stackoverflow.com/a/30810322/7595472
  26. /** @param {CopyInfo} copyInfo */
  27. function fallbackCopyTextToClipboard(copyInfo) {
  28. var textArea = document.createElement('textarea');
  29. textArea.value = copyInfo.getText();
  30. // Avoid scrolling to bottom
  31. textArea.style.top = '0';
  32. textArea.style.left = '0';
  33. textArea.style.position = 'fixed';
  34. document.body.appendChild(textArea);
  35. textArea.focus();
  36. textArea.select();
  37. try {
  38. var successful = document.execCommand('copy');
  39. setTimeout(function () {
  40. if (successful) {
  41. copyInfo.success();
  42. } else {
  43. copyInfo.error();
  44. }
  45. }, 1);
  46. } catch (err) {
  47. setTimeout(function () {
  48. copyInfo.error(err);
  49. }, 1);
  50. }
  51. document.body.removeChild(textArea);
  52. }
  53. /** @param {CopyInfo} copyInfo */
  54. function copyTextToClipboard(copyInfo) {
  55. if (navigator.clipboard) {
  56. navigator.clipboard.writeText(copyInfo.getText()).then(copyInfo.success, function () {
  57. // try the fallback in case `writeText` didn't work
  58. fallbackCopyTextToClipboard(copyInfo);
  59. });
  60. } else {
  61. fallbackCopyTextToClipboard(copyInfo);
  62. }
  63. }
  64. /**
  65. * Selects the text content of the given element.
  66. *
  67. * @param {Element} element
  68. */
  69. function selectElementText(element) {
  70. // https://stackoverflow.com/a/20079910/7595472
  71. window.getSelection().selectAllChildren(element);
  72. }
  73. /**
  74. * Traverses up the DOM tree to find data attributes that override the default plugin settings.
  75. *
  76. * @param {Element} startElement An element to start from.
  77. * @returns {Settings} The plugin settings.
  78. * @typedef {Record<"copy" | "copy-error" | "copy-success" | "copy-timeout", string | number>} Settings
  79. */
  80. function getSettings(startElement) {
  81. /** @type {Settings} */
  82. var settings = {
  83. 'copy': 'Copy',
  84. 'copy-error': 'Press Ctrl+C to copy',
  85. 'copy-success': 'Copied!',
  86. 'copy-timeout': 5000
  87. };
  88. var prefix = 'data-prismjs-';
  89. for (var key in settings) {
  90. var attr = prefix + key;
  91. var element = startElement;
  92. while (element && !element.hasAttribute(attr)) {
  93. element = element.parentElement;
  94. }
  95. if (element) {
  96. settings[key] = element.getAttribute(attr);
  97. }
  98. }
  99. return settings;
  100. }
  101. Prism.plugins.toolbar.registerButton('copy-to-clipboard', function (env) {
  102. var element = env.element;
  103. var settings = getSettings(element);
  104. var linkCopy = document.createElement('button');
  105. linkCopy.className = 'copy-to-clipboard-button';
  106. linkCopy.setAttribute('type', 'button');
  107. var linkSpan = document.createElement('span');
  108. linkCopy.appendChild(linkSpan);
  109. setState('copy');
  110. registerClipboard(linkCopy, {
  111. getText: function () {
  112. return element.textContent;
  113. },
  114. success: function () {
  115. setState('copy-success');
  116. resetText();
  117. },
  118. error: function () {
  119. setState('copy-error');
  120. setTimeout(function () {
  121. selectElementText(element);
  122. }, 1);
  123. resetText();
  124. }
  125. });
  126. return linkCopy;
  127. function resetText() {
  128. setTimeout(function () { setState('copy'); }, settings['copy-timeout']);
  129. }
  130. /** @param {"copy" | "copy-error" | "copy-success"} state */
  131. function setState(state) {
  132. linkSpan.textContent = settings[state];
  133. linkCopy.setAttribute('data-copy-state', state);
  134. }
  135. });
  136. }());