Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/src/vs/editor/contrib/suggest/browser/suggestWidget.ts
4797 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import * as dom from '../../../../base/browser/dom.js';
7
import { IKeyboardEvent } from '../../../../base/browser/keyboardEvent.js';
8
import '../../../../base/browser/ui/codicons/codiconStyles.js'; // The codicon symbol styles are defined here and must be loaded
9
import { IListEvent, IListGestureEvent, IListMouseEvent } from '../../../../base/browser/ui/list/list.js';
10
import { List } from '../../../../base/browser/ui/list/listWidget.js';
11
import { CancelablePromise, createCancelablePromise, disposableTimeout, TimeoutTimer } from '../../../../base/common/async.js';
12
import { onUnexpectedError } from '../../../../base/common/errors.js';
13
import { Emitter, Event, PauseableEmitter } from '../../../../base/common/event.js';
14
import { DisposableStore, IDisposable, MutableDisposable } from '../../../../base/common/lifecycle.js';
15
import { clamp } from '../../../../base/common/numbers.js';
16
import * as strings from '../../../../base/common/strings.js';
17
import './media/suggest.css';
18
import { ContentWidgetPositionPreference, ICodeEditor, IContentWidget, IContentWidgetPosition, IEditorMouseEvent } from '../../../browser/editorBrowser.js';
19
import { EmbeddedCodeEditorWidget } from '../../../browser/widget/codeEditor/embeddedCodeEditorWidget.js';
20
import { EditorOption } from '../../../common/config/editorOptions.js';
21
import { IPosition } from '../../../common/core/position.js';
22
import { SuggestWidgetStatus } from './suggestWidgetStatus.js';
23
import '../../symbolIcons/browser/symbolIcons.js'; // The codicon symbol colors are defined here and must be loaded to get colors
24
import * as nls from '../../../../nls.js';
25
import { IContextKey, IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js';
26
import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js';
27
import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
28
import { activeContrastBorder, editorForeground, editorWidgetBackground, editorWidgetBorder, listFocusHighlightForeground, listHighlightForeground, quickInputListFocusBackground, quickInputListFocusForeground, quickInputListFocusIconForeground, registerColor, transparent } from '../../../../platform/theme/common/colorRegistry.js';
29
import { IThemeService } from '../../../../platform/theme/common/themeService.js';
30
import { CompletionModel } from './completionModel.js';
31
import { ResizableHTMLElement } from '../../../../base/browser/ui/resizable/resizable.js';
32
import { CompletionItem, Context as SuggestContext, suggestWidgetStatusbarMenu } from './suggest.js';
33
import { canExpandCompletionItem, SuggestDetailsOverlay, SuggestDetailsWidget } from './suggestWidgetDetails.js';
34
import { ItemRenderer } from './suggestWidgetRenderer.js';
35
import { getListStyles } from '../../../../platform/theme/browser/defaultStyles.js';
36
import { status } from '../../../../base/browser/ui/aria/aria.js';
37
import { CompletionItemKinds } from '../../../common/languages.js';
38
import { isWindows } from '../../../../base/common/platform.js';
39
40
/**
41
* Suggest widget colors
42
*/
43
registerColor('editorSuggestWidget.background', editorWidgetBackground, nls.localize('editorSuggestWidgetBackground', 'Background color of the suggest widget.'));
44
registerColor('editorSuggestWidget.border', editorWidgetBorder, nls.localize('editorSuggestWidgetBorder', 'Border color of the suggest widget.'));
45
export const editorSuggestWidgetForeground = registerColor('editorSuggestWidget.foreground', editorForeground, nls.localize('editorSuggestWidgetForeground', 'Foreground color of the suggest widget.'));
46
registerColor('editorSuggestWidget.selectedForeground', quickInputListFocusForeground, nls.localize('editorSuggestWidgetSelectedForeground', 'Foreground color of the selected entry in the suggest widget.'));
47
registerColor('editorSuggestWidget.selectedIconForeground', quickInputListFocusIconForeground, nls.localize('editorSuggestWidgetSelectedIconForeground', 'Icon foreground color of the selected entry in the suggest widget.'));
48
export const editorSuggestWidgetSelectedBackground = registerColor('editorSuggestWidget.selectedBackground', quickInputListFocusBackground, nls.localize('editorSuggestWidgetSelectedBackground', 'Background color of the selected entry in the suggest widget.'));
49
registerColor('editorSuggestWidget.highlightForeground', listHighlightForeground, nls.localize('editorSuggestWidgetHighlightForeground', 'Color of the match highlights in the suggest widget.'));
50
registerColor('editorSuggestWidget.focusHighlightForeground', listFocusHighlightForeground, nls.localize('editorSuggestWidgetFocusHighlightForeground', 'Color of the match highlights in the suggest widget when an item is focused.'));
51
registerColor('editorSuggestWidgetStatus.foreground', transparent(editorSuggestWidgetForeground, .5), nls.localize('editorSuggestWidgetStatusForeground', 'Foreground color of the suggest widget status.'));
52
53
const enum State {
54
Hidden,
55
Loading,
56
Empty,
57
Open,
58
Frozen,
59
Details,
60
onDetailsKeyDown
61
}
62
63
export interface ISelectedSuggestion {
64
item: CompletionItem;
65
index: number;
66
model: CompletionModel;
67
}
68
69
class PersistedWidgetSize {
70
71
private readonly _key: string;
72
73
constructor(
74
private readonly _service: IStorageService,
75
editor: ICodeEditor
76
) {
77
this._key = `suggestWidget.size/${editor.getEditorType()}/${editor instanceof EmbeddedCodeEditorWidget}`;
78
}
79
80
restore(): dom.Dimension | undefined {
81
const raw = this._service.get(this._key, StorageScope.PROFILE) ?? '';
82
try {
83
const obj = JSON.parse(raw);
84
if (dom.Dimension.is(obj)) {
85
return dom.Dimension.lift(obj);
86
}
87
} catch {
88
// ignore
89
}
90
return undefined;
91
}
92
93
store(size: dom.Dimension) {
94
this._service.store(this._key, JSON.stringify(size), StorageScope.PROFILE, StorageTarget.MACHINE);
95
}
96
97
reset(): void {
98
this._service.remove(this._key, StorageScope.PROFILE);
99
}
100
}
101
102
export class SuggestWidget implements IDisposable {
103
104
private static LOADING_MESSAGE: string = nls.localize('suggestWidget.loading', "Loading...");
105
private static NO_SUGGESTIONS_MESSAGE: string = nls.localize('suggestWidget.noSuggestions', "No suggestions.");
106
107
private _state: State = State.Hidden;
108
private _isAuto: boolean = false;
109
private _loadingTimeout?: IDisposable;
110
private readonly _pendingLayout = new MutableDisposable();
111
private readonly _pendingShowDetails = new MutableDisposable();
112
private _currentSuggestionDetails?: CancelablePromise<void>;
113
private _focusedItem?: CompletionItem;
114
private _ignoreFocusEvents: boolean = false;
115
private _completionModel?: CompletionModel;
116
private _cappedHeight?: { wanted: number; capped: number };
117
private _forceRenderingAbove: boolean = false;
118
private _explainMode: boolean = false;
119
120
readonly element: ResizableHTMLElement;
121
private readonly _messageElement: HTMLElement;
122
private readonly _listElement: HTMLElement;
123
private readonly _list: List<CompletionItem>;
124
private readonly _status: SuggestWidgetStatus;
125
private readonly _details: SuggestDetailsOverlay;
126
private readonly _contentWidget: SuggestContentWidget;
127
private readonly _persistedSize: PersistedWidgetSize;
128
129
private readonly _ctxSuggestWidgetVisible: IContextKey<boolean>;
130
private readonly _ctxSuggestWidgetDetailsVisible: IContextKey<boolean>;
131
private readonly _ctxSuggestWidgetMultipleSuggestions: IContextKey<boolean>;
132
private readonly _ctxSuggestWidgetHasFocusedSuggestion: IContextKey<boolean>;
133
private readonly _ctxSuggestWidgetDetailsFocused: IContextKey<boolean>;
134
135
private readonly _showTimeout = new TimeoutTimer();
136
private readonly _disposables = new DisposableStore();
137
138
139
private readonly _onDidSelect = new PauseableEmitter<ISelectedSuggestion>();
140
private readonly _onDidFocus = new PauseableEmitter<ISelectedSuggestion>();
141
private readonly _onDidHide = new Emitter<this>();
142
private readonly _onDidShow = new Emitter<this>();
143
144
readonly onDidSelect: Event<ISelectedSuggestion> = this._onDidSelect.event;
145
readonly onDidFocus: Event<ISelectedSuggestion> = this._onDidFocus.event;
146
readonly onDidHide: Event<this> = this._onDidHide.event;
147
readonly onDidShow: Event<this> = this._onDidShow.event;
148
149
private readonly _onDetailsKeydown = new Emitter<IKeyboardEvent>();
150
readonly onDetailsKeyDown: Event<IKeyboardEvent> = this._onDetailsKeydown.event;
151
152
constructor(
153
private readonly editor: ICodeEditor,
154
@IStorageService private readonly _storageService: IStorageService,
155
@IContextKeyService _contextKeyService: IContextKeyService,
156
@IThemeService _themeService: IThemeService,
157
@IInstantiationService instantiationService: IInstantiationService,
158
) {
159
this.element = new ResizableHTMLElement();
160
this.element.domNode.classList.add('editor-widget', 'suggest-widget');
161
162
this._contentWidget = new SuggestContentWidget(this, editor);
163
this._persistedSize = new PersistedWidgetSize(_storageService, editor);
164
165
class ResizeState {
166
constructor(
167
readonly persistedSize: dom.Dimension | undefined,
168
readonly currentSize: dom.Dimension,
169
public persistHeight = false,
170
public persistWidth = false,
171
) { }
172
}
173
174
let state: ResizeState | undefined;
175
this._disposables.add(this.element.onDidWillResize(() => {
176
this._contentWidget.lockPreference();
177
state = new ResizeState(this._persistedSize.restore(), this.element.size);
178
}));
179
this._disposables.add(this.element.onDidResize(e => {
180
181
this._resize(e.dimension.width, e.dimension.height);
182
183
if (state) {
184
state.persistHeight = state.persistHeight || !!e.north || !!e.south;
185
state.persistWidth = state.persistWidth || !!e.east || !!e.west;
186
}
187
188
if (!e.done) {
189
return;
190
}
191
192
if (state) {
193
// only store width or height value that have changed and also
194
// only store changes that are above a certain threshold
195
const { itemHeight, defaultSize } = this.getLayoutInfo();
196
const threshold = Math.round(itemHeight / 2);
197
let { width, height } = this.element.size;
198
if (!state.persistHeight || Math.abs(state.currentSize.height - height) <= threshold) {
199
height = state.persistedSize?.height ?? defaultSize.height;
200
}
201
if (!state.persistWidth || Math.abs(state.currentSize.width - width) <= threshold) {
202
width = state.persistedSize?.width ?? defaultSize.width;
203
}
204
this._persistedSize.store(new dom.Dimension(width, height));
205
}
206
207
// reset working state
208
this._contentWidget.unlockPreference();
209
state = undefined;
210
}));
211
212
this._messageElement = dom.append(this.element.domNode, dom.$('.message'));
213
this._listElement = dom.append(this.element.domNode, dom.$('.tree'));
214
215
const details = this._disposables.add(instantiationService.createInstance(SuggestDetailsWidget, this.editor));
216
details.onDidClose(() => this.toggleDetails(), this, this._disposables);
217
this._details = new SuggestDetailsOverlay(details, this.editor);
218
219
const applyIconStyle = () => this.element.domNode.classList.toggle('no-icons', !this.editor.getOption(EditorOption.suggest).showIcons);
220
applyIconStyle();
221
222
const renderer = instantiationService.createInstance(ItemRenderer, this.editor);
223
this._disposables.add(renderer);
224
this._disposables.add(renderer.onDidToggleDetails(() => this.toggleDetails()));
225
226
this._list = new List('SuggestWidget', this._listElement, {
227
getHeight: (_element: CompletionItem): number => this.getLayoutInfo().itemHeight,
228
getTemplateId: (_element: CompletionItem): string => 'suggestion'
229
}, [renderer], {
230
alwaysConsumeMouseWheel: true,
231
useShadows: false,
232
mouseSupport: false,
233
multipleSelectionSupport: false,
234
accessibilityProvider: {
235
getRole: () => isWindows ? 'listitem' : 'option',
236
getWidgetAriaLabel: () => nls.localize('suggest', "Suggest"),
237
getWidgetRole: () => 'listbox',
238
getAriaLabel: (item: CompletionItem) => {
239
240
let label = item.textLabel;
241
const kindLabel = CompletionItemKinds.toLabel(item.completion.kind);
242
if (typeof item.completion.label !== 'string') {
243
const { detail, description } = item.completion.label;
244
if (detail && description) {
245
label = nls.localize('label.full', '{0} {1}, {2}, {3}', label, detail, description, kindLabel);
246
} else if (detail) {
247
label = nls.localize('label.detail', '{0} {1}, {2}', label, detail, kindLabel);
248
} else if (description) {
249
label = nls.localize('label.desc', '{0}, {1}, {2}', label, description, kindLabel);
250
}
251
} else {
252
label = nls.localize('label', '{0}, {1}', label, kindLabel);
253
}
254
if (!item.isResolved || !this._isDetailsVisible()) {
255
return label;
256
}
257
258
const { documentation, detail } = item.completion;
259
const docs = strings.format(
260
'{0}{1}',
261
detail || '',
262
documentation ? (typeof documentation === 'string' ? documentation : documentation.value) : '');
263
264
return nls.localize('ariaCurrenttSuggestionReadDetails', "{0}, docs: {1}", label, docs);
265
},
266
}
267
});
268
this._list.style(getListStyles({
269
listInactiveFocusBackground: editorSuggestWidgetSelectedBackground,
270
listInactiveFocusOutline: activeContrastBorder
271
}));
272
273
this._status = instantiationService.createInstance(SuggestWidgetStatus, this.element.domNode, suggestWidgetStatusbarMenu, undefined);
274
const applyStatusBarStyle = () => this.element.domNode.classList.toggle('with-status-bar', this.editor.getOption(EditorOption.suggest).showStatusBar);
275
applyStatusBarStyle();
276
277
this._disposables.add(this._list.onMouseDown(e => this._onListMouseDownOrTap(e)));
278
this._disposables.add(this._list.onTap(e => this._onListMouseDownOrTap(e)));
279
this._disposables.add(this._list.onDidChangeSelection(e => this._onListSelection(e)));
280
this._disposables.add(this._list.onDidChangeFocus(e => this._onListFocus(e)));
281
this._disposables.add(this.editor.onDidChangeCursorSelection(() => this._onCursorSelectionChanged()));
282
this._disposables.add(this.editor.onDidChangeConfiguration(e => {
283
if (e.hasChanged(EditorOption.suggest)) {
284
applyStatusBarStyle();
285
applyIconStyle();
286
}
287
if (this._completionModel && (e.hasChanged(EditorOption.fontInfo) || e.hasChanged(EditorOption.suggestFontSize) || e.hasChanged(EditorOption.suggestLineHeight))) {
288
this._list.splice(0, this._list.length, this._completionModel.items);
289
}
290
}));
291
292
this._ctxSuggestWidgetVisible = SuggestContext.Visible.bindTo(_contextKeyService);
293
this._ctxSuggestWidgetDetailsVisible = SuggestContext.DetailsVisible.bindTo(_contextKeyService);
294
this._ctxSuggestWidgetMultipleSuggestions = SuggestContext.MultipleSuggestions.bindTo(_contextKeyService);
295
this._ctxSuggestWidgetHasFocusedSuggestion = SuggestContext.HasFocusedSuggestion.bindTo(_contextKeyService);
296
this._ctxSuggestWidgetDetailsFocused = SuggestContext.DetailsFocused.bindTo(_contextKeyService);
297
298
const detailsFocusTracker = dom.trackFocus(this._details.widget.domNode);
299
this._disposables.add(detailsFocusTracker);
300
this._disposables.add(detailsFocusTracker.onDidFocus(() => this._ctxSuggestWidgetDetailsFocused.set(true)));
301
this._disposables.add(detailsFocusTracker.onDidBlur(() => this._ctxSuggestWidgetDetailsFocused.set(false)));
302
303
this._disposables.add(dom.addStandardDisposableListener(this._details.widget.domNode, 'keydown', e => {
304
this._onDetailsKeydown.fire(e);
305
}));
306
307
this._disposables.add(this.editor.onMouseDown((e: IEditorMouseEvent) => this._onEditorMouseDown(e)));
308
}
309
310
dispose(): void {
311
this._details.widget.dispose();
312
this._details.dispose();
313
this._list.dispose();
314
this._status.dispose();
315
this._disposables.dispose();
316
this._loadingTimeout?.dispose();
317
this._pendingLayout.dispose();
318
this._pendingShowDetails.dispose();
319
this._showTimeout.dispose();
320
this._contentWidget.dispose();
321
this.element.dispose();
322
}
323
324
private _onEditorMouseDown(mouseEvent: IEditorMouseEvent): void {
325
if (this._details.widget.domNode.contains(mouseEvent.target.element)) {
326
// Clicking inside details
327
this._details.widget.domNode.focus();
328
} else {
329
// Clicking outside details and inside suggest
330
if (this.element.domNode.contains(mouseEvent.target.element)) {
331
this.editor.focus();
332
}
333
}
334
}
335
336
private _onCursorSelectionChanged(): void {
337
if (this._state !== State.Hidden) {
338
this._contentWidget.layout();
339
}
340
}
341
342
private _onListMouseDownOrTap(e: IListMouseEvent<CompletionItem> | IListGestureEvent<CompletionItem>): void {
343
if (typeof e.element === 'undefined' || typeof e.index === 'undefined') {
344
return;
345
}
346
347
// prevent stealing browser focus from the editor
348
e.browserEvent.preventDefault();
349
e.browserEvent.stopPropagation();
350
351
this._select(e.element, e.index);
352
}
353
354
private _onListSelection(e: IListEvent<CompletionItem>): void {
355
if (e.elements.length) {
356
this._select(e.elements[0], e.indexes[0]);
357
}
358
}
359
360
private _select(item: CompletionItem, index: number): void {
361
const completionModel = this._completionModel;
362
if (completionModel) {
363
this._onDidSelect.fire({ item, index, model: completionModel });
364
this.editor.focus();
365
}
366
}
367
368
private _onListFocus(e: IListEvent<CompletionItem>): void {
369
if (this._ignoreFocusEvents) {
370
return;
371
}
372
373
if (this._state === State.Details) {
374
// This can happen when focus is in the details-panel and when
375
// arrow keys are pressed to select next/prev items
376
this._setState(State.Open);
377
}
378
379
if (!e.elements.length) {
380
if (this._currentSuggestionDetails) {
381
this._currentSuggestionDetails.cancel();
382
this._currentSuggestionDetails = undefined;
383
this._focusedItem = undefined;
384
}
385
386
this.editor.setAriaOptions({ activeDescendant: undefined });
387
this._ctxSuggestWidgetHasFocusedSuggestion.set(false);
388
return;
389
}
390
391
if (!this._completionModel) {
392
return;
393
}
394
395
this._ctxSuggestWidgetHasFocusedSuggestion.set(true);
396
const item = e.elements[0];
397
const index = e.indexes[0];
398
399
if (item !== this._focusedItem) {
400
401
this._currentSuggestionDetails?.cancel();
402
this._currentSuggestionDetails = undefined;
403
404
this._focusedItem = item;
405
406
this._list.reveal(index);
407
408
this._currentSuggestionDetails = createCancelablePromise(async token => {
409
const loading = disposableTimeout(() => {
410
if (this._isDetailsVisible()) {
411
this._showDetails(true, false);
412
}
413
}, 250);
414
const sub = token.onCancellationRequested(() => loading.dispose());
415
try {
416
return await item.resolve(token);
417
} finally {
418
loading.dispose();
419
sub.dispose();
420
}
421
});
422
423
this._currentSuggestionDetails.then(() => {
424
if (index >= this._list.length || item !== this._list.element(index)) {
425
return;
426
}
427
428
// item can have extra information, so re-render
429
this._ignoreFocusEvents = true;
430
this._list.splice(index, 1, [item]);
431
this._list.setFocus([index]);
432
this._ignoreFocusEvents = false;
433
434
if (this._isDetailsVisible()) {
435
this._showDetails(false, false);
436
} else {
437
this.element.domNode.classList.remove('docs-side');
438
}
439
440
this.editor.setAriaOptions({ activeDescendant: this._list.getElementID(index) });
441
}).catch(onUnexpectedError);
442
}
443
444
// emit an event
445
this._onDidFocus.fire({ item, index, model: this._completionModel });
446
}
447
448
private _setState(state: State): void {
449
450
if (this._state === state) {
451
return;
452
}
453
this._state = state;
454
455
this.element.domNode.classList.toggle('frozen', state === State.Frozen);
456
this.element.domNode.classList.remove('message');
457
458
switch (state) {
459
case State.Hidden:
460
dom.hide(this._messageElement, this._listElement, this._status.element);
461
this._details.hide(true);
462
this._status.hide();
463
this._contentWidget.hide();
464
this._ctxSuggestWidgetVisible.reset();
465
this._ctxSuggestWidgetMultipleSuggestions.reset();
466
this._ctxSuggestWidgetHasFocusedSuggestion.reset();
467
this._showTimeout.cancel();
468
this.element.domNode.classList.remove('visible');
469
this._list.splice(0, this._list.length);
470
this._focusedItem = undefined;
471
this._cappedHeight = undefined;
472
this._explainMode = false;
473
break;
474
case State.Loading:
475
this.element.domNode.classList.add('message');
476
this._messageElement.textContent = SuggestWidget.LOADING_MESSAGE;
477
dom.hide(this._listElement, this._status.element);
478
dom.show(this._messageElement);
479
this._details.hide();
480
this._show();
481
this._focusedItem = undefined;
482
status(SuggestWidget.LOADING_MESSAGE);
483
break;
484
case State.Empty:
485
this.element.domNode.classList.add('message');
486
this._messageElement.textContent = SuggestWidget.NO_SUGGESTIONS_MESSAGE;
487
dom.hide(this._listElement, this._status.element);
488
dom.show(this._messageElement);
489
this._details.hide();
490
this._show();
491
this._focusedItem = undefined;
492
status(SuggestWidget.NO_SUGGESTIONS_MESSAGE);
493
break;
494
case State.Open:
495
dom.hide(this._messageElement);
496
dom.show(this._listElement, this._status.element);
497
this._show();
498
break;
499
case State.Frozen:
500
dom.hide(this._messageElement);
501
dom.show(this._listElement, this._status.element);
502
this._show();
503
break;
504
case State.Details:
505
dom.hide(this._messageElement);
506
dom.show(this._listElement, this._status.element);
507
this._details.show();
508
this._show();
509
this._details.widget.focus();
510
break;
511
}
512
}
513
514
private _show(): void {
515
this._status.show();
516
this._contentWidget.show();
517
this._layout(this._persistedSize.restore());
518
this._ctxSuggestWidgetVisible.set(true);
519
520
this._showTimeout.cancelAndSet(() => {
521
this.element.domNode.classList.add('visible');
522
this._onDidShow.fire(this);
523
}, 100);
524
}
525
526
showTriggered(auto: boolean, delay: number) {
527
if (this._state !== State.Hidden) {
528
return;
529
}
530
this._contentWidget.setPosition(this.editor.getPosition());
531
this._isAuto = !!auto;
532
533
if (!this._isAuto) {
534
this._loadingTimeout = disposableTimeout(() => this._setState(State.Loading), delay);
535
}
536
}
537
538
showSuggestions(completionModel: CompletionModel, selectionIndex: number, isFrozen: boolean, isAuto: boolean, noFocus: boolean): void {
539
540
this._contentWidget.setPosition(this.editor.getPosition());
541
this._loadingTimeout?.dispose();
542
543
this._currentSuggestionDetails?.cancel();
544
this._currentSuggestionDetails = undefined;
545
546
if (this._completionModel !== completionModel) {
547
this._completionModel = completionModel;
548
}
549
550
if (isFrozen && this._state !== State.Empty && this._state !== State.Hidden) {
551
this._setState(State.Frozen);
552
return;
553
}
554
555
const visibleCount = this._completionModel.items.length;
556
const isEmpty = visibleCount === 0;
557
this._ctxSuggestWidgetMultipleSuggestions.set(visibleCount > 1);
558
559
if (isEmpty) {
560
this._setState(isAuto ? State.Hidden : State.Empty);
561
this._completionModel = undefined;
562
return;
563
}
564
565
this._focusedItem = undefined;
566
567
// calling list.splice triggers focus event which this widget forwards. That can lead to
568
// suggestions being cancelled and the widget being cleared (and hidden). All this happens
569
// before revealing and focusing is done which means revealing and focusing will fail when
570
// they get run.
571
this._onDidFocus.pause();
572
this._onDidSelect.pause();
573
try {
574
this._list.splice(0, this._list.length, this._completionModel.items);
575
this._setState(isFrozen ? State.Frozen : State.Open);
576
this._list.reveal(selectionIndex, 0, selectionIndex === 0 ? 0 : this.getLayoutInfo().itemHeight * 0.33);
577
this._list.setFocus(noFocus ? [] : [selectionIndex]);
578
} finally {
579
this._onDidFocus.resume();
580
this._onDidSelect.resume();
581
}
582
583
this._pendingLayout.value = dom.runAtThisOrScheduleAtNextAnimationFrame(dom.getWindow(this.element.domNode), () => {
584
this._pendingLayout.clear();
585
this._layout(this.element.size);
586
// Reset focus border
587
this._details.widget.domNode.classList.remove('focused');
588
});
589
}
590
591
focusSelected(): void {
592
if (this._list.length > 0) {
593
this._list.setFocus([0]);
594
}
595
}
596
597
selectNextPage(): boolean {
598
switch (this._state) {
599
case State.Hidden:
600
return false;
601
case State.Details:
602
this._details.widget.pageDown();
603
return true;
604
case State.Loading:
605
return !this._isAuto;
606
default:
607
this._list.focusNextPage();
608
return true;
609
}
610
}
611
612
selectNext(): boolean {
613
switch (this._state) {
614
case State.Hidden:
615
return false;
616
case State.Loading:
617
return !this._isAuto;
618
default:
619
this._list.focusNext(1, true);
620
return true;
621
}
622
}
623
624
selectLast(): boolean {
625
switch (this._state) {
626
case State.Hidden:
627
return false;
628
case State.Details:
629
this._details.widget.scrollBottom();
630
return true;
631
case State.Loading:
632
return !this._isAuto;
633
default:
634
this._list.focusLast();
635
return true;
636
}
637
}
638
639
selectPreviousPage(): boolean {
640
switch (this._state) {
641
case State.Hidden:
642
return false;
643
case State.Details:
644
this._details.widget.pageUp();
645
return true;
646
case State.Loading:
647
return !this._isAuto;
648
default:
649
this._list.focusPreviousPage();
650
return true;
651
}
652
}
653
654
selectPrevious(): boolean {
655
switch (this._state) {
656
case State.Hidden:
657
return false;
658
case State.Loading:
659
return !this._isAuto;
660
default:
661
this._list.focusPrevious(1, true);
662
return false;
663
}
664
}
665
666
selectFirst(): boolean {
667
switch (this._state) {
668
case State.Hidden:
669
return false;
670
case State.Details:
671
this._details.widget.scrollTop();
672
return true;
673
case State.Loading:
674
return !this._isAuto;
675
default:
676
this._list.focusFirst();
677
return true;
678
}
679
}
680
681
getFocusedItem(): ISelectedSuggestion | undefined {
682
if (this._state !== State.Hidden
683
&& this._state !== State.Empty
684
&& this._state !== State.Loading
685
&& this._completionModel
686
&& this._list.getFocus().length > 0
687
) {
688
689
return {
690
item: this._list.getFocusedElements()[0],
691
index: this._list.getFocus()[0],
692
model: this._completionModel
693
};
694
}
695
return undefined;
696
}
697
698
toggleDetailsFocus(): void {
699
if (this._state === State.Details) {
700
// Should return the focus to the list item.
701
this._list.setFocus(this._list.getFocus());
702
this._setState(State.Open);
703
} else if (this._state === State.Open) {
704
this._setState(State.Details);
705
if (!this._isDetailsVisible()) {
706
this.toggleDetails(true);
707
} else {
708
this._details.widget.focus();
709
}
710
}
711
}
712
713
toggleDetails(focused: boolean = false): void {
714
if (this._isDetailsVisible()) {
715
// hide details widget
716
this._pendingShowDetails.clear();
717
this._ctxSuggestWidgetDetailsVisible.set(false);
718
this._setDetailsVisible(false);
719
this._details.hide();
720
this.element.domNode.classList.remove('shows-details');
721
722
} else if ((canExpandCompletionItem(this._list.getFocusedElements()[0]) || this._explainMode) && (this._state === State.Open || this._state === State.Details || this._state === State.Frozen)) {
723
// show details widget (iff possible)
724
this._ctxSuggestWidgetDetailsVisible.set(true);
725
this._setDetailsVisible(true);
726
this._showDetails(false, focused);
727
}
728
}
729
730
private _showDetails(loading: boolean, focused: boolean): void {
731
this._pendingShowDetails.value = dom.runAtThisOrScheduleAtNextAnimationFrame(dom.getWindow(this.element.domNode), () => {
732
this._pendingShowDetails.clear();
733
this._details.show();
734
let didFocusDetails = false;
735
if (loading) {
736
this._details.widget.renderLoading();
737
} else {
738
this._details.widget.renderItem(this._list.getFocusedElements()[0], this._explainMode);
739
}
740
if (!this._details.widget.isEmpty) {
741
this._positionDetails();
742
this.element.domNode.classList.add('shows-details');
743
if (focused) {
744
this._details.widget.focus();
745
didFocusDetails = true;
746
}
747
} else {
748
this._details.hide();
749
}
750
if (!didFocusDetails) {
751
this.editor.focus();
752
}
753
});
754
}
755
756
toggleExplainMode(): void {
757
if (this._list.getFocusedElements()[0]) {
758
this._explainMode = !this._explainMode;
759
if (!this._isDetailsVisible()) {
760
this.toggleDetails();
761
} else {
762
this._showDetails(false, false);
763
}
764
}
765
}
766
767
resetPersistedSize(): void {
768
this._persistedSize.reset();
769
}
770
771
hideWidget(): void {
772
this._pendingLayout.clear();
773
this._pendingShowDetails.clear();
774
this._loadingTimeout?.dispose();
775
776
this._setState(State.Hidden);
777
this._onDidHide.fire(this);
778
this.element.clearSashHoverState();
779
780
// ensure that a reasonable widget height is persisted so that
781
// accidential "resize-to-single-items" cases aren't happening
782
const dim = this._persistedSize.restore();
783
const minPersistedHeight = Math.ceil(this.getLayoutInfo().itemHeight * 4.3);
784
if (dim && dim.height < minPersistedHeight) {
785
this._persistedSize.store(dim.with(undefined, minPersistedHeight));
786
}
787
}
788
789
isFrozen(): boolean {
790
return this._state === State.Frozen;
791
}
792
793
_afterRender(position: ContentWidgetPositionPreference | null) {
794
if (position === null) {
795
if (this._isDetailsVisible()) {
796
this._details.hide(); //todo@jrieken soft-hide
797
}
798
return;
799
}
800
if (this._state === State.Empty || this._state === State.Loading) {
801
// no special positioning when widget isn't showing list
802
return;
803
}
804
if (this._isDetailsVisible() && !this._details.widget.isEmpty) {
805
this._details.show();
806
}
807
this._positionDetails();
808
}
809
810
private _layout(size: dom.Dimension | undefined): void {
811
if (!this.editor.hasModel()) {
812
return;
813
}
814
if (!this.editor.getDomNode()) {
815
// happens when running tests
816
return;
817
}
818
819
const bodyBox = dom.getClientArea(this.element.domNode.ownerDocument.body);
820
const info = this.getLayoutInfo();
821
822
if (!size) {
823
size = info.defaultSize;
824
}
825
826
let height = size.height;
827
let width = size.width;
828
829
// status bar
830
this._status.element.style.height = `${info.itemHeight}px`;
831
832
if (this._state === State.Empty || this._state === State.Loading) {
833
// showing a message only
834
height = info.itemHeight + info.borderHeight;
835
width = info.defaultSize.width / 2;
836
this.element.enableSashes(false, false, false, false);
837
this.element.minSize = this.element.maxSize = new dom.Dimension(width, height);
838
this._contentWidget.setPreference(ContentWidgetPositionPreference.BELOW);
839
840
} else {
841
// showing items
842
843
// width math
844
const maxWidth = bodyBox.width - info.borderHeight - 2 * info.horizontalPadding;
845
if (width > maxWidth) {
846
width = maxWidth;
847
}
848
const preferredWidth = this._completionModel ? this._completionModel.stats.pLabelLen * info.typicalHalfwidthCharacterWidth : width;
849
850
// height math
851
const fullHeight = info.statusBarHeight + this._list.contentHeight + info.borderHeight;
852
const minHeight = info.itemHeight + info.statusBarHeight;
853
const editorBox = dom.getDomNodePagePosition(this.editor.getDomNode());
854
const cursorBox = this.editor.getScrolledVisiblePosition(this.editor.getPosition());
855
const cursorBottom = editorBox.top + cursorBox.top + cursorBox.height;
856
const maxHeightBelow = Math.min(bodyBox.height - cursorBottom - info.verticalPadding, fullHeight);
857
const availableSpaceAbove = editorBox.top + cursorBox.top - info.verticalPadding;
858
const maxHeightAbove = Math.min(availableSpaceAbove, fullHeight);
859
let maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow) + info.borderHeight, fullHeight);
860
861
if (height === this._cappedHeight?.capped) {
862
// Restore the old (wanted) height when the current
863
// height is capped to fit
864
height = this._cappedHeight.wanted;
865
}
866
867
if (height < minHeight) {
868
height = minHeight;
869
}
870
if (height > maxHeight) {
871
height = maxHeight;
872
}
873
874
const forceRenderingAboveRequiredSpace = 150;
875
if ((height > maxHeightBelow && maxHeightAbove > maxHeightBelow) || (this._forceRenderingAbove && availableSpaceAbove > forceRenderingAboveRequiredSpace)) {
876
this._contentWidget.setPreference(ContentWidgetPositionPreference.ABOVE);
877
this.element.enableSashes(true, true, false, false);
878
maxHeight = maxHeightAbove;
879
} else {
880
this._contentWidget.setPreference(ContentWidgetPositionPreference.BELOW);
881
this.element.enableSashes(false, true, true, false);
882
maxHeight = maxHeightBelow;
883
}
884
this.element.preferredSize = new dom.Dimension(preferredWidth, info.defaultSize.height);
885
this.element.maxSize = new dom.Dimension(maxWidth, maxHeight);
886
this.element.minSize = new dom.Dimension(220, minHeight);
887
888
// Know when the height was capped to fit and remember
889
// the wanted height for later. This is required when going
890
// left to widen suggestions.
891
this._cappedHeight = height === fullHeight
892
? { wanted: this._cappedHeight?.wanted ?? size.height, capped: height }
893
: undefined;
894
}
895
this._resize(width, height);
896
}
897
898
private _resize(width: number, height: number): void {
899
900
const { width: maxWidth, height: maxHeight } = this.element.maxSize;
901
width = Math.min(maxWidth, width);
902
height = Math.min(maxHeight, height);
903
904
const { statusBarHeight } = this.getLayoutInfo();
905
this._list.layout(height - statusBarHeight, width);
906
this._listElement.style.height = `${height - statusBarHeight}px`;
907
this.element.layout(height, width);
908
this._contentWidget.layout();
909
910
this._positionDetails();
911
}
912
913
private _positionDetails(): void {
914
if (this._isDetailsVisible()) {
915
this._details.placeAtAnchor(this.element.domNode, this._contentWidget.getPosition()?.preference[0] === ContentWidgetPositionPreference.BELOW);
916
}
917
}
918
919
getLayoutInfo() {
920
const fontInfo = this.editor.getOption(EditorOption.fontInfo);
921
const itemHeight = clamp(this.editor.getOption(EditorOption.suggestLineHeight) || fontInfo.lineHeight, 8, 1000);
922
const statusBarHeight = !this.editor.getOption(EditorOption.suggest).showStatusBar || this._state === State.Empty || this._state === State.Loading ? 0 : itemHeight;
923
const borderWidth = this._details.widget.getLayoutInfo().borderWidth;
924
const borderHeight = 2 * borderWidth;
925
926
return {
927
itemHeight,
928
statusBarHeight,
929
borderWidth,
930
borderHeight,
931
typicalHalfwidthCharacterWidth: fontInfo.typicalHalfwidthCharacterWidth,
932
verticalPadding: 22,
933
horizontalPadding: 14,
934
defaultSize: new dom.Dimension(430, statusBarHeight + 12 * itemHeight)
935
};
936
}
937
938
private _isDetailsVisible(): boolean {
939
return this._storageService.getBoolean('expandSuggestionDocs', StorageScope.PROFILE, false);
940
}
941
942
private _setDetailsVisible(value: boolean) {
943
this._storageService.store('expandSuggestionDocs', value, StorageScope.PROFILE, StorageTarget.USER);
944
}
945
946
forceRenderingAbove() {
947
if (!this._forceRenderingAbove) {
948
this._forceRenderingAbove = true;
949
this._layout(this._persistedSize.restore());
950
}
951
}
952
953
stopForceRenderingAbove() {
954
this._forceRenderingAbove = false;
955
}
956
}
957
958
export class SuggestContentWidget implements IContentWidget {
959
960
readonly allowEditorOverflow = true;
961
readonly suppressMouseDown = false;
962
963
private _position?: IPosition | null;
964
private _preference?: ContentWidgetPositionPreference;
965
private _preferenceLocked = false;
966
967
private _added: boolean = false;
968
private _hidden: boolean = false;
969
970
constructor(
971
private readonly _widget: SuggestWidget,
972
private readonly _editor: ICodeEditor
973
) { }
974
975
dispose(): void {
976
if (this._added) {
977
this._added = false;
978
this._editor.removeContentWidget(this);
979
}
980
}
981
982
getId(): string {
983
return 'editor.widget.suggestWidget';
984
}
985
986
getDomNode(): HTMLElement {
987
return this._widget.element.domNode;
988
}
989
990
show(): void {
991
this._hidden = false;
992
if (!this._added) {
993
this._added = true;
994
this._editor.addContentWidget(this);
995
}
996
}
997
998
hide(): void {
999
if (!this._hidden) {
1000
this._hidden = true;
1001
this.layout();
1002
}
1003
}
1004
1005
layout(): void {
1006
this._editor.layoutContentWidget(this);
1007
}
1008
1009
getPosition(): IContentWidgetPosition | null {
1010
if (this._hidden || !this._position || !this._preference) {
1011
return null;
1012
}
1013
return {
1014
position: this._position,
1015
preference: [this._preference]
1016
};
1017
}
1018
1019
beforeRender() {
1020
const { height, width } = this._widget.element.size;
1021
const { borderWidth, horizontalPadding } = this._widget.getLayoutInfo();
1022
return new dom.Dimension(width + 2 * borderWidth + horizontalPadding, height + 2 * borderWidth);
1023
}
1024
1025
afterRender(position: ContentWidgetPositionPreference | null) {
1026
this._widget._afterRender(position);
1027
}
1028
1029
setPreference(preference: ContentWidgetPositionPreference) {
1030
if (!this._preferenceLocked) {
1031
this._preference = preference;
1032
}
1033
}
1034
1035
lockPreference() {
1036
this._preferenceLocked = true;
1037
}
1038
1039
unlockPreference() {
1040
this._preferenceLocked = false;
1041
}
1042
1043
setPosition(position: IPosition | null): void {
1044
this._position = position;
1045
}
1046
}
1047
1048