Skip to content

Build your personal knowledge base with Trilium Notes

feat(menu): list the context menu's items and separators

Elian Dorandad3757b0cbb
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index a28dc0ea9d..d2b5a8192b 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -35,7 +35,6 @@ describe("contextMenu", () => {
const menu = container?.querySelector<HTMLElement>(".tn-menu");
expect(menu?.getAttribute("role")).toBe("menu");
- expect(menu?.textContent).toBe("Hello world");
expect(document.body.classList.contains("context-menu-shown")).toBe(true);
await contextMenu.hide();
@@ -48,6 +47,55 @@ describe("contextMenu", () => {
expect(onHide).toHaveBeenCalledTimes(1);
});
+ describe("items", () => {
+ it("lists the items and separators in order, without repeating a separator", async () => {
+ const container = buildPage();
+ const contextMenu = await buildContextMenu();
+
+ await contextMenu.show({
+ x: 10, y: 10, selectMenuItemHandler: () => {},
+ items: [
+ { title: "Cut" },
+ { title: "Copy" },
+ { kind: "separator" },
+ { kind: "separator" },
+ { title: "Paste" }
+ ]
+ });
+
+ const rows = [ ...container?.querySelectorAll(".tn-menu > *") ?? [] ]
+ .map(row => row.getAttribute("role") === "separator" ? "---" : row.textContent);
+ expect(rows).toEqual([ "Cut", "Copy", "---", "Paste" ]);
+ expect(container?.querySelector("[role=menuitem]")?.classList.contains("tn-menu-item")).toBe(true);
+ });
+
+ it("runs an item pressed with the primary button, then hides", async () => {
+ const container = buildPage();
+ const contextMenu = await buildContextMenu();
+ const calls: string[] = [];
+ const item = { title: "Copy", handler: () => { calls.push("handler"); } };
+
+ await contextMenu.show({
+ x: 10, y: 10, items: [ item ],
+ selectMenuItemHandler: (selected) => { calls.push(`select ${selected.title}`); }
+ });
+ const row = container?.querySelector<HTMLElement>("[role=menuitem]");
+ if (!row) throw new Error("expected a menu item");
+
+ // Other buttons do nothing.
+ row.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 2 }));
+ expect(calls).toEqual([]);
+ expect(contextMenu.isShown()).toBe(true);
+
+ const press = new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 });
+ row.dispatchEvent(press);
+ expect(calls).toEqual([ "handler", "select Copy" ]);
+ expect(contextMenu.isShown()).toBe(false);
+ // The press does not move focus, so a text editor keeps its selection for the command.
+ expect(press.defaultPrevented).toBe(true);
+ });
+ });
+
describe("placement", () => {
/** Opens the menu with the size a browser would lay it out at; happy-dom lays out nothing. */
async function place(options: { x: number, y: number, width: number, height: number, orientation?: "left" }) {
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index ae3f5de09a..a65543d2dd 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -75,7 +75,7 @@ export interface MenuCommandItem<T> {
}
export type MenuItem<T> = MenuCommandItem<T> | CustomMenuItem | MenuSeparatorItem | MenuHeader;
-export type MenuHandler<T> = (item: MenuCommandItem<T>, e: JQuery.MouseDownEvent<HTMLElement, undefined, HTMLElement, HTMLElement>) => void;
+export type MenuHandler<T> = (item: MenuCommandItem<T>, e: MouseEvent) => void;
export type ContextMenuEvent = PointerEvent | MouseEvent | JQuery.ContextMenuEvent;
class ContextMenu {
@@ -113,7 +113,17 @@ class ContextMenu {
this.cover?.classList.add("show");
document.body.classList.add("context-menu-shown");
- render(h(Menu, { x: options.x, y: options.y, orientation: options.orientation }), this.container);
+ render(h(Menu<T>, {
+ x: options.x,
+ y: options.y,
+ orientation: options.orientation,
+ items: options.items,
+ onSelect: (item, e) => {
+ void this.hide();
+ item.handler?.(item, e);
+ options.selectMenuItemHandler(item, e);
+ }
+ }), this.container);
}
/**
diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.ts
index bd8f60570d..9a51adda12 100644
--- a/apps/client/src/menus/context_menu_legacy.ts
+++ b/apps/client/src/menus/context_menu_legacy.ts
@@ -221,10 +221,6 @@ class ContextMenu {
}
if (itemKind === "separator") {
- if (prevItemKind === "separator") {
- // Skip consecutive separators
- continue;
- }
$group.append($("<div>").addClass("dropdown-divider"));
shouldResetGroup = true; // End the group after the next item
} else if (itemKind === "header") {
@@ -326,14 +322,7 @@ class ContextMenu {
.addClass("className" in item ? item.className ?? "" : "")
.append($link)
.on("contextmenu", (e) => false)
- // important to use mousedown instead of click since the former does not change focus
- // (especially important for focused text for spell check)
.on("mousedown", (e) => {
- if (e.which !== 1) {
- // only left click triggers menu items
- return false;
- }
-
if (this.isMobile && "items" in item && item.items) {
const $item = $(e.target).closest(".dropdown-item");
@@ -351,12 +340,6 @@ class ContextMenu {
this.hide();
}
- if ("handler" in item && item.handler) {
- item.handler(item, e);
- }
-
- this.options?.selectMenuItemHandler(item, e);
-
// it's important to stop the propagation especially for sub-menus, otherwise the event
// might be handled again by top-level menu
return false;
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.tsx
index 4c635c47f6..82bb3cb224 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.spec.tsx
@@ -294,7 +294,7 @@ describe("related notes menu", () => {
expect(searchItem).toMatchObject({ uiIcon: "bx bx-search-alt" });
// A note entry navigates to it; the search entry searches for every carrier of the name.
- const pressEvent = {} as JQuery.MouseDownEvent<HTMLElement, undefined, HTMLElement, HTMLElement>;
+ const pressEvent = new MouseEvent("mousedown");
if ("handler" in noteItem) {
noteItem.handler?.(noteItem, pressEvent);
}
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index cadd562e0d..65ffcf5df7 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -26,3 +26,23 @@
backdrop-filter: var(--dropdown-backdrop-filter);
}
}
+
+.tn-menu-item {
+ padding-block: var(--menu-item-vertical-padding);
+ padding-inline: var(--menu-item-start-padding) var(--menu-item-end-padding);
+ cursor: pointer;
+ user-select: none;
+ white-space: nowrap;
+
+ &:hover {
+ color: var(--hover-item-text-color);
+ background-color: var(--hover-item-background-color);
+ }
+}
+
+.tn-menu-separator {
+ /* Spans the menu's padding, like the theme's `.dropdown-divider`. */
+ margin-block: var(--menu-padding-size);
+ margin-inline: calc(0px - var(--menu-padding-size));
+ border-top: 1px solid var(--menu-item-delimiter-color);
+}
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 12c6efd0d2..7605e5c52c 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -3,20 +3,24 @@ import "./Menu.css";
import { computePosition, flip, type Placement, shift, size, type VirtualElement } from "@floating-ui/dom";
import { useCallback, useLayoutEffect, useRef } from "preact/hooks";
+import type { MenuCommandItem, MenuItem, MenuSeparatorItem } from "../../menus/context_menu";
import { useResizeObserver } from "./hooks";
-export interface MenuProps {
+export interface MenuProps<T> {
/** Where the menu opens, in viewport coordinates. */
x: number;
y: number;
/** Opens the menu towards the left of {@link x} instead of towards the right. */
orientation?: "left";
+ items: MenuItem<T>[];
+ /** Called when an item is pressed with the primary button. */
+ onSelect(item: MenuCommandItem<T>, e: MouseEvent): void;
}
/** How many pixels the menu keeps from the edges of the viewport. */
const VIEWPORT_PADDING = 5;
-export default function Menu({ x, y, orientation }: MenuProps) {
+export default function Menu<T>({ x, y, orientation, items, onSelect }: MenuProps<T>) {
const menuRef = useRef<HTMLDivElement>(null);
const place = useCallback(() => {
if (!menuRef.current) return;
@@ -29,11 +33,48 @@ export default function Menu({ x, y, orientation }: MenuProps) {
return (
<div ref={menuRef} className="tn-menu" role="menu">
- Hello world
+ {menuRows(items).map((row, index) => ("kind" in row && row.kind === "separator"
+ ? <div key={index} className="tn-menu-separator" role="separator" />
+ : <MenuRow key={index} item={row as MenuCommandItem<T>} onSelect={onSelect} />
+ ))}
</div>
);
}
+function MenuRow<T>({ item, onSelect }: { item: MenuCommandItem<T>, onSelect: MenuProps<T>["onSelect"] }) {
+ return (
+ <div
+ className="tn-menu-item"
+ role="menuitem"
+ // `mousedown` rather than `click`, and its default prevented, so the press does not move
+ // focus: a text editor keeps the selection that commands such as a spelling fix act on.
+ onMouseDown={(e) => {
+ if (e.button !== 0) return;
+ e.preventDefault();
+ onSelect(item, e);
+ }}
+ >
+ {item.title}
+ </div>
+ );
+}
+
+/** The items `Menu` renders so far, with a run of separators reduced to one. */
+function menuRows<T>(items: MenuItem<T>[]) {
+ const rows: (MenuCommandItem<T> | MenuSeparatorItem)[] = [];
+ for (const item of items) {
+ const kind = "kind" in item ? item.kind : undefined;
+ if (kind === "separator") {
+ const previous = rows.at(-1);
+ if (previous && "kind" in previous) continue;
+ rows.push(item as MenuSeparatorItem);
+ } else if (!kind) {
+ rows.push(item as MenuCommandItem<T>);
+ }
+ }
+ return rows;
+}
+
/**
* Positions `menu` beside `anchor`, preferring `placement` and then the placements that mirror it,
* the way a native menu opens above or to the left of a pointer that is near the viewport's edge.