Skip to content

Build your personal knowledge base with Trilium Notes

fix(menu): mount only the last context menu asked for while Menu loads

Elian Doran4604ebfe1bd6
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index 03f20abed2..18333d7b32 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -90,6 +90,23 @@ describe("contextMenu", () => {
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();
+
+ await Promise.all([
+ contextMenu.show({ x: 10, y: 20, items: [ { title: "First" } ], selectMenuItemHandler: () => {} }),
+ contextMenu.show({ x: 30, y: 40, items: [ { title: "Second" } ], selectMenuItemHandler: () => {} })
+ ]);
+
+ const menus = document.querySelectorAll("#context-menu-container");
+ expect(menus).toHaveLength(1);
+ expect(menus[0].textContent).toContain("Second");
+
+ await contextMenu.hide();
+ expect(document.body.innerHTML).toBe(`<div id="app"></div>`);
+ });
+
describe("items", () => {
it("lists the items and separators in order, without repeating a separator", async () => {
buildPage();
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 9bc2367a21..a1437435d5 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -93,6 +93,8 @@ class ContextMenu {
* Menu key or Shift+F10, as callers pass no event to tell by.
*/
private lastInputWasKey = false;
+ /** Counts `show()` calls, so that only the latest one mounts a menu. */
+ private lastShowRequest = 0;
constructor() {
this.cover = utils.isMobile() ? document.getElementById("context-menu-cover") : null;
@@ -124,15 +126,18 @@ class ContextMenu {
note_tooltip.dismissAllTooltips();
hideShownTooltips();
+ const request = ++this.lastShowRequest;
+ // Loaded here rather than imported: the core services that import this module would
+ // otherwise reach the widget tree through the rows `Menu` draws, in a cycle.
+ const { default: Menu } = await import("../widgets/react/Menu");
+ // A later `show()` made during the import replaces this one.
+ if (request !== this.lastShowRequest) return;
+
if (this.isShown) {
// Unmount first so the menu opens fresh at the new location.
await this.hide();
}
- // Loaded here rather than imported: the core services that import this module would
- // otherwise reach the widget tree through the rows `Menu` draws, in a cycle.
- const { default: Menu } = await import("../widgets/react/Menu");
-
this.options = options;
this.focusBeforeShow = document.activeElement;
// The menu takes focus, which a modal's focus trap would otherwise pull back into the modal.