-
Notifications
You must be signed in to change notification settings - Fork 27.8k
/
codeActionMenu.ts
772 lines (659 loc) · 28.5 KB
/
codeActionMenu.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
/*---------------------------------------------------------------------------------------------
* 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 { IAnchor } from 'vs/base/browser/ui/contextview/contextview';
import { IListEvent, IListMouseEvent, IListRenderer } from 'vs/base/browser/ui/list/list';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { Action, IAction, Separator } from 'vs/base/common/actions';
import { canceled } from 'vs/base/common/errors';
import { ResolvedKeybinding } from 'vs/base/common/keybindings';
import { Lazy } from 'vs/base/common/lazy';
import { Disposable, dispose, MutableDisposable, IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import 'vs/css!./media/action';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorOption } from 'vs/editor/common/config/editorOptions';
import { IPosition, Position } from 'vs/editor/common/core/position';
import { IEditorContribution, ScrollType } from 'vs/editor/common/editorCommon';
import { CodeAction, Command } from 'vs/editor/common/languages';
import { ITextModel } from 'vs/editor/common/model';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { codeActionCommandId, CodeActionItem, CodeActionSet, fixAllCommandId, organizeImportsCommandId, refactorCommandId, sourceActionCommandId } from 'vs/editor/contrib/codeAction/browser/codeAction';
import { CodeActionAutoApply, CodeActionCommandArgs, CodeActionKind, CodeActionTrigger, CodeActionTriggerSource } from 'vs/editor/contrib/codeAction/browser/types';
import { localize } from 'vs/nls';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import 'vs/base/browser/ui/codicons/codiconStyles'; // The codicon symbol styles are defined here and must be loaded
import 'vs/editor/contrib/symbolIcons/browser/symbolIcons'; // The codicon symbol colors are defined here and must be loaded to get colors
import { Codicon } from 'vs/base/common/codicons';
export const Context = {
Visible: new RawContextKey<boolean>('CodeActionMenuVisible', false, localize('CodeActionMenuVisible', "Whether the code action list widget is visible"))
};
interface CodeActionWidgetDelegate {
onSelectCodeAction: (action: CodeActionItem, trigger: CodeActionTrigger) => Promise<any>;
}
interface ResolveCodeActionKeybinding {
readonly kind: CodeActionKind;
readonly preferred: boolean;
readonly resolvedKeybinding: ResolvedKeybinding;
}
class CodeActionAction extends Action {
constructor(
public readonly action: CodeAction,
callback: () => Promise<void>,
) {
super(action.command ? action.command.id : action.title, stripNewlines(action.title), undefined, !action.disabled, callback);
}
}
function stripNewlines(str: string): string {
return str.replace(/\r\n|\r|\n/g, ' ');
}
export interface CodeActionShowOptions {
readonly includeDisabledActions: boolean;
readonly fromLightbulb?: boolean;
}
export interface ICodeActionMenuItem {
action: IAction;
isSeparator: boolean;
isEnabled: boolean;
isDocumentation: boolean;
isHeader: boolean;
headerTitle: string;
index: number;
disposables?: IDisposable[];
}
export interface ICodeMenuOptions {
useCustomDrawn?: boolean;
ariaLabel?: string;
ariaDescription?: string;
minBottomMargin?: number;
optionsAsChildren?: boolean;
}
export interface ICodeActionMenuTemplateData {
root: HTMLElement;
text: HTMLElement;
detail: HTMLElement;
decoratorRight: HTMLElement;
disposables: IDisposable[];
icon: HTMLElement;
}
const TEMPLATE_ID = 'codeActionWidget';
const codeActionLineHeight = 24;
const headerLineHeight = 26;
class CodeMenuRenderer implements IListRenderer<ICodeActionMenuItem, ICodeActionMenuTemplateData> {
constructor(
private readonly acceptKeybindings: [string, string],
@IKeybindingService private readonly keybindingService: IKeybindingService,
) { }
get templateId(): string { return TEMPLATE_ID; }
renderTemplate(container: HTMLElement): ICodeActionMenuTemplateData {
const data: ICodeActionMenuTemplateData = Object.create(null);
data.disposables = [];
data.root = container;
data.text = document.createElement('span');
const iconContainer = document.createElement('div');
iconContainer.className = 'icon-container';
data.icon = document.createElement('div');
iconContainer.append(data.icon);
container.append(iconContainer);
container.append(data.text);
return data;
}
renderElement(element: ICodeActionMenuItem, index: number, templateData: ICodeActionMenuTemplateData): void {
const data: ICodeActionMenuTemplateData = templateData;
const isSeparator = element.isSeparator;
const isHeader = element.isHeader;
if (isSeparator) {
data.root.classList.add('separator');
data.root.style.height = '10px';
} else if (isHeader) {
const text = element.headerTitle;
data.text.textContent = text;
element.isEnabled = false;
data.root.classList.add('group-header');
} else {
const text = element.action.label;
data.text.textContent = text;
element.isEnabled = element.action.enabled;
if (element.action instanceof CodeActionAction) {
// Check documentation type
element.isDocumentation = element.action.action.kind === CodeActionMenu.documentationID;
if (element.isDocumentation) {
data.text.textContent = text;
data.root.classList.add('documentation');
} else {
// Icons and Label modifaction based on group
const group = element.action.action.kind;
if (CodeActionKind.SurroundWith.contains(new CodeActionKind(String(group)))) {
data.icon.className = Codicon.symbolArray.classNames;
} else if (CodeActionKind.Extract.contains(new CodeActionKind(String(group)))) {
data.icon.className = Codicon.wrench.classNames;
} else if (CodeActionKind.Convert.contains(new CodeActionKind(String(group)))) {
data.icon.className = Codicon.zap.classNames;
data.icon.style.color = `var(--vscode-editorLightBulbAutoFix-foreground)`;
} else if (CodeActionKind.QuickFix.contains(new CodeActionKind(String(group)))) {
data.icon.className = Codicon.lightBulb.classNames;
data.icon.style.color = `var(--vscode-editorLightBulb-foreground)`;
} else {
data.icon.className = Codicon.lightBulb.classNames;
data.icon.style.color = `var(--vscode-editorLightBulb-foreground)`;
}
// Check if action has disabled reason
if (element.action.action.disabled) {
data.root.title = element.action.action.disabled;
} else {
const updateLabel = () => {
const [accept, preview] = this.acceptKeybindings;
data.root.title = localize({ key: 'label', comment: ['placeholders are keybindings, e.g "F2 to Apply, Shift+F2 to Preview"'] }, "{0} to Apply, {1} to Preview", this.keybindingService.lookupKeybinding(accept)?.getLabel(), this.keybindingService.lookupKeybinding(preview)?.getLabel());
};
updateLabel();
}
}
}
}
if (!element.isEnabled) {
data.root.classList.add('option-disabled');
data.root.style.backgroundColor = 'transparent !important';
data.icon.style.opacity = '0.4';
} else {
data.root.classList.remove('option-disabled');
}
}
disposeTemplate(templateData: ICodeActionMenuTemplateData): void {
templateData.disposables = dispose(templateData.disposables);
}
}
export class CodeActionMenu extends Disposable implements IEditorContribution {
private readonly _showingActions = this._register(new MutableDisposable<CodeActionSet>());
private codeActionList = this._register(new MutableDisposable<List<ICodeActionMenuItem>>());
private options: ICodeActionMenuItem[] = [];
private _visible: boolean = false;
private _ctxMenuWidgetVisible: IContextKey<boolean>;
private viewItems: ICodeActionMenuItem[] = [];
private focusedEnabledItem: number | undefined;
private currSelectedItem: number | undefined;
private hasSeparator: boolean = false;
private block?: HTMLElement;
private pointerBlock?: HTMLElement;
public static readonly documentationID: string = '_documentation';
public static readonly ID: string = 'editor.contrib.codeActionMenu';
public static get(editor: ICodeEditor): CodeActionMenu | null {
return editor.getContribution<CodeActionMenu>(CodeActionMenu.ID);
}
private readonly _keybindingResolver: CodeActionKeybindingResolver;
private listRenderer: CodeMenuRenderer;
constructor(
private readonly _editor: ICodeEditor,
private readonly _delegate: CodeActionWidgetDelegate,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@IKeybindingService keybindingService: IKeybindingService,
@ILanguageFeaturesService private readonly _languageFeaturesService: ILanguageFeaturesService,
@ITelemetryService private readonly _telemetryService: ITelemetryService,
@IThemeService _themeService: IThemeService,
@IConfigurationService private readonly _configurationService: IConfigurationService,
@IContextViewService private readonly _contextViewService: IContextViewService,
@IContextKeyService private readonly _contextKeyService: IContextKeyService,
) {
super();
this._keybindingResolver = new CodeActionKeybindingResolver({
getKeybindings: () => keybindingService.getKeybindings()
});
this._ctxMenuWidgetVisible = Context.Visible.bindTo(this._contextKeyService);
this.listRenderer = new CodeMenuRenderer([`onEnterSelectCodeAction`, `onEnterSelectCodeActionWithPreview`], keybindingService);
}
get isVisible(): boolean {
return this._visible;
}
private isCodeActionWidgetEnabled(model: ITextModel): boolean {
return this._configurationService.getValue('editor.experimental.useCustomCodeActionMenu', {
resource: model.uri
});
}
private _onListSelection(e: IListEvent<ICodeActionMenuItem>): void {
if (e.elements.length) {
e.elements.forEach(element => {
if (element.isEnabled) {
element.action.run();
this.hideCodeActionWidget();
}
});
}
}
private _onListHover(e: IListMouseEvent<ICodeActionMenuItem>): void {
if (!e.element) {
this.currSelectedItem = undefined;
this.codeActionList.value?.setFocus([]);
} else {
if (e.element?.isEnabled) {
this.codeActionList.value?.setFocus([e.element.index]);
this.focusedEnabledItem = this.viewItems.indexOf(e.element);
this.currSelectedItem = e.element.index;
} else {
this.currSelectedItem = undefined;
this.codeActionList.value?.setFocus([e.element.index]);
}
}
}
private _onListClick(e: IListMouseEvent<ICodeActionMenuItem>): void {
if (e.element) {
if (!e.element.isEnabled) {
this.currSelectedItem = undefined;
this.codeActionList.value?.setFocus([]);
}
}
}
private renderCodeActionMenuList(element: HTMLElement, inputArray: IAction[]): IDisposable {
const renderDisposables = new DisposableStore();
const renderMenu = document.createElement('div');
// Render invisible div to block mouse interaction in the rest of the UI
const menuBlock = document.createElement('div');
this.block = element.appendChild(menuBlock);
this.block.classList.add('context-view-block');
this.block.style.position = 'fixed';
this.block.style.cursor = 'initial';
this.block.style.left = '0';
this.block.style.top = '0';
this.block.style.width = '100%';
this.block.style.height = '100%';
this.block.style.zIndex = '-1';
renderDisposables.add(dom.addDisposableListener(this.block, dom.EventType.MOUSE_DOWN, e => e.stopPropagation()));
renderMenu.id = 'codeActionMenuWidget';
renderMenu.classList.add('codeActionMenuWidget');
element.appendChild(renderMenu);
this.codeActionList.value = new List('codeActionWidget', renderMenu, {
getHeight(element) {
if (element.isSeparator) {
return 10;
} else if (element.isHeader) {
return headerLineHeight;
}
return codeActionLineHeight;
},
getTemplateId(element) {
return 'codeActionWidget';
}
}, [this.listRenderer],
{
keyboardSupport: false,
}
);
const pointerBlockDiv = document.createElement('div');
this.pointerBlock = element.appendChild(pointerBlockDiv);
this.pointerBlock.classList.add('context-view-pointerBlock');
this.pointerBlock.style.position = 'fixed';
this.pointerBlock.style.cursor = 'initial';
this.pointerBlock.style.left = '0';
this.pointerBlock.style.top = '0';
this.pointerBlock.style.width = '100%';
this.pointerBlock.style.height = '100%';
this.pointerBlock.style.zIndex = '2';
// Removes block on click INSIDE widget or ANY mouse movement
renderDisposables.add(dom.addDisposableListener(this.pointerBlock, dom.EventType.POINTER_MOVE, () => this.pointerBlock?.remove()));
renderDisposables.add(dom.addDisposableListener(this.pointerBlock, dom.EventType.MOUSE_DOWN, () => this.pointerBlock?.remove()));
renderDisposables.add(this.codeActionList.value.onMouseClick(e => this._onListClick(e)));
renderDisposables.add(this.codeActionList.value.onMouseOver(e => this._onListHover(e)));
renderDisposables.add(this.codeActionList.value.onDidChangeFocus(e => this.codeActionList.value?.domFocus()));
renderDisposables.add(this.codeActionList.value.onDidChangeSelection(e => this._onListSelection(e)));
renderDisposables.add(this._editor.onDidLayoutChange(e => this.hideCodeActionWidget()));
// Filters and groups code actions by their group
const menuEntries: IAction[][] = [];
// Code Action Groups
const quickfixGroup: IAction[] = [];
const extractGroup: IAction[] = [];
const convertGroup: IAction[] = [];
const surroundGroup: IAction[] = [];
const sourceGroup: IAction[] = [];
const separatorGroup: IAction[] = [];
const documentationGroup: IAction[] = [];
const otherGroup: IAction[] = [];
inputArray.forEach((item, index) => {
if (item instanceof CodeActionAction) {
const optionKind = item.action.kind;
if (CodeActionKind.SurroundWith.contains(new CodeActionKind(String(optionKind)))) {
surroundGroup.push(item);
} else if (CodeActionKind.QuickFix.contains(new CodeActionKind(String(optionKind)))) {
quickfixGroup.push(item);
} else if (CodeActionKind.Extract.contains(new CodeActionKind(String(optionKind)))) {
extractGroup.push(item);
} else if (CodeActionKind.Convert.contains(new CodeActionKind(String(optionKind)))) {
convertGroup.push(item);
} else if (CodeActionKind.Source.contains(new CodeActionKind(String(optionKind)))) {
sourceGroup.push(item);
} else if (optionKind === CodeActionMenu.documentationID) {
documentationGroup.push(item);
} else {
otherGroup.push(item);
}
} else if (item.id === `vs.actions.separator`) {
separatorGroup.push(item);
}
});
menuEntries.push(quickfixGroup, extractGroup, convertGroup, surroundGroup, sourceGroup, otherGroup, separatorGroup, documentationGroup);
const menuEntriesToPush = (menuID: string, entry: IAction[]) => {
totalActionEntries.push(menuID);
totalActionEntries.push(...entry);
numHeaders++;
};
// Creates flat list of all menu entries with headers as separators
let numHeaders = 0;
const totalActionEntries: (IAction | string)[] = [];
menuEntries.forEach(entry => {
if (entry.length > 0 && entry[0] instanceof CodeActionAction) {
const firstAction = entry[0].action.kind;
if (CodeActionKind.SurroundWith.contains(new CodeActionKind(String(firstAction)))) {
menuEntriesToPush(localize('codeAction.widget.id.surround', 'Surround With...'), entry);
} else if (CodeActionKind.QuickFix.contains(new CodeActionKind(String(firstAction)))) {
menuEntriesToPush(localize('codeAction.widget.id.quickfix', 'Quick Fix...'), entry);
} else if (CodeActionKind.Extract.contains(new CodeActionKind(String(firstAction)))) {
menuEntriesToPush(localize('codeAction.widget.id.extract', 'Extract...'), entry);
} else if (CodeActionKind.Convert.contains(new CodeActionKind(String(firstAction)))) {
menuEntriesToPush(localize('codeAction.widget.id.convert', 'Convert...'), entry);
} else if (CodeActionKind.Source.contains(new CodeActionKind(String(firstAction)))) {
menuEntriesToPush(localize('codeAction.widget.id.source', 'Source Action...'), entry);
} else if (firstAction === CodeActionMenu.documentationID) {
totalActionEntries.push(...entry);
}
} else {
// case for separator - not a code action action
totalActionEntries.push(...entry);
}
});
// Populating the list widget and tracking enabled options.
totalActionEntries.forEach((item, index) => {
if (typeof item === `string`) {
const menuItem = <ICodeActionMenuItem>{ isEnabled: false, isSeparator: false, index, isHeader: true, headerTitle: item };
this.options.push(menuItem);
} else {
const currIsSeparator = item.class === 'separator';
if (currIsSeparator) {
// set to true forever because there is a separator
this.hasSeparator = true;
}
const menuItem = <ICodeActionMenuItem>{ action: item, isEnabled: item.enabled, isSeparator: currIsSeparator, index };
if (item.enabled) {
this.viewItems.push(menuItem);
}
this.options.push(menuItem);
}
});
this.codeActionList.value.splice(0, this.codeActionList.value.length, this.options);
// Updating list height, depending on how many separators and headers there are.
const height = this.hasSeparator ? (totalActionEntries.length - 1) * codeActionLineHeight + 10 : totalActionEntries.length * codeActionLineHeight;
const heightWithHeaders = height + numHeaders * headerLineHeight - numHeaders * codeActionLineHeight;
renderMenu.style.height = String(heightWithHeaders) + 'px';
this.codeActionList.value.layout(heightWithHeaders);
// For finding width dynamically (not using resize observer)
const arr: number[] = [];
this.options.forEach((item, index) => {
if (!this.codeActionList.value) {
return;
}
const element = document.getElementById(this.codeActionList.value?.getElementID(index))?.getElementsByTagName('span')[0].offsetWidth;
arr.push(Number(element));
});
// resize observer - can be used in the future since list widget supports dynamic height but not width
const maxWidth = Math.max(...arr);
// 52 is the additional padding for the list widget (26 left, 26 right)
renderMenu.style.width = maxWidth + 52 + 5 + 'px';
this.codeActionList.value?.layout(heightWithHeaders, maxWidth);
// List selection
if (this.viewItems.length < 1 || this.viewItems.every(item => item.isDocumentation)) {
this.currSelectedItem = undefined;
} else {
this.focusedEnabledItem = 0;
this.currSelectedItem = this.viewItems[0].index;
this.codeActionList.value.setFocus([this.currSelectedItem]);
}
// List Focus
this.codeActionList.value.domFocus();
const focusTracker = dom.trackFocus(element);
const blurListener = focusTracker.onDidBlur(() => {
this.hideCodeActionWidget();
});
renderDisposables.add(blurListener);
renderDisposables.add(focusTracker);
this._ctxMenuWidgetVisible.set(true);
return renderDisposables;
}
protected focusPrevious() {
if (typeof this.focusedEnabledItem === 'undefined') {
this.focusedEnabledItem = this.viewItems[0].index;
} else if (this.viewItems.length < 1) {
return false;
}
const startIndex = this.focusedEnabledItem;
let item: ICodeActionMenuItem;
do {
this.focusedEnabledItem = this.focusedEnabledItem - 1;
if (this.focusedEnabledItem < 0) {
this.focusedEnabledItem = this.viewItems.length - 1;
}
item = this.viewItems[this.focusedEnabledItem];
this.codeActionList.value?.setFocus([item.index]);
this.currSelectedItem = item.index;
} while (this.focusedEnabledItem !== startIndex && ((!item.isEnabled) || item.action.id === Separator.ID));
return true;
}
protected focusNext() {
if (typeof this.focusedEnabledItem === 'undefined') {
this.focusedEnabledItem = this.viewItems.length - 1;
} else if (this.viewItems.length < 1) {
return false;
}
const startIndex = this.focusedEnabledItem;
let item: ICodeActionMenuItem;
do {
this.focusedEnabledItem = (this.focusedEnabledItem + 1) % this.viewItems.length;
item = this.viewItems[this.focusedEnabledItem];
this.codeActionList.value?.setFocus([item.index]);
this.currSelectedItem = item.index;
} while (this.focusedEnabledItem !== startIndex && ((!item.isEnabled) || item.action.id === Separator.ID));
return true;
}
public navigateListWithKeysUp() {
this.focusPrevious();
}
public navigateListWithKeysDown() {
this.focusNext();
}
public onEnterSet() {
if (typeof this.currSelectedItem === 'number') {
this.codeActionList.value?.setSelection([this.currSelectedItem]);
}
}
override dispose() {
super.dispose();
}
hideCodeActionWidget() {
this._ctxMenuWidgetVisible.reset();
this.options = [];
this.viewItems = [];
this.focusedEnabledItem = 0;
this.currSelectedItem = undefined;
this.hasSeparator = false;
this._contextViewService.hideContextView({ source: this });
}
codeActionTelemetry(openedFromString: CodeActionTriggerSource, didCancel: boolean, CodeActions: CodeActionSet) {
type ApplyCodeActionEvent = {
codeActionFrom: CodeActionTriggerSource;
validCodeActions: number;
cancelled: boolean;
};
type ApplyCodeEventClassification = {
codeActionFrom: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The kind of action used to opened the code action.' };
validCodeActions: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The total number of valid actions that are highlighted and can be used.' };
cancelled: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'The indicator if the menu was selected or cancelled.' };
owner: 'mjbvz';
comment: 'Event used to gain insights into how code actions are being triggered';
};
this._telemetryService.publicLog2<ApplyCodeActionEvent, ApplyCodeEventClassification>('codeAction.applyCodeAction', {
codeActionFrom: openedFromString,
validCodeActions: CodeActions.validActions.length,
cancelled: didCancel,
});
}
public async show(trigger: CodeActionTrigger, codeActions: CodeActionSet, at: IAnchor | IPosition, options: CodeActionShowOptions): Promise<void> {
const model = this._editor.getModel();
if (!model) {
return;
}
const actionsToShow = options.includeDisabledActions ? codeActions.allActions : codeActions.validActions;
if (!actionsToShow.length) {
this._visible = false;
return;
}
if (!this._editor.getDomNode()) {
// cancel when editor went off-dom
this._visible = false;
throw canceled();
}
this._visible = true;
this._showingActions.value = codeActions;
const menuActions = this.getMenuActions(trigger, actionsToShow, codeActions.documentation);
const anchor = Position.isIPosition(at) ? this._toCoords(at) : at || { x: 0, y: 0 };
const resolver = this._keybindingResolver.getResolver();
const useShadowDOM = this._editor.getOption(EditorOption.useShadowDOM);
if (this.isCodeActionWidgetEnabled(model)) {
this._contextViewService.showContextView({
getAnchor: () => anchor,
render: (container: HTMLElement) => this.renderCodeActionMenuList(container, menuActions),
onHide: (didCancel) => {
const openedFromString = (options.fromLightbulb) ? CodeActionTriggerSource.Lightbulb : trigger.triggerAction;
this.codeActionTelemetry(openedFromString, didCancel, codeActions);
this._visible = false;
this._editor.focus();
},
},
this._editor.getDomNode()!, false,
);
} else {
this._contextMenuService.showContextMenu({
domForShadowRoot: useShadowDOM ? this._editor.getDomNode()! : undefined,
getAnchor: () => anchor,
getActions: () => menuActions,
onHide: (didCancel) => {
const openedFromString = (options.fromLightbulb) ? CodeActionTriggerSource.Lightbulb : trigger.triggerAction;
this.codeActionTelemetry(openedFromString, didCancel, codeActions);
this._visible = false;
this._editor.focus();
},
autoSelectFirstItem: true,
getKeyBinding: action => action instanceof CodeActionAction ? resolver(action.action) : undefined,
});
}
}
private getMenuActions(
trigger: CodeActionTrigger,
actionsToShow: readonly CodeActionItem[],
documentation: readonly Command[]
): IAction[] {
const toCodeActionAction = (item: CodeActionItem): CodeActionAction => new CodeActionAction(item.action, () => this._delegate.onSelectCodeAction(item, trigger));
const result: IAction[] = actionsToShow
.map(toCodeActionAction);
const allDocumentation: Command[] = [...documentation];
const model = this._editor.getModel();
if (model && result.length) {
for (const provider of this._languageFeaturesService.codeActionProvider.all(model)) {
if (provider._getAdditionalMenuItems) {
allDocumentation.push(...provider._getAdditionalMenuItems({ trigger: trigger.type, only: trigger.filter?.include?.value }, actionsToShow.map(item => item.action)));
}
}
}
if (allDocumentation.length) {
result.push(new Separator(), ...allDocumentation.map(command => toCodeActionAction(new CodeActionItem({
title: command.title,
command: command,
kind: CodeActionMenu.documentationID
}, undefined))));
}
return result;
}
private _toCoords(position: IPosition): { x: number; y: number } {
if (!this._editor.hasModel()) {
return { x: 0, y: 0 };
}
this._editor.revealPosition(position, ScrollType.Immediate);
this._editor.render();
// Translate to absolute editor position
const cursorCoords = this._editor.getScrolledVisiblePosition(position);
const editorCoords = dom.getDomNodePagePosition(this._editor.getDomNode());
const x = editorCoords.left + cursorCoords.left;
const y = editorCoords.top + cursorCoords.top + cursorCoords.height;
return { x, y };
}
}
export class CodeActionKeybindingResolver {
private static readonly codeActionCommands: readonly string[] = [
refactorCommandId,
codeActionCommandId,
sourceActionCommandId,
organizeImportsCommandId,
fixAllCommandId
];
constructor(
private readonly _keybindingProvider: {
getKeybindings(): readonly ResolvedKeybindingItem[];
},
) { }
public getResolver(): (action: CodeAction) => ResolvedKeybinding | undefined {
// Lazy since we may not actually ever read the value
const allCodeActionBindings = new Lazy<readonly ResolveCodeActionKeybinding[]>(() =>
this._keybindingProvider.getKeybindings()
.filter(item => CodeActionKeybindingResolver.codeActionCommands.indexOf(item.command!) >= 0)
.filter(item => item.resolvedKeybinding)
.map((item): ResolveCodeActionKeybinding => {
// Special case these commands since they come built-in with VS Code and don't use 'commandArgs'
let commandArgs = item.commandArgs;
if (item.command === organizeImportsCommandId) {
commandArgs = { kind: CodeActionKind.SourceOrganizeImports.value };
} else if (item.command === fixAllCommandId) {
commandArgs = { kind: CodeActionKind.SourceFixAll.value };
}
return {
resolvedKeybinding: item.resolvedKeybinding!,
...CodeActionCommandArgs.fromUser(commandArgs, {
kind: CodeActionKind.None,
apply: CodeActionAutoApply.Never
})
};
}));
return (action) => {
if (action.kind) {
const binding = this.bestKeybindingForCodeAction(action, allCodeActionBindings.getValue());
return binding?.resolvedKeybinding;
}
return undefined;
};
}
private bestKeybindingForCodeAction(
action: CodeAction,
candidates: readonly ResolveCodeActionKeybinding[],
): ResolveCodeActionKeybinding | undefined {
if (!action.kind) {
return undefined;
}
const kind = new CodeActionKind(action.kind);
return candidates
.filter(candidate => candidate.kind.contains(kind))
.filter(candidate => {
if (candidate.preferred) {
// If the candidate keybinding only applies to preferred actions, the this action must also be preferred
return action.isPreferred;
}
return true;
})
.reduceRight((currentBest, candidate) => {
if (!currentBest) {
return candidate;
}
// Select the more specific binding
return currentBest.kind.contains(candidate.kind) ? candidate : currentBest;
}, undefined as ResolveCodeActionKeybinding | undefined);
}
}