/
handler.ts
729 lines (649 loc) · 19.2 KB
/
handler.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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
CodeEditor,
COMPLETER_ACTIVE_CLASS,
COMPLETER_ENABLED_CLASS
} from '@jupyterlab/codeeditor';
import { Text } from '@jupyterlab/coreutils';
import {
CellChange,
FileChange,
ISharedBaseCell,
ISharedFile,
ISharedText,
SourceChange
} from '@jupyter/ydoc';
import { IDataConnector } from '@jupyterlab/statedb';
import { LabIcon } from '@jupyterlab/ui-components';
import { IDisposable } from '@lumino/disposable';
import { Message, MessageLoop } from '@lumino/messaging';
import { ISignal, Signal } from '@lumino/signaling';
import {
CompletionTriggerKind,
IInlineCompletionItem,
IInlineCompletionList,
IInlineCompletionProviderInfo,
InlineCompletionTriggerKind,
IProviderReconciliator
} from './tokens';
import { Completer } from './widget';
import { InlineCompleter } from './inline';
/**
* A completion handler for editors.
*/
export class CompletionHandler implements IDisposable {
/**
* Construct a new completion handler for a widget.
*/
constructor(options: CompletionHandler.IOptions) {
this.completer = options.completer;
this.inlineCompleter = options.inlineCompleter;
this.completer.selected.connect(this.onCompletionSelected, this);
this.completer.visibilityChanged.connect(this.onVisibilityChanged, this);
this._reconciliator = options.reconciliator;
}
/**
* The completer widget managed by the handler.
*/
readonly completer: Completer;
readonly inlineCompleter: InlineCompleter | undefined;
set reconciliator(reconciliator: IProviderReconciliator) {
this._reconciliator = reconciliator;
}
/**
* The editor used by the completion handler.
*/
get editor(): CodeEditor.IEditor | null | undefined {
return this._editor;
}
set editor(newValue: CodeEditor.IEditor | null | undefined) {
if (newValue === this._editor) {
return;
}
let editor = this._editor;
// Clean up and disconnect from old editor.
if (editor && !editor.isDisposed) {
const model = editor.model;
editor.host.classList.remove(COMPLETER_ENABLED_CLASS);
editor.host.classList.remove(COMPLETER_ACTIVE_CLASS);
model.selections.changed.disconnect(this.onSelectionsChanged, this);
model.sharedModel.changed.disconnect(this._onSharedModelChanged, this);
}
// Reset completer state.
this.completer.reset();
this.completer.editor = newValue;
// Update the editor and signal connections.
editor = this._editor = newValue;
if (editor) {
const model = editor.model;
this._enabled = false;
model.selections.changed.connect(this.onSelectionsChanged, this);
// We expect the model to be an editor, a file editor, or a cell.
const sharedModel = model.sharedModel as
| ISharedText
| ISharedFile
| ISharedBaseCell;
// For cells and files the `changed` signal is not limited to text,
// but also fires on changes to metadata, outputs, execution count,
// and state changes, hence we need to filter the change type.
sharedModel.changed.connect(this._onSharedModelChanged, this);
// On initial load, manually check the cursor position.
this.onSelectionsChanged();
if (this.inlineCompleter) {
this.inlineCompleter.editor = editor;
}
}
}
/**
* Get whether the completion handler is disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Enable/disable continuous hinting mode.
*/
set autoCompletion(value: boolean) {
this._autoCompletion = value;
}
get autoCompletion(): boolean {
return this._autoCompletion;
}
/**
* Dispose of the resources used by the handler.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
Signal.clearData(this);
}
/**
* Invoke the inline completer on explicit user request.
*/
invokeInline(): void {
const editor = this._editor;
if (editor) {
this._makeInlineRequest(
editor.getCursorPosition(),
InlineCompletionTriggerKind.Invoke
).catch(reason => {
console.warn('Inline invoke request bailed', reason);
});
}
}
/**
* Invoke the handler and launch a completer.
*/
invoke(): void {
MessageLoop.sendMessage(this, CompletionHandler.Msg.InvokeRequest);
}
/**
* Process a message sent to the completion handler.
*/
processMessage(msg: Message): void {
switch (msg.type) {
case CompletionHandler.Msg.InvokeRequest.type:
this.onInvokeRequest(msg);
break;
default:
break;
}
}
/**
* Get the state of the text editor at the given position.
*/
protected getState(
editor: CodeEditor.IEditor,
position: CodeEditor.IPosition
): Completer.ITextState {
return {
text: editor.model.sharedModel.getSource(),
line: position.line,
column: position.column
};
}
/**
* Handle a completion selected signal from the completion widget.
*/
protected onCompletionSelected(completer: Completer, val: string): void {
const model = completer.model;
const editor = this._editor;
if (!editor || !model) {
return;
}
const patch = model.createPatch(val);
if (!patch) {
return;
}
const { start, end, value } = patch;
const cursorBeforeChange = editor.getOffsetAt(editor.getCursorPosition());
// we need to update the shared model in a single transaction so that the undo manager works as expected
editor.model.sharedModel.updateSource(start, end, value);
if (cursorBeforeChange <= end && cursorBeforeChange >= start) {
editor.setCursorPosition(editor.getPositionAt(start + value.length)!);
}
}
/**
* Handle `invoke-request` messages.
*/
protected onInvokeRequest(msg: Message): void {
// If there is no completer model, bail.
if (!this.completer.model) {
return;
}
// If a completer session is already active, bail.
if (this.completer.model.original) {
return;
}
const editor = this._editor;
if (editor) {
this._makeRequest(
editor.getCursorPosition(),
CompletionTriggerKind.Invoked
).catch(reason => {
console.warn('Invoke request bailed', reason);
});
}
}
/**
* Handle selection changed signal from an editor.
*
* #### Notes
* If a sub-class reimplements this method, then that class must either call
* its super method or it must take responsibility for adding and removing
* the completer completable class to the editor host node.
*
* Despite the fact that the editor widget adds a class whenever there is a
* primary selection, this method checks independently for two reasons:
*
* 1. The editor widget connects to the same signal to add that class, so
* there is no guarantee that the class will be added before this method
* is invoked so simply checking for the CSS class's existence is not an
* option. Secondarily, checking the editor state should be faster than
* querying the DOM in either case.
* 2. Because this method adds a class that indicates whether completer
* functionality ought to be enabled, relying on the behavior of the
* `jp-mod-has-primary-selection` to filter out any editors that have
* a selection means the semantic meaning of `jp-mod-completer-enabled`
* is obscured because there may be cases where the enabled class is added
* even though the completer is not available.
*/
protected onSelectionsChanged(): void {
const model = this.completer.model;
const editor = this._editor;
if (!editor) {
return;
}
const inlineModel = this.inlineCompleter?.model;
if (inlineModel) {
// Dispatch selection change.
inlineModel.handleSelectionChange(editor.getSelection());
}
const host = editor.host;
// If there is no model, return.
if (!model) {
this._enabled = false;
host.classList.remove(COMPLETER_ENABLED_CLASS);
return;
}
// If we are currently performing a subset match,
// return without resetting the completer.
if (model.subsetMatch) {
return;
}
const position = editor.getCursorPosition();
const line = editor.getLine(position.line);
if (!line) {
this._enabled = false;
model.reset(true);
host.classList.remove(COMPLETER_ENABLED_CLASS);
return;
}
const { start, end } = editor.getSelection();
// If there is a text selection, return.
if (start.column !== end.column || start.line !== end.line) {
this._enabled = false;
model.reset(true);
host.classList.remove(COMPLETER_ENABLED_CLASS);
return;
}
// If the part of the line before the cursor is white space, return.
if (line.slice(0, position.column).match(/^\s*$/)) {
this._enabled = false;
model.reset(true);
host.classList.remove(COMPLETER_ENABLED_CLASS);
return;
}
// Enable completion.
if (!this._enabled) {
this._enabled = true;
host.classList.add(COMPLETER_ENABLED_CLASS);
}
// Dispatch the cursor change.
model.handleCursorChange(this.getState(editor, editor.getCursorPosition()));
}
/**
* Handle a text changed signal from an editor.
*/
protected async onTextChanged(
str: ISharedText,
changed: SourceChange
): Promise<void> {
if (!this._enabled) {
return;
}
const model = this.completer.model;
const editor = this.editor;
if (!editor) {
return;
}
if (
model &&
this._autoCompletion &&
this._reconciliator.shouldShowContinuousHint &&
(await this._reconciliator.shouldShowContinuousHint(
this.completer.isVisible,
changed
))
) {
void this._makeRequest(
editor.getCursorPosition(),
CompletionTriggerKind.TriggerCharacter
);
}
const inlineModel = this.inlineCompleter?.model;
if (inlineModel) {
// Dispatch the text change to inline completer
// (this happens before request is sent)
inlineModel.handleTextChange(changed);
if (this._continuousInline) {
void this._makeInlineRequest(
editor.getCursorPosition(),
InlineCompletionTriggerKind.Automatic
);
}
}
if (model) {
// If there is a text selection, no completion is allowed.
const { start, end } = editor.getSelection();
if (start.column !== end.column || start.line !== end.line) {
return;
}
// Dispatch the text change.
model.handleTextChange(this.getState(editor, editor.getCursorPosition()));
}
}
/**
* Handle a visibility change signal from a completer widget.
*/
protected onVisibilityChanged(completer: Completer): void {
// Completer is not active.
if (completer.isDisposed || completer.isHidden) {
if (this._editor) {
this._editor.host.classList.remove(COMPLETER_ACTIVE_CLASS);
this._editor.focus();
}
return;
}
// Completer is active.
if (this._editor) {
this._editor.host.classList.add(COMPLETER_ACTIVE_CLASS);
}
}
/**
* Handle a text shared model change signal from an editor.
*/
private async _onSharedModelChanged(
str: ISharedText,
changed: SourceChange | CellChange | FileChange
): Promise<void> {
if (changed.sourceChange) {
await this.onTextChanged(str, changed);
}
}
/**
* Make a completion request.
*/
private _makeRequest(
position: CodeEditor.IPosition,
trigger: CompletionTriggerKind
): Promise<void> {
const editor = this.editor;
if (!editor) {
return Promise.reject(new Error('No active editor'));
}
const request = this._composeRequest(editor, position);
const state = this.getState(editor, position);
return this._reconciliator
.fetch(request, trigger)
.then(reply => {
if (!reply) {
return;
}
const model = this._updateModel(state, reply.start, reply.end);
if (!model) {
return;
}
if (model.setCompletionItems) {
model.setCompletionItems(reply.items);
}
})
.catch(p => {
/* Fails silently. */
});
}
private async _makeInlineRequest(
position: CodeEditor.IPosition,
trigger: InlineCompletionTriggerKind
) {
const editor = this.editor;
if (!editor) {
return Promise.reject(new Error('No active editor'));
}
if (!this.inlineCompleter) {
return Promise.reject(new Error('No inline completer'));
}
const line = editor.getLine(position.line);
if (typeof line === 'undefined' || position.column < line.length) {
// only auto-trigger on end of line
return;
}
const request = this._composeRequest(editor, position);
const model = this.inlineCompleter.model;
if (!model) {
return;
}
model.cursor = position;
const current = ++this._fetchingInline;
const promises = this._reconciliator.fetchInline(request, trigger);
const completed = new Set<
Promise<IInlineCompletionList<CompletionHandler.IInlineItem> | null>
>();
for (const promise of promises) {
promise
.then(result => {
if (!result || !result.items) {
return;
}
if (current !== this._fetchingInline) {
return;
}
completed.add(promise);
if (completed.size === 1) {
model.setCompletions(result);
} else {
model.appendCompletions(result);
}
})
.catch(e => {
// Emit warning for debugging.
console.warn(e);
})
.finally(() => {
// Mark the provider promise as completed.
completed.add(promise);
// Let the model know that we are awaiting for fewer providers now.
const remaining = promises.length - completed.size;
model.notifyProgress({
pendingProviders: remaining,
totalProviders: promises.length
});
});
}
}
private _fetchingInline = 0;
private _composeRequest(
editor: CodeEditor.IEditor,
position: CodeEditor.IPosition
): CompletionHandler.IRequest {
const text = editor.model.sharedModel.getSource();
const mimeType = editor.model.mimeType;
const offset = Text.jsIndexToCharIndex(editor.getOffsetAt(position), text);
return { text, offset, mimeType };
}
/**
* Updates model with text state and current cursor position.
*/
private _updateModel(
state: Completer.ITextState,
start: number,
end: number
): Completer.IModel | null {
const model = this.completer.model;
const text = state.text;
if (!model) {
return null;
}
// Update the original request.
model.original = state;
// Update the cursor.
model.cursor = {
start: Text.charIndexToJsIndex(start, text),
end: Text.charIndexToJsIndex(end, text)
};
return model;
}
private _reconciliator: IProviderReconciliator;
private _editor: CodeEditor.IEditor | null | undefined = null;
private _enabled = false;
private _isDisposed = false;
private _autoCompletion = false;
private _continuousInline = true;
}
/**
* A namespace for cell completion handler statics.
*/
export namespace CompletionHandler {
/**
* The instantiation options for cell completion handlers.
*/
export interface IOptions {
/**
* The completion widget the handler will connect to.
*/
completer: Completer;
/**
* The inline completer widget; when absent inline completion is disabled.
*/
inlineCompleter?: InlineCompleter;
/**
* The reconciliator that will fetch and merge completions from active providers.
*/
reconciliator: IProviderReconciliator;
}
/**
* Type alias for ICompletionItem list.
* Implementers of this interface should be responsible for
* deduping and sorting the items in the list.
*/
export type ICompletionItems = ReadonlyArray<ICompletionItem>;
/**
* Completion item object based off of LSP CompletionItem.
* Compared to the old kernel completions interface, this enhances the completions UI to support:
* - differentiation between inserted text and user facing text
* - documentation for each completion item to be displayed adjacently
* - deprecation styling
* - custom icons
* and other potential new features.
*/
export interface ICompletionItem {
/**
* User facing completion.
* If insertText is not set, this will be inserted.
*/
label: string;
/**
* Completion to be inserted.
*/
insertText?: string;
/**
* Type of this completion item.
*/
type?: string;
/**
* LabIcon object for icon to be rendered with completion type.
*/
icon?: LabIcon;
/**
* A human-readable string with additional information
* about this item, like type or symbol information.
*/
documentation?: string;
/**
* Indicates if the item is deprecated.
*/
deprecated?: boolean;
/**
* Method allowing to update fields asynchronously.
*/
resolve?: (
patch?: Completer.IPatch
) => Promise<CompletionHandler.ICompletionItem>;
}
/**
* Connector for completion items.
*
* @deprecated since v4 to add a new source of completions, register a completion provider;
* to customise how completions get merged, provide a custom reconciliator.
*/
export type ICompletionItemsConnector = IDataConnector<
CompletionHandler.ICompletionItemsReply,
void,
CompletionHandler.IRequest
>;
/**
* A reply to a completion items fetch request.
*/
export interface ICompletionItemsReply<
T extends
CompletionHandler.ICompletionItem = CompletionHandler.ICompletionItem
> {
/**
* The starting index for the substring being replaced by completion.
*/
start: number;
/**
* The end index for the substring being replaced by completion.
*/
end: number;
/**
* A list of completion items. default to CompletionHandler.ICompletionItems
*/
items: Array<T>;
}
/**
* Stream event type.
*/
export enum StraemEvent {
opened,
update,
closed
}
export interface IInlineItem extends IInlineCompletionItem {
/**
* The source provider information.
*/
provider: IInlineCompletionProviderInfo;
/**
* Signal emitted when the item gets updated by streaming.
*/
stream: ISignal<IInlineItem, StraemEvent>;
/**
* Most recent streamed token if any.
*/
lastStreamed?: string;
/**
* Whether streaming is in progress.
*/
streaming: boolean;
}
/**
* The details of a completion request.
*/
export interface IRequest {
/**
* The cursor offset position within the text being completed.
*/
offset: number;
/**
* The text being completed.
*/
text: string;
/**
* The MIME type under the cursor.
*/
mimeType?: string;
}
/**
* A namespace for completion handler messages.
*/
export namespace Msg {
/**
* A singleton `'invoke-request'` message.
*/
export const InvokeRequest = new Message('invoke-request');
}
}