UNPKG

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