-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
widget.ts
1466 lines (1305 loc) · 41.7 KB
/
widget.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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { Sanitizer } from '@jupyterlab/apputils';
import { CodeEditor } from '@jupyterlab/codeeditor';
import { IRenderMime, renderText } from '@jupyterlab/rendermime';
import { HoverBox, LabIcon } from '@jupyterlab/ui-components';
import { JSONObject } from '@lumino/coreutils';
import { IDisposable } from '@lumino/disposable';
import { ElementExt } from '@lumino/domutils';
import { Message } from '@lumino/messaging';
import { ISignal, Signal } from '@lumino/signaling';
import { Widget } from '@lumino/widgets';
import { CompletionHandler } from './handler';
/**
* The class name added to completer menu items.
*/
const ITEM_CLASS = 'jp-Completer-item';
/**
* The class name added to an active completer menu item.
*/
const ACTIVE_CLASS = 'jp-mod-active';
/**
* The class used by item listing which determines the height of the completer.
*/
const LIST_CLASS = 'jp-Completer-list';
/**
* Class of the documentation panel.
*/
const DOC_PANEL_CLASS = 'jp-Completer-docpanel';
/**
* A flag to indicate that event handlers are caught in the capture phase.
*/
const USE_CAPTURE = true;
/**
* The number of colors defined for the completer type annotations.
* These are listed in completer/style/index.css#102-152.
*/
const N_COLORS = 10;
/**
* A widget that enables text completion.
*
* #### Notes
* The completer is intended to be absolutely positioned on the
* page and hover over any other content, so it should be attached directly
* to `document.body`, or a node that is the full size of `document.body`.
* Attaching it to other nodes may incorrectly locate the completer.
*/
export class Completer extends Widget {
/**
* Construct a text completer menu widget.
*/
constructor(options: Completer.IOptions) {
super({ node: document.createElement('div') });
this.sanitizer = options.sanitizer ?? new Sanitizer();
this._defaultRenderer = Completer.getDefaultRenderer(this.sanitizer);
this._renderer = options.renderer ?? this._defaultRenderer;
this._docPanel = this._createDocPanelNode();
this.model = options.model ?? null;
this.editor = options.editor ?? null;
this.addClass('jp-Completer');
this._updateConstraints();
}
/**
* Cache style constraints from CSS.
*/
protected _updateConstraints() {
const tempNode = document.createElement('div');
tempNode.classList.add(LIST_CLASS);
tempNode.style.visibility = 'hidden';
tempNode.style.overflowY = 'scroll';
document.body.appendChild(tempNode);
const computedStyle = window.getComputedStyle(tempNode);
this._maxHeight = parseInt(computedStyle.maxHeight, 10);
this._minHeight = parseInt(computedStyle.minHeight, 10);
this._scrollbarWidth = tempNode.offsetWidth - tempNode.clientWidth;
document.body.removeChild(tempNode);
const tempDocPanel = this._createDocPanelNode();
this._docPanelWidth = Private.measureSize(
tempDocPanel,
'inline-block'
).width;
}
/**
* The sanitizer used to sanitize untrusted HTML inputs.
*/
readonly sanitizer: IRenderMime.ISanitizer;
/**
* The active index.
*/
get activeIndex(): number {
return this._activeIndex;
}
/**
* The editor used by the completion widget.
*/
get editor(): CodeEditor.IEditor | null | undefined {
return this._editor;
}
set editor(newValue: CodeEditor.IEditor | null | undefined) {
this._editor = newValue;
}
/**
* A signal emitted when a selection is made from the completer menu.
*/
get selected(): ISignal<this, string> {
return this._selected;
}
/**
* A signal emitted when the completer widget's visibility changes.
*
* #### Notes
* This signal is useful when there are multiple floating widgets that may
* contend with the same space and ought to be mutually exclusive.
*/
get visibilityChanged(): ISignal<this, void> {
return this._visibilityChanged;
}
/**
* A signal emitted when the active index changes.
*/
get indexChanged(): ISignal<this, number> {
return this._indexChanged;
}
/**
* The model used by the completer widget.
*/
get model(): Completer.IModel | null {
return this._model;
}
set model(model: Completer.IModel | null) {
if ((!model && !this._model) || model === this._model) {
return;
}
if (this._model) {
this._model.stateChanged.disconnect(this.onModelStateChanged, this);
this._model.queryChanged.disconnect(this.onModelQueryChanged, this);
}
this._model = model;
if (this._model) {
this._model.stateChanged.connect(this.onModelStateChanged, this);
this._model.queryChanged.connect(this.onModelQueryChanged, this);
}
}
/**
* The completer used by the completer widget.
*/
get renderer(): Completer.IRenderer {
return this._renderer;
}
set renderer(renderer: Completer.IRenderer) {
this._renderer = renderer;
}
/**
* Enable/disable the document panel.
*/
set showDocsPanel(showDoc: boolean) {
this._showDoc = showDoc;
}
get showDocsPanel(): boolean {
return this._showDoc;
}
/**
* Dispose of the resources held by the completer widget.
*/
dispose(): void {
this._sizeCache = undefined;
this._model = null;
super.dispose();
}
/**
* Handle the DOM events for the widget.
*
* @param event - The DOM event sent to the widget.
*
* #### Notes
* This method implements the DOM `EventListener` interface and is
* called in response to events on the dock panel's node. It should
* not be called directly by user code.
*/
handleEvent(event: Event): void {
if (this.isHidden || !this._editor) {
return;
}
switch (event.type) {
case 'keydown':
this._evtKeydown(event as KeyboardEvent);
break;
case 'pointerdown':
this._evtPointerdown(event as PointerEvent);
break;
case 'scroll':
this._evtScroll(event as MouseEvent);
break;
default:
break;
}
}
/**
* Reset the widget.
*/
reset(): void {
this._activeIndex = 0;
this._lastSubsetMatch = '';
if (this._model) {
this._model.reset(true);
}
this._docPanel.style.display = 'none';
// Clear size cache.
this._sizeCache = undefined;
this.node.scrollTop = 0;
}
/**
* Emit the selected signal for the current active item and reset.
*/
selectActive(): void {
const active = this.node.querySelector(`.${ACTIVE_CLASS}`) as HTMLElement;
if (!active) {
this.reset();
return;
}
this._selected.emit(active.getAttribute('data-value') as string);
this.reset();
}
/**
* Handle `after-attach` messages for the widget.
*/
protected onAfterAttach(msg: Message): void {
document.addEventListener('keydown', this, USE_CAPTURE);
document.addEventListener('pointerdown', this, USE_CAPTURE);
document.addEventListener('scroll', this, USE_CAPTURE);
}
/**
* Handle `before-detach` messages for the widget.
*/
protected onBeforeDetach(msg: Message): void {
document.removeEventListener('keydown', this, USE_CAPTURE);
document.removeEventListener('pointerdown', this, USE_CAPTURE);
document.removeEventListener('scroll', this, USE_CAPTURE);
}
/**
* Handle model state changes.
*/
protected onModelStateChanged(): void {
if (this.isAttached) {
this._activeIndex = 0;
this._indexChanged.emit(this._activeIndex);
this.update();
}
}
/**
* Handle model query changes.
*/
protected onModelQueryChanged(
model: Completer.IModel,
queryChange: Completer.IQueryChange
): void {
// If query was changed by the user typing, the filtered down items
// may no longer reach/exceed the maxHeight of the completer widget,
// hence size needs to be recalculated.
if (this._sizeCache && queryChange.origin === 'editorUpdate') {
const newItems = model.completionItems();
const oldItems = this._sizeCache.items;
// Only reset size if the number of items changed, or the longest item changed.
const oldWidest = oldItems[this._findWidestItemIndex(oldItems)];
const newWidest = newItems[this._findWidestItemIndex(newItems)];
const heuristic = this._getPreferredItemWidthHeuristic();
if (
newItems.length !== this._sizeCache.items.length ||
heuristic(oldWidest) !== heuristic(newWidest)
) {
this._sizeCache = undefined;
}
}
}
/**
* Handle `update-request` messages.
*/
protected onUpdateRequest(msg: Message): void {
const model = this._model;
if (!model) {
return;
}
// If this is the first time the current completer session has loaded,
// populate any initial subset match. This is being done before node
// gets rendered to avoid rendering it twice.
if (!model.query) {
this._populateSubset();
}
let items = model.completionItems();
// If there are no items, reset and bail.
if (!items.length) {
if (!this.isHidden) {
this.reset();
this.hide();
this._visibilityChanged.emit(undefined);
}
return;
}
// Update constraints before any DOM modifications
this._updateConstraints();
// Do not trigger any geometry updates from async code when in lock.
this._geometryLock = true;
const node = this._createCompleterNode(model, items);
let active = node.querySelectorAll(`.${ITEM_CLASS}`)[
this._activeIndex
] as HTMLElement;
active.classList.add(ACTIVE_CLASS);
const resolvedItem = this.model?.resolveItem(items[this._activeIndex]);
// Add the documentation panel
if (this._showDoc) {
this._docPanel.innerText = '';
node.appendChild(this._docPanel);
this._docPanelExpanded = false;
this._docPanel.style.display = 'none';
this._updateDocPanel(resolvedItem, active);
}
if (this.isHidden) {
this.show();
this._setGeometry();
this._visibilityChanged.emit(undefined);
} else {
this._setGeometry();
}
this._geometryLock = false;
}
/**
* Get cached dimensions of the completer box.
*/
protected get sizeCache(): Completer.IDimensions | undefined {
if (!this._sizeCache) {
return;
}
return {
width: this._sizeCache.width + this._sizeCache.docPanelWidth,
height: Math.max(this._sizeCache.height, this._sizeCache.docPanelHeight)
};
}
private _createDocPanelNode() {
const docPanel = document.createElement('div');
docPanel.className = DOC_PANEL_CLASS;
return docPanel;
}
private _createCompleterNode(
model: Completer.IModel,
items: CompletionHandler.ICompletionItems
): HTMLElement {
const current = ++this._renderCounter;
// Clear the node.
let node = this.node;
node.textContent = '';
// Compute an ordered list of all the types in the typeMap, this is computed
// once by the model each time new data arrives for efficiency.
let orderedTypes = model.orderedTypes();
// Populate the completer items.
let ul = document.createElement('ul');
ul.className = LIST_CLASS;
// Add first N items to fill the first "page" assuming that the completer
// would reach its maximum allowed height.
const first = this._renderer.createCompletionItemNode(
items[0],
orderedTypes
);
const renderedItems = [first];
const firstItemSize = Private.measureSize(first, 'inline-grid');
const pageSize = Math.max(
Math.ceil(this._maxHeight / firstItemSize.height),
5
);
// We add one item in case if height heuristic is inaccurate.
const toRenderImmediately = Math.min(pageSize + 1, items.length);
const start = performance.now();
for (let i = 1; i < toRenderImmediately; i++) {
const li = this._renderer.createCompletionItemNode(
items[i],
orderedTypes
);
renderedItems.push(li);
}
for (const li of renderedItems) {
ul.appendChild(li);
}
// Pre-calculate size:
// - height will equal first element height times number of items,
// or maximum allowed height if there are more items than fit on a page,
// - width will be estimated from the widest item.
const widestItemIndex = this._findWidestItemIndex(items);
const widestItem =
widestItemIndex < renderedItems.length
? renderedItems[widestItemIndex]
: this._renderer.createCompletionItemNode(
items[widestItemIndex],
orderedTypes
);
// The node needs to be cloned to avoid side-effect of detaching it.
const widestItemSize = Private.measureSize(
widestItem.cloneNode(true) as HTMLElement,
'inline-grid'
);
this._sizeCache = {
height: Math.min(this._maxHeight, firstItemSize.height * items.length),
width: widestItemSize.width + this._scrollbarWidth,
items: items,
docPanelWidth: 0,
docPanelHeight: 0
};
if (toRenderImmediately < items.length) {
// Render remaining items on idle in subsequent animation frames,
// in chunks of size such that each frame would take about 16ms
// allowing for 4ms of overhead, but keep the chunks no smaller
// than 5 items at a time.
const timePerItem = (performance.now() - start) / toRenderImmediately;
const chunkSize = Math.max(5, Math.floor(12 / timePerItem));
let alreadyRendered = toRenderImmediately;
let previousChunkFinal = renderedItems[renderedItems.length - 1];
const renderChunk = () => {
if (alreadyRendered >= items.length) {
return;
}
// Add a filler so that the list with partially rendered items has the total
// height equal to the (predicted) final height to avoid scrollbar jitter.
const predictedMissingHeight =
firstItemSize.height * (items.length - alreadyRendered);
previousChunkFinal.style.marginBottom = `${predictedMissingHeight}px`;
requestAnimationFrame(() => {
if (current != this._renderCounter) {
// Bail if rendering afresh was requested in the meantime.
return;
}
previousChunkFinal.style.marginBottom = '';
const limit = Math.min(items.length, alreadyRendered + chunkSize);
for (let i = alreadyRendered; i < limit; i++) {
const li = this._renderer.createCompletionItemNode(
items[i],
orderedTypes
);
ul.appendChild(li);
previousChunkFinal = li;
}
alreadyRendered = limit;
renderChunk();
});
};
renderChunk();
}
node.appendChild(ul);
return node;
}
/**
* Use preferred heuristic to find the index of the widest item.
*/
private _findWidestItemIndex(
items: CompletionHandler.ICompletionItems
): number {
const widthHeuristic = this._getPreferredItemWidthHeuristic();
const widthHeuristics = items.map(widthHeuristic);
return widthHeuristics.indexOf(Math.max(...widthHeuristics));
}
/**
* Get item width heuristic function from renderer if available,
* or the default one otherwise.
*/
private _getPreferredItemWidthHeuristic(): (
item: CompletionHandler.ICompletionItem
) => number {
return this._renderer.itemWidthHeuristic
? this._renderer.itemWidthHeuristic.bind(this._renderer)
: this._defaultRenderer.itemWidthHeuristic.bind(this._defaultRenderer);
}
/**
* Cycle through the available completer items.
*
* #### Notes
* When the user cycles all the way `down` to the last index, subsequent
* `down` cycles will cycle to the first index. When the user cycles `up` to
* the first item, subsequent `up` cycles will cycle to the last index.
*/
private _cycle(direction: Private.scrollType): void {
const items = this.node.querySelectorAll(`.${ITEM_CLASS}`);
const index = this._activeIndex;
const last = items.length - 1;
let active = this.node.querySelector(`.${ACTIVE_CLASS}`) as HTMLElement;
active.classList.remove(ACTIVE_CLASS);
switch (direction) {
case 'up':
this._activeIndex = index === 0 ? last : index - 1;
break;
case 'down':
this._activeIndex = index < last ? index + 1 : 0;
break;
case 'pageUp':
case 'pageDown': {
// Measure the number of items on a page and clamp to the list length.
const container = this.node.getBoundingClientRect();
const current = active.getBoundingClientRect();
const page = Math.floor(container.height / current.height);
const sign = direction === 'pageUp' ? -1 : 1;
this._activeIndex = Math.min(Math.max(0, index + sign * page), last);
break;
}
}
active = items[this._activeIndex] as HTMLElement;
active.classList.add(ACTIVE_CLASS);
let completionList = this.node.querySelector(`.${LIST_CLASS}`) as Element;
ElementExt.scrollIntoViewIfNeeded(completionList, active);
this._indexChanged.emit(this._activeIndex);
const visibleCompletionItems = this.model?.completionItems();
const activeCompletionItem = visibleCompletionItems?.[this._activeIndex];
if (activeCompletionItem) {
const resolvedItem = this.model?.resolveItem(activeCompletionItem);
if (this._showDoc) {
this._updateDocPanel(resolvedItem, active);
}
}
}
/**
* Handle keydown events for the widget.
*/
private _evtKeydown(event: KeyboardEvent) {
if (this.isHidden || !this._editor) {
return;
}
if (!this._editor.host.contains(event.target as HTMLElement)) {
this.reset();
return;
}
switch (event.keyCode) {
case 9: {
// Tab key
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
const model = this._model;
if (!model) {
return;
}
// Autoinsert single completions on manual request (tab)
const items = model.completionItems();
if (items && items.length === 1) {
this._selected.emit(items[0].insertText || items[0].label);
this.reset();
return;
}
const populated = this._populateSubset();
// If the common subset was found and set on `query`,
// or if there is a `query` in the initialization options,
// then emit a completion signal with that `query` (=subset match),
// but only if the query has actually changed.
// See: https://github.com/jupyterlab/jupyterlab/issues/10439#issuecomment-875189540
if (model.query && model.query !== this._lastSubsetMatch) {
model.subsetMatch = true;
this._selected.emit(model.query);
model.subsetMatch = false;
this._lastSubsetMatch = model.query;
}
// If the query changed, update rendering of the options.
if (populated) {
this.update();
}
this._cycle(event.shiftKey ? 'up' : 'down');
return;
}
case 27: // Esc key
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
this.reset();
return;
case 33: // PageUp
case 34: // PageDown
case 38: // Up arrow key
case 40: {
// Down arrow key
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
const cycle = Private.keyCodeMap[event.keyCode];
this._cycle(cycle);
return;
}
default:
return;
}
}
/**
* Handle mousedown events for the widget.
*/
private _evtPointerdown(event: PointerEvent) {
if (this.isHidden || !this._editor) {
return;
}
if (Private.nonstandardClick(event)) {
this.reset();
return;
}
let target = event.target as HTMLElement;
while (target !== document.documentElement) {
// If the user has made a selection, emit its value and reset the widget.
if (target.classList.contains(ITEM_CLASS)) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
this._selected.emit(target.getAttribute('data-value') as string);
this.reset();
return;
}
// If the mouse event happened anywhere else in the widget, bail.
if (target === this.node) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
return;
}
target = target.parentElement as HTMLElement;
}
this.reset();
}
/**
* Handle scroll events for the widget
*/
private _evtScroll(event: MouseEvent) {
if (this.isHidden || !this._editor) {
return;
}
const { node } = this;
// All scrolls except scrolls in the actual hover box node may cause the
// referent editor that anchors the node to move, so the only scroll events
// that can safely be ignored are ones that happen inside the hovering node.
if (node.contains(event.target as HTMLElement)) {
return;
}
// Set the geometry of the node asynchronously.
requestAnimationFrame(() => {
this._setGeometry();
});
}
/**
* Populate the completer up to the longest initial subset of items.
*
* @returns `true` if a subset match was found and populated.
*/
private _populateSubset(): boolean {
const { model } = this;
if (!model) {
return false;
}
const items = model.completionItems();
const subset = Private.commonSubset(
items.map(item => item.insertText || item.label)
);
const { query } = model;
// If a common subset exists and it is not the current query, highlight it.
if (subset && subset !== query && subset.indexOf(query) === 0) {
model.query = subset;
return true;
}
return false;
}
/**
* Set the visible dimensions of the widget.
*/
private _setGeometry(): void {
const { node } = this;
const model = this._model;
const editor = this._editor;
// This is an overly defensive test: `cursor` will always exist if
// `original` exists, except in contrived tests. But since it is possible
// to generate a runtime error, the check occurs here.
if (!editor || !model || !model.original || !model.cursor) {
return;
}
const start = model.cursor.start;
const position = editor.getPositionAt(start) as CodeEditor.IPosition;
const anchor = editor.getCoordinateForPosition(position);
if (!anchor) {
return;
}
const style = window.getComputedStyle(node);
const borderLeft = parseInt(style.borderLeftWidth!, 10) || 0;
const paddingLeft = parseInt(style.paddingLeft!, 10) || 0;
// When the editor is attached to the main area, contain the completer hover box
// to the full area available (rather than to the editor itself); the available
// area excludes the toolbar, hence the first Widget child between MainAreaWidget
// and editor is preferred. The difference is negligible in File Editor, but
// substantial for Notebooks.
const host =
(editor.host.closest('.jp-MainAreaWidget > .lm-Widget') as HTMLElement) ||
editor.host;
const items = model.completionItems();
// Fast cache invalidation (only checks for length rather than length + width)
if (this._sizeCache && this._sizeCache.items.length !== items.length) {
this._sizeCache = undefined;
}
// Calculate the geometry of the completer.
HoverBox.setGeometry({
anchor,
host: host,
maxHeight: this._maxHeight,
minHeight: this._minHeight,
node: node,
size: this.sizeCache,
offset: { horizontal: borderLeft + paddingLeft },
privilege: 'below',
style: style,
outOfViewDisplay: {
top: 'stick-inside',
bottom: 'stick-inside',
left: 'stick-inside',
right: 'stick-outside'
}
});
const current = ++this._geometryCounter;
if (!this._sizeCache) {
// If size was not pre-calculated using heuristics, save the actual
// size into cache once rendered.
requestAnimationFrame(() => {
if (current != this._geometryCounter) {
// Do not set size to cache if it may already be outdated.
return;
}
let rect = node.getBoundingClientRect();
let panel = this._docPanel.getBoundingClientRect();
this._sizeCache = {
width: rect.width - panel.width,
height: rect.height,
items: items,
docPanelWidth: panel.width,
docPanelHeight: panel.height
};
});
}
}
/**
* Update the display-state and contents of the documentation panel
*/
private _updateDocPanel(
resolvedItem: Promise<CompletionHandler.ICompletionItem | null> | undefined,
activeNode: HTMLElement
): void {
let docPanel = this._docPanel;
if (!resolvedItem) {
this._toggleDocPanel(false);
return;
}
const loadingIndicator =
this._renderer.createLoadingDocsIndicator?.() ??
this._defaultRenderer.createLoadingDocsIndicator();
activeNode.appendChild(loadingIndicator);
resolvedItem
.then(activeItem => {
if (!activeItem) {
return;
}
if (!docPanel) {
return;
}
if (activeItem.documentation) {
const node =
this._renderer.createDocumentationNode?.(activeItem) ??
this._defaultRenderer.createDocumentationNode(activeItem);
docPanel.textContent = '';
docPanel.appendChild(node);
this._toggleDocPanel(true);
} else {
this._toggleDocPanel(false);
}
})
.catch(e => console.error(e))
.finally(() => {
activeNode.removeChild(loadingIndicator);
});
}
private _toggleDocPanel(show: boolean): void {
let docPanel = this._docPanel;
if (show) {
if (this._docPanelExpanded) {
return;
}
docPanel.style.display = '';
this._docPanelExpanded = true;
} else {
if (!this._docPanelExpanded) {
return;
}
docPanel.style.display = 'none';
this._docPanelExpanded = false;
}
const sizeCache = this._sizeCache;
if (sizeCache) {
sizeCache.docPanelHeight = show ? this._maxHeight : 0;
sizeCache.docPanelWidth = show ? this._docPanelWidth : 0;
if (!this._geometryLock) {
this._setGeometry();
}
}
}
private _activeIndex = 0;
private _editor: CodeEditor.IEditor | null | undefined = null;
private _model: Completer.IModel | null = null;
private _renderer: Completer.IRenderer;
private _defaultRenderer: Completer.Renderer;
private _selected = new Signal<this, string>(this);
private _visibilityChanged = new Signal<this, void>(this);
private _indexChanged = new Signal<this, number>(this);
private _lastSubsetMatch: string = '';
private _showDoc: boolean;
private _sizeCache: Private.IDimensionsCache | undefined;
/**
* The maximum height of a completer widget.
*/
private _maxHeight: number;
/**
* The minimum height of a completer widget.
*/
private _minHeight: number;
private _scrollbarWidth: number;
private _docPanelWidth: number;
private _docPanel: HTMLElement;
private _geometryLock = false;
/**
* Increasing this counter invalidates previous request to save geometry cache in animation callback.
*/
private _geometryCounter: number = 0;
private _docPanelExpanded = false;
private _renderCounter: number = 0;
}
export namespace Completer {
/**
* A type map that may add type annotations to completer matches.
*/
export type TypeMap = { [index: string]: string | null };
/**
* The initialization options for a completer widget.
*/
export interface IOptions {
/**
* The semantic parent of the completer widget, its referent editor.
*/
editor?: CodeEditor.IEditor | null;
/**
* The model for the completer widget.
*/
model?: IModel;
/**
* The renderer for the completer widget nodes.
*/
renderer?: IRenderer;
/**
* Flag to show or hide the document panel.
*/
showDoc?: boolean;
/**
* Sanitizer used to sanitize html strings
*/
sanitizer?: IRenderMime.ISanitizer;
}
/**
* An interface for a completion request reflecting the state of the editor.
*/
export interface ITextState extends JSONObject {
/**
* The current value of the editor.
*/
readonly text: string;
/**
* The line number of the editor cursor.
*/
readonly line: number;
/**
* The character number of the editor cursor within a line.
*/
readonly column: number;
}
/**
* Information about the query string change.
*/
export interface IQueryChange {
/**
* The new value of the query.
*/
newValue: string;
/**
* The event which caused the query to change, one of:
* - `editorUpdate`: as a result of editor change, e.g. user typing code,
* - `setter`: programatically, e.g. by the logic in the widget,
* - `reset`: due to completer model being reset.
*/