-
Notifications
You must be signed in to change notification settings - Fork 99
/
clipboard-polyfill.ts
288 lines (242 loc) · 8.13 KB
/
clipboard-polyfill.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import {Promise} from "es6-promise";
import {DT, suppressDTWarnings} from "./DT";
// Debug log strings should be short, since they are copmiled into the production build.
// TODO: Compile debug logging code out of production builds?
var debugLog: (s: string) => void = function(s: string) {};
var showWarnings = true;
var warnOrLog = function() {
(console.warn || console.log).call(arguments);
}; // IE9 workaround (can't bind console functions).
var warn = warnOrLog.bind(console, "[clipboard-polyfill]");
var TEXT_PLAIN = "text/plain";
declare global {
interface Navigator {
clipboard: {
writeText?: (s: string) => Promise<void>;
readText?: () => Promise<string>;
};
}
}
export default class ClipboardPolyfill {
public static readonly DT = DT;
public static setDebugLog(f: (s: string) => void): void {
debugLog = f;
}
public static suppressWarnings() {
showWarnings = false;
suppressDTWarnings();
}
public static write(data: DT): Promise<void> {
if (showWarnings && !data.getData(TEXT_PLAIN)) {
warn("clipboard.write() was called without a "+
"`text/plain` data type. On some platforms, this may result in an "+
"empty clipboard. Call clipboard.suppressWarnings() "+
"to suppress this warning.");
}
return new Promise<void>((resolve, reject) => {
// Internet Explorer
if (seemToBeInIE()) {
if (writeIE(data)) {
resolve()
} else {
reject(new Error("Copying failed, possibly because the user rejected it."));
}
return;
}
var tracker = execCopy(data);
if (tracker.success) {
debugLog("regular execCopy worked");
resolve();
return;
}
// Success detection on Edge is not possible, due to bugs in all 4
// detection mechanisms we could try to use. Assume success.
if (navigator.userAgent.indexOf("Edge") > -1) {
debugLog("UA \"Edge\" => assuming success");
resolve();
return;
}
// Fallback 1 for desktop Safari.
tracker = copyUsingTempSelection(document.body, data);
if (tracker.success) {
debugLog("copyUsingTempSelection worked");
resolve();
return;
}
// Fallback 2 for desktop Safari.
tracker = copyUsingTempElem(data);
if (tracker.success) {
debugLog("copyUsingTempElem worked");
resolve();
return;
}
// Fallback for iOS Safari.
var text = data.getData(TEXT_PLAIN);
if (text !== undefined && copyTextUsingDOM(text)) {
debugLog("copyTextUsingDOM worked");
resolve();
return;
}
reject(new Error("Copy command failed."));
});
}
public static writeText(s: string): Promise<void> {
if (navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(s);
}
var dt = new DT();
dt.setData(TEXT_PLAIN, s);
return this.write(dt);
}
public static read(): Promise<DT> {
return new Promise((resolve, reject) => {
if (seemToBeInIE()) {
readIE().then(
(s: string) => resolve(DTFromText(s)),
reject
);
return;
}
// TODO: Attempt to read using async clipboard API.
reject("Read is not supported in your browser.")
});
}
public static readText(): Promise<string> {
if (navigator.clipboard && navigator.clipboard.readText) {
return navigator.clipboard.readText();
}
if (seemToBeInIE()) {
return readIE();
}
return new Promise((resolve, reject) => {
// TODO: Attempt to read using async clipboard API.
reject("Read is not supported in your browser.")
});
}
}
/******** Implementations ********/
class FallbackTracker {
public success: boolean = false;
}
function copyListener(tracker: FallbackTracker, data: DT, e: ClipboardEvent): void {
debugLog("listener called");
tracker.success = true;
data.forEach((value: string, key: string) => {
e.clipboardData.setData(key, value);
if (key === TEXT_PLAIN && e.clipboardData.getData(key) != value) {
debugLog("setting text/plain failed");
tracker.success = false;
}
});
e.preventDefault();
}
function execCopy(data: DT): FallbackTracker {
var tracker = new FallbackTracker();
var listener = copyListener.bind(this, tracker, data);
document.addEventListener("copy", listener);
try {
// We ignore the return value, since FallbackTracker tells us whether the
// listener was called. It seems that checking the return value here gives
// us no extra information in any browser.
document.execCommand("copy");
} finally {
document.removeEventListener("copy", listener);
}
return tracker;
}
// Create a temporary DOM element to select, so that `execCommand()` is not
// rejected.
function copyUsingTempSelection(e: HTMLElement, data: DT): FallbackTracker {
selectionSet(e);
var tracker = execCopy(data);
selectionClear();
return tracker;
}
// Create a temporary DOM element to select, so that `execCommand()` is not
// rejected.
function copyUsingTempElem(data: DT): FallbackTracker {
var tempElem = document.createElement("div");
// Place some text in the elem so that Safari has something to select.
tempElem.textContent = "temporary element";
document.body.appendChild(tempElem);
var tracker = copyUsingTempSelection(tempElem, data);
document.body.removeChild(tempElem);
return tracker;
}
// Uses shadow DOM.
function copyTextUsingDOM(str: string): boolean {
debugLog("copyTextUsingDOM");
var tempElem = document.createElement("div");
// Use shadow DOM if available.
var spanParent: Node = tempElem;
if (tempElem.attachShadow) {
debugLog("Using shadow DOM.");
spanParent = tempElem.attachShadow({mode: "open"});
}
var span = document.createElement("span");
span.innerText = str;
// span.style.whiteSpace = "pre-wrap"; // TODO: Use `innerText` above instead?
spanParent.appendChild(span);
document.body.appendChild(tempElem);
selectionSet(span);
var result = document.execCommand("copy");
selectionClear();
document.body.removeChild(tempElem);
return result;
}
/******** Selection ********/
function selectionSet(elem: Element): void {
var sel = document.getSelection();
var range = document.createRange();
range.selectNodeContents(elem);
sel.removeAllRanges();
sel.addRange(range);
}
function selectionClear(): void {
var sel = document.getSelection();
sel.removeAllRanges();
}
/******** Convenience ********/
function DTFromText(s: string): DT {
var dt = new DT();
dt.setData(TEXT_PLAIN, s);
return dt;
}
/******** Internet Explorer ********/
interface IEWindow extends Window {
clipboardData: {
setData: (key: string, value: string) => boolean;
// Always results in a string: https://msdn.microsoft.com/en-us/library/ms536436(v=vs.85).aspx
getData: (key: string) => string;
}
}
function seemToBeInIE(): boolean {
return typeof ClipboardEvent === "undefined" &&
typeof (window as IEWindow).clipboardData !== "undefined" &&
typeof (window as IEWindow).clipboardData.setData !== "undefined";
}
function writeIE(data: DT): boolean {
// IE supports text or URL, but not HTML: https://msdn.microsoft.com/en-us/library/ms536744(v=vs.85).aspx
// TODO: Write URLs to `text/uri-list`? https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types
var text = data.getData(TEXT_PLAIN);
if (text !== undefined) {
return (window as IEWindow).clipboardData.setData("Text", text);
}
throw ("No `text/plain` value was specified.");
}
// Returns "" if the read failed, e.g. because the user rejected the permission.
function readIE(): Promise<string> {
return new Promise((resolve, reject) => {
var text = (window as IEWindow).clipboardData.getData("Text");
if (text === "") {
reject(new Error("Empty clipboard or could not read plain text from clipboard"));
} else {
resolve(text);
}
})
}
/******** Expose `clipboard` on the global object in browser. ********/
// TODO: Figure out how to expose ClipboardPolyfill as self.clipboard using
// WebPack?
declare var module: any;
module.exports = ClipboardPolyfill;