Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(menu): dismiss the context menu on a press anywhere outside it
Elian Dorandc02e7a9ca6c
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex 4b88057a7f..63e15ed1be 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -569,14 +569,81 @@ describe("contextMenu", () => {});});- it("hides on a click anywhere on the page", async () => {- buildPage();- const contextMenu = await buildContextMenu();+ describe("dismissal", () => {+ function pressOn(target: Element | null | undefined, init: PointerEventInit = {}) {+ target?.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, button: 0, ...init }));+ }- await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });- document.getElementById("app")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ it("hides on a press outside it, with any button, even one its target stops", async () => {+ buildPage();+ const app = document.getElementById("app");+ // As the note tree and the calendar stop their own presses and clicks.+ app?.addEventListener("pointerdown", (e) => e.stopPropagation());+ app?.addEventListener("click", (e) => e.stopPropagation());+ const contextMenu = await buildContextMenu();- expect(contextMenu.isShown()).toBe(false);+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ pressOn(app);+ expect(contextMenu.isShown()).toBe(false);++ // Ctrl+right-click, which opens a note in a popup instead of a menu, and fires no click.+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ pressOn(app, { button: 2, ctrlKey: true });+ expect(contextMenu.isShown()).toBe(false);+ });++ it("stays up on a press or a click inside it that runs nothing", async () => {+ buildPage();+ const contextMenu = await buildContextMenu();++ await contextMenu.show({+ x: 10, y: 10, selectMenuItemHandler: () => {},+ items: [ { kind: "header", title: "Colour" }, { title: "Red" } ]+ });+ const header = menuElement()?.querySelector(".dropdown-header");+ if (!header) throw new Error("expected a header");+ pressOn(header);+ header.dispatchEvent(new MouseEvent("click", { bubbles: true }));++ expect(contextMenu.isShown()).toBe(true);+ });++ it("hides on Escape, which goes no further", async () => {+ buildPage();+ const contextMenu = await buildContextMenu();+ // A dialog under the menu, which Escape would otherwise close too.+ const dialogHeard = vi.fn();+ document.addEventListener("keydown", dialogHeard);++ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ expect(contextMenu.isShown()).toBe(false);+ expect(dialogHeard).not.toHaveBeenCalled();++ // With no menu up, Escape is left to whatever else listens.+ document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ expect(dialogHeard).toHaveBeenCalledTimes(1);+ document.removeEventListener("keydown", dialogHeard);+ });++ it("says whether the press behind a click put a menu away, for a host that acts on neither", async () => {+ buildPage();+ const app = document.getElementById("app");+ const contextMenu = await buildContextMenu();+ const click = () => app?.dispatchEvent(new MouseEvent("click", { bubbles: true }));++ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ pressOn(app);+ expect(contextMenu.dismissedByLastPress()).toBe(true);++ // Only until the click that press makes has been handled.+ click();+ await vi.waitFor(() => expect(contextMenu.dismissedByLastPress()).toBe(false));++ // A press with no menu up put nothing away.+ pressOn(app);+ expect(contextMenu.dismissedByLastPress()).toBe(false);+ });});it("opens inside whatever has the screen, and in the body once nothing does", async () => {diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex ef07c273d5..9bdd2662c8 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -83,15 +83,30 @@ class ContextMenu {/** What `Menu` renders into while a menu is up. */private host?: HTMLElement;private options?: ContextMenuOptions<any>;+ /** See {@link dismissedByLastPress}. */+ private pressDismissed = false;constructor() {this.cover = utils.isMobile() ? document.getElementById("context-menu-cover") : null;- if (this.cover) {- this.cover.addEventListener("click", () => this.hide());- } else {- document.addEventListener("click", () => this.hide());- }+ // Capture phase, so that a host stopping its own presses, as the note tree does, cannot+ // keep them from here. `pointerdown` covers every button, including a Ctrl+right-click+ // that fires no `click`, and a tap on the mobile cover.+ document.addEventListener("pointerdown", (e) => {+ const outside = this.isShown() && !this.host?.contains(e.target as Node);+ this.pressDismissed = outside;+ if (outside) void this.hide();+ }, true);+ // The click a dismissing press makes is handled by then, see `dismissedByLastPress()`.+ document.addEventListener("click", () => {+ setTimeout(() => this.pressDismissed = false);+ }, true);+ document.addEventListener("keydown", (e) => {+ if (e.key !== "Escape" || !this.isShown()) return;+ // A dialog under the menu stays open.+ e.stopPropagation();+ void this.hide();+ }, true);}async show<T>(options: ContextMenuOptions<T>) {@@ -129,14 +144,19 @@ class ContextMenu {}), this.host);}- /**- * Whether a menu is up. A host that stops a press from reaching the document, whose click- * otherwise hides the menu, uses this to hide the menu itself.- */isShown() {return !!this.options;}+ /**+ * Whether the press behind the click being handled put a menu away. A host whose click would+ * otherwise act, such as the calendar opening an event, does nothing for it: one press, one+ * thing.+ */+ dismissedByLastPress() {+ return this.pressDismissed;+ }+async hide() {const options = this.options;this.options = undefined;diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.tsindex 5731e9680d..b3e79fcadf 100644--- a/apps/client/src/menus/context_menu_legacy.ts+++ b/apps/client/src/menus/context_menu_legacy.ts@@ -92,9 +92,6 @@ class ContextMenu {if (this.isMobile) {this.$cover = $("#context-menu-cover");- this.$cover.on("click", () => this.hide());- } else {- $(document).on("click", (e) => this.hide());}}diff --git a/apps/client/src/widgets/collections/calendar/index.tsx b/apps/client/src/widgets/collections/calendar/index.tsxindex de30fd06ef..260b6e3174 100644--- a/apps/client/src/widgets/collections/calendar/index.tsx+++ b/apps/client/src/widgets/collections/calendar/index.tsx@@ -270,13 +270,8 @@ export default function CalendarView({ note, noteIds }: ViewModeProps<CalendarVi// chip both of them are drawn beside.note_tooltip.dismissAllTooltips();- // A menu standing open is what the click is for: putting it away is what a click anywhere- // means while one is up, and the stop above is what kept this one from saying so on its own- // (see isShown in context_menu.ts). The event is not opened as well — one press, one thing.- if (contextMenu.isShown()) {- void contextMenu.hide();- return;- }+ // The press behind this click put a context menu away, so the event does not open too.+ if (contextMenu.dismissedByLastPress()) return;const noteId = e.event.extendedProps.noteId;if (noteId) {diff --git a/apps/client/src/widgets/collections/table/context_menu.ts b/apps/client/src/widgets/collections/table/context_menu.tsindex 2cb5ce4754..550150ddd4 100644--- a/apps/client/src/widgets/collections/table/context_menu.ts+++ b/apps/client/src/widgets/collections/table/context_menu.ts@@ -20,13 +20,6 @@ export function useContextMenu(parentNote: FNote, parentComponent: Component | nconst headerRow = tabulator.current?.element.querySelector(".tabulator-header-contents");headerRow?.addEventListener("contextmenu", (e) => showHeaderContextMenu(parentComponent, e as MouseEvent, tabulator.current!));}- // Pressing the expand button prevents bubbling and the context menu remains menu when it shouldn't.- if (tabulator.current?.options.dataTree) {- const dismissContextMenu = () => contextMenu.hide();- events["dataTreeRowExpanded"] = dismissContextMenu;- events["dataTreeRowCollapsed"] = dismissContextMenu;- }-return events;}diff --git a/apps/client/src/widgets/note_tree.ts b/apps/client/src/widgets/note_tree.tsindex 1e0fc41bd9..ccf7e404ae 100644--- a/apps/client/src/widgets/note_tree.ts+++ b/apps/client/src/widgets/note_tree.ts@@ -11,7 +11,6 @@ import appContext, { type CommandListenerData, type EventData } from "../componeimport type { SetNoteOpts } from "../components/note_context.js";import type FBranch from "../entities/fbranch.js";import type FNote from "../entities/fnote.js";-import contextMenu from "../menus/context_menu.js";import type { TreeCommandNames } from "../menus/tree_context_menu.js";import branchService from "../services/branches.js";import froca from "../services/froca.js";@@ -489,9 +488,6 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {return true;},activate: async (event, data) => {- // click event won't propagate so let's close context menu manually- contextMenu.hide();-// hide all dropdowns, fix calendar widget dropdown doesn't close when click on a note$('.dropdown-menu').parent('.dropdown').find('[data-bs-toggle="dropdown"]').dropdown('hide');