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
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { $, addDisposableListener, append, asCSSUrl, EventType, ModifierKeyEmitter, prepend } from 'vs/base/browser/dom';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { ActionViewItem, BaseActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems';
import { DropdownMenuActionViewItem, IDropdownMenuActionViewItemOptions } from 'vs/base/browser/ui/dropdown/dropdownActionViewItem';
import { ActionRunner, IAction, IRunEvent, Separator, SubmenuAction } from 'vs/base/common/actions';
import { Event } from 'vs/base/common/event';
import { UILabelProvider } from 'vs/base/common/keybindingLabels';
import { KeyCode } from 'vs/base/common/keyCodes';
import { combinedDisposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { isLinux, isWindows, OS } from 'vs/base/common/platform';
import 'vs/css!./menuEntryActionViewItem';
import { localize } from 'vs/nls';
import { IMenu, IMenuActionOptions, IMenuService, MenuItemAction, SubmenuItemAction } from 'vs/platform/actions/common/actions';
import { ICommandAction, Icon } from 'vs/platform/action/common/action';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService';
import { isDark } from 'vs/platform/theme/common/theme';
import { IHoverDelegate } from 'vs/base/browser/ui/iconLabel/iconHoverDelegate';
import { assertType } from 'vs/base/common/types';
export function createAndFillInContextMenuActions(menu: IMenu, options: IMenuActionOptions | undefined, target: IAction[] | { primary: IAction[]; secondary: IAction[] }, primaryGroup?: string): IDisposable {
const groups = menu.getActions(options);
const modifierKeyEmitter = ModifierKeyEmitter.getInstance();
const useAlternativeActions = modifierKeyEmitter.keyStatus.altKey || ((isWindows || isLinux) && modifierKeyEmitter.keyStatus.shiftKey);
fillInActions(groups, target, useAlternativeActions, primaryGroup ? actionGroup => actionGroup === primaryGroup : actionGroup => actionGroup === 'navigation');
return asDisposable(groups);
}
export function createAndFillInActionBarActions(menu: IMenu, options: IMenuActionOptions | undefined, target: IAction[] | { primary: IAction[]; secondary: IAction[] }, primaryGroup?: string | ((actionGroup: string) => boolean), primaryMaxCount?: number, shouldInlineSubmenu?: (action: SubmenuAction, group: string, groupSize: number) => boolean, useSeparatorsInPrimaryActions?: boolean): IDisposable {
const groups = menu.getActions(options);
const isPrimaryAction = typeof primaryGroup === 'string' ? (actionGroup: string) => actionGroup === primaryGroup : primaryGroup;
// Action bars handle alternative actions on their own so the alternative actions should be ignored
fillInActions(groups, target, false, isPrimaryAction, primaryMaxCount, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
return asDisposable(groups);
}
function asDisposable(groups: ReadonlyArray<[string, ReadonlyArray<MenuItemAction | SubmenuItemAction>]>): IDisposable {
const disposables = new DisposableStore();
for (const [, actions] of groups) {
for (const action of actions) {
disposables.add(action);
}
}
return disposables;
}
function fillInActions(
groups: ReadonlyArray<[string, ReadonlyArray<MenuItemAction | SubmenuItemAction>]>, target: IAction[] | { primary: IAction[]; secondary: IAction[] },
useAlternativeActions: boolean,
isPrimaryAction: (actionGroup: string) => boolean = actionGroup => actionGroup === 'navigation',
primaryMaxCount: number = Number.MAX_SAFE_INTEGER,
shouldInlineSubmenu: (action: SubmenuAction, group: string, groupSize: number) => boolean = () => false,
useSeparatorsInPrimaryActions: boolean = false
): void {
let primaryBucket: IAction[];
let secondaryBucket: IAction[];
if (Array.isArray(target)) {
primaryBucket = target;
secondaryBucket = target;
} else {
primaryBucket = target.primary;
secondaryBucket = target.secondary;
}
const submenuInfo = new Set<{ group: string; action: SubmenuAction; index: number }>();
for (const [group, actions] of groups) {
let target: IAction[];
if (isPrimaryAction(group)) {
target = primaryBucket;
if (target.length > 0 && useSeparatorsInPrimaryActions) {
target.push(new Separator());
}
} else {
target = secondaryBucket;
if (target.length > 0) {
target.push(new Separator());
}
}
for (let action of actions) {
if (useAlternativeActions) {
action = action instanceof MenuItemAction && action.alt ? action.alt : action;
}
const newLen = target.push(action);
// keep submenu info for later inlining
if (action instanceof SubmenuAction) {
submenuInfo.add({ group, action, index: newLen - 1 });
}
}
}
// ask the outside if submenu should be inlined or not. only ask when
// there would be enough space
for (const { group, action, index } of submenuInfo) {
const target = isPrimaryAction(group) ? primaryBucket : secondaryBucket;
// inlining submenus with length 0 or 1 is easy,
// larger submenus need to be checked with the overall limit
const submenuActions = action.actions;
if ((submenuActions.length <= 1 || target.length + submenuActions.length - 2 <= primaryMaxCount) && shouldInlineSubmenu(action, group, target.length)) {
target.splice(index, 1, ...submenuActions);
}
}
// overflow items from the primary group into the secondary bucket
if (primaryBucket !== secondaryBucket && primaryBucket.length > primaryMaxCount) {
const overflow = primaryBucket.splice(primaryMaxCount, primaryBucket.length - primaryMaxCount);
secondaryBucket.unshift(...overflow, new Separator());
}
}
export interface IMenuEntryActionViewItemOptions {
draggable?: boolean;
keybinding?: string;
hoverDelegate?: IHoverDelegate;
}
function registerConfigureMenu(contextMenuService: IContextMenuService, item: BaseActionViewItem, action: MenuItemAction | SubmenuItemAction): IDisposable {
assertType(item.element);
return addDisposableListener(item.element, 'contextmenu', event => {
if (!action.hideActions) {
return;
}
event.preventDefault();
event.stopPropagation();
contextMenuService.showContextMenu({
getAnchor: () => item.element!,
getActions: () => action.hideActions!.asList()
});
}, true);
}
export class MenuEntryActionViewItem extends ActionViewItem {
private _wantsAltCommand: boolean = false;
private readonly _itemClassDispose = this._register(new MutableDisposable());
private readonly _altKey: ModifierKeyEmitter;
constructor(
action: MenuItemAction,
options: IMenuEntryActionViewItemOptions | undefined,
@IKeybindingService protected readonly _keybindingService: IKeybindingService,
@INotificationService protected _notificationService: INotificationService,
@IContextKeyService protected _contextKeyService: IContextKeyService,
@IThemeService protected _themeService: IThemeService,
@IContextMenuService protected _contextMenuService: IContextMenuService
) {
super(undefined, action, { icon: !!(action.class || action.item.icon), label: !action.class && !action.item.icon, draggable: options?.draggable, keybinding: options?.keybinding, hoverDelegate: options?.hoverDelegate });
this._altKey = ModifierKeyEmitter.getInstance();
}
protected get _menuItemAction(): MenuItemAction {
return <MenuItemAction>this._action;
}
protected get _commandAction(): MenuItemAction {
return this._wantsAltCommand && this._menuItemAction.alt || this._menuItemAction;
}
override async onClick(event: MouseEvent): Promise<void> {
event.preventDefault();
event.stopPropagation();
try {
await this.actionRunner.run(this._commandAction, this._context);
} catch (err) {
this._notificationService.error(err);
}
}
override render(container: HTMLElement): void {
super.render(container);
container.classList.add('menu-entry');
this._updateItemClass(this._menuItemAction.item);
let mouseOver = false;
let alternativeKeyDown = this._altKey.keyStatus.altKey || ((isWindows || isLinux) && this._altKey.keyStatus.shiftKey);
const updateAltState = () => {
const wantsAltCommand = mouseOver && alternativeKeyDown && !!this._commandAction.alt?.enabled;
if (wantsAltCommand !== this._wantsAltCommand) {
this._wantsAltCommand = wantsAltCommand;
this.updateLabel();
this.updateTooltip();
this.updateClass();
}
};
if (this._menuItemAction.alt) {
this._register(this._altKey.event(value => {
alternativeKeyDown = value.altKey || ((isWindows || isLinux) && value.shiftKey);
updateAltState();
}));
}
this._register(addDisposableListener(container, 'mouseleave', _ => {
mouseOver = false;
updateAltState();
}));
this._register(addDisposableListener(container, 'mouseenter', _ => {
mouseOver = true;
updateAltState();
}));
this._register(registerConfigureMenu(this._contextMenuService, this, this._menuItemAction));
}
override updateLabel(): void {
if (this.options.label && this.label) {
this.label.textContent = this._commandAction.label;
}
}
override getTooltip() {
const keybinding = this._keybindingService.lookupKeybinding(this._commandAction.id, this._contextKeyService);
const keybindingLabel = keybinding && keybinding.getLabel();
const tooltip = this._commandAction.tooltip || this._commandAction.label;
let title = keybindingLabel
? localize('titleAndKb', "{0} ({1})", tooltip, keybindingLabel)
: tooltip;
if (!this._wantsAltCommand && this._menuItemAction.alt?.enabled) {
const altTooltip = this._menuItemAction.alt.tooltip || this._menuItemAction.alt.label;
const altKeybinding = this._keybindingService.lookupKeybinding(this._menuItemAction.alt.id, this._contextKeyService);
const altKeybindingLabel = altKeybinding && altKeybinding.getLabel();
const altTitleSection = altKeybindingLabel
? localize('titleAndKb', "{0} ({1})", altTooltip, altKeybindingLabel)
: altTooltip;
title = localize('titleAndKbAndAlt', "{0}\n[{1}] {2}", title, UILabelProvider.modifierLabels[OS].altKey, altTitleSection);
}
return title;
}
override updateClass(): void {
if (this.options.icon) {
if (this._commandAction !== this._menuItemAction) {
if (this._menuItemAction.alt) {
this._updateItemClass(this._menuItemAction.alt.item);
}
} else {
this._updateItemClass(this._menuItemAction.item);
}
}
}
private _updateItemClass(item: ICommandAction): void {
this._itemClassDispose.value = undefined;
const { element, label } = this;
if (!element || !label) {
return;
}
const icon = this._commandAction.checked && (item.toggled as { icon?: Icon })?.icon ? (item.toggled as { icon: Icon }).icon : item.icon;
if (!icon) {
return;
}
if (ThemeIcon.isThemeIcon(icon)) {
// theme icons
const iconClasses = ThemeIcon.asClassNameArray(icon);
label.classList.add(...iconClasses);
this._itemClassDispose.value = toDisposable(() => {
label.classList.remove(...iconClasses);
});
} else {
// icon path/url
label.style.backgroundImage = (
isDark(this._themeService.getColorTheme().type)
? asCSSUrl(icon.dark)
: asCSSUrl(icon.light)
);
label.classList.add('icon');
this._itemClassDispose.value = combinedDisposable(
toDisposable(() => {
label.style.backgroundImage = '';
label.classList.remove('icon');
}),
this._themeService.onDidColorThemeChange(() => {
// refresh when the theme changes in case we go between dark <-> light
this.updateClass();
})
);
}
}
}
export class SubmenuEntryActionViewItem extends DropdownMenuActionViewItem {
constructor(
action: SubmenuItemAction,
options: IDropdownMenuActionViewItemOptions | undefined,
@IContextMenuService protected _contextMenuService: IContextMenuService,
@IThemeService protected _themeService: IThemeService
) {
const dropdownOptions = Object.assign({}, options ?? Object.create(null), {
menuAsChild: options?.menuAsChild ?? false,
classNames: options?.classNames ?? (ThemeIcon.isThemeIcon(action.item.icon) ? ThemeIcon.asClassName(action.item.icon) : undefined),
});
super(action, { getActions: () => action.actions }, _contextMenuService, dropdownOptions);
}
override render(container: HTMLElement): void {
super.render(container);
assertType(this.element);
container.classList.add('menu-entry');
const action = <SubmenuItemAction>this._action;
const { icon } = action.item;
if (icon && !ThemeIcon.isThemeIcon(icon)) {
this.element.classList.add('icon');
const setBackgroundImage = () => {
if (this.element) {
this.element.style.backgroundImage = (
isDark(this._themeService.getColorTheme().type)
? asCSSUrl(icon.dark)
: asCSSUrl(icon.light)
);
}
};
setBackgroundImage();
this._register(this._themeService.onDidColorThemeChange(() => {
// refresh when the theme changes in case we go between dark <-> light
setBackgroundImage();
}));
}
this._register(registerConfigureMenu(this._contextMenuService, this, action));
}
}
export interface IDropdownWithDefaultActionViewItemOptions extends IDropdownMenuActionViewItemOptions {
renderKeybindingWithDefaultActionLabel?: boolean;
}
export class DropdownWithDefaultActionViewItem extends BaseActionViewItem {
private readonly _options: IDropdownWithDefaultActionViewItemOptions | undefined;
private _defaultAction: ActionViewItem;
private _dropdown: DropdownMenuActionViewItem;
private _container: HTMLElement | null = null;
private _storageKey: string;
get onDidChangeDropdownVisibility(): Event<boolean> {
return this._dropdown.onDidChangeVisibility;
}
constructor(
submenuAction: SubmenuItemAction,
options: IDropdownWithDefaultActionViewItemOptions | undefined,
@IKeybindingService protected readonly _keybindingService: IKeybindingService,
@INotificationService protected _notificationService: INotificationService,
@IContextMenuService protected _contextMenuService: IContextMenuService,
@IMenuService protected _menuService: IMenuService,
@IInstantiationService protected _instaService: IInstantiationService,
@IStorageService protected _storageService: IStorageService
) {
super(null, submenuAction);
this._options = options;
this._storageKey = `${submenuAction.item.submenu.id}_lastActionId`;
// determine default action
let defaultAction: IAction | undefined;
const defaultActionId = _storageService.get(this._storageKey, StorageScope.WORKSPACE);
if (defaultActionId) {
defaultAction = submenuAction.actions.find(a => defaultActionId === a.id);
}
if (!defaultAction) {
defaultAction = submenuAction.actions[0];
}
this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, <MenuItemAction>defaultAction, { keybinding: this._getDefaultActionKeybindingLabel(defaultAction) });
const dropdownOptions = Object.assign({}, options ?? Object.create(null), {
menuAsChild: options?.menuAsChild ?? true,
classNames: options?.classNames ?? ['codicon', 'codicon-chevron-down'],
actionRunner: options?.actionRunner ?? new ActionRunner()
});
this._dropdown = new DropdownMenuActionViewItem(submenuAction, submenuAction.actions, this._contextMenuService, dropdownOptions);
this._dropdown.actionRunner.onDidRun((e: IRunEvent) => {
if (e.action instanceof MenuItemAction) {
this.update(e.action);
}
});
}
private update(lastAction: MenuItemAction): void {
this._storageService.store(this._storageKey, lastAction.id, StorageScope.WORKSPACE, StorageTarget.USER);
this._defaultAction.dispose();
this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, lastAction, { keybinding: this._getDefaultActionKeybindingLabel(lastAction) });
this._defaultAction.actionRunner = new class extends ActionRunner {
override async runAction(action: IAction, context?: unknown): Promise<void> {
await action.run(undefined);
}
}();
if (this._container) {
this._defaultAction.render(prepend(this._container, $('.action-container')));
}
}
private _getDefaultActionKeybindingLabel(defaultAction: IAction) {
let defaultActionKeybinding: string | undefined;
if (this._options?.renderKeybindingWithDefaultActionLabel) {
const kb = this._keybindingService.lookupKeybinding(defaultAction.id);
if (kb) {
defaultActionKeybinding = `(${kb.getLabel()})`;
}
}
return defaultActionKeybinding;
}
override setActionContext(newContext: unknown): void {
super.setActionContext(newContext);
this._defaultAction.setActionContext(newContext);
this._dropdown.setActionContext(newContext);
}
override render(container: HTMLElement): void {
this._container = container;
super.render(this._container);
this._container.classList.add('monaco-dropdown-with-default');
const primaryContainer = $('.action-container');
this._defaultAction.render(append(this._container, primaryContainer));
this._register(addDisposableListener(primaryContainer, EventType.KEY_DOWN, (e: KeyboardEvent) => {
const event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.RightArrow)) {
this._defaultAction.element!.tabIndex = -1;
this._dropdown.focus();
event.stopPropagation();
}
}));
const dropdownContainer = $('.dropdown-action-container');
this._dropdown.render(append(this._container, dropdownContainer));
this._register(addDisposableListener(dropdownContainer, EventType.KEY_DOWN, (e: KeyboardEvent) => {
const event = new StandardKeyboardEvent(e);
if (event.equals(KeyCode.LeftArrow)) {
this._defaultAction.element!.tabIndex = 0;
this._dropdown.setFocusable(false);
this._defaultAction.element?.focus();
event.stopPropagation();
}
}));
this._register(registerConfigureMenu(this._contextMenuService, this, (<SubmenuItemAction>this.action)));
}
override focus(fromRight?: boolean): void {
if (fromRight) {
this._dropdown.focus();
} else {
this._defaultAction.element!.tabIndex = 0;
this._defaultAction.element!.focus();
}
}
override blur(): void {
this._defaultAction.element!.tabIndex = -1;
this._dropdown.blur();
this._container!.blur();
}
override setFocusable(focusable: boolean): void {
if (focusable) {
this._defaultAction.element!.tabIndex = 0;
} else {
this._defaultAction.element!.tabIndex = -1;
this._dropdown.setFocusable(false);
}
}
override dispose() {
this._defaultAction.dispose();
this._dropdown.dispose();
super.dispose();
}
}
/**
* Creates action view items for menu actions or submenu actions.
*/
export function createActionViewItem(instaService: IInstantiationService, action: IAction, options?: IDropdownMenuActionViewItemOptions | IMenuEntryActionViewItemOptions): undefined | MenuEntryActionViewItem | SubmenuEntryActionViewItem | BaseActionViewItem {
if (action instanceof MenuItemAction) {
return instaService.createInstance(MenuEntryActionViewItem, action, options);
} else if (action instanceof SubmenuItemAction) {
if (action.item.rememberDefaultAction) {
return instaService.createInstance(DropdownWithDefaultActionViewItem, action, options);
} else {
return instaService.createInstance(SubmenuEntryActionViewItem, action, options);
}
} else {
return undefined;
}
}
|