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