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
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as dom from 'vs/base/browser/dom';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import 'vs/base/browser/ui/codicons/codiconStyles'; // The codicon symbol styles are defined here and must be loaded
import { IListEvent, IListGestureEvent, IListMouseEvent } from 'vs/base/browser/ui/list/list';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { CancelablePromise, createCancelablePromise, disposableTimeout, TimeoutTimer } from 'vs/base/common/async';
import { onUnexpectedError } from 'vs/base/common/errors';
import { Emitter, Event } from 'vs/base/common/event';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { clamp } from 'vs/base/common/numbers';
import * as strings from 'vs/base/common/strings';
import 'vs/css!./media/suggest';
import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition, IEditorMouseEvent } from 'vs/editor/browser/editorBrowser';
import { EmbeddedCodeEditorWidget } from 'vs/editor/browser/widget/embeddedCodeEditorWidget';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { IPosition } from 'vs/editor/common/core/position';
import { SuggestWidgetStatus } from 'vs/editor/contrib/suggest/browser/suggestWidgetStatus';
import 'vs/editor/contrib/symbolIcons/browser/symbolIcons'; // The codicon symbol colors are defined here and must be loaded to get colors
import * as nls from 'vs/nls';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { activeContrastBorder, editorForeground, editorWidgetBackground, editorWidgetBorder, listFocusHighlightForeground, listHighlightForeground, quickInputListFocusBackground, quickInputListFocusForeground, quickInputListFocusIconForeground, registerColor, transparent } from 'vs/platform/theme/common/colorRegistry';
import { attachListStyler } from 'vs/platform/theme/common/styler';
import { isHighContrast } from 'vs/platform/theme/common/theme';
import { IColorTheme, IThemeService } from 'vs/platform/theme/common/themeService';
import { CompletionModel } from './completionModel';
import { ResizableHTMLElement } from './resizable';
import { CompletionItem, Context as SuggestContext } from './suggest';
import { canExpandCompletionItem, SuggestDetailsOverlay, SuggestDetailsWidget } from './suggestWidgetDetails';
import { getAriaId, ItemRenderer } from './suggestWidgetRenderer';
/**
* Suggest widget colors
*/
export const editorSuggestWidgetBackground = registerColor('editorSuggestWidget.background', { dark: editorWidgetBackground, light: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, nls.localize('editorSuggestWidgetBackground', 'Background color of the suggest widget.'));
export const editorSuggestWidgetBorder = registerColor('editorSuggestWidget.border', { dark: editorWidgetBorder, light: editorWidgetBorder, hcDark: editorWidgetBorder, hcLight: editorWidgetBorder }, nls.localize('editorSuggestWidgetBorder', 'Border color of the suggest widget.'));
export const editorSuggestWidgetForeground = registerColor('editorSuggestWidget.foreground', { dark: editorForeground, light: editorForeground, hcDark: editorForeground, hcLight: editorForeground }, nls.localize('editorSuggestWidgetForeground', 'Foreground color of the suggest widget.'));
export const editorSuggestWidgetSelectedForeground = registerColor('editorSuggestWidget.selectedForeground', { dark: quickInputListFocusForeground, light: quickInputListFocusForeground, hcDark: quickInputListFocusForeground, hcLight: quickInputListFocusForeground }, nls.localize('editorSuggestWidgetSelectedForeground', 'Foreground color of the selected entry in the suggest widget.'));
export const editorSuggestWidgetSelectedIconForeground = registerColor('editorSuggestWidget.selectedIconForeground', { dark: quickInputListFocusIconForeground, light: quickInputListFocusIconForeground, hcDark: quickInputListFocusIconForeground, hcLight: quickInputListFocusIconForeground }, nls.localize('editorSuggestWidgetSelectedIconForeground', 'Icon foreground color of the selected entry in the suggest widget.'));
export const editorSuggestWidgetSelectedBackground = registerColor('editorSuggestWidget.selectedBackground', { dark: quickInputListFocusBackground, light: quickInputListFocusBackground, hcDark: quickInputListFocusBackground, hcLight: quickInputListFocusBackground }, nls.localize('editorSuggestWidgetSelectedBackground', 'Background color of the selected entry in the suggest widget.'));
export const editorSuggestWidgetHighlightForeground = registerColor('editorSuggestWidget.highlightForeground', { dark: listHighlightForeground, light: listHighlightForeground, hcDark: listHighlightForeground, hcLight: listHighlightForeground }, nls.localize('editorSuggestWidgetHighlightForeground', 'Color of the match highlights in the suggest widget.'));
export const editorSuggestWidgetHighlightFocusForeground = registerColor('editorSuggestWidget.focusHighlightForeground', { dark: listFocusHighlightForeground, light: listFocusHighlightForeground, hcDark: listFocusHighlightForeground, hcLight: listFocusHighlightForeground }, nls.localize('editorSuggestWidgetFocusHighlightForeground', 'Color of the match highlights in the suggest widget when an item is focused.'));
export const editorSuggestWidgetStatusForeground = registerColor('editorSuggestWidgetStatus.foreground', { dark: transparent(editorSuggestWidgetForeground, .5), light: transparent(editorSuggestWidgetForeground, .5), hcDark: transparent(editorSuggestWidgetForeground, .5), hcLight: transparent(editorSuggestWidgetForeground, .5) }, nls.localize('editorSuggestWidgetStatusForeground', 'Foreground color of the suggest widget status.'));
const enum State {
Hidden,
Loading,
Empty,
Open,
Frozen,
Details
}
export interface ISelectedSuggestion {
item: CompletionItem;
index: number;
model: CompletionModel;
}
class PersistedWidgetSize {
private readonly _key: string;
constructor(
private readonly _service: IStorageService,
editor: ICodeEditor
) {
this._key = `suggestWidget.size/${editor.getEditorType()}/${editor instanceof EmbeddedCodeEditorWidget}`;
}
restore(): dom.Dimension | undefined {
const raw = this._service.get(this._key, StorageScope.GLOBAL) ?? '';
try {
const obj = JSON.parse(raw);
if (dom.Dimension.is(obj)) {
return dom.Dimension.lift(obj);
}
} catch {
// ignore
}
return undefined;
}
store(size: dom.Dimension) {
this._service.store(this._key, JSON.stringify(size), StorageScope.GLOBAL, StorageTarget.MACHINE);
}
reset(): void {
this._service.remove(this._key, StorageScope.GLOBAL);
}
}
export class SuggestWidget implements IDisposable {
private static LOADING_MESSAGE: string = nls.localize('suggestWidget.loading', "Loading...");
private static NO_SUGGESTIONS_MESSAGE: string = nls.localize('suggestWidget.noSuggestions', "No suggestions.");
private _state: State = State.Hidden;
private _isAuto: boolean = false;
private _loadingTimeout?: IDisposable;
private _currentSuggestionDetails?: CancelablePromise<void>;
private _focusedItem?: CompletionItem;
private _ignoreFocusEvents: boolean = false;
private _completionModel?: CompletionModel;
private _cappedHeight?: { wanted: number; capped: number };
private _forceRenderingAbove: boolean = false;
private _explainMode: boolean = false;
readonly element: ResizableHTMLElement;
private readonly _messageElement: HTMLElement;
private readonly _listElement: HTMLElement;
private readonly _list: List<CompletionItem>;
private readonly _status: SuggestWidgetStatus;
private readonly _details: SuggestDetailsOverlay;
private readonly _contentWidget: SuggestContentWidget;
private readonly _persistedSize: PersistedWidgetSize;
private readonly _ctxSuggestWidgetVisible: IContextKey<boolean>;
private readonly _ctxSuggestWidgetDetailsVisible: IContextKey<boolean>;
private readonly _ctxSuggestWidgetMultipleSuggestions: IContextKey<boolean>;
private readonly _showTimeout = new TimeoutTimer();
private readonly _disposables = new DisposableStore();
private readonly _onDidSelect = new Emitter<ISelectedSuggestion>();
private readonly _onDidFocus = new Emitter<ISelectedSuggestion>();
private readonly _onDidHide = new Emitter<this>();
private readonly _onDidShow = new Emitter<this>();
readonly onDidSelect: Event<ISelectedSuggestion> = this._onDidSelect.event;
readonly onDidFocus: Event<ISelectedSuggestion> = this._onDidFocus.event;
readonly onDidHide: Event<this> = this._onDidHide.event;
readonly onDidShow: Event<this> = this._onDidShow.event;
private readonly _onDetailsKeydown = new Emitter<IKeyboardEvent>();
readonly onDetailsKeyDown: Event<IKeyboardEvent> = this._onDetailsKeydown.event;
constructor(
private readonly editor: ICodeEditor,
@IStorageService private readonly _storageService: IStorageService,
@IContextKeyService _contextKeyService: IContextKeyService,
@IThemeService _themeService: IThemeService,
@IInstantiationService instantiationService: IInstantiationService,
) {
this.element = new ResizableHTMLElement();
this.element.domNode.classList.add('editor-widget', 'suggest-widget');
this._contentWidget = new SuggestContentWidget(this, editor);
this._persistedSize = new PersistedWidgetSize(_storageService, editor);
class ResizeState {
constructor(
readonly persistedSize: dom.Dimension | undefined,
readonly currentSize: dom.Dimension,
public persistHeight = false,
public persistWidth = false,
) { }
}
let state: ResizeState | undefined;
this._disposables.add(this.element.onDidWillResize(() => {
this._contentWidget.lockPreference();
state = new ResizeState(this._persistedSize.restore(), this.element.size);
}));
this._disposables.add(this.element.onDidResize(e => {
this._resize(e.dimension.width, e.dimension.height);
if (state) {
state.persistHeight = state.persistHeight || !!e.north || !!e.south;
state.persistWidth = state.persistWidth || !!e.east || !!e.west;
}
if (!e.done) {
return;
}
if (state) {
// only store width or height value that have changed and also
// only store changes that are above a certain threshold
const { itemHeight, defaultSize } = this.getLayoutInfo();
const threshold = Math.round(itemHeight / 2);
let { width, height } = this.element.size;
if (!state.persistHeight || Math.abs(state.currentSize.height - height) <= threshold) {
height = state.persistedSize?.height ?? defaultSize.height;
}
if (!state.persistWidth || Math.abs(state.currentSize.width - width) <= threshold) {
width = state.persistedSize?.width ?? defaultSize.width;
}
this._persistedSize.store(new dom.Dimension(width, height));
}
// reset working state
this._contentWidget.unlockPreference();
state = undefined;
}));
this._messageElement = dom.append(this.element.domNode, dom.$('.message'));
this._listElement = dom.append(this.element.domNode, dom.$('.tree'));
const details = instantiationService.createInstance(SuggestDetailsWidget, this.editor);
details.onDidClose(this.toggleDetails, this, this._disposables);
this._details = new SuggestDetailsOverlay(details, this.editor);
const applyIconStyle = () => this.element.domNode.classList.toggle('no-icons', !this.editor.getOption(EditorOption.suggest).showIcons);
applyIconStyle();
const renderer = instantiationService.createInstance(ItemRenderer, this.editor);
this._disposables.add(renderer);
this._disposables.add(renderer.onDidToggleDetails(() => this.toggleDetails()));
this._list = new List('SuggestWidget', this._listElement, {
getHeight: (_element: CompletionItem): number => this.getLayoutInfo().itemHeight,
getTemplateId: (_element: CompletionItem): string => 'suggestion'
}, [renderer], {
alwaysConsumeMouseWheel: true,
useShadows: false,
mouseSupport: false,
multipleSelectionSupport: false,
accessibilityProvider: {
getRole: () => 'option',
getWidgetAriaLabel: () => nls.localize('suggest', "Suggest"),
getWidgetRole: () => 'listbox',
getAriaLabel: (item: CompletionItem) => {
let label = item.textLabel;
if (typeof item.completion.label !== 'string') {
const { detail, description } = item.completion.label;
if (detail && description) {
label = nls.localize('label.full', '{0}{1}, {2}', label, detail, description);
} else if (detail) {
label = nls.localize('label.detail', '{0}{1}', label, detail);
} else if (description) {
label = nls.localize('label.desc', '{0}, {1}', label, description);
}
}
if (!item.isResolved || !this._isDetailsVisible()) {
return label;
}
const { documentation, detail } = item.completion;
const docs = strings.format(
'{0}{1}',
detail || '',
documentation ? (typeof documentation === 'string' ? documentation : documentation.value) : '');
return nls.localize('ariaCurrenttSuggestionReadDetails', "{0}, docs: {1}", label, docs);
},
}
});
this._status = instantiationService.createInstance(SuggestWidgetStatus, this.element.domNode);
const applyStatusBarStyle = () => this.element.domNode.classList.toggle('with-status-bar', this.editor.getOption(EditorOption.suggest).showStatusBar);
applyStatusBarStyle();
this._disposables.add(attachListStyler(this._list, _themeService, {
listInactiveFocusBackground: editorSuggestWidgetSelectedBackground,
listInactiveFocusOutline: activeContrastBorder
}));
this._disposables.add(_themeService.onDidColorThemeChange(t => this._onThemeChange(t)));
this._onThemeChange(_themeService.getColorTheme());
this._disposables.add(this._list.onMouseDown(e => this._onListMouseDownOrTap(e)));
this._disposables.add(this._list.onTap(e => this._onListMouseDownOrTap(e)));
this._disposables.add(this._list.onDidChangeSelection(e => this._onListSelection(e)));
this._disposables.add(this._list.onDidChangeFocus(e => this._onListFocus(e)));
this._disposables.add(this.editor.onDidChangeCursorSelection(() => this._onCursorSelectionChanged()));
this._disposables.add(this.editor.onDidChangeConfiguration(e => {
if (e.hasChanged(EditorOption.suggest)) {
applyStatusBarStyle();
applyIconStyle();
}
}));
this._ctxSuggestWidgetVisible = SuggestContext.Visible.bindTo(_contextKeyService);
this._ctxSuggestWidgetDetailsVisible = SuggestContext.DetailsVisible.bindTo(_contextKeyService);
this._ctxSuggestWidgetMultipleSuggestions = SuggestContext.MultipleSuggestions.bindTo(_contextKeyService);
this._disposables.add(dom.addStandardDisposableListener(this._details.widget.domNode, 'keydown', e => {
this._onDetailsKeydown.fire(e);
}));
this._disposables.add(this.editor.onMouseDown((e: IEditorMouseEvent) => this._onEditorMouseDown(e)));
}
dispose(): void {
this._details.widget.dispose();
this._details.dispose();
this._list.dispose();
this._status.dispose();
this._disposables.dispose();
this._loadingTimeout?.dispose();
this._showTimeout.dispose();
this._contentWidget.dispose();
this.element.dispose();
}
private _onEditorMouseDown(mouseEvent: IEditorMouseEvent): void {
if (this._details.widget.domNode.contains(mouseEvent.target.element)) {
// Clicking inside details
this._details.widget.domNode.focus();
} else {
// Clicking outside details and inside suggest
if (this.element.domNode.contains(mouseEvent.target.element)) {
this.editor.focus();
}
}
}
private _onCursorSelectionChanged(): void {
if (this._state !== State.Hidden) {
this._contentWidget.layout();
}
}
private _onListMouseDownOrTap(e: IListMouseEvent<CompletionItem> | IListGestureEvent<CompletionItem>): void {
if (typeof e.element === 'undefined' || typeof e.index === 'undefined') {
return;
}
// prevent stealing browser focus from the editor
e.browserEvent.preventDefault();
e.browserEvent.stopPropagation();
this._select(e.element, e.index);
}
private _onListSelection(e: IListEvent<CompletionItem>): void {
if (e.elements.length) {
this._select(e.elements[0], e.indexes[0]);
}
}
private _select(item: CompletionItem, index: number): void {
const completionModel = this._completionModel;
if (completionModel) {
this._onDidSelect.fire({ item, index, model: completionModel });
this.editor.focus();
}
}
private _onThemeChange(theme: IColorTheme) {
this._details.widget.borderWidth = isHighContrast(theme.type) ? 2 : 1;
}
private _onListFocus(e: IListEvent<CompletionItem>): void {
if (this._ignoreFocusEvents) {
return;
}
if (!e.elements.length) {
if (this._currentSuggestionDetails) {
this._currentSuggestionDetails.cancel();
this._currentSuggestionDetails = undefined;
this._focusedItem = undefined;
}
this.editor.setAriaOptions({ activeDescendant: undefined });
return;
}
if (!this._completionModel) {
return;
}
const item = e.elements[0];
const index = e.indexes[0];
if (item !== this._focusedItem) {
this._currentSuggestionDetails?.cancel();
this._currentSuggestionDetails = undefined;
this._focusedItem = item;
this._list.reveal(index);
this._currentSuggestionDetails = createCancelablePromise(async token => {
const loading = disposableTimeout(() => {
if (this._isDetailsVisible()) {
this.showDetails(true);
}
}, 250);
const sub = token.onCancellationRequested(() => loading.dispose());
const result = await item.resolve(token);
loading.dispose();
sub.dispose();
return result;
});
this._currentSuggestionDetails.then(() => {
if (index >= this._list.length || item !== this._list.element(index)) {
return;
}
// item can have extra information, so re-render
this._ignoreFocusEvents = true;
this._list.splice(index, 1, [item]);
this._list.setFocus([index]);
this._ignoreFocusEvents = false;
if (this._isDetailsVisible()) {
this.showDetails(false);
} else {
this.element.domNode.classList.remove('docs-side');
}
this.editor.setAriaOptions({ activeDescendant: getAriaId(index) });
}).catch(onUnexpectedError);
}
// emit an event
this._onDidFocus.fire({ item, index, model: this._completionModel });
}
private _setState(state: State): void {
if (this._state === state) {
return;
}
this._state = state;
this.element.domNode.classList.toggle('frozen', state === State.Frozen);
this.element.domNode.classList.remove('message');
switch (state) {
case State.Hidden:
dom.hide(this._messageElement, this._listElement, this._status.element);
this._details.hide(true);
this._status.hide();
this._contentWidget.hide();
this._ctxSuggestWidgetVisible.reset();
this._ctxSuggestWidgetMultipleSuggestions.reset();
this._showTimeout.cancel();
this.element.domNode.classList.remove('visible');
this._list.splice(0, this._list.length);
this._focusedItem = undefined;
this._cappedHeight = undefined;
this._explainMode = false;
break;
case State.Loading:
this.element.domNode.classList.add('message');
this._messageElement.textContent = SuggestWidget.LOADING_MESSAGE;
dom.hide(this._listElement, this._status.element);
dom.show(this._messageElement);
this._details.hide();
this._show();
this._focusedItem = undefined;
break;
case State.Empty:
this.element.domNode.classList.add('message');
this._messageElement.textContent = SuggestWidget.NO_SUGGESTIONS_MESSAGE;
dom.hide(this._listElement, this._status.element);
dom.show(this._messageElement);
this._details.hide();
this._show();
this._focusedItem = undefined;
break;
case State.Open:
dom.hide(this._messageElement);
dom.show(this._listElement, this._status.element);
this._show();
break;
case State.Frozen:
dom.hide(this._messageElement);
dom.show(this._listElement, this._status.element);
this._show();
break;
case State.Details:
dom.hide(this._messageElement);
dom.show(this._listElement, this._status.element);
this._details.show();
this._show();
break;
}
}
private _show(): void {
this._status.show();
this._contentWidget.show();
this._layout(this._persistedSize.restore());
this._ctxSuggestWidgetVisible.set(true);
this._showTimeout.cancelAndSet(() => {
this.element.domNode.classList.add('visible');
this._onDidShow.fire(this);
}, 100);
}
showTriggered(auto: boolean, delay: number) {
if (this._state !== State.Hidden) {
return;
}
this._contentWidget.setPosition(this.editor.getPosition());
this._isAuto = !!auto;
if (!this._isAuto) {
this._loadingTimeout = disposableTimeout(() => this._setState(State.Loading), delay);
}
}
showSuggestions(completionModel: CompletionModel, selectionIndex: number, isFrozen: boolean, isAuto: boolean): void {
this._contentWidget.setPosition(this.editor.getPosition());
this._loadingTimeout?.dispose();
this._currentSuggestionDetails?.cancel();
this._currentSuggestionDetails = undefined;
if (this._completionModel !== completionModel) {
this._completionModel = completionModel;
}
if (isFrozen && this._state !== State.Empty && this._state !== State.Hidden) {
this._setState(State.Frozen);
return;
}
const visibleCount = this._completionModel.items.length;
const isEmpty = visibleCount === 0;
this._ctxSuggestWidgetMultipleSuggestions.set(visibleCount > 1);
if (isEmpty) {
this._setState(isAuto ? State.Hidden : State.Empty);
this._completionModel = undefined;
return;
}
this._focusedItem = undefined;
this._list.splice(0, this._list.length, this._completionModel.items);
this._setState(isFrozen ? State.Frozen : State.Open);
this._list.reveal(selectionIndex, 0);
this._list.setFocus([selectionIndex]);
this._layout(this.element.size);
// Reset focus border
this._details.widget.domNode.classList.remove('focused');
}
selectNextPage(): boolean {
switch (this._state) {
case State.Hidden:
return false;
case State.Details:
this._details.widget.pageDown();
return true;
case State.Loading:
return !this._isAuto;
default:
this._list.focusNextPage();
return true;
}
}
selectNext(): boolean {
switch (this._state) {
case State.Hidden:
return false;
case State.Loading:
return !this._isAuto;
default:
this._list.focusNext(1, true);
return true;
}
}
selectLast(): boolean {
switch (this._state) {
case State.Hidden:
return false;
case State.Details:
this._details.widget.scrollBottom();
return true;
case State.Loading:
return !this._isAuto;
default:
this._list.focusLast();
return true;
}
}
selectPreviousPage(): boolean {
switch (this._state) {
case State.Hidden:
return false;
case State.Details:
this._details.widget.pageUp();
return true;
case State.Loading:
return !this._isAuto;
default:
this._list.focusPreviousPage();
return true;
}
}
selectPrevious(): boolean {
switch (this._state) {
case State.Hidden:
return false;
case State.Loading:
return !this._isAuto;
default:
this._list.focusPrevious(1, true);
return false;
}
}
selectFirst(): boolean {
switch (this._state) {
case State.Hidden:
return false;
case State.Details:
this._details.widget.scrollTop();
return true;
case State.Loading:
return !this._isAuto;
default:
this._list.focusFirst();
return true;
}
}
getFocusedItem(): ISelectedSuggestion | undefined {
if (this._state !== State.Hidden
&& this._state !== State.Empty
&& this._state !== State.Loading
&& this._completionModel
) {
return {
item: this._list.getFocusedElements()[0],
index: this._list.getFocus()[0],
model: this._completionModel
};
}
return undefined;
}
toggleDetailsFocus(): void {
if (this._state === State.Details) {
this._setState(State.Open);
this._details.widget.domNode.classList.remove('focused');
} else if (this._state === State.Open && this._isDetailsVisible()) {
this._setState(State.Details);
this._details.widget.domNode.classList.add('focused');
}
}
toggleDetails(): void {
if (this._isDetailsVisible()) {
// hide details widget
this._ctxSuggestWidgetDetailsVisible.set(false);
this._setDetailsVisible(false);
this._details.hide();
this.element.domNode.classList.remove('shows-details');
} else if ((canExpandCompletionItem(this._list.getFocusedElements()[0]) || this._explainMode) && (this._state === State.Open || this._state === State.Details || this._state === State.Frozen)) {
// show details widget (iff possible)
this._ctxSuggestWidgetDetailsVisible.set(true);
this._setDetailsVisible(true);
this.showDetails(false);
}
}
showDetails(loading: boolean): void {
this._details.show();
if (loading) {
this._details.widget.renderLoading();
} else {
this._details.widget.renderItem(this._list.getFocusedElements()[0], this._explainMode);
}
this._positionDetails();
this.editor.focus();
this.element.domNode.classList.add('shows-details');
}
toggleExplainMode(): void {
if (this._list.getFocusedElements()[0]) {
this._explainMode = !this._explainMode;
if (!this._isDetailsVisible()) {
this.toggleDetails();
} else {
this.showDetails(false);
}
}
}
resetPersistedSize(): void {
this._persistedSize.reset();
}
hideWidget(): void {
this._loadingTimeout?.dispose();
this._setState(State.Hidden);
this._onDidHide.fire(this);
this.element.clearSashHoverState();
// ensure that a reasonable widget height is persisted so that
// accidential "resize-to-single-items" cases aren't happening
const dim = this._persistedSize.restore();
const minPersistedHeight = Math.ceil(this.getLayoutInfo().itemHeight * 4.3);
if (dim && dim.height < minPersistedHeight) {
this._persistedSize.store(dim.with(undefined, minPersistedHeight));
}
}
isFrozen(): boolean {
return this._state === State.Frozen;
}
_afterRender(position: ContentWidgetPositionPreference | null) {
if (position === null) {
if (this._isDetailsVisible()) {
this._details.hide(); //todo@jrieken soft-hide
}
return;
}
if (this._state === State.Empty || this._state === State.Loading) {
// no special positioning when widget isn't showing list
return;
}
if (this._isDetailsVisible()) {
this._details.show();
}
this._positionDetails();
}
private _layout(size: dom.Dimension | undefined): void {
if (!this.editor.hasModel()) {
return;
}
if (!this.editor.getDomNode()) {
// happens when running tests
return;
}
const bodyBox = dom.getClientArea(document.body);
const info = this.getLayoutInfo();
if (!size) {
size = info.defaultSize;
}
let height = size.height;
let width = size.width;
// status bar
this._status.element.style.lineHeight = `${info.itemHeight}px`;
if (this._state === State.Empty || this._state === State.Loading) {
// showing a message only
height = info.itemHeight + info.borderHeight;
width = info.defaultSize.width / 2;
this.element.enableSashes(false, false, false, false);
this.element.minSize = this.element.maxSize = new dom.Dimension(width, height);
this._contentWidget.setPreference(ContentWidgetPositionPreference.BELOW);
} else {
// showing items
// width math
const maxWidth = bodyBox.width - info.borderHeight - 2 * info.horizontalPadding;
if (width > maxWidth) {
width = maxWidth;
}
const preferredWidth = this._completionModel ? this._completionModel.stats.pLabelLen * info.typicalHalfwidthCharacterWidth : width;
// height math
const fullHeight = info.statusBarHeight + this._list.contentHeight + info.borderHeight;
const minHeight = info.itemHeight + info.statusBarHeight;
const editorBox = dom.getDomNodePagePosition(this.editor.getDomNode());
const cursorBox = this.editor.getScrolledVisiblePosition(this.editor.getPosition());
const cursorBottom = editorBox.top + cursorBox.top + cursorBox.height;
const maxHeightBelow = Math.min(bodyBox.height - cursorBottom - info.verticalPadding, fullHeight);
const availableSpaceAbove = editorBox.top + cursorBox.top - info.verticalPadding;
const maxHeightAbove = Math.min(availableSpaceAbove, fullHeight);
let maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow) + info.borderHeight, fullHeight);
if (height === this._cappedHeight?.capped) {
// Restore the old (wanted) height when the current
// height is capped to fit
height = this._cappedHeight.wanted;
}
if (height < minHeight) {
height = minHeight;
}
if (height > maxHeight) {
height = maxHeight;
}
const forceRenderingAboveRequiredSpace = 150;
if (height > maxHeightBelow || (this._forceRenderingAbove && availableSpaceAbove > forceRenderingAboveRequiredSpace)) {
this._contentWidget.setPreference(ContentWidgetPositionPreference.ABOVE);
this.element.enableSashes(true, true, false, false);
maxHeight = maxHeightAbove;
} else {
this._contentWidget.setPreference(ContentWidgetPositionPreference.BELOW);
this.element.enableSashes(false, true, true, false);
maxHeight = maxHeightBelow;
}
this.element.preferredSize = new dom.Dimension(preferredWidth, info.defaultSize.height);
this.element.maxSize = new dom.Dimension(maxWidth, maxHeight);
this.element.minSize = new dom.Dimension(220, minHeight);
// Know when the height was capped to fit and remember
// the wanted height for later. This is required when going
// left to widen suggestions.
this._cappedHeight = height === fullHeight
? { wanted: this._cappedHeight?.wanted ?? size.height, capped: height }
: undefined;
}
this._resize(width, height);
}
private _resize(width: number, height: number): void {
const { width: maxWidth, height: maxHeight } = this.element.maxSize;
width = Math.min(maxWidth, width);
height = Math.min(maxHeight, height);
const { statusBarHeight } = this.getLayoutInfo();
this._list.layout(height - statusBarHeight, width);
this._listElement.style.height = `${height - statusBarHeight}px`;
this.element.layout(height, width);
this._contentWidget.layout();
this._positionDetails();
}
private _positionDetails(): void {
if (this._isDetailsVisible()) {
this._details.placeAtAnchor(this.element.domNode, this._contentWidget.getPosition()?.preference[0] === ContentWidgetPositionPreference.BELOW);
}
}
getLayoutInfo() {
const fontInfo = this.editor.getOption(EditorOption.fontInfo);
const itemHeight = clamp(this.editor.getOption(EditorOption.suggestLineHeight) || fontInfo.lineHeight, 8, 1000);
const statusBarHeight = !this.editor.getOption(EditorOption.suggest).showStatusBar || this._state === State.Empty || this._state === State.Loading ? 0 : itemHeight;
const borderWidth = this._details.widget.borderWidth;
const borderHeight = 2 * borderWidth;
return {
itemHeight,
statusBarHeight,
borderWidth,
borderHeight,
typicalHalfwidthCharacterWidth: fontInfo.typicalHalfwidthCharacterWidth,
verticalPadding: 22,
horizontalPadding: 14,
defaultSize: new dom.Dimension(430, statusBarHeight + 12 * itemHeight + borderHeight)
};
}
private _isDetailsVisible(): boolean {
return this._storageService.getBoolean('expandSuggestionDocs', StorageScope.GLOBAL, false);
}
private _setDetailsVisible(value: boolean) {
this._storageService.store('expandSuggestionDocs', value, StorageScope.GLOBAL, StorageTarget.USER);
}
forceRenderingAbove() {
if (!this._forceRenderingAbove) {
this._forceRenderingAbove = true;
this._layout(this._persistedSize.restore());
}
}
stopForceRenderingAbove() {
this._forceRenderingAbove = false;
}
}
export class SuggestContentWidget implements IContentWidget {
readonly allowEditorOverflow = true;
readonly suppressMouseDown = false;
private _position?: IPosition | null;
private _preference?: ContentWidgetPositionPreference;
private _preferenceLocked = false;
private _added: boolean = false;
private _hidden: boolean = false;
constructor(
private readonly _widget: SuggestWidget,
private readonly _editor: ICodeEditor
) { }
dispose(): void {
if (this._added) {
this._added = false;
this._editor.removeContentWidget(this);
}
}
getId(): string {
return 'editor.widget.suggestWidget';
}
getDomNode(): HTMLElement {
return this._widget.element.domNode;
}
show(): void {
this._hidden = false;
if (!this._added) {
this._added = true;
this._editor.addContentWidget(this);
}
}
hide(): void {
if (!this._hidden) {
this._hidden = true;
this.layout();
}
}
layout(): void {
this._editor.layoutContentWidget(this);
}
getPosition(): IContentWidgetPosition | null {
if (this._hidden || !this._position || !this._preference) {
return null;
}
return {
position: this._position,
preference: [this._preference]
};
}
beforeRender() {
const { height, width } = this._widget.element.size;
const { borderWidth, horizontalPadding } = this._widget.getLayoutInfo();
return new dom.Dimension(width + 2 * borderWidth + horizontalPadding, height + 2 * borderWidth);
}
afterRender(position: ContentWidgetPositionPreference | null) {
this._widget._afterRender(position);
}
setPreference(preference: ContentWidgetPositionPreference) {
if (!this._preferenceLocked) {
this._preference = preference;
}
}
lockPreference() {
this._preferenceLocked = true;
}
unlockPreference() {
this._preferenceLocked = false;
}
setPosition(position: IPosition | null): void {
this._position = position;
}
}
|