Skip to content

Build your personal knowledge base with Trilium Notes

fix(menus): close open menus when a shortcut runs

Elian Doranc7455f24b3ee
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index 38acbcc3ba..e95937e2c4 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -117,6 +117,21 @@ describe("contextMenu", () => {
expect(onHide).toHaveBeenCalledTimes(1);
});
+ it("hides for `closeOpenPopups()`, as a keyboard shortcut opening a dialog calls it", async () => {
+ buildPage();
+ const contextMenu = await buildContextMenu();
+ const { closeOpenPopups } = await import("../widgets/react/Popup");
+ const onHide = vi.fn();
+
+ await contextMenu.show({ x: 10, y: 20, items, selectMenuItemHandler: () => {}, onHide });
+ closeOpenPopups();
+ await vi.waitFor(() => expect(menuElement()).toBeNull());
+ expect(contextMenu.isShown).toBe(false);
+
+ closeOpenPopups();
+ expect(onHide).toHaveBeenCalledTimes(1);
+ });
+
it("shows only the last of two menus asked for while `Menu` still loads, and hides it", async () => {
buildPage();
const contextMenu = await buildContextMenu();
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 5cc2ff1d69..16cf2245f2 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -7,6 +7,7 @@ import type { NotePresetId } from "../services/note_presets.js";
import { onSystemBack } from "../services/system_back.js";
import utils from "../services/utils.js";
import { suspendModalFocusTraps } from "../widgets/react/modal_focustrap";
+import { registerOpenPopup } from "../widgets/react/Popup";
/**
* Where the menu opens: beside a point, towards the right unless `orientation` says otherwise, or
@@ -166,6 +167,8 @@ class ContextMenu {
private stopFollowingLayout?: () => void;
/** Stops closing the menu on the system back gesture. */
private stopAnsweringBack?: () => void;
+ /** Stops closing the menu for `closeOpenPopups()`. */
+ private unregisterOpenPopup?: () => void;
constructor() {
this.cover = utils.isMobile() ? document.getElementById("context-menu-cover") : null;
@@ -224,6 +227,7 @@ class ContextMenu {
void this.hide();
return true;
});
+ this.unregisterOpenPopup = registerOpenPopup(() => void this.hide());
// A mobile menu is a sheet or placed at the press depending on the layout, decided here,
// so it closes when a tablet turns past that width.
if (utils.isMobile() && !options.forcePositionOnMobile) {
@@ -278,6 +282,8 @@ class ContextMenu {
this.stopFollowingLayout = undefined;
this.stopAnsweringBack?.();
this.stopAnsweringBack = undefined;
+ this.unregisterOpenPopup?.();
+ this.unregisterOpenPopup = undefined;
this.cover?.classList.remove("show");
document.body.classList.remove("context-menu-shown");
diff --git a/apps/client/src/services/keyboard_actions.spec.ts b/apps/client/src/services/keyboard_actions.spec.ts
index fbb53988cb..7b2a9645f7 100644
--- a/apps/client/src/services/keyboard_actions.spec.ts
+++ b/apps/client/src/services/keyboard_actions.spec.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionKeyboardShortcut } from "@triliumnext/commons";
import appContext from "../components/app_context.js";
+import { closeOpenPopups } from "../widgets/react/Popup";
// `appContext` pulls in a very large dependency graph (CKEditor, CodeMirror,
// Tabulator, …) and at module-load `keyboard_actions.ts` only needs
@@ -13,6 +14,8 @@ vi.mock("../components/app_context.js", () => ({
}
}));
+vi.mock("../widgets/react/Popup", () => ({ closeOpenPopups: vi.fn() }));
+
// `updateDisplayedShortcuts` formats shortcuts via keyboard_shortcut_display, which resolves each key
// label through i18n. Stub `t` to resolve the shortcut-key labels the way the translation files do.
vi.mock("./i18n.js", () => ({
@@ -135,7 +138,13 @@ describe("keyboard_actions", () => {
const boundShortcuts = spy!.mock.calls.map((c) => c[0]);
expect(boundShortcuts).toEqual(["ctrl+1", "ctrl+2"]);
- // The bound handler routes to appContext.triggerCommand with the active ntx id.
+ // The bound handler closes open menus, then routes to appContext.triggerCommand with the
+ // active ntx id.
+ vi.mocked(closeOpenPopups).mockClear();
+ vi.mocked(appContext.triggerCommand).mockImplementationOnce(() => {
+ expect(closeOpenPopups).toHaveBeenCalledTimes(1);
+ return Promise.resolve();
+ });
const handler = spy!.mock.calls[0][1] as () => void;
handler();
expect(appContext.triggerCommand).toHaveBeenCalledWith("winA", { ntxId: "ntx-active" });
diff --git a/apps/client/src/services/keyboard_actions.ts b/apps/client/src/services/keyboard_actions.ts
index 09cd22ba23..bfe38fd004 100644
--- a/apps/client/src/services/keyboard_actions.ts
+++ b/apps/client/src/services/keyboard_actions.ts
@@ -4,6 +4,7 @@ import { formatShortcut, joinShortcut } from "./keyboard_shortcut_display.js";
import shortcutService, { ShortcutBinding } from "./shortcuts.js";
import { isPreAuthScreen, isShare } from "./utils.js";
import type Component from "../components/component.js";
+import { closeOpenPopups } from "../widgets/react/Popup";
import type { ActionKeyboardShortcut } from "@triliumnext/commons";
const keyboardActionRepo: Record<string, ActionKeyboardShortcut> = {};
@@ -94,6 +95,8 @@ async function setupWindowShortcutsForElement($el: JQuery<HTMLElement>) {
}
function runWindowAction(actionName: ActionKeyboardShortcut["actionName"]) {
+ // Otherwise an open menu stays over a dialog that the action opens.
+ closeOpenPopups();
return appContext.triggerCommand(actionName, { ntxId: appContext.tabManager.activeNtxId });
}
diff --git a/apps/client/src/widgets/react/Popup.spec.tsx b/apps/client/src/widgets/react/Popup.spec.tsx
index 79805171ce..4fe80783db 100644
--- a/apps/client/src/widgets/react/Popup.spec.tsx
+++ b/apps/client/src/widgets/react/Popup.spec.tsx
@@ -1,7 +1,7 @@
import { render } from "preact";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import Popup, { placeFloating, type PopupProps } from "./Popup";
+import Popup, { closeOpenPopups, placeFloating, type PopupProps } from "./Popup";
describe("Popup", () => {
const host = document.createElement("div");
@@ -282,6 +282,14 @@ describe("Popup", () => {
expect(dialogHeard).not.toHaveBeenCalled();
document.removeEventListener("keydown", dialogHeard);
outside.remove();
+
+ // As for a keyboard shortcut that opens a dialog.
+ onDismiss.mockClear();
+ closeOpenPopups();
+ expect(onDismiss).toHaveBeenCalledExactlyOnceWith("escape");
+ render(null, host);
+ closeOpenPopups();
+ expect(onDismiss).toHaveBeenCalledTimes(1);
});
it("drops the click after a dismissing press unless it lands on what was pressed", async () => {
diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsx
index 48fafb52a2..377bceac87 100644
--- a/apps/client/src/widgets/react/Popup.tsx
+++ b/apps/client/src/widgets/react/Popup.tsx
@@ -198,6 +198,7 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
dismiss.current("escape");
return true;
}), []);
+ useLayoutEffect(() => registerOpenPopup(() => dismiss.current?.("escape")), []);
// Out of any ancestor that would clip it or, with a transform or a filter, place its fixed
// position against itself. A browser showing an element fullscreen paints only that element.
@@ -220,6 +221,25 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
container ?? document.fullscreenElement ?? document.body);
}
+/** The functions that close the popups and menus open now; see {@link closeOpenPopups}. */
+const openPopups = new Set<() => void>();
+
+/** Registers `close` for {@link closeOpenPopups} until the returned function runs. */
+export function registerOpenPopup(close: () => void) {
+ openPopups.add(close);
+ return () => {
+ openPopups.delete(close);
+ };
+}
+
+/**
+ * Closes every open popup and the context menu, for something that takes over the screen, such as
+ * a dialog opened by a keyboard shortcut.
+ */
+export function closeOpenPopups() {
+ for (const close of [ ...openPopups ]) close();
+}
+
/**
* Drops the click that follows a press dismissing a popup when it lands on something other than
* `pressed` or an element containing it. A cover or backdrop is removed with the popup before a