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
refactor(menu): style the context menu with the dropdown markup it had
Elian Doran72add0d4f868
diff --git a/apps/client/index.html b/apps/client/index.htmlindex 1f632ad82b..dee8ca1a59 100644--- a/apps/client/index.html+++ b/apps/client/index.html@@ -144,7 +144,7 @@</div><div id="context-menu-cover"></div>- <div id="context-menu-container"></div>+ <div id="context-menu-host"></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 50af1bc298..8545961824 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -2,9 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";vi.mock("../services/note_tooltip", () => ({ default: { dismissAllTooltips: vi.fn() } }));-/** The page as the shell leaves it: the menu's own element, at the end of the body. */+/** The page as the shell leaves it: the element the menu mounts into, at the end of the body. */function buildPage() {- document.body.innerHTML = `<div id="app"></div><div id="context-menu-container"></div>`;+ document.body.innerHTML = `<div id="app"></div><div id="context-menu-host"></div>`;+ return document.getElementById("context-menu-host");+}++/** The open menu, under the id the stylesheets and the app's floating layers know it by. */+function menuElement() {return document.getElementById("context-menu-container");}@@ -26,19 +31,24 @@ beforeEach(() => {});describe("contextMenu", () => {- it("renders the menu into its container and removes it on hide", async () => {- const container = buildPage();+ it("renders the menu into its host and removes it on hide", async () => {+ const host = buildPage();const contextMenu = await buildContextMenu();const onHide = vi.fn();await contextMenu.show({ x: 10, y: 20, items, selectMenuItemHandler: () => {}, onHide });- const menu = container?.querySelector<HTMLElement>(".tn-menu");+ const menu = menuElement();+ expect(menu?.parentElement).toBe(host);expect(menu?.getAttribute("role")).toBe("menu");+ // The classes the old menu carried, which the stylesheets and themes style it by.+ expect([ ...menu?.classList ?? [] ]).toEqual(expect.arrayContaining([+ "dropdown-menu", "dropdown-menu-sm", "dropend", "show"+ ]));expect(document.body.classList.contains("context-menu-shown")).toBe(true);await contextMenu.hide();- expect(container?.querySelector(".tn-menu")).toBeNull();+ expect(menuElement()).toBeNull();expect(document.body.classList.contains("context-menu-shown")).toBe(false);expect(onHide).toHaveBeenCalledTimes(1);@@ -49,28 +59,32 @@ describe("contextMenu", () => {describe("items", () => {it("lists the items and separators in order, without repeating a separator", async () => {- const container = buildPage();+ buildPage();const contextMenu = await buildContextMenu();await contextMenu.show({x: 10, y: 10, selectMenuItemHandler: () => {},items: [{ title: "Cut" },- { title: "Copy" },+ { title: "Copy", className: "destructive-action" },{ 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);+ const rows = [ ...menuElement()?.children ?? [] ]+ .map(row => `${row.tagName.toLowerCase()}.${row.className} ${row.textContent}`);+ expect(rows).toEqual([+ "li.dropdown-item Cut",+ "li.dropdown-item destructive-action Copy",+ "div.dropdown-divider ",+ "li.dropdown-item Paste"+ ]);});it("renders a title as HTML, as callers escape and mark it up", async () => {- const container = buildPage();+ buildPage();const contextMenu = await buildContextMenu();await contextMenu.show({@@ -78,13 +92,13 @@ describe("contextMenu", () => {items: [ { title: `Tolkien & <sons> <span class="tn-menu-name">Not set</span>` } ]});- const row = container?.querySelector("[role=menuitem]");+ const row = menuElement()?.querySelector("[role=menuitem]");expect(row?.textContent).toBe("Tolkien & <sons> Not set");expect(row?.querySelector(".tn-menu-name")).not.toBeNull();});it("shows an item's icon, a check mark in its place when checked, and a slot for none", async () => {- const container = buildPage();+ buildPage();const contextMenu = await buildContextMenu();await contextMenu.show({@@ -97,20 +111,24 @@ describe("contextMenu", () => {]});- const icons = [ ...container?.querySelectorAll("[role=menuitem]") ?? [] ]- .map(row => row.querySelector(".tn-icon")?.className ?? null);- expect(icons).toEqual([- "bx bx-list-ul use-note-color color-e64d4d tn-icon",+ // Each row is a span of icon slot, gap and title, which `.dropdown-item > span` lays out.+ const slots = [ ...menuElement()?.querySelectorAll("li.dropdown-item") ?? [] ].map(row => {+ const [ icon, gap ] = row.querySelector(":scope > span")?.children ?? [];+ expect(gap?.className).toBe("tn-menu-gap");+ return icon?.className || icon?.textContent;+ });+ expect(slots).toEqual([+ "bx bx-list-ul tn-icon use-note-color color-e64d4d","bx bx-check tn-icon",- "bx bx-empty tn-icon",- null+ "\u00a0",+ ""]);// Only the icon is tinted, so the title keeps the menu's own colour.- expect(container?.querySelectorAll(".use-note-color")).toHaveLength(1);+ expect(menuElement()?.querySelectorAll(".use-note-color")).toHaveLength(1);});it("runs an item pressed with the primary button, then hides", async () => {- const container = buildPage();+ buildPage();const contextMenu = await buildContextMenu();const calls: string[] = [];const item = { title: "Copy", handler: () => { calls.push("handler"); } };@@ -119,7 +137,7 @@ describe("contextMenu", () => {x: 10, y: 10, items: [ item ],selectMenuItemHandler: (selected) => { calls.push(`select ${selected.title}`); }});- const row = container?.querySelector<HTMLElement>("[role=menuitem]");+ const row = menuElement()?.querySelector<HTMLElement>("[role=menuitem]");if (!row) throw new Error("expected a menu item");// Other buttons do nothing.@@ -139,7 +157,7 @@ describe("contextMenu", () => {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" }) {- const container = buildPage();+ buildPage();const contextMenu = await buildContextMenu();// Floating UI reads the viewport from the root element's client size.vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);@@ -148,7 +166,7 @@ describe("contextMenu", () => {vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(options.height);await contextMenu.show({ ...options, items, selectMenuItemHandler: () => {} });- const menu = container?.querySelector<HTMLElement>(".tn-menu");+ const menu = menuElement();if (!menu) throw new Error("expected the menu to render");await vi.waitFor(() => expect(menu.style.visibility).toBe("visible"));return menu;diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex a65543d2dd..e9ed980d53 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -86,7 +86,7 @@ class ContextMenu {private options?: ContextMenuOptions<any>;constructor() {- this.container = document.getElementById("context-menu-container");+ this.container = document.getElementById("context-menu-host");this.home = this.container?.parentElement ?? null;this.cover = utils.isMobile() ? document.getElementById("context-menu-cover") : null;@@ -114,6 +114,9 @@ class ContextMenu {document.body.classList.add("context-menu-shown");render(h(Menu<T>, {+ // The id and classes the stylesheets, themes and `floating_layers` know this menu by.+ id: "context-menu-container",+ className: "dropdown-menu-sm dropend",x: options.x,y: options.y,orientation: options.orientation,diff --git a/apps/client/src/menus/context_menu_legacy.ts b/apps/client/src/menus/context_menu_legacy.tsindex f2cf041af6..f676128258 100644--- a/apps/client/src/menus/context_menu_legacy.ts+++ b/apps/client/src/menus/context_menu_legacy.ts@@ -92,7 +92,6 @@ class ContextMenu {constructor() {this.$widget = $("#context-menu-container");- this.$widget.addClass("dropend");this.home = this.$widget[0]?.parentElement ?? null;this.isMobile = utils.isMobile();@@ -300,7 +299,6 @@ class ContextMenu {const $item = $("<li>").addClass("dropdown-item")- .addClass("className" in item ? item.className ?? "" : "").append($link).on("contextmenu", (e) => false).on("mousedown", (e) => {diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 424c5ef19a..76474f81ac 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1667,11 +1667,15 @@ 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 {+/* Only mounts the context menu, so it takes no part in the page's layout. */+#context-menu-host {display: contents;}+#context-menu-container {+ max-height: 100vh;+}+body.mobile #context-menu-container.mobile-bottom-menu {position: fixed !important;inset-inline-start: 0 !important;@@ -1701,6 +1705,7 @@ 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.cssindex 4ca0b729e9..3048258e22 100644--- a/apps/client/src/widgets/react/Menu.css+++ b/apps/client/src/widgets/react/Menu.css@@ -1,63 +1,9 @@-.tn-menu {+/* The look comes from `.dropdown-menu`; this only places it. */+.dropdown-menu.tn-menu {position: fixed;top: 0;left: 0;- /* Matches the z-index the context menu had, above dialogs and floating panels. */- z-index: 2000;/* `placeMenu()` shows the menu once it has a position. */visibility: hidden;- min-width: 10rem;overflow-y: auto;- 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);- }-}--.tn-menu-item {- display: flex;- align-items: center;- gap: 0.5em;- 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-icon {- flex: none;- translate: 0 var(--menu-item-icon-vert-offset);- color: var(--menu-item-icon-color);- font-size: 1.1em;- }-- /* `iconColorClass` tints the icon with the color of what the item stands for. */- .tn-icon.use-note-color {- color: var(--custom-color, var(--menu-item-icon-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.tsxindex ee13668772..e6ccf84938 100644--- a/apps/client/src/widgets/react/Menu.tsx+++ b/apps/client/src/widgets/react/Menu.tsx@@ -1,13 +1,20 @@import "./Menu.css";import { computePosition, flip, type Placement, shift, size, type VirtualElement } from "@floating-ui/dom";+import clsx from "clsx";import { useCallback, useLayoutEffect, useRef } from "preact/hooks";import type { MenuCommandItem, MenuItem, MenuSeparatorItem } from "../../menus/context_menu";import { useResizeObserver } from "./hooks";-import Icon from "./Icon";+/**+ * A menu of commands, drawn with the markup Bootstrap's dropdowns use (`.dropdown-menu`,+ * `.dropdown-item`, `.dropdown-divider`), so the stylesheets and themes that style those style+ * this too. Only the placement is its own.+ */export interface MenuProps<T> {+ id?: string;+ className?: string;/** Where the menu opens, in viewport coordinates. */x: number;y: number;@@ -21,7 +28,7 @@ export interface MenuProps<T> {/** How many pixels the menu keeps from the edges of the viewport. */const VIEWPORT_PADDING = 5;-export default function Menu<T>({ x, y, orientation, items, onSelect }: MenuProps<T>) {+export default function Menu<T>({ id, className, x, y, orientation, items, onSelect }: MenuProps<T>) {const menuRef = useRef<HTMLDivElement>(null);const place = useCallback(() => {if (!menuRef.current) return;@@ -33,9 +40,9 @@ export default function Menu<T>({ x, y, orientation, items, onSelect }: MenuPropuseResizeObserver(menuRef, place);return (- <div ref={menuRef} className="tn-menu" role="menu">+ <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="tn-menu-separator" role="separator" />+ ? <div key={index} className="dropdown-divider" role="separator" />: <MenuRow key={index} item={row as MenuCommandItem<T>} onSelect={onSelect} />))}</div>@@ -44,8 +51,8 @@ export default function Menu<T>({ x, y, orientation, items, onSelect }: MenuPropfunction MenuRow<T>({ item, onSelect }: { item: MenuCommandItem<T>, onSelect: MenuProps<T>["onSelect"] }) {return (- <div- className="tn-menu-item"+ <li+ className={clsx("dropdown-item", item.className)}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.@@ -55,15 +62,29 @@ function MenuRow<T>({ item, onSelect }: { item: MenuCommandItem<T>, onSelect: MeonSelect(item, e);}}>- {("uiIcon" in item || "checked" in item) && (- <Icon icon={item.checked ? "bx bx-check" : item.uiIcon} className={item.iconColorClass} />- )}- {/* Callers pass HTML: titles escaped with `escapeHtml()` or boxed by `menuName()`. */}- <span dangerouslySetInnerHTML={{ __html: item.title }} />- </div>+ <span>+ <MenuIconSlot item={item} />+ <span className="tn-menu-gap" />+ {/* Callers pass HTML: titles escaped with `escapeHtml()` or boxed by `menuName()`. */}+ <span dangerouslySetInnerHTML={{ __html: item.title }} />+ </span>+ </li>);}+/**+ * The icon, or a check mark in its place. An item that sets `uiIcon` to nothing gets a blank slot,+ * and one without `uiIcon` or `checked` an empty one.+ */+function MenuIconSlot<T>({ item }: { item: MenuCommandItem<T> }) {+ if (!("uiIcon" in item || "checked" in item)) return <span />;++ const icon = item.checked ? "bx bx-check" : item.uiIcon;+ return icon+ ? <span className={clsx(icon, "tn-icon", item.iconColorClass)} />+ : <span>{"\u00a0"}</span>;+}+/** 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)[] = [];diff --git a/apps/standalone/src/index.html b/apps/standalone/src/index.htmlindex 9321521198..3061b73624 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 id="context-menu-container"></div>+ <div id="context-menu-host"></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 -->