-
Notifications
You must be signed in to change notification settings - Fork 20
/
codemirror-adapter.ts
570 lines (491 loc) · 18 KB
/
codemirror-adapter.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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/// <reference types="@types/codemirror" />
/// <reference types="@types/codemirror/codemirror-showhint" />
import debounce from 'lodash-es/debounce';
import * as lsProtocol from 'vscode-languageserver-protocol';
import { Location, LocationLink, MarkupContent } from 'vscode-languageserver-protocol';
import { getFilledDefaults, IEditorAdapter, ILspConnection, IPosition, ITextEditorOptions, ITokenInfo } from './types';
interface IScreenCoord {
x: number;
y: number;
}
class CodeMirrorAdapter extends IEditorAdapter<CodeMirror.Editor> {
public options: ITextEditorOptions;
public editor: CodeMirror.Editor;
public connection: ILspConnection;
private hoverMarker: CodeMirror.TextMarker;
private signatureWidget: CodeMirror.LineWidget;
private token: ITokenInfo;
private markedDiagnostics: CodeMirror.TextMarker[] = [];
private highlightMarkers: CodeMirror.TextMarker[] = [];
private hoverCharacter: IPosition;
private debouncedGetHover: (position: IPosition) => void;
private connectionListeners: { [key: string]: () => void } = {};
private editorListeners: { [key: string]: () => void } = {};
private documentListeners: { [key: string]: () => void } = {};
private tooltip: HTMLElement;
private isShowingContextMenu: boolean = false;
constructor(connection: ILspConnection, options: ITextEditorOptions, editor: CodeMirror.Editor) {
super(connection, options, editor);
this.connection = connection;
this.options = getFilledDefaults(options);
this.editor = editor;
this.debouncedGetHover = debounce((position: IPosition) => {
this.connection.getHoverTooltip(position);
}, this.options.quickSuggestionsDelay);
this._addListeners();
}
public handleMouseOver(ev: MouseEvent) {
if (this.isShowingContextMenu || !this._isEventInsideVisible(ev) || !this._isEventOnCharacter(ev)) {
return;
}
const docPosition: IPosition = this.editor.coordsChar({
left: ev.clientX,
top: ev.clientY,
}, 'window');
if (
!(this.hoverCharacter &&
docPosition.line === this.hoverCharacter.line && docPosition.ch === this.hoverCharacter.ch)
) {
// Avoid sending duplicate requests in a row
this.hoverCharacter = docPosition;
this.debouncedGetHover(docPosition);
}
}
public handleChange(cm: CodeMirror.Editor, change: CodeMirror.EditorChange) {
const location = this.editor.getDoc().getCursor('end');
this.connection.sendChange();
const completionCharacters = this.connection.getLanguageCompletionCharacters();
const signatureCharacters = this.connection.getLanguageSignatureCharacters();
const code = this.editor.getDoc().getValue();
const lines = code.split('\n');
const line = lines[location.line];
const typedCharacter = line[location.ch - 1];
if (typeof typedCharacter === 'undefined') {
// Line was cleared
this._removeSignatureWidget();
} else if (completionCharacters.indexOf(typedCharacter) > -1) {
this.token = this._getTokenEndingAtPosition(code, location, completionCharacters);
this.connection.getCompletion(
location,
this.token,
completionCharacters.find((c) => c === typedCharacter),
lsProtocol.CompletionTriggerKind.TriggerCharacter,
);
} else if (signatureCharacters.indexOf(typedCharacter) > -1) {
this.token = this._getTokenEndingAtPosition(code, location, signatureCharacters);
this.connection.getSignatureHelp(location);
} else if (!/\W/.test(typedCharacter)) {
this.connection.getCompletion(
location,
this.token,
'',
lsProtocol.CompletionTriggerKind.Invoked,
);
this.token = this._getTokenEndingAtPosition(code, location, completionCharacters.concat(signatureCharacters));
} else {
this._removeSignatureWidget();
}
}
public handleHover(response: lsProtocol.Hover) {
this._removeHover();
this._removeTooltip();
if (!response || !response.contents || (Array.isArray(response.contents) && response.contents.length === 0)) {
return;
}
let start = this.hoverCharacter;
let end = this.hoverCharacter;
if (response.range) {
start = {
line: response.range.start.line,
ch: response.range.start.character,
} as CodeMirror.Position;
end = {
line: response.range.end.line,
ch: response.range.end.character,
} as CodeMirror.Position;
this.hoverMarker = this.editor.getDoc().markText(start, end, {
css: 'text-decoration: underline',
});
}
let tooltipText;
if (MarkupContent.is(response.contents)) {
tooltipText = response.contents.value;
} else if (Array.isArray(response.contents)) {
const firstItem = response.contents[0];
if (MarkupContent.is(firstItem)) {
tooltipText = firstItem.value;
} else if (firstItem === null) {
return;
} else if (typeof firstItem === 'object') {
tooltipText = firstItem.value;
} else {
tooltipText = firstItem;
}
} else if (typeof response.contents === 'string') {
tooltipText = response.contents;
}
const htmlElement = document.createElement('div');
htmlElement.innerText = tooltipText;
const coords = this.editor.charCoords(start, 'page');
this._showTooltip(htmlElement, {
x: coords.left,
y: coords.top,
});
}
public handleHighlight(items: lsProtocol.DocumentHighlight[]) {
this._highlightRanges((items || []).map((i) => i.range));
}
public handleCompletion(completions: lsProtocol.CompletionItem[]): void {
if (!this.token) {
return;
}
const bestCompletions = this._getFilteredCompletions(this.token.text, completions);
let start = this.token.start;
if (/^\W$/.test(this.token.text)) {
// Special case for completion on the completion trigger itself, the completion goes after
start = this.token.end;
}
this.editor.showHint({
completeSingle: false,
hint: () => {
return {
from: start,
to: this.token.end,
list: bestCompletions.map((completion) => completion.label),
};
},
} as CodeMirror.ShowHintOptions);
}
public handleDiagnostic(response: lsProtocol.PublishDiagnosticsParams) {
this.editor.clearGutter('CodeMirror-lsp');
this.markedDiagnostics.forEach((marker) => {
marker.clear();
});
this.markedDiagnostics = [];
response.diagnostics.forEach((diagnostic: lsProtocol.Diagnostic) => {
const start = {
line: diagnostic.range.start.line,
ch: diagnostic.range.start.character,
} as CodeMirror.Position;
const end = {
line: diagnostic.range.end.line,
ch: diagnostic.range.end.character,
} as CodeMirror.Position;
this.markedDiagnostics.push(this.editor.getDoc().markText(start, end, {
title: diagnostic.message,
className: 'cm-error',
}));
const childEl = document.createElement('div');
childEl.classList.add('CodeMirror-lsp-guttermarker');
childEl.title = diagnostic.message;
this.editor.setGutterMarker(start.line, 'CodeMirror-lsp', childEl);
});
}
public handleSignature(result: lsProtocol.SignatureHelp) {
this._removeSignatureWidget();
this._removeTooltip();
if (!result || !result.signatures.length || !this.token) {
return;
}
const htmlElement = document.createElement('div');
result.signatures.forEach((item: lsProtocol.SignatureInformation) => {
const el = document.createElement('div');
el.innerText = item.label;
htmlElement.appendChild(el);
});
const coords = this.editor.charCoords(this.token.start, 'page');
this._showTooltip(htmlElement, {
x: coords.left,
y: coords.top,
});
}
public handleGoTo(location: Location | Location[] | LocationLink[] | null) {
this._removeTooltip();
if (!location) {
return;
}
const documentUri = this.connection.getDocumentUri();
let scrollTo: IPosition;
if (lsProtocol.Location.is(location)) {
if (location.uri !== documentUri) {
return;
}
this._highlightRanges([location.range]);
scrollTo = {
line: location.range.start.line,
ch: location.range.start.character,
};
} else if ((location as any[]).every((l) => lsProtocol.Location.is(l))) {
const locations = (location as Location[]).filter((l) => l.uri === documentUri);
this._highlightRanges(locations.map((l) => l.range));
scrollTo = {
line: locations[0].range.start.line,
ch: locations[0].range.start.character,
};
} else if ((location as any[]).every((l) => lsProtocol.LocationLink.is(l))) {
const locations = (location as LocationLink[]).filter((l) => l.targetUri === documentUri);
this._highlightRanges(locations.map((l) => l.targetRange));
scrollTo = {
line: locations[0].targetRange.start.line,
ch: locations[0].targetRange.start.character,
};
}
this.editor.scrollIntoView(scrollTo);
}
public remove() {
this._removeSignatureWidget();
this._removeHover();
this._removeTooltip();
// Show-hint addon doesn't remove itself. This could remove other uses in the project
document.querySelectorAll('.CodeMirror-hints').forEach((e) => e.remove());
this.editor.off('change', this.editorListeners.change);
this.editor.off('cursorActivity', this.editorListeners.cursorActivity);
this.editor.off('cursorActivity', this.editorListeners.cursorActivity);
this.editor.getWrapperElement().removeEventListener('mousemove', this.editorListeners.mouseover);
this.editor.getWrapperElement().removeEventListener('contextmenu', this.editorListeners.contextmenu);
Object.keys(this.connectionListeners).forEach((key) => {
this.connection.off(key as any, this.connectionListeners[key]);
});
Object.keys(this.documentListeners).forEach((key) => {
document.removeEventListener(key as any, this.documentListeners[key]);
});
}
private _addListeners() {
const changeListener = debounce(this.handleChange.bind(this), this.options.debounceSuggestionsWhileTyping);
this.editor.on('change', changeListener);
this.editorListeners.change = changeListener;
const self = this;
this.connectionListeners = {
hover: this.handleHover.bind(self),
highlight: this.handleHighlight.bind(self),
completion: this.handleCompletion.bind(self),
signature: this.handleSignature.bind(self),
diagnostic: this.handleDiagnostic.bind(self),
goTo: this.handleGoTo.bind(self),
};
Object.keys(this.connectionListeners).forEach((key) => {
this.connection.on(key as any, this.connectionListeners[key]);
});
const mouseOverListener = this.handleMouseOver.bind(this);
this.editor.getWrapperElement().addEventListener('mousemove', mouseOverListener);
this.editorListeners.mouseover = mouseOverListener;
const debouncedCursor = debounce(() => {
this.connection.getDocumentHighlights(this.editor.getDoc().getCursor('start'));
}, this.options.quickSuggestionsDelay);
const rightClickHandler = this._handleRightClick.bind(this);
this.editor.getWrapperElement().addEventListener('contextmenu', rightClickHandler);
this.editorListeners.contextmenu = rightClickHandler;
this.editor.on('cursorActivity', debouncedCursor);
this.editorListeners.cursorActivity = debouncedCursor;
const clickOutsideListener = this._handleClickOutside.bind(this);
document.addEventListener('click', clickOutsideListener);
this.documentListeners.clickOutside = clickOutsideListener;
}
private _getTokenEndingAtPosition(code: string, location: IPosition, splitCharacters: string[]): ITokenInfo {
const lines = code.split('\n');
const line = lines[location.line];
const typedCharacter = line[location.ch - 1];
if (splitCharacters.indexOf(typedCharacter) > -1) {
return {
text: typedCharacter,
start: {
line: location.line,
ch: location.ch - 1,
},
end: location,
};
}
let wordStartChar = 0;
for (let i = location.ch - 1; i >= 0; i--) {
const char = line[i];
if (/\W/u.test(char)) {
break;
}
wordStartChar = i;
}
return {
text: line.substr(wordStartChar, location.ch),
start: {
line: location.line,
ch: wordStartChar,
},
end: location,
};
}
private _getFilteredCompletions(
triggerWord: string,
items: lsProtocol.CompletionItem[],
): lsProtocol.CompletionItem[] {
if (/\W+/.test(triggerWord)) {
return items;
}
const word = triggerWord.toLowerCase();
return items.filter((item: lsProtocol.CompletionItem) => {
if (item.filterText && item.filterText.toLowerCase().indexOf(word) === 0) {
return true;
} else {
return item.label.toLowerCase().indexOf(word) === 0;
}
}).sort((a: lsProtocol.CompletionItem, b: lsProtocol.CompletionItem) => {
const inA = (a.label.indexOf(triggerWord) === 0) ? -1 : 1;
const inB = b.label.indexOf(triggerWord) === 0 ? 1 : -1;
return inA + inB;
});
}
private _isEventInsideVisible(ev: MouseEvent) {
// Only handle mouseovers inside CodeMirror's bounding box
let isInsideSizer = false;
let target: HTMLElement = ev.target as HTMLElement;
while (target !== document.body) {
if (target.classList.contains('CodeMirror-sizer')) {
isInsideSizer = true;
break;
}
target = target.parentElement;
}
return isInsideSizer;
}
private _isEventOnCharacter(ev: MouseEvent) {
const docPosition: IPosition = this.editor.coordsChar({
left: ev.clientX,
top: ev.clientY,
}, 'window');
const token = this.editor.getTokenAt(docPosition);
const hasToken = !!token.string.length;
return hasToken;
}
private _handleRightClick(ev: MouseEvent) {
if (!this._isEventInsideVisible(ev) || !this._isEventOnCharacter(ev)) {
return;
}
if (
!this.connection.isDefinitionSupported() &&
!this.connection.isTypeDefinitionSupported() &&
!this.connection.isReferencesSupported() &&
!this.connection.isImplementationSupported()
) {
return;
}
ev.preventDefault();
const docPosition: IPosition = this.editor.coordsChar({
left: ev.clientX,
top: ev.clientY,
}, 'window');
const htmlElement = document.createElement('div');
htmlElement.classList.add('CodeMirror-lsp-context');
if (this.connection.isDefinitionSupported()) {
const goToDefinition = document.createElement('div');
goToDefinition.innerText = 'Go to Definition';
goToDefinition.addEventListener('click', () => {
this.connection.getDefinition(docPosition);
});
htmlElement.appendChild(goToDefinition);
}
if (this.connection.isTypeDefinitionSupported()) {
const goToTypeDefinition = document.createElement('div');
goToTypeDefinition.innerText = 'Go to Type Definition';
goToTypeDefinition.addEventListener('click', () => {
this.connection.getTypeDefinition(docPosition);
});
htmlElement.appendChild(goToTypeDefinition);
}
if (this.connection.isReferencesSupported()) {
const getReferences = document.createElement('div');
getReferences.innerText = 'Find all References';
getReferences.addEventListener('click', () => {
this.connection.getReferences(docPosition);
});
htmlElement.appendChild(getReferences);
}
const coords = this.editor.charCoords(docPosition, 'page');
this._showTooltip(htmlElement, {
x: coords.left,
y: coords.bottom + this.editor.defaultTextHeight(),
});
this.isShowingContextMenu = true;
}
private _handleClickOutside(ev: MouseEvent) {
if (this.isShowingContextMenu) {
let target: HTMLElement = ev.target as HTMLElement;
let isInside = false;
while (target !== document.body) {
if (target.classList.contains('CodeMirror-lsp-tooltip')) {
isInside = true;
break;
}
target = target.parentElement;
}
if (isInside) {
return;
}
// Only remove tooltip if clicked outside right click
this._removeTooltip();
}
}
private _showTooltip(el: HTMLElement, coords: IScreenCoord) {
if (this.isShowingContextMenu) {
return;
}
this._removeTooltip();
let top = coords.y - this.editor.defaultTextHeight();
this.tooltip = document.createElement('div');
this.tooltip.classList.add('CodeMirror-lsp-tooltip');
this.tooltip.style.left = `${coords.x}px`;
this.tooltip.style.top = `${top}px`;
this.tooltip.appendChild(el);
document.body.appendChild(this.tooltip);
// Measure and reposition after rendering first version
requestAnimationFrame(() => {
top += this.editor.defaultTextHeight();
top -= this.tooltip.offsetHeight;
this.tooltip.style.left = `${coords.x}px`;
this.tooltip.style.top = `${top}px`;
});
}
private _removeTooltip() {
if (this.tooltip) {
this.isShowingContextMenu = false;
this.tooltip.remove();
}
}
private _removeSignatureWidget() {
if (this.signatureWidget) {
this.signatureWidget.clear();
this.signatureWidget = null;
}
if (this.tooltip) {
this._removeTooltip();
}
}
private _removeHover() {
if (this.hoverMarker) {
this.hoverMarker.clear();
this.hoverMarker = null;
}
}
private _highlightRanges(items: lsProtocol.Range[]) {
if (this.highlightMarkers) {
this.highlightMarkers.forEach((marker) => {
marker.clear();
});
}
this.highlightMarkers = [];
if (!items.length) {
return;
}
items.forEach((item) => {
const start = {
line: item.start.line,
ch: item.start.character,
} as CodeMirror.Position;
const end = {
line: item.end.line,
ch: item.end.character,
} as CodeMirror.Position;
this.highlightMarkers.push(this.editor.getDoc().markText(start, end, {
css: 'background-color: #dde',
}));
});
}
}
export default CodeMirrorAdapter;