diff --git a/packages/core/src/browser/menu/browser-context-menu-renderer.ts b/packages/core/src/browser/menu/browser-context-menu-renderer.ts index 73159a64817c7..2e5025049512d 100644 --- a/packages/core/src/browser/menu/browser-context-menu-renderer.ts +++ b/packages/core/src/browser/menu/browser-context-menu-renderer.ts @@ -18,13 +18,9 @@ export class BrowserContextMenuRenderer implements ContextMenuRenderer { render(path: string, anchor: Anchor, onHide?: () => void): void { const contextMenu = this.menuFactory.createContextMenu(path); const { x, y } = anchor instanceof MouseEvent ? { x: anchor.clientX, y: anchor.clientY } : anchor; - const previouslyActive = window.document.activeElement as HTMLElement; - contextMenu.aboutToClose.connect(() => { - previouslyActive.focus(); - if (onHide) { - onHide(); - } - }); + if (onHide) { + contextMenu.aboutToClose.connect(() => onHide()); + } contextMenu.open(x, y); } diff --git a/packages/core/src/browser/menu/browser-menu-plugin.ts b/packages/core/src/browser/menu/browser-menu-plugin.ts index 6ec72ae3e3ef5..c7b70d98c7d09 100644 --- a/packages/core/src/browser/menu/browser-menu-plugin.ts +++ b/packages/core/src/browser/menu/browser-menu-plugin.ts @@ -96,6 +96,7 @@ class DynamicMenuBarWidget extends MenuBarWidget { super['_openChildMenu'](); }; } + } /** * A menu widget that would recompute its items on update @@ -115,6 +116,17 @@ class DynamicMenuWidget extends MenuWidget { this.updateSubMenus(this, this.menu, this.options.commands); } + public open(x: number, y: number, options?: MenuWidget.IOpenOptions): void { + // we want to restore the focus after the menu closes. + const previouslyActive = window.document.activeElement as HTMLElement; + const cb = () => { + previouslyActive.focus(); + this.aboutToClose.disconnect(cb); + }; + this.aboutToClose.connect(cb); + super.open(x, y, options); + } + private updateSubMenus(parent: MenuWidget, menu: CompositeMenuNode, commands: PhosphorCommandRegistry): void { for (const item of menu.children) { if (item instanceof CompositeMenuNode) {