copy-button.html 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <script>
  2. /**
  3. * Set up copy/paste for code blocks
  4. */
  5. const clipboardButton = id =>
  6. `<a id="copy-button-${id}" class="btn copybtn o-tooltip--left" data-tooltip="Copy" data-clipboard-target="#${id}">
  7. <img src="{{ site.images_url | relative_url }}/copy-button.svg" alt="Copy to clipboard">
  8. </a>`
  9. // Clears selected text since ClipboardJS will select the text when copying
  10. const clearSelection = () => {
  11. if (window.getSelection) {
  12. window.getSelection().removeAllRanges()
  13. } else if (document.selection) {
  14. document.selection.empty()
  15. }
  16. }
  17. // Changes tooltip text for two seconds, then changes it back
  18. const temporarilyChangeTooltip = (el, newText) => {
  19. const oldText = el.getAttribute('data-tooltip')
  20. el.setAttribute('data-tooltip', newText)
  21. setTimeout(() => el.setAttribute('data-tooltip', oldText), 2000)
  22. }
  23. const addCopyButtonToCodeCells = () => {
  24. // If ClipboardJS hasn't loaded, wait a bit and try again. This
  25. // happens because we load ClipboardJS asynchronously.
  26. if (window.ClipboardJS === undefined) {
  27. setTimeout(addCopyButtonToCodeCells, 250)
  28. return
  29. }
  30. pageElements['codeCells'].forEach((codeCell) => {
  31. const id = codeCell.getAttribute('id')
  32. if (document.getElementById("copy-button" + id) == null) {
  33. codeCell.insertAdjacentHTML('afterend', clipboardButton(id));
  34. }
  35. })
  36. const clipboard = new ClipboardJS('.copybtn')
  37. clipboard.on('success', event => {
  38. clearSelection()
  39. temporarilyChangeTooltip(event.trigger, 'Copied!')
  40. })
  41. clipboard.on('error', event => {
  42. temporarilyChangeTooltip(event.trigger, 'Failed to copy')
  43. })
  44. // Get rid of clipboard before the next page visit to avoid memory leak
  45. document.addEventListener('turbolinks:before-visit', () =>
  46. clipboard.destroy()
  47. )
  48. }
  49. initFunction(addCopyButtonToCodeCells);
  50. </script>