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
feat(menu): render the context menu's custom items
Elian Doraneb9506a6fa43
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex f075c73972..27c6a55e9c 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -160,6 +160,40 @@ describe("contextMenu", () => {]);});+ it("renders a custom item's component in its place, and hides on a click inside it", async () => {+ buildPage();+ const contextMenu = await buildContextMenu();+ const { h } = await import("preact");+ const { useState } = await import("preact/hooks");+ // A component with state of its own, as the colour pickers are.+ function Swatches() {+ const [ picked ] = useState("red");+ return h("div", { className: "swatches" }, picked);+ }++ await contextMenu.show({+ x: 10, y: 10, selectMenuItemHandler: () => {},+ items: [+ { title: "Delete" },+ { kind: "separator" },+ { kind: "custom", componentFn: Swatches },+ { kind: "separator" },+ { title: "Export" }+ ]+ });++ const rows = [ ...menuElement()?.children ?? [] ].map(row => `${row.tagName.toLowerCase()}.${row.className}`);+ expect(rows).toEqual([+ "li.dropdown-item", "div.dropdown-divider", "li.dropdown-custom-item", "div.dropdown-divider", "li.dropdown-item"+ ]);+ const custom = menuElement()?.querySelector<HTMLElement>(".dropdown-custom-item");+ expect(custom?.innerHTML).toBe(`<div class="swatches">red</div>`);++ // On its own, without reaching the page's listener: on mobile only the cover has one.+ custom?.dispatchEvent(new MouseEvent("click", { bubbles: false }));+ expect(contextMenu.isShown()).toBe(false);+ });+it("runs an item pressed with the primary button, then hides", async () => {buildPage();const contextMenu = await buildContextMenu();diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex 7afe8f2e43..2b2c993c91 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -123,7 +123,8 @@ class ContextMenu {void this.hide();item.handler?.(item, e);options.selectMenuItemHandler(item, e);- }+ },+ onClose: () => void this.hide()}), this.host);}diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.tsindex 18fb7b1884..f544d1d695 100644--- a/apps/client/src/menus/context_menu_legacy.ts+++ b/apps/client/src/menus/context_menu_legacy.ts@@ -3,7 +3,7 @@import { KeyboardActionNames } from "@triliumnext/commons";import { Tooltip } from "bootstrap";-import { h, JSX, render } from "preact";+import { JSX } from "preact";import note_tooltip from "../services/note_tooltip.js";import utils from "../services/utils.js";@@ -222,13 +222,7 @@ class ContextMenu {$group.append($("<h6>").addClass("dropdown-header").text((item as MenuHeader).title));shouldResetGroup = true;} else {- if (itemKind === "custom") {- // Custom menu item- $group.append(this.createCustomMenuItem(item as CustomMenuItem));- } else {- // Standard menu item- $group.append(this.createMenuItem(item as MenuCommandItem<any>));- }+ $group.append(this.createMenuItem(item as MenuCommandItem<any>));// After adding a menu item, if the previous item was a separator or header,// reset the group so that the next item will be appended directly to the parent.@@ -243,14 +237,6 @@ class ContextMenu {}}- private createCustomMenuItem(item: CustomMenuItem) {- const element = document.createElement("li");- element.classList.add("dropdown-custom-item");- element.onclick = () => this.hide();- render(h(item.componentFn, {}), element);- return element;- }-private createMenuItem(item: MenuCommandItem<any>) {const $link = $("<span>");diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxindex 4f58e61f1b..a1c0e85e50 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -4,7 +4,7 @@ import { autoUpdate, computePosition, flip, type Placement, shift, size, type Viimport clsx from "clsx";import { useLayoutEffect, useRef } from "preact/hooks";-import type { MenuCommandItem, MenuItem, MenuSeparatorItem } from "../../menus/context_menu";+import type { CustomMenuItem, MenuCommandItem, MenuItem, MenuSeparatorItem } from "../../menus/context_menu";import { getActionSync } from "../../services/keyboard_actions";import { joinElements } from "./react_utils";import { renderShortcutKbds } from "./shortcut_kbd";@@ -25,12 +25,14 @@ export interface MenuProps<T> {items: MenuItem<T>[];/** Called when an item is pressed with the primary button. */onSelect(item: MenuCommandItem<T>, e: MouseEvent): void;+ /** Called on a click inside a custom item, which closes the menu like a pressed item does. */+ onClose(): void;}/** How many pixels the menu keeps from the edges of the viewport. */const VIEWPORT_PADDING = 5;-export default function Menu<T>({ id, className, x, y, orientation, items, onSelect }: MenuProps<T>) {+export default function Menu<T>({ id, className, x, y, orientation, items, onSelect, onClose }: MenuProps<T>) {const menuRef = useRef<HTMLDivElement>(null);useLayoutEffect(() => {@@ -45,10 +47,15 @@ export default function Menu<T>({ id, className, x, y, orientation, items, onSelreturn (<div ref={menuRef} id={id} className={clsx("dropdown-menu show tn-menu", className)} role="menu">- {menuRows(items).map((row, index) => ("kind" in row && row.kind === "separator"- ? <div key={index} className="dropdown-divider" role="separator" />- : <MenuRow key={index} item={row as MenuCommandItem<T>} onSelect={onSelect} />- ))}+ {menuRows(items).map((row, index) => {+ if (!("kind" in row)) return <MenuRow key={index} item={row} onSelect={onSelect} />;+ if (row.kind === "separator") return <div key={index} className="dropdown-divider" role="separator" />;+ return (+ <li key={index} className="dropdown-custom-item" onClick={onClose}>+ <row.componentFn />+ </li>+ );+ })}</div>);}@@ -110,15 +117,15 @@ function MenuIconSlot<T>({ item }: { item: MenuCommandItem<T> }) {/** 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)[] = [];+ const rows: (MenuCommandItem<T> | MenuSeparatorItem | CustomMenuItem)[] = [];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;+ if (previous && "kind" in previous && previous.kind === "separator") continue;rows.push(item as MenuSeparatorItem);- } else if (!kind) {- rows.push(item as MenuCommandItem<T>);+ } else if (kind !== "header") {+ rows.push(item as MenuCommandItem<T> | CustomMenuItem);}}return rows;