@theia/core
Version:
Theia is a cloud & desktop IDE framework implemented in TypeScript.
552 lines • 24.2 kB
JavaScript
// *****************************************************************************
// Copyright (C) 2017 TypeFox and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-only WITH Classpath-exception-2.0
// *****************************************************************************
import { __decorate, __param } from "tslib";
import { injectable, inject } from 'inversify';
import { MenuBar, Menu as MenuWidget, Widget } from '@lumino/widgets';
import { CommandRegistry as LuminoCommandRegistry } from '@lumino/commands';
import { environment, Disposable, DisposableCollection, AcceleratorSource, ArrayUtils, PreferenceService } from '../../common/index.js';
import { KeybindingRegistry } from '../keybinding.js';
import { ContextKeyService } from '../context-key-service.js';
import { ContextMenuContext } from './context-menu-context.js';
import { waitForRevealed } from '../widgets/index.js';
import { ApplicationShell } from '../shell/index.js';
import { CorePreferences } from '../../common/core-preferences.js';
import { ElementExt } from '@lumino/domutils';
import { CommandMenu, CompoundMenuNode, MAIN_MENU_BAR, RenderedMenuNode } from '../../common/menu/menu-types.js';
import { MenuModelRegistry } from '../../common/menu/menu-model-registry.js';
export class MenuBarWidget extends MenuBar {
}
;
let BrowserMainMenuFactory = class BrowserMainMenuFactory {
createMenuBar() {
const menuBar = new DynamicMenuBarWidget();
menuBar.id = 'theia:menubar';
this.corePreferences.ready.then(() => {
this.showMenuBar(menuBar);
});
const disposable = new DisposableCollection(this.corePreferences.onPreferenceChanged(change => {
if (change.preferenceName === 'window.menuBarVisibility') {
this.showMenuBar(menuBar, this.corePreferences['window.menuBarVisibility']);
}
}), this.keybindingRegistry.onKeybindingsChanged(() => {
this.showMenuBar(menuBar);
}), this.menuProvider.onDidChange(evt => {
if (ArrayUtils.startsWith(evt.path, MAIN_MENU_BAR)) {
this.showMenuBar(menuBar);
}
}));
menuBar.disposed.connect(() => disposable.dispose());
return menuBar;
}
getMenuBarVisibility() {
return this.corePreferences.get('window.menuBarVisibility', 'classic');
}
showMenuBar(menuBar, preference = this.getMenuBarVisibility()) {
if (preference && ['classic', 'visible', 'toggle'].includes(preference)) {
menuBar.clearMenus();
this.fillMenuBar(menuBar);
}
else {
menuBar.clearMenus();
}
}
fillMenuBar(menuBar) {
const menuModel = this.menuProvider.getMenuNode(MAIN_MENU_BAR);
const menuCommandRegistry = new LuminoCommandRegistry();
for (const menu of menuModel.children) {
if (CompoundMenuNode.is(menu) && RenderedMenuNode.is(menu)) {
const menuWidget = this.createMenuWidget(MAIN_MENU_BAR, menu, this.contextKeyService, { commands: menuCommandRegistry });
menuBar.addMenu(menuWidget);
}
}
}
createContextMenu(effectiveMenuPath, menuModel, contextMatcher, args, context) {
const menuCommandRegistry = new LuminoCommandRegistry();
const contextMenu = this.createMenuWidget(effectiveMenuPath, menuModel, contextMatcher, { commands: menuCommandRegistry, context }, args);
return contextMenu;
}
createMenuWidget(parentPath, menu, contextMatcher, options, args) {
return new DynamicMenuWidget(parentPath, menu, options, contextMatcher, this.services, args);
}
get services() {
return {
contextKeyService: this.contextKeyService,
context: this.context,
menuWidgetFactory: this,
};
}
};
__decorate([
inject(ContextKeyService)
], BrowserMainMenuFactory.prototype, "contextKeyService", void 0);
__decorate([
inject(ContextMenuContext)
], BrowserMainMenuFactory.prototype, "context", void 0);
__decorate([
inject(CorePreferences)
], BrowserMainMenuFactory.prototype, "corePreferences", void 0);
__decorate([
inject(KeybindingRegistry)
], BrowserMainMenuFactory.prototype, "keybindingRegistry", void 0);
__decorate([
inject(MenuModelRegistry)
], BrowserMainMenuFactory.prototype, "menuProvider", void 0);
BrowserMainMenuFactory = __decorate([
injectable()
], BrowserMainMenuFactory);
export { BrowserMainMenuFactory };
export function isMenuElement(element) {
return !!element && element.className.includes('lm-Menu');
}
export class DynamicMenuBarWidget extends MenuBarWidget {
constructor() {
// Disable Lumino's overflow menu feature. The feature has a bug where
// `onUpdateRequest` consumes a stale `_overflowIndex` (only recomputed at the
// end of the method), which causes a RangeError when the menu bar is rendered
// at zero width. Additionally, Theia's CSS does not constrain the menu bar's
// offsetWidth to the available space, so the overflow detection never triggers.
// See https://github.com/eclipse-theia/theia/issues/17352
// See https://github.com/jupyterlab/lumino/issues/811
super({ overflowMenuOptions: { isVisible: false } });
// HACK we need to hook in on private method _openChildMenu. Don't do this at home!
DynamicMenuBarWidget.prototype['_openChildMenu'] = () => {
if (this.activeMenu instanceof DynamicMenuWidget) {
// `childMenu` is `null` if we open the menu. For example, menu is not shown and you click on `Edit`.
// However, the `childMenu` is set, when `Edit` was already open and you move the mouse over `Select`.
// We want to save the focus object for the former case only.
if (!this.childMenu) {
const { activeElement } = document;
// we do not want to restore focus to menus
if (activeElement instanceof HTMLElement && !isMenuElement(activeElement)) {
this.previousFocusedElement = activeElement;
}
}
this.activeMenu.aboutToShow({ previousFocusedElement: this.previousFocusedElement });
}
super['_openChildMenu']();
};
}
async activateMenu(label, ...labels) {
const menu = this.menus.find(m => m.title.label === label);
if (!menu) {
throw new Error(`could not find '${label}' menu`);
}
this.activeMenu = menu;
this.openActiveMenu();
await waitForRevealed(menu);
const menuPath = [label, ...labels];
let current = menu;
for (const itemLabel of labels) {
const item = current.items.find(i => i.label === itemLabel);
if (!item || !item.submenu) {
throw new Error(`could not find '${itemLabel}' submenu in ${menuPath.map(l => "'" + l + "'").join(' -> ')} menu`);
}
current.activeItem = item;
current.triggerActiveItem();
current = item.submenu;
await waitForRevealed(current);
}
return current;
}
async triggerMenuItem(label, ...labels) {
if (!labels.length) {
throw new Error('menu item label is not specified');
}
const menuPath = [label, ...labels.slice(0, labels.length - 1)];
const menu = await this.activateMenu(menuPath[0], ...menuPath.slice(1));
const item = menu.items.find(i => i.label === labels[labels.length - 1]);
if (!item) {
throw new Error(`could not find '${labels[labels.length - 1]}' item in ${menuPath.map(l => "'" + l + "'").join(' -> ')} menu`);
}
menu.activeItem = item;
menu.triggerActiveItem();
return item;
}
}
export class MenuServices {
}
/**
* A menu widget that would recompute its items on update.
*/
export class DynamicMenuWidget extends MenuWidget {
static { this.nextCommmandId = 0; }
constructor(effectiveMenuPath, menu, options, contextMatcher, services, args) {
super(options);
this.effectiveMenuPath = effectiveMenuPath;
this.menu = menu;
this.options = options;
this.contextMatcher = contextMatcher;
this.services = services;
this.args = args;
if (RenderedMenuNode.is(this.menu)) {
if (this.menu.label) {
this.title.label = this.menu.label;
}
if (this.menu.icon) {
this.title.iconClass = this.menu.icon;
}
}
this.updateSubMenus(this.effectiveMenuPath, this, this.menu, this.options.commands, this.contextMatcher, this.options.context);
}
onAfterAttach(msg) {
super.onAfterAttach(msg);
this.node.ownerDocument.addEventListener('pointerdown', this, true);
}
onBeforeDetach(msg) {
this.node.ownerDocument.removeEventListener('pointerdown', this, true);
super.onBeforeDetach(msg);
}
handleEvent(event) {
if (event.type === 'pointerdown') {
this.handlePointerDown(event);
}
super.handleEvent(event);
}
handlePointerDown(event) {
// this code is copied from the superclass because we cannot use the hit
// test from the "Private" implementation namespace
if (this['_parentMenu']) {
return;
}
// The mouse button which is pressed is irrelevant. If the press
// is not on a menu, the entire hierarchy is closed and the event
// is allowed to propagate. This allows other code to act on the
// event, such as focusing the clicked element.
if (!this.hitTestMenus(this, event.clientX, event.clientY)) {
this.close();
}
}
hitTestMenus(menu, x, y) {
for (let temp = menu; temp; temp = temp.childMenu) {
if (ElementExt.hitTest(temp.node, x, y)) {
return true;
}
}
return false;
}
aboutToShow({ previousFocusedElement }) {
this.preserveFocusedElement(previousFocusedElement);
this.clearItems();
this.runWithPreservedFocusContext(() => {
this.updateSubMenus(this.effectiveMenuPath, this, this.menu, this.options.commands, this.contextMatcher, this.options.context);
});
}
open(x, y, options) {
const cb = () => {
this.restoreFocusedElement();
this.aboutToClose.disconnect(cb);
};
this.aboutToClose.connect(cb);
this.preserveFocusedElement();
super.open(x, y, options);
}
updateSubMenus(parentPath, parent, menu, commands, contextMatcher, context) {
const items = this.createItems(parentPath, menu.children, commands, contextMatcher, context);
while (items[items.length - 1]?.type === 'separator') {
items.pop();
}
for (const item of items) {
parent.addItem(item);
}
}
createItems(parentPath, nodes, phCommandRegistry, contextMatcher, context) {
const result = [];
for (const node of nodes) {
const nodePath = node.effectiveMenuPath || [...parentPath, node.id];
if (node.isVisible(nodePath, contextMatcher, context, ...(this.args || []))) {
if (CompoundMenuNode.is(node)) {
if (RenderedMenuNode.is(node)) {
const submenu = this.services.menuWidgetFactory.createMenuWidget(nodePath, node, this.contextMatcher, this.options, this.args);
if (submenu.items.length > 0) {
result.push({ type: 'submenu', submenu });
}
}
else if (node.id !== 'inline') {
const items = this.createItems(nodePath, node.children, phCommandRegistry, contextMatcher, context);
if (items.length > 0) {
if (result[result.length - 1]?.type !== 'separator') {
result.push({ type: 'separator' });
}
result.push(...items);
result.push({ type: 'separator' });
}
}
}
else if (CommandMenu.is(node)) {
const id = !phCommandRegistry.hasCommand(node.id) ? node.id : `${node.id}:${DynamicMenuWidget.nextCommmandId++}`;
const enabled = node.isEnabled(nodePath, ...(this.args || []));
const toggled = node.isToggled ? !!node.isToggled(nodePath, ...(this.args || [])) : false;
phCommandRegistry.addCommand(id, {
execute: () => {
// Restore focus to the previously focused element before executing
// the command so that focus-dependent commands like clipboard
// operations target the correct element instead of the menu.
if (this.previousFocusedElement) {
this.previousFocusedElement.focus({ preventScroll: true });
}
node.run(nodePath, ...(this.args || []));
},
isEnabled: () => enabled,
isToggled: () => toggled,
isVisible: () => true,
label: node.label,
iconClass: node.icon,
});
const accelerator = (AcceleratorSource.is(node) ? node.getAccelerator(this.options.context, 'logical') : []);
if (accelerator.length > 0) {
phCommandRegistry.addKeyBinding({
command: id,
keys: accelerator,
selector: '.p-Widget' // We have the PhosphorJS dependency anyway.
});
}
result.push({
command: id,
type: 'command'
});
}
}
}
return result;
}
preserveFocusedElement(previousFocusedElement = document.activeElement) {
if (!this.previousFocusedElement && previousFocusedElement instanceof HTMLElement && !isMenuElement(previousFocusedElement)) {
this.previousFocusedElement = previousFocusedElement;
return true;
}
return false;
}
restoreFocusedElement() {
if (this.previousFocusedElement) {
this.previousFocusedElement.focus({ preventScroll: true });
this.previousFocusedElement = undefined;
return true;
}
return false;
}
runWithPreservedFocusContext(what) {
let focusToRestore = undefined;
const { activeElement } = document;
if (this.previousFocusedElement &&
activeElement instanceof HTMLElement &&
this.previousFocusedElement !== activeElement) {
focusToRestore = activeElement;
this.previousFocusedElement.focus({ preventScroll: true });
}
try {
what();
}
finally {
if (focusToRestore && !isMenuElement(focusToRestore)) {
focusToRestore.focus({ preventScroll: true });
}
}
}
}
let BrowserMenuBarContribution = class BrowserMenuBarContribution {
constructor(factory) {
this.factory = factory;
this.toggleModeListeners = new DisposableCollection();
}
onStart(app) {
this.appendMenu(app.shell);
}
get menuBar() {
return this.shell.topPanel.widgets.find(w => w instanceof MenuBarWidget);
}
appendMenu(shell) {
const logo = this.createLogo();
shell.addWidget(logo, { area: 'top' });
const menu = this.factory.createMenuBar();
shell.addWidget(menu, { area: 'top' });
this.menuWidget = menu;
this.logoWidget = logo;
if (environment.electron.is()) {
this.preferenceService.ready.then(() => {
this.updateElectronMenuToggleMode(menu, logo);
});
this.preferenceService.onPreferenceChanged(change => {
if (change.preferenceName === 'window.menuBarVisibility') {
this.updateElectronMenuToggleMode(menu, logo);
}
});
}
else {
// In the browser, the whole top panel is hidden for compact/hidden/toggle
// (handled by ApplicationShell). For toggle mode, this installs an Alt-key
// listener that temporarily shows the top panel.
this.preferenceService.ready.then(() => {
this.updateBrowserMenuToggleMode(menu);
});
this.preferenceService.onPreferenceChanged(change => {
if (change.preferenceName === 'window.menuBarVisibility') {
this.updateBrowserMenuToggleMode(menu);
}
});
}
}
/**
* Manages Lumino menu bar visibility and Alt-key toggling in Electron.
*
* With native title bar, the native Electron menu bar handles toggle via
* `autoHideMenuBar`, so the Lumino menu bar is simply hidden.
*
* With custom title bar, the Lumino menu bar is the only menu bar visible
* to the user. For 'toggle' mode, an Alt-key listener is installed to
* show/hide the menu bar widget.
*/
updateElectronMenuToggleMode(menu, logo) {
this.toggleModeListeners.dispose();
const pref = this.preferenceService.get('window.menuBarVisibility', 'classic');
this.applyElectronMenuBarVisibility(menu, logo, pref);
if (pref === 'toggle') {
this.toggleModeListeners = this.installAltKeyToggle(menu, () => this.getElectronToggleTargets(menu, logo));
}
}
/**
* Establishes the resting visibility of the menu bar widgets in Electron, i.e. the state
* a clean Alt press toggles away from in 'toggle' mode.
*/
applyElectronMenuBarVisibility(menu, logo, pref) {
const shouldHide = ['compact', 'hidden', 'toggle'].includes(pref);
menu.setHidden(shouldHide);
logo.setHidden(shouldHide);
}
/**
* The widgets a clean Alt press shows and hides in 'toggle' mode in Electron.
*/
getElectronToggleTargets(menu, logo) {
return [menu, logo];
}
/**
* Manages Alt-key toggle behavior for 'toggle' mode in the browser.
* The top panel's initial visibility is handled by {@link ApplicationShell.setTopPanelVisibility};
* this method only installs or removes the Alt-key listener.
*/
updateBrowserMenuToggleMode(menu) {
this.toggleModeListeners.dispose();
const pref = this.preferenceService.get('window.menuBarVisibility', 'classic');
if (pref === 'toggle') {
this.toggleModeListeners = this.installAltKeyToggle(menu, () => [this.shell.topPanel]);
}
}
/**
* Installs Alt-key listeners to toggle menu bar visibility.
* A clean Alt press (press and release without other keys) shows the
* given toggle targets and focuses the first menu. Pressing Alt again
* or clicking outside hides them.
*
* @param menu the menu bar widget to focus when shown
* @param toggleTargets supplies the widgets to show/hide on Alt toggle. It is consulted on
* each gesture, because the targets can depend on state that changes while the listener is
* installed, e.g. whether the window is in full screen.
*/
installAltKeyToggle(menu, toggleTargets) {
const disposables = new DisposableCollection();
let altKeyPressed = false;
let lastKeyWasAlt = false;
const isHidden = () => toggleTargets().some(w => w.isHidden);
const hide = () => {
for (const w of toggleTargets()) {
w.setHidden(true);
}
};
const show = () => {
for (const w of toggleTargets()) {
w.setHidden(false);
}
};
const onKeyDown = (e) => {
if (e.key === 'Alt') {
if (!e.repeat) {
altKeyPressed = true;
lastKeyWasAlt = true;
}
}
else {
// Any other key invalidates the Alt-only gesture
lastKeyWasAlt = false;
}
};
// Mouse interaction while Alt is held is a modifier gesture of its own, e.g. Alt+click to add a
// cursor or Alt+scroll to scroll faster, so it invalidates the Alt-only gesture as any other key does.
const onPointerInteraction = () => {
lastKeyWasAlt = false;
};
const onKeyUp = (e) => {
if (e.key !== 'Alt') {
return;
}
const wasCleanAltPress = altKeyPressed && lastKeyWasAlt;
altKeyPressed = false;
lastKeyWasAlt = false;
if (!wasCleanAltPress) {
return;
}
// Keep the browser from acting on the solitary Alt press itself: Firefox, for
// instance, focuses its own menu bar, which would then toggle along with ours.
e.preventDefault();
if (isHidden()) {
show();
menu.activeIndex = 0;
menu.node.focus();
}
else {
hide();
}
};
// When a menu closes and focus leaves the menu bar, hide it again
const onFocusOut = () => {
// Use setTimeout to allow focus to settle (e.g. focus moving between menu items)
setTimeout(() => {
if (!isHidden() && !menu.node.contains(document.activeElement)) {
hide();
}
}, 100);
};
document.addEventListener('keydown', onKeyDown, true);
document.addEventListener('keyup', onKeyUp, true);
document.addEventListener('mousedown', onPointerInteraction, true);
document.addEventListener('wheel', onPointerInteraction, { capture: true, passive: true });
menu.node.addEventListener('focusout', onFocusOut);
disposables.push(Disposable.create(() => {
document.removeEventListener('keydown', onKeyDown, true);
document.removeEventListener('keyup', onKeyUp, true);
document.removeEventListener('mousedown', onPointerInteraction, true);
document.removeEventListener('wheel', onPointerInteraction, true);
menu.node.removeEventListener('focusout', onFocusOut);
}));
return disposables;
}
createLogo() {
const logo = new Widget();
logo.id = 'theia:icon';
logo.addClass('theia-icon');
return logo;
}
};
__decorate([
inject(ApplicationShell)
], BrowserMenuBarContribution.prototype, "shell", void 0);
__decorate([
inject(PreferenceService)
], BrowserMenuBarContribution.prototype, "preferenceService", void 0);
BrowserMenuBarContribution = __decorate([
injectable(),
__param(0, inject(BrowserMainMenuFactory))
], BrowserMenuBarContribution);
export { BrowserMenuBarContribution };
//# sourceMappingURL=browser-menu-plugin.js.map