-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
ghost-text.js
335 lines (284 loc) 路 8.83 KB
/
ghost-text.js
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import GThumane from './humane-ghosttext.js';
import unsafeMessenger from './unsafe-messenger.js';
import optionsStorage from './options-storage.js';
const knownElements = new Map();
const activeFields = new Set();
const eventOptions = {bubbles: true};
const optionsPromise = optionsStorage.getAll();
let isWaitingForActivation = false;
const startTimeout = 15_000;
let timeoutHandle;
class ContentEditableWrapper {
constructor(element) {
this.el = element;
this.dataset = element.dataset;
this.addEventListener = element.addEventListener.bind(element);
this.removeEventListener = element.removeEventListener.bind(element);
this.dispatchEvent = element.dispatchEvent.bind(element);
}
get value() {
return this.el.innerHTML;
}
set value(html) {
this.el.innerHTML = html;
}
}
class AdvancedTextWrapper {
constructor(element, visualElement) {
this.el = element;
this.dataset = visualElement.dataset;
this.el.addEventListener('gt:input', event => {
this._value = event.detail.value;
});
this.el.dispatchEvent(
new CustomEvent('gt:get', {
bubbles: true,
}),
);
}
addEventListener(type, callback) {
this.el.addEventListener(`gt:${type}`, callback);
}
removeEventListener(type, callback) {
this.el.removeEventListener(`gt:${type}`, callback);
}
get value() {
return this._value;
}
set value(value) {
if (this._value !== value) {
this._value = value;
this.el.setAttribute('gt-value', value);
this.el.dispatchEvent(new CustomEvent('gt:transfer'));
}
}
}
function wrapField(field) {
const monaco = field.closest('.monaco-editor');
if (monaco) {
const visualElement = monaco.querySelector('.monaco-editor-background');
return new AdvancedTextWrapper(monaco, visualElement);
}
if (field.classList.contains('ace_text-input')) {
const ace = field.parentNode;
const visualElement = ace.querySelector('.ace_scroller');
return new AdvancedTextWrapper(ace, visualElement);
}
// If `field` is inside CodeMirror widget, it should be handled independently of it
const cm = field.closest('.CodeMirror, .CodeMirror-linewidget');
if (cm && cm.matches('.CodeMirror')) {
const visualElement = cm.querySelector('.CodeMirror-sizer');
return new AdvancedTextWrapper(cm, visualElement);
}
if (field.isContentEditable) {
return new ContentEditableWrapper(field);
}
return field;
}
class GhostTextField {
constructor(field) {
this.field = wrapField(field);
this.field.dataset.gtField = '';
this.send = this.send.bind(this);
this.receive = this.receive.bind(this);
this.deactivate = this.deactivate.bind(this);
this.tryFocus = this.tryFocus.bind(this);
field.addEventListener('focus', this.tryFocus);
this.state = 'inactive';
}
async activate() {
if (this.state === 'active') {
return;
}
this.state = 'active';
activeFields.add(this);
this.field.dataset.gtField = 'loading';
this.port = chrome.runtime.connect({name: 'new-field'});
this.port.onMessage.addListener(async message => {
if (message.message) {
this.receive({data: message.message});
} else if (message.close) {
this.deactivate(false);
updateCount();
} else if (message.ready) {
const options = await optionsPromise;
if (options.notifyOnConnect) {
notify('log', 'Connected! You can switch to your editor');
}
this.field.addEventListener('input', this.send);
this.field.dataset.gtField = 'enabled';
// Send first value to init tab
this.send();
updateCount();
} else if (message.error) {
notify('warn', message.error);
this.deactivate(false);
}
});
}
send(event) {
if (event && event.detail?.ghostTextSyntheticEvent) {
return;
}
console.info('sending', this.field.value.length, 'characters');
this.port.postMessage(
JSON.stringify({
title: document.title, // TODO: move to first fetch
url: location.host, // TODO: move to first fetch
syntax: '', // TODO: move to first fetch
text: this.field.value,
selections: [
{
start: this.field.selectionStart || 0,
end: this.field.selectionEnd || 0,
},
],
}),
);
}
receive(event) {
const {text, selections} = JSON.parse(event.data);
if (this.field.value !== text) {
this.field.value = text;
if (this.field.dispatchEvent) {
// These are in the right order
this.field.dispatchEvent(new KeyboardEvent('keydown'), eventOptions);
this.field.dispatchEvent(new KeyboardEvent('keypress'), eventOptions);
this.field.dispatchEvent(new CompositionEvent('textInput'), eventOptions);
this.field.dispatchEvent(new CustomEvent('input', { // InputEvent doesn't support custom data
...eventOptions,
detail: {
ghostTextSyntheticEvent: true,
},
}));
this.field.dispatchEvent(new KeyboardEvent('keyup'), eventOptions);
}
}
if (selections && typeof selections[0] === 'object') {
this.field.selectionStart = selections[0].start;
this.field.selectionEnd = selections[0].end;
} else {
console.warn('GhostText for your editor is not sending the selections. Open an issue on its repository');
}
}
async deactivate(wasSuccessful = true) {
if (this.state === 'inactive') {
return;
}
this.state = 'inactive';
console.log('Disabling field');
activeFields.delete(this);
this.port.disconnect();
this.field.removeEventListener('input', this.send);
this.field.dataset.gtField = '';
const options = await optionsPromise;
if (options.focusOnDisconnect) {
chrome.runtime.sendMessage({
code: 'focus-tab',
});
}
if (wasSuccessful) {
updateCount();
}
}
tryFocus() {
if (isWaitingForActivation && this.state === 'inactive') {
clearTimeout(timeoutHandle);
this.activate();
isWaitingForActivation = false;
document.body.classList.remove('GT--waiting');
}
}
static deactivateAll() {
for (const field of activeFields) {
field.deactivate();
}
}
}
async function updateCount() {
chrome.runtime.sendMessage({
code: 'connection-count',
count: activeFields.size,
});
if (activeFields.size === 0) {
const options = await optionsPromise;
if (options.notifyOnConnect) {
notify('log', 'Disconnected! \n <a href="https://github.com/fregante/GhostText/issues" target="_blank">Report issues</a>');
}
}
}
const selector = `
textarea,
[contenteditable=""],
[contenteditable="true"]
`;
function registerElements() {
for (const element of document.querySelectorAll(selector)) {
// TODO: Only handle areas that are visible
// && element.getBoundingClientRect().width > 20
if (!knownElements.has(element)) {
knownElements.set(element, new GhostTextField(element));
}
}
}
function getMessageDisplayTime(message) {
const wpm = 100; // 180 is the average words read per minute, make it slower
return message.split(' ').length / wpm * 60_000;
}
function notify(type, message, timeout = getMessageDisplayTime(message)) {
console[type]('GhostText:', message);
GThumane.remove();
message = message.replace(/\n/g, '<br>');
const notification = GThumane.log(message, {
timeout,
addnCls: type === 'log' ? '' : 'ghost-text-message-error',
});
document.addEventListener('click', () => notification.remove(), {once: true});
}
function startGT() {
clearTimeout(timeoutHandle);
registerElements();
console.info(knownElements.size + ' fields on the page');
if (knownElements.size === 0) {
notify('warn', 'No supported fields found. <a href="https://ghosttext.fregante.com/troubleshooting/#no-supported-fields">Need help?</a>');
return;
}
if (knownElements.size === activeFields.size) {
notify('log', 'All the fields on the page are active. Right-click the GhostText icon if you want to stop the connection');
return;
}
// Automatically activate the focused field, unless it's already is active
const focusedField = knownElements.get(document.activeElement);
if (focusedField && !activeFields.has(focusedField)) {
focusedField.activate();
return;
}
// Automatically activate the only inactive field on the page
const inactiveFields = [...knownElements.values()].filter(field => !activeFields.has(field));
if (inactiveFields.length === 1 && !document.querySelector('iframe')) {
inactiveFields[0].activate();
return;
}
isWaitingForActivation = true;
document.body.classList.add('GT--waiting');
if (activeFields.size === 0) {
notify('log', 'Click on the desired element to activate it.', startTimeout);
} else {
notify('log', 'Click on the desired element to activate it or right-click the GhostText icon to stop the connection.', startTimeout);
}
clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(stopGT, startTimeout);
}
function stopGT() {
GhostTextField.deactivateAll();
isWaitingForActivation = false;
document.body.classList.remove('GT--waiting');
}
function init() {
const script = document.createElement('script');
script.textContent = '(' + unsafeMessenger.toString() + ')()';
document.head.append(script);
}
window.startGT = startGT;
window.stopGT = stopGT;
init();