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 through a new Preact Menu component
Elian Doran6ce7c766e2e3
diff --git a/apps/client/index.html b/apps/client/index.htmlindex f4908f279d..1f632ad82b 100644--- a/apps/client/index.html+++ b/apps/client/index.html@@ -144,7 +144,7 @@</div><div id="context-menu-cover"></div>- <div class="dropdown-menu dropdown-menu-sm" id="context-menu-container" style="display: none"></div>+ <div id="context-menu-container"></div><!-- Required to match the PWA's top bar color with the theme --><!-- This works even when the user directly changes --root-background in CSS -->diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex d90587f97e..4372b3ef15 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -1,15 +1,6 @@-/**- * The menu over an element that has the screen to itself.- *- * A browser showing an element fullscreen draws that element and nothing else, and this menu lives at- * the end of the page: over a map given the screen (see the geo map's and the mind map's toolbars) a- * right-click laid the menu out, positioned it, and painted none of it — nothing appeared to happen- * at all. It goes wherever the screen is instead.- */import { beforeEach, describe, expect, it, vi } from "vitest";vi.mock("../services/note_tooltip", () => ({ default: { dismissAllTooltips: vi.fn() } }));-vi.mock("../services/keyboard_actions", () => ({ default: { updateDisplayedShortcuts: vi.fn() } }));/** The page as the shell leaves it: the menu's own element, at the end of the body. */function buildPage() {@@ -35,139 +26,76 @@ beforeEach(() => {});describe("contextMenu", () => {- it("stands at the end of the page while nothing has the screen", async () => {- const menu = buildPage();+ it("renders the menu into its container and removes it on hide", async () => {+ const container = buildPage();const contextMenu = await buildContextMenu();+ const onHide = vi.fn();- await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ await contextMenu.show({ x: 10, y: 20, items, selectMenuItemHandler: () => {}, onHide });- expect(menu?.parentElement).toBe(document.body);+ 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();+ expect(container?.querySelector(".tn-menu")).toBeNull();+ expect(document.body.classList.contains("context-menu-shown")).toBe(false);+ expect(onHide).toHaveBeenCalledTimes(1);++ // A later click on the page hides nothing, so `onHide` does not run again.+ await contextMenu.hide();+ expect(onHide).toHaveBeenCalledTimes(1);});- it("moves inside whatever has the screen, and back once nothing does", async () => {- const menu = buildPage();+ it("opens at the pointer and stays inside the viewport", async () => {+ const container = buildPage();const contextMenu = await buildContextMenu();- const map = document.getElementById("app");-- setFullscreenElement(map);- await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });- // Anywhere else it would be laid out and left unpainted, which reads as a menu that never opened.- expect(menu?.parentElement).toBe(map);+ Object.defineProperty(document.documentElement, "clientWidth", { value: 1000, configurable: true });+ Object.defineProperty(document.documentElement, "clientHeight", { value: 800, configurable: true });+ const menu = () => container?.querySelector<HTMLElement>(".tn-menu");- setFullscreenElement(null);- await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ await contextMenu.show({ x: 10, y: 20, items, selectMenuItemHandler: () => {} });+ expect([ menu()?.style.left, menu()?.style.top ]).toEqual([ "10px", "20px" ]);- expect(menu?.parentElement).toBe(document.body);+ // happy-dom measures the menu as 0×0, so it is pushed back to the edge less the padding.+ await contextMenu.show({ x: 2000, y: 2000, items, selectMenuItemHandler: () => {} });+ await vi.waitFor(() => expect([ menu()?.style.left, menu()?.style.top ]).toEqual([ "995px", "795px" ]));});- /**- * A submenu opens towards the trailing edge, and a menu raised near that edge would draw it off- * the screen. It goes on the other side of its parent instead, which is what the page already- * does for the launcher bar lying on its side.- */- it("opens a submenu on the other side of a menu standing at the edge", async () => {+ it("hides on a click anywhere on the page", async () => {buildPage();const contextMenu = await buildContextMenu();- Object.defineProperty(document.documentElement, "clientWidth",- { value: 1000, configurable: true });- Object.defineProperty(document.documentElement, "clientHeight",- { value: 800, configurable: true });-- await contextMenu.show({- x: 900, y: 10,- items: [ { title: "More states", items } ],- selectMenuItemHandler: () => {}- });- const parent = document.querySelector<HTMLElement>(".dropdown-submenu");- const submenu = parent?.querySelector<HTMLElement>(".dropdown-menu");- if (!parent || !submenu) throw new Error("expected a submenu");-- // jQuery binds `mouseenter` as a native `mouseover`, which is what the hover has to be.- const hover = () =>- parent.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));-- // happy-dom measures nothing, so the submenu is told where it stands.- const place = (left: number, width: number) =>- Object.defineProperty(submenu, "getBoundingClientRect", {- value: () => ({- left, right: left + width, width,- top: 10, bottom: 110, height: 100- }),- configurable: true- });-- place(910, 300);- hover();- expect(submenu.classList.contains("submenu-flip-start")).toBe(true);-- // Where it fits as it is, it is left where it opens.- place(500, 300);- hover();- expect(submenu.classList.contains("submenu-flip-start")).toBe(false);-- // And where it fits on neither side, since flipping would only clip the other end.- place(910, 950);- hover();- expect(submenu.classList.contains("submenu-flip-start")).toBe(false);+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ document.getElementById("app")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));++ expect(contextMenu.isShown()).toBe(false);});- it("tints an item's icon with the colour class it carries, and only the icon", async () => {+ it("stands at the end of the page while nothing has the screen", async () => {const menu = buildPage();const contextMenu = await buildContextMenu();- await contextMenu.show({- x: 10,- y: 10,- selectMenuItemHandler: () => {},- items: [- { title: "To Do", uiIcon: "bx bx-list-ul", iconColorClass: "use-note-color color-e64d4d" },- { title: "Done", uiIcon: "bx bx-check" }- ]- });+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });- const icons = [ ...menu?.querySelectorAll(".dropdown-item .tn-icon") ?? [] ];- expect(icons.map(icon => icon.classList.contains("use-note-color"))).toEqual([ true, false ]);- // The label sits beside the icon rather than inside it, so it keeps the menu's own colour.- expect(menu?.querySelectorAll(".dropdown-item .use-note-color")).toHaveLength(1);+ expect(menu?.parentElement).toBe(document.body);});- it("puts itself away once a submenu's parent acts, and stays up for one that only folds", async () => {+ it("moves inside whatever has the screen, and back once nothing does", async () => {const menu = buildPage();const contextMenu = await buildContextMenu();- const picked: string[] = [];-- const show = () => contextMenu.show({- x: 10,- y: 10,- selectMenuItemHandler: (item) => { picked.push(String(item.title)); },- items: [- { title: "Open note", command: "openNoteInNewTab", items: [ { title: "New tab" } ] },- { title: "More", items: [ { title: "Archived" } ] }- ]- });- const pressRow = (title: string) => {- // Read off the row's own line: its text also holds whatever its submenu lists.- const row = [ ...menu?.querySelectorAll("li.dropdown-item") ?? [] ]- .find((item) => item.querySelector(":scope > span")?.textContent?.trim() === title);- expect(row, title).toBeTruthy();- const press = new MouseEvent("mousedown", { bubbles: true, button: 0 });- // happy-dom leaves the legacy `which` unset, which is what the menu reads for the- // primary button.- Object.defineProperty(press, "which", { value: 1 });- row?.dispatchEvent(press);- };-- await show();- pressRow("Open note");- expect(picked).toEqual([ "Open note" ]);- expect(contextMenu.isShown()).toBe(false);+ const map = document.getElementById("app");- await show();- pressRow("More");- expect(picked).toEqual([ "Open note", "More" ]);- // Nothing ran, so the menu is left standing for the submenu to be reached from.- expect(contextMenu.isShown()).toBe(true);+ setFullscreenElement(map);+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });+ // A browser paints only the fullscreen element, so a menu outside it never shows.+ expect(menu?.parentElement).toBe(map);++ setFullscreenElement(null);+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });++ expect(menu?.parentElement).toBe(document.body);});it("hides a Bootstrap tooltip that is up when the menu opens", async () => {@@ -218,8 +146,6 @@ describe("contextMenu", () => {buildPage();const contextMenu = await buildContextMenu();- // A host that answers a press itself keeps it from the document, whose click is what puts- // the menu away — so it has to ask, rather than let a standing menu outlive the press.expect(contextMenu.isShown()).toBe(false);await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex 69f93a07b8..e033ad1cde 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -2,10 +2,9 @@ import { KeyboardActionNames } from "@triliumnext/commons";import { Tooltip } from "bootstrap";import { h, JSX, render } from "preact";-import keyboardActionService, { getActionSync } from "../services/keyboard_actions.js";-import { formatShortcut, joinShortcut } from "../services/keyboard_shortcut_display.js";import note_tooltip from "../services/note_tooltip.js";import utils from "../services/utils.js";+import Menu from "../widgets/react/Menu";export interface ContextMenuOptions<T> {x: number;@@ -80,385 +79,73 @@ export type MenuHandler<T> = (item: MenuCommandItem<T>, e: JQuery.MouseDownEventexport type ContextMenuEvent = PointerEvent | MouseEvent | JQuery.ContextMenuEvent;class ContextMenu {- private $widget: JQuery<HTMLElement>;- private $cover?: JQuery<HTMLElement>;- private options?: ContextMenuOptions<any>;- private isMobile: boolean;+ private readonly container: HTMLElement | null;+ private readonly cover: HTMLElement | null;/** Where the menu stands while nothing has the screen to itself. See {@link hostInWhateverHasTheScreen}. */- private home: HTMLElement | null;+ private readonly home: HTMLElement | null;+ private options?: ContextMenuOptions<any>;constructor() {- this.$widget = $("#context-menu-container");- this.$widget.addClass("dropend");- this.home = this.$widget[0]?.parentElement ?? null;- this.isMobile = utils.isMobile();+ this.container = document.getElementById("context-menu-container");+ this.home = this.container?.parentElement ?? null;+ this.cover = utils.isMobile() ? document.getElementById("context-menu-cover") : null;- if (this.isMobile) {- this.$cover = $("#context-menu-cover");- this.$cover.on("click", () => this.hide());+ if (this.cover) {+ this.cover.addEventListener("click", () => this.hide());} else {- $(document).on("click", (e) => this.hide());+ document.addEventListener("click", () => this.hide());}}async show<T>(options: ContextMenuOptions<T>) {- this.options = options;-note_tooltip.dismissAllTooltips();hideShownTooltips();- if (this.$widget.hasClass("show")) {- // The menu is already visible. Hide the menu then open it again- // at the new location to re-trigger the opening animation.+ if (this.isShown()) {+ // Unmount first so the menu opens fresh at the new location.await this.hide();}- this.hostInWhateverHasTheScreen();-- this.$widget.toggleClass("mobile-bottom-menu", !this.options.forcePositionOnMobile);- this.$cover?.addClass("show");- $("body").addClass("context-menu-shown");+ if (!this.container) return;- this.$widget.empty();-- this.addItems(this.$widget, options.items);-- keyboardActionService.updateDisplayedShortcuts(this.$widget);+ this.options = options;+ this.hostInWhateverHasTheScreen(this.container);+ this.cover?.classList.add("show");+ document.body.classList.add("context-menu-shown");- this.positionMenu();+ render(h(Menu, { x: options.x, y: options.y }), this.container);}/*** Puts the menu inside the element that currently has the screen to itself, and back where it- * belongs once nothing does.- *- * A browser showing an element fullscreen draws that element and nothing else: this menu lives at- * the end of the page, so over a map or a diagram given the screen (see `useFullscreen`) it was- * laid out, positioned and left unpainted — a right-click that appeared to do nothing at all.- * Moved into whatever is being shown, it is drawn as usual; it is positioned against the viewport- * either way, so nothing about where it lands changes.+ * belongs once nothing does. A browser showing an element fullscreen paints only that element,+ * so a menu outside it would never appear.*/- private hostInWhateverHasTheScreen() {- const menu = this.$widget[0];+ private hostInWhateverHasTheScreen(container: HTMLElement) {const host = document.fullscreenElement ?? this.home;- if (menu && host && menu.parentElement !== host) {- host.appendChild(menu);- }- }-- positionMenu() {- if (!this.options) {- return;- }-- // the code below tries to detect when dropdown would overflow from page- // in such case we'll position it above click coordinates, so it will fit into the client-- const CONTEXT_MENU_PADDING = 5; // How many pixels to pad the context menu from edge of screen- const CONTEXT_MENU_OFFSET = 0; // How many pixels to offset the context menu by relative to cursor, see #3157-- const clientHeight = document.documentElement.clientHeight;- const clientWidth = document.documentElement.clientWidth;- const contextMenuHeight = this.$widget.outerHeight();- const contextMenuWidth = this.$widget.outerWidth();- let top, left;-- if (contextMenuHeight && this.options.y + contextMenuHeight - CONTEXT_MENU_OFFSET > clientHeight - CONTEXT_MENU_PADDING) {- // Overflow: bottom- top = clientHeight - contextMenuHeight - CONTEXT_MENU_PADDING;- } else if (this.options.y - CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {- // Overflow: top- top = CONTEXT_MENU_PADDING;- } else {- top = this.options.y - CONTEXT_MENU_OFFSET;- }-- if (this.options.orientation === "left" && contextMenuWidth) {- if (this.options.x + CONTEXT_MENU_OFFSET > clientWidth - CONTEXT_MENU_PADDING) {- // Overflow: right- left = clientWidth - contextMenuWidth - CONTEXT_MENU_OFFSET;- } else if (this.options.x - contextMenuWidth + CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {- // Overflow: left- left = CONTEXT_MENU_PADDING;- } else {- left = this.options.x - contextMenuWidth + CONTEXT_MENU_OFFSET;- }- } else if (contextMenuWidth && this.options.x + contextMenuWidth - CONTEXT_MENU_OFFSET > clientWidth - CONTEXT_MENU_PADDING) {- // Overflow: right- left = clientWidth - contextMenuWidth - CONTEXT_MENU_PADDING;- } else if (this.options.x - CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {- // Overflow: left- left = CONTEXT_MENU_PADDING;- } else {- left = this.options.x - CONTEXT_MENU_OFFSET;+ if (host && container.parentElement !== host) {+ host.appendChild(container);}-- this.$widget- .css({- display: "block",- top,- left- })- .addClass("show");- }-- private repositionSubmenu(submenuEl: HTMLElement) {- const CONTEXT_MENU_PADDING = 5;-- // Reset so the natural (downward, trailing) placement is measured on every hover.- submenuEl.classList.remove("submenu-flip-up");- submenuEl.classList.remove("submenu-flip-start");-- const rect = submenuEl.getBoundingClientRect();- const clientHeight = document.documentElement.clientHeight;- const clientWidth = document.documentElement.clientWidth;- const overflowsBottom = rect.bottom > clientHeight - CONTEXT_MENU_PADDING;- // Only flip up if there is actually more room above the parent than below, otherwise flipping- // would just clip the other end.- const fitsWhenFlippedUp = rect.top - rect.height >= CONTEXT_MENU_PADDING;-- if (overflowsBottom && fitsWhenFlippedUp) {- submenuEl.classList.add("submenu-flip-up");- }-- // The same for the side it opens on, which is the trailing one by default and the leading- // one in a right-to-left page. Whichever edge it runs past, the flip puts it on the other- // side of its parent, and only where the whole submenu fits there.- const fitsWhenFlippedToStart = rect.left - rect.width >= CONTEXT_MENU_PADDING;- const fitsWhenFlippedToEnd = rect.right + rect.width <= clientWidth - CONTEXT_MENU_PADDING;-- if ((rect.right > clientWidth - CONTEXT_MENU_PADDING && fitsWhenFlippedToStart)- || (rect.left < CONTEXT_MENU_PADDING && fitsWhenFlippedToEnd)) {- submenuEl.classList.add("submenu-flip-start");- }- }-- addItems($parent: JQuery<HTMLElement>, items: MenuItem<any>[], multicolumn = false) {- let $group = $parent; // The current group or parent element to which items are being appended- let shouldStartNewGroup = false; // If true, the next item will start a new group- let shouldResetGroup = false; // If true, the next item will be the last one from the group- let prevItemKind: string = "";-- for (let index = 0; index < items.length; index++) {- const item = items[index];- const itemKind = ("kind" in item) ? item.kind : "";-- if (!item) {- continue;- }-- // If the current item is a header, start a new group. This group will contain the- // header and the next item that follows the header.- if (itemKind === "header") {- if (multicolumn && !shouldResetGroup) {- shouldStartNewGroup = true;- }- }-- // If the next item is a separator, start a new group. This group will contain the- // current item, the separator, and the next item after the separator.- const nextItem = (index < items.length - 1) ? items[index + 1] : null;- if (multicolumn && nextItem && "kind" in nextItem && nextItem.kind === "separator") {- if (!shouldResetGroup) {- shouldStartNewGroup = true;- } else {- shouldResetGroup = true; // Continue the current group- }- }-- // Create a new group to avoid column breaks before and after the seaparator / header.- // This is a workaround for Firefox not supporting break-before / break-after: avoid- // for columns.- if (shouldStartNewGroup) {- $group = $("<div class='dropdown-no-break'>");- $parent.append($group);- shouldStartNewGroup = false;- }-- 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") {- $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>));- }-- // 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.- if (shouldResetGroup) {- $group = $parent;- shouldResetGroup = false;- };- }-- prevItemKind = itemKind;-- }- }-- 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 $icon = $("<span>");-- if ("uiIcon" in item || "checked" in item) {- const icon = (item.checked ? "bx bx-check" : item.uiIcon);- if (icon) {- $icon.addClass([icon, "tn-icon"]);- if (item.iconColorClass) {- $icon.addClass(item.iconColorClass);- }- } else {- $icon.append(" ");- }- }-- const $link = $("<span>")- .append($icon)- // An element, not spaces: in a flex row, text merges with a plain title but is- // trimmed before one boxed by `menuName()`, indenting the two kinds of row apart.- .append($("<span>").addClass("tn-menu-gap"))- .append(item.title);-- if ("badges" in item && item.badges) {- for (const badge of item.badges) {- const badgeElement = $(`<span class="badge">`).text(badge.title);-- if (badge.className) {- badgeElement.addClass(badge.className);- }-- $link.append(badgeElement);- }- }-- if ("keyboardShortcut" in item && item.keyboardShortcut) {- const shortcuts = getActionSync(item.keyboardShortcut).effectiveShortcuts;- if (shortcuts) {- const allShortcuts: string[] = [];- for (const effectiveShortcut of shortcuts) {- const tokens = formatShortcut(effectiveShortcut);- // On macOS the glyphs sit in one <kbd> (⇧⌘J); elsewhere each token gets its own.- allShortcuts.push(utils.isMac()- ? `<kbd>${joinShortcut(tokens)}</kbd>`- : tokens.map(key => `<kbd>${key}</kbd>`).join("+"));- }-- if (allShortcuts.length) {- const container = $("<span>").addClass("keyboard-shortcut");- container.append($(allShortcuts.join(",")));- $link.append(container);- }- }- } else if ("shortcut" in item && item.shortcut) {- $link.append($("<kbd>").text(item.shortcut));- }-- if ("trailingIcon" in item && item.trailingIcon) {- $link.append($("<span>")- .addClass([ item.trailingIcon, "tn-icon", "menu-trailing-icon" ]));- }-- const $item = $("<li>")- .addClass("dropdown-item")- .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");-- $item.toggleClass("submenu-open");- $item.find("ul.dropdown-menu").toggleClass("show");- return false;- }-- // A submenu's parent stays open so that it can still be expanded. One carrying a- // command or handler of its own is dismissed like any other item once it has run.- const opensSubmenu = "items" in item && !!item.items;- const acts = ("handler" in item && !!item.handler)- || ("command" in item && !!item.command);- if (!opensSubmenu || acts) {- 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;- });-- if ("enabled" in item && item.enabled !== undefined && !item.enabled) {- $item.addClass("disabled");- }-- if ("items" in item && item.items) {- $item.addClass("dropdown-submenu");- $link.addClass("dropdown-toggle");-- const $subMenu = $("<ul>").addClass("dropdown-menu");- const hasColumns = !!item.columns && item.columns > 1;- if (!this.isMobile && hasColumns) {- $subMenu.css("column-count", item.columns!);- }-- this.addItems($subMenu, item.items, hasColumns);-- $item.append($subMenu);-- // Submenus open downward by default (CSS `:hover`); flip them up when the parent item sits- // near the bottom of the viewport, otherwise the submenu would be clipped off-screen.- if (!this.isMobile) {- $item.on("mouseenter", () => this.repositionSubmenu($subMenu[0]));- }- }- return $item;}/**- * Whether a menu is up. For a host that answers a press itself and so keeps it from the- * document, whose click is what would otherwise put the menu away (see the listener bound in- * the constructor): such a host has to know a standing menu is what its press is really for.+ * 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.$widget.hasClass("show");+ return !!this.options;}async hide() {- this.options?.onHide?.();- this.$widget.removeClass("show");- this.$cover?.removeClass("show");- $("body").removeClass("context-menu-shown");- this.$widget.hide();+ const options = this.options;+ this.options = undefined;+ this.cover?.classList.remove("show");+ document.body.classList.remove("context-menu-shown");++ if (options && this.container) {+ render(null, this.container);+ options.onHide?.();+ }}}diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.tsnew file mode 100644index 0000000000..5682e39604--- /dev/null+++ b/apps/client/src/menus/context_menu_legacy.ts@@ -0,0 +1,478 @@+// Reference copy of the jQuery context menu from before the `Menu` rewrite. Nothing imports it.+// Delete a piece once `Menu` covers it, and the file once `Menu` reaches parity.++import { KeyboardActionNames } from "@triliumnext/commons";+import { Tooltip } from "bootstrap";+import { h, JSX, render } from "preact";++import keyboardActionService, { getActionSync } from "../services/keyboard_actions.js";+import { formatShortcut, joinShortcut } from "../services/keyboard_shortcut_display.js";+import note_tooltip from "../services/note_tooltip.js";+import utils from "../services/utils.js";++export interface ContextMenuOptions<T> {+ x: number;+ y: number;+ orientation?: "left";+ selectMenuItemHandler: MenuHandler<T>;+ items: MenuItem<T>[];+ /** On mobile, if set to `true` then the context menu is shown near the element. If `false` (default), then the context menu is shown at the bottom of the screen. */+ forcePositionOnMobile?: boolean;+ onHide?: () => void;+}++export interface CustomMenuItem {+ kind: "custom",+ componentFn: () => JSX.Element | null;+}++export interface MenuSeparatorItem {+ kind: "separator";+}++export interface MenuHeader {+ title: string;+ kind: "header";+}++export interface MenuItemBadge {+ title: string;+ className?: string;+}++export interface MenuCommandItem<T> {+ title: string;+ command?: T;+ type?: string;+ mime?: string;+ /**+ * The icon to display in the menu item.+ *+ * If not set, no icon is displayed and the item will appear shifted slightly to the left if there are other items with icons. To avoid this, use `bx bx-empty`.+ */+ uiIcon?: string;+ /**+ * Classes tinting {@link uiIcon} with the colour of whatever the item stands for, as+ * `cssClassManager.createClassForColor()` and `FNote#getColorClass()` return them. Only the+ * icon is tinted, the label staying readable against the highlight.+ */+ iconColorClass?: string;+ badges?: MenuItemBadge[];+ templateNoteId?: string;+ enabled?: boolean;+ handler?: MenuHandler<T>;+ items?: MenuItem<T>[] | null;+ shortcut?: string;+ keyboardShortcut?: KeyboardActionNames;+ spellingSuggestion?: string;+ checked?: boolean;+ /** Classes put on the item itself, for a menu styling one of its entries differently. */+ className?: string;+ /**+ * An icon shown at the trailing edge of the item, where a shortcut would go.+ *+ * Unlike {@link checked}, which takes the place of {@link uiIcon}, this leaves the item's own+ * icon standing — for a list where that icon is what tells one entry from another.+ */+ trailingIcon?: string;+ columns?: number;+}++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 ContextMenuEvent = PointerEvent | MouseEvent | JQuery.ContextMenuEvent;++class ContextMenu {+ private $widget: JQuery<HTMLElement>;+ private $cover?: JQuery<HTMLElement>;+ private options?: ContextMenuOptions<any>;+ private isMobile: boolean;+ /** Where the menu stands while nothing has the screen to itself. See {@link hostInWhateverHasTheScreen}. */+ private home: HTMLElement | null;++ constructor() {+ this.$widget = $("#context-menu-container");+ this.$widget.addClass("dropend");+ this.home = this.$widget[0]?.parentElement ?? null;+ this.isMobile = utils.isMobile();++ if (this.isMobile) {+ this.$cover = $("#context-menu-cover");+ this.$cover.on("click", () => this.hide());+ } else {+ $(document).on("click", (e) => this.hide());+ }+ }++ async show<T>(options: ContextMenuOptions<T>) {+ this.options = options;++ note_tooltip.dismissAllTooltips();+ hideShownTooltips();++ if (this.$widget.hasClass("show")) {+ // The menu is already visible. Hide the menu then open it again+ // at the new location to re-trigger the opening animation.+ await this.hide();+ }++ this.hostInWhateverHasTheScreen();++ this.$widget.toggleClass("mobile-bottom-menu", !this.options.forcePositionOnMobile);+ this.$cover?.addClass("show");+ $("body").addClass("context-menu-shown");++ this.$widget.empty();++ this.addItems(this.$widget, options.items);++ keyboardActionService.updateDisplayedShortcuts(this.$widget);++ this.positionMenu();+ }++ /**+ * Puts the menu inside the element that currently has the screen to itself, and back where it+ * belongs once nothing does.+ *+ * A browser showing an element fullscreen draws that element and nothing else: this menu lives at+ * the end of the page, so over a map or a diagram given the screen (see `useFullscreen`) it was+ * laid out, positioned and left unpainted — a right-click that appeared to do nothing at all.+ * Moved into whatever is being shown, it is drawn as usual; it is positioned against the viewport+ * either way, so nothing about where it lands changes.+ */+ private hostInWhateverHasTheScreen() {+ const menu = this.$widget[0];+ const host = document.fullscreenElement ?? this.home;+ if (menu && host && menu.parentElement !== host) {+ host.appendChild(menu);+ }+ }++ positionMenu() {+ if (!this.options) {+ return;+ }++ // the code below tries to detect when dropdown would overflow from page+ // in such case we'll position it above click coordinates, so it will fit into the client++ const CONTEXT_MENU_PADDING = 5; // How many pixels to pad the context menu from edge of screen+ const CONTEXT_MENU_OFFSET = 0; // How many pixels to offset the context menu by relative to cursor, see #3157++ const clientHeight = document.documentElement.clientHeight;+ const clientWidth = document.documentElement.clientWidth;+ const contextMenuHeight = this.$widget.outerHeight();+ const contextMenuWidth = this.$widget.outerWidth();+ let top, left;++ if (contextMenuHeight && this.options.y + contextMenuHeight - CONTEXT_MENU_OFFSET > clientHeight - CONTEXT_MENU_PADDING) {+ // Overflow: bottom+ top = clientHeight - contextMenuHeight - CONTEXT_MENU_PADDING;+ } else if (this.options.y - CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {+ // Overflow: top+ top = CONTEXT_MENU_PADDING;+ } else {+ top = this.options.y - CONTEXT_MENU_OFFSET;+ }++ if (this.options.orientation === "left" && contextMenuWidth) {+ if (this.options.x + CONTEXT_MENU_OFFSET > clientWidth - CONTEXT_MENU_PADDING) {+ // Overflow: right+ left = clientWidth - contextMenuWidth - CONTEXT_MENU_OFFSET;+ } else if (this.options.x - contextMenuWidth + CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {+ // Overflow: left+ left = CONTEXT_MENU_PADDING;+ } else {+ left = this.options.x - contextMenuWidth + CONTEXT_MENU_OFFSET;+ }+ } else if (contextMenuWidth && this.options.x + contextMenuWidth - CONTEXT_MENU_OFFSET > clientWidth - CONTEXT_MENU_PADDING) {+ // Overflow: right+ left = clientWidth - contextMenuWidth - CONTEXT_MENU_PADDING;+ } else if (this.options.x - CONTEXT_MENU_OFFSET < CONTEXT_MENU_PADDING) {+ // Overflow: left+ left = CONTEXT_MENU_PADDING;+ } else {+ left = this.options.x - CONTEXT_MENU_OFFSET;+ }++ this.$widget+ .css({+ display: "block",+ top,+ left+ })+ .addClass("show");+ }++ private repositionSubmenu(submenuEl: HTMLElement) {+ const CONTEXT_MENU_PADDING = 5;++ // Reset so the natural (downward, trailing) placement is measured on every hover.+ submenuEl.classList.remove("submenu-flip-up");+ submenuEl.classList.remove("submenu-flip-start");++ const rect = submenuEl.getBoundingClientRect();+ const clientHeight = document.documentElement.clientHeight;+ const clientWidth = document.documentElement.clientWidth;+ const overflowsBottom = rect.bottom > clientHeight - CONTEXT_MENU_PADDING;+ // Only flip up if there is actually more room above the parent than below, otherwise flipping+ // would just clip the other end.+ const fitsWhenFlippedUp = rect.top - rect.height >= CONTEXT_MENU_PADDING;++ if (overflowsBottom && fitsWhenFlippedUp) {+ submenuEl.classList.add("submenu-flip-up");+ }++ // The same for the side it opens on, which is the trailing one by default and the leading+ // one in a right-to-left page. Whichever edge it runs past, the flip puts it on the other+ // side of its parent, and only where the whole submenu fits there.+ const fitsWhenFlippedToStart = rect.left - rect.width >= CONTEXT_MENU_PADDING;+ const fitsWhenFlippedToEnd = rect.right + rect.width <= clientWidth - CONTEXT_MENU_PADDING;++ if ((rect.right > clientWidth - CONTEXT_MENU_PADDING && fitsWhenFlippedToStart)+ || (rect.left < CONTEXT_MENU_PADDING && fitsWhenFlippedToEnd)) {+ submenuEl.classList.add("submenu-flip-start");+ }+ }++ addItems($parent: JQuery<HTMLElement>, items: MenuItem<any>[], multicolumn = false) {+ let $group = $parent; // The current group or parent element to which items are being appended+ let shouldStartNewGroup = false; // If true, the next item will start a new group+ let shouldResetGroup = false; // If true, the next item will be the last one from the group+ let prevItemKind: string = "";++ for (let index = 0; index < items.length; index++) {+ const item = items[index];+ const itemKind = ("kind" in item) ? item.kind : "";++ if (!item) {+ continue;+ }++ // If the current item is a header, start a new group. This group will contain the+ // header and the next item that follows the header.+ if (itemKind === "header") {+ if (multicolumn && !shouldResetGroup) {+ shouldStartNewGroup = true;+ }+ }++ // If the next item is a separator, start a new group. This group will contain the+ // current item, the separator, and the next item after the separator.+ const nextItem = (index < items.length - 1) ? items[index + 1] : null;+ if (multicolumn && nextItem && "kind" in nextItem && nextItem.kind === "separator") {+ if (!shouldResetGroup) {+ shouldStartNewGroup = true;+ } else {+ shouldResetGroup = true; // Continue the current group+ }+ }++ // Create a new group to avoid column breaks before and after the seaparator / header.+ // This is a workaround for Firefox not supporting break-before / break-after: avoid+ // for columns.+ if (shouldStartNewGroup) {+ $group = $("<div class='dropdown-no-break'>");+ $parent.append($group);+ shouldStartNewGroup = false;+ }++ 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") {+ $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>));+ }++ // 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.+ if (shouldResetGroup) {+ $group = $parent;+ shouldResetGroup = false;+ };+ }++ prevItemKind = itemKind;++ }+ }++ 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 $icon = $("<span>");++ if ("uiIcon" in item || "checked" in item) {+ const icon = (item.checked ? "bx bx-check" : item.uiIcon);+ if (icon) {+ $icon.addClass([icon, "tn-icon"]);+ if (item.iconColorClass) {+ $icon.addClass(item.iconColorClass);+ }+ } else {+ $icon.append(" ");+ }+ }++ const $link = $("<span>")+ .append($icon)+ // An element, not spaces: in a flex row, text merges with a plain title but is+ // trimmed before one boxed by `menuName()`, indenting the two kinds of row apart.+ .append($("<span>").addClass("tn-menu-gap"))+ .append(item.title);++ if ("badges" in item && item.badges) {+ for (const badge of item.badges) {+ const badgeElement = $(`<span class="badge">`).text(badge.title);++ if (badge.className) {+ badgeElement.addClass(badge.className);+ }++ $link.append(badgeElement);+ }+ }++ if ("keyboardShortcut" in item && item.keyboardShortcut) {+ const shortcuts = getActionSync(item.keyboardShortcut).effectiveShortcuts;+ if (shortcuts) {+ const allShortcuts: string[] = [];+ for (const effectiveShortcut of shortcuts) {+ const tokens = formatShortcut(effectiveShortcut);+ // On macOS the glyphs sit in one <kbd> (⇧⌘J); elsewhere each token gets its own.+ allShortcuts.push(utils.isMac()+ ? `<kbd>${joinShortcut(tokens)}</kbd>`+ : tokens.map(key => `<kbd>${key}</kbd>`).join("+"));+ }++ if (allShortcuts.length) {+ const container = $("<span>").addClass("keyboard-shortcut");+ container.append($(allShortcuts.join(",")));+ $link.append(container);+ }+ }+ } else if ("shortcut" in item && item.shortcut) {+ $link.append($("<kbd>").text(item.shortcut));+ }++ if ("trailingIcon" in item && item.trailingIcon) {+ $link.append($("<span>")+ .addClass([ item.trailingIcon, "tn-icon", "menu-trailing-icon" ]));+ }++ const $item = $("<li>")+ .addClass("dropdown-item")+ .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");++ $item.toggleClass("submenu-open");+ $item.find("ul.dropdown-menu").toggleClass("show");+ return false;+ }++ // A submenu's parent stays open so that it can still be expanded. One carrying a+ // command or handler of its own is dismissed like any other item once it has run.+ const opensSubmenu = "items" in item && !!item.items;+ const acts = ("handler" in item && !!item.handler)+ || ("command" in item && !!item.command);+ if (!opensSubmenu || acts) {+ 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;+ });++ if ("enabled" in item && item.enabled !== undefined && !item.enabled) {+ $item.addClass("disabled");+ }++ if ("items" in item && item.items) {+ $item.addClass("dropdown-submenu");+ $link.addClass("dropdown-toggle");++ const $subMenu = $("<ul>").addClass("dropdown-menu");+ const hasColumns = !!item.columns && item.columns > 1;+ if (!this.isMobile && hasColumns) {+ $subMenu.css("column-count", item.columns!);+ }++ this.addItems($subMenu, item.items, hasColumns);++ $item.append($subMenu);++ // Submenus open downward by default (CSS `:hover`); flip them up when the parent item sits+ // near the bottom of the viewport, otherwise the submenu would be clipped off-screen.+ if (!this.isMobile) {+ $item.on("mouseenter", () => this.repositionSubmenu($subMenu[0]));+ }+ }+ return $item;+ }++ /**+ * Whether a menu is up. For a host that answers a press itself and so keeps it from the+ * document, whose click is what would otherwise put the menu away (see the listener bound in+ * the constructor): such a host has to know a standing menu is what its press is really for.+ */+ isShown() {+ return this.$widget.hasClass("show");+ }++ async hide() {+ this.options?.onHide?.();+ this.$widget.removeClass("show");+ this.$cover?.removeClass("show");+ $("body").removeClass("context-menu-shown");+ this.$widget.hide();+ }+}++const contextMenu = new ContextMenu();++export default contextMenu;++// Bootstrap sets `aria-describedby` on a trigger while its tooltip is shown. `hide()` also clears+// the hover and focus triggers that keep the tooltip up.+function hideShownTooltips() {+ for (const trigger of document.querySelectorAll("[aria-describedby]")) {+ Tooltip.getInstance(trigger)?.hide();+ }+}diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex a6e0a351da..424c5ef19a 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1667,9 +1667,9 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-tbackground: rgba(0, 0, 0, 0.1);}+/* Only hosts the rendered `.tn-menu`, so it takes no part in the page's layout. */#context-menu-container {- max-height: 100vh;- /* !!! Cannot set overflow: auto, submenus will break !!! */+ display: contents;}body.mobile #context-menu-container.mobile-bottom-menu {@@ -1701,7 +1701,6 @@ body.mobile .dropdown-submenu > .dropdown-menu {max-height: none;}-#context-menu-container,#context-menu-container .dropdown-menu,.tabulator-popup-container {padding: 3px 0;diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.cssnew file mode 100644index 0000000000..f220fe488c--- /dev/null+++ b/apps/client/src/widgets/react/Menu.css@@ -0,0 +1,23 @@+.tn-menu {+ position: fixed;+ /* Matches the z-index the context menu had, above dialogs and floating panels. */+ z-index: 2000;+ min-width: 10rem;+ padding: var(--menu-padding-size);+ border: 1px solid var(--dropdown-border-color);+ border-radius: var(--dropdown-border-radius);+ background: var(--menu-background-color);+ color: var(--menu-text-color);+ box-shadow: 0 10px 20px rgba(0, 0, 0, var(--dropdown-shadow-opacity));+ font-size: 0.9rem;++ /* The blur sits on a pseudo-element: on the menu itself it blurs nothing over note content. */+ &::before {+ content: "";+ position: absolute;+ inset: 0;+ z-index: -1;+ border-radius: inherit;+ backdrop-filter: var(--dropdown-backdrop-filter);+ }+}diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsxnew file mode 100644index 0000000000..dade21447c--- /dev/null+++ b/apps/client/src/widgets/react/Menu.tsx@@ -0,0 +1,39 @@+import "./Menu.css";++import { useLayoutEffect, useRef, useState } from "preact/hooks";++export interface MenuProps {+ /** Where the menu opens, in viewport coordinates. */+ x: number;+ y: number;+}++/** How many pixels the menu keeps from the edges of the viewport. */+const VIEWPORT_PADDING = 5;++export default function Menu({ x, y }: MenuProps) {+ const menuRef = useRef<HTMLDivElement>(null);+ const [ position, setPosition ] = useState({ left: x, top: y });++ useLayoutEffect(() => {+ const menu = menuRef.current;+ if (!menu) return;++ const { width, height } = menu.getBoundingClientRect();+ const { clientWidth, clientHeight } = document.documentElement;+ setPosition({+ left: clampToViewport(x, clientWidth - width),+ top: clampToViewport(y, clientHeight - height)+ });+ }, [ x, y ]);++ return (+ <div ref={menuRef} className="tn-menu" role="menu" style={position}>+ Hello world+ </div>+ );+}++function clampToViewport(value: number, max: number) {+ return Math.max(VIEWPORT_PADDING, Math.min(value, max - VIEWPORT_PADDING));+}diff --git a/apps/standalone/src/index.html b/apps/standalone/src/index.htmlindex fe31517bbc..9321521198 100644--- a/apps/standalone/src/index.html+++ b/apps/standalone/src/index.html@@ -144,7 +144,7 @@</div><div id="context-menu-cover"></div>- <div class="dropdown-menu dropdown-menu-sm" id="context-menu-container" style="display: none"></div>+ <div id="context-menu-container"></div><!-- Required for match the PWA's top bar color with the theme --><!-- This works even when the user directly changes --root-background in CSS -->