-
Notifications
You must be signed in to change notification settings - Fork 30k
/
clipboardService.ts
164 lines (130 loc) · 5.62 KB
/
clipboardService.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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { isSafari, isWebkitWebView } from 'vs/base/browser/browser';
import { $, addDisposableListener } from 'vs/base/browser/dom';
import { DeferredPromise } from 'vs/base/common/async';
import { Disposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { ILayoutService } from 'vs/platform/layout/browser/layoutService';
import { ILogService } from 'vs/platform/log/common/log';
export class BrowserClipboardService extends Disposable implements IClipboardService {
declare readonly _serviceBrand: undefined;
private readonly mapTextToType = new Map<string, string>(); // unsupported in web (only in-memory)
constructor(
@ILayoutService private readonly layoutService: ILayoutService,
@ILogService private readonly logService: ILogService) {
super();
if (isSafari || isWebkitWebView) {
this.installWebKitWriteTextWorkaround();
}
}
private webKitPendingClipboardWritePromise: DeferredPromise<string> | undefined;
// In Safari, it has the following note:
//
// "The request to write to the clipboard must be triggered during a user gesture.
// A call to clipboard.write or clipboard.writeText outside the scope of a user
// gesture(such as "click" or "touch" event handlers) will result in the immediate
// rejection of the promise returned by the API call."
// From: https://webkit.org/blog/10855/async-clipboard-api/
//
// Since extensions run in a web worker, and handle gestures in an asynchronous way,
// they are not classified by Safari as "in response to a user gesture" and will reject.
//
// This function sets up some handlers to work around that behavior.
private installWebKitWriteTextWorkaround(): void {
const handler = () => {
const currentWritePromise = new DeferredPromise<string>();
// Cancel the previous promise since we just created a new one in response to this new event
if (this.webKitPendingClipboardWritePromise && !this.webKitPendingClipboardWritePromise.isSettled) {
this.webKitPendingClipboardWritePromise.cancel();
}
this.webKitPendingClipboardWritePromise = currentWritePromise;
// The ctor of ClipboardItem allows you to pass in a promise that will resolve to a string.
// This allows us to pass in a Promise that will either be cancelled by another event or
// resolved with the contents of the first call to this.writeText.
// see https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem/ClipboardItem#parameters
navigator.clipboard.write([new ClipboardItem({
'text/plain': currentWritePromise.p,
})]).catch(async err => {
if (!(err instanceof Error) || err.name !== 'NotAllowedError' || !currentWritePromise.isRejected) {
this.logService.error(err);
}
});
};
if (this.layoutService.hasContainer) {
this._register(addDisposableListener(this.layoutService.container, 'click', handler));
this._register(addDisposableListener(this.layoutService.container, 'keydown', handler));
}
}
async writeText(text: string, type?: string): Promise<void> {
// With type: only in-memory is supported
if (type) {
this.mapTextToType.set(type, text);
return;
}
if (this.webKitPendingClipboardWritePromise) {
// For Safari, we complete this Promise which allows the call to `navigator.clipboard.write()`
// above to resolve and successfully copy to the clipboard. If we let this continue, Safari
// would throw an error because this call stack doesn't appear to originate from a user gesture.
return this.webKitPendingClipboardWritePromise.complete(text);
}
// Guard access to navigator.clipboard with try/catch
// as we have seen DOMExceptions in certain browsers
// due to security policies.
try {
return await navigator.clipboard.writeText(text);
} catch (error) {
console.error(error);
}
// Fallback to textarea and execCommand solution
const activeElement = document.activeElement;
const textArea: HTMLTextAreaElement = document.body.appendChild($('textarea', { 'aria-hidden': true }));
textArea.style.height = '1px';
textArea.style.width = '1px';
textArea.style.position = 'absolute';
textArea.value = text;
textArea.focus();
textArea.select();
document.execCommand('copy');
if (activeElement instanceof HTMLElement) {
activeElement.focus();
}
document.body.removeChild(textArea);
return;
}
async readText(type?: string): Promise<string> {
// With type: only in-memory is supported
if (type) {
return this.mapTextToType.get(type) || '';
}
// Guard access to navigator.clipboard with try/catch
// as we have seen DOMExceptions in certain browsers
// due to security policies.
try {
return await navigator.clipboard.readText();
} catch (error) {
console.error(error);
return '';
}
}
private findText = ''; // unsupported in web (only in-memory)
async readFindText(): Promise<string> {
return this.findText;
}
async writeFindText(text: string): Promise<void> {
this.findText = text;
}
private resources: URI[] = []; // unsupported in web (only in-memory)
async writeResources(resources: URI[]): Promise<void> {
this.resources = resources;
}
async readResources(): Promise<URI[]> {
return this.resources;
}
async hasResources(): Promise<boolean> {
return this.resources.length > 0;
}
}