clipboard.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. MimeData
  5. } from '@phosphor/coreutils';
  6. /**
  7. * The clipboard interface.
  8. */
  9. export
  10. namespace Clipboard {
  11. /**
  12. * Get the application clipboard instance.
  13. */
  14. export
  15. function getInstance(): MimeData {
  16. return Private.instance;
  17. }
  18. /**
  19. * Set the application clipboard instance.
  20. */
  21. export
  22. function setInstance(value: MimeData): void {
  23. Private.instance = value;
  24. }
  25. /**
  26. * Copy text to the system clipboard.
  27. *
  28. * #### Notes
  29. * This can only be called in response to a user input event.
  30. */
  31. export
  32. function copyToSystem(text: string): void {
  33. let node = document.body;
  34. let handler = (event: ClipboardEvent) => {
  35. let data = event.clipboardData || (window as any).clipboardData;
  36. data.setData('text', text);
  37. event.preventDefault();
  38. node.removeEventListener('copy', handler);
  39. };
  40. node.addEventListener('copy', handler);
  41. generateEvent(node);
  42. }
  43. /**
  44. * Generate a clipboard event on a node.
  45. *
  46. * @param node - The element on which to generate the event.
  47. *
  48. * @param type - The type of event to generate.
  49. * `'paste'` events cannot be programmatically generated.
  50. *
  51. * #### Notes
  52. * This can only be called in response to a user input event.
  53. */
  54. export
  55. function generateEvent(node: HTMLElement, type: 'copy' | 'cut' = 'copy'): void {
  56. // http://stackoverflow.com/a/5210367
  57. // Identify selected text.
  58. let sel = window.getSelection();
  59. // Save the current selection.
  60. let savedRanges: any[] = [];
  61. for (let i = 0, len = sel.rangeCount; i < len; ++i) {
  62. savedRanges[i] = sel.getRangeAt(i).cloneRange();
  63. }
  64. // Select the node content.
  65. let range = document.createRange();
  66. range.selectNodeContents(node);
  67. sel.removeAllRanges();
  68. sel.addRange(range);
  69. // Execute the command.
  70. document.execCommand(type);
  71. // Restore the previous selection.
  72. sel = window.getSelection();
  73. sel.removeAllRanges();
  74. for (let i = 0, len = savedRanges.length; i < len; ++i) {
  75. sel.addRange(savedRanges[i]);
  76. }
  77. }
  78. }
  79. /**
  80. * The namespace for module private data.
  81. */
  82. namespace Private {
  83. /**
  84. * The application clipboard instance.
  85. */
  86. export
  87. let instance = new MimeData();
  88. }