Skip to content

Build your personal knowledge base with Trilium Notes

client/ui/menus: add support for actions on menu headings

Adorian Doran3e92878e1314
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 5cb2f6dfed..9b4ce726a9 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -34,6 +34,21 @@ export interface MenuSeparatorItem {
export interface MenuHeader {
title: string;
kind: "header";
+ /** Icon buttons at the end of the heading, for secondary actions such as help or options. */
+ actions?: MenuHeaderActions;
+}
+
+/** The actions of a {@link MenuHeader}: at most three. */
+export type MenuHeaderActions = [] | [MenuHeaderAction] | [MenuHeaderAction, MenuHeaderAction]
+ | [MenuHeaderAction, MenuHeaderAction, MenuHeaderAction];
+
+export interface MenuHeaderAction {
+ /** The classes of the icon, such as `bx bx-help-circle`. */
+ icon: string;
+ /** The name of the action, shown as the button's tooltip. */
+ caption: string;
+ /** Called after the menu closes. */
+ callback: (e: MouseEvent) => void;
}
/** A row of items side by side, each drawn as its icon over its title. */
diff --git a/apps/client/src/widgets/react/FormList.css b/apps/client/src/widgets/react/FormList.css
index a06c699b7e..ff7016e9ab 100644
--- a/apps/client/src/widgets/react/FormList.css
+++ b/apps/client/src/widgets/react/FormList.css
@@ -48,14 +48,28 @@
}
}
-.dropdown-header.dropdown-header-with-action {
+.dropdown-header.tn-menu-header-with-actions {
display: flex;
align-items: center;
- justify-content: space-between;
- gap: 0.5em;
+ gap: 1em;
+
+ > .tn-menu-header-actions {
+ --icon-button-size: 22px;
+ --icon-button-color: var(--menu-item-icon-color);
+
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ margin-inline: auto -4px;
+ /* The buttons overflow the line evenly, so the heading keeps its height. */
+ height: 0;
+ letter-spacing: normal;
- /* Shrink the whole icon-action box (not just the glyph) to the 26px used by
- the right-panel card-header-buttons — .icon-action derives its width,
- height and font-size from this variable. */
- --icon-button-size: 26px;
+ .icon-action {
+ padding: 0;
+ width: var(--icon-button-size);
+ height: var(--icon-button-size);
+ font-size: calc(var(--icon-button-size) * 0.65);
+ }
+ }
}
diff --git a/apps/client/src/widgets/react/FormList.spec.tsx b/apps/client/src/widgets/react/FormList.spec.tsx
index d15a382cf9..cb7ea0fc0f 100644
--- a/apps/client/src/widgets/react/FormList.spec.tsx
+++ b/apps/client/src/widgets/react/FormList.spec.tsx
@@ -46,6 +46,21 @@ describe("FormListHeader", () => {
expect(row?.getAttribute("role")).toBe("none");
expect(row?.querySelector("h6.dropdown-header")?.textContent).toBe("<b>Doing</b>");
});
+
+ it("runs its actions outside a menu too", () => {
+ const host = document.createElement("div");
+ const callback = vi.fn();
+ render((
+ <menu role="none">
+ <FormListHeader text="Fonts" actions={[ { icon: "bx bx-cog", caption: "Options", callback } ]} />
+ </menu>
+ ), host);
+ const button = host.querySelector<HTMLButtonElement>("h6 > .tn-menu-header-actions > button");
+ if (!button) throw new Error("expected the action's button");
+
+ button.click();
+ expect(callback).toHaveBeenCalledWith(expect.any(MouseEvent));
+ });
});
describe("FormListItem", () => {
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index c4268fd195..0c7ea8b76f 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -7,6 +7,7 @@ import clsx from "clsx";
import { ComponentChildren, createPortal, type CSSProperties, RefObject } from "preact";
import { useContext, useLayoutEffect, useMemo, useRef } from "preact/hooks";
+import type { MenuHeaderActions } from "../../menus/context_menu";
import { t } from "../../services/i18n";
import { getActionSync } from "../../services/keyboard_actions";
import { handleRightToLeftPlacement, isMobile, openInAppHelpFromUrl } from "../../services/utils";
@@ -415,17 +416,45 @@ function FormListContent({ children, badges, description, disabled, disabledTool
interface FormListHeaderOpts {
/** Usually a heading, but anything a group can be introduced by: a summary, a row of marks. */
text: ComponentChildren;
- /** Optional element rendered right-aligned in the header (e.g. an edit action). */
- action?: ComponentChildren;
+ /** Icon buttons at the end of the heading, which keep it as tall as a heading without them. */
+ actions?: MenuHeaderActions;
}
-export function FormListHeader({ text, action }: FormListHeaderOpts) {
+/** The most actions a heading shows, as `MenuHeaderActions` allows. A script can pass more. */
+const MAX_HEADER_ACTIONS = 3;
+
+export function FormListHeader({ text, actions = [] }: FormListHeaderOpts) {
+ const menu = useContext(MenuContext);
+ const level = useContext(MenuLevelContext);
+ const shownActions = actions.slice(0, MAX_HEADER_ACTIONS);
+ const hasActions = shownActions.length > 0;
+
// Its heading speaks for the row, which a menu does not count among its items.
return (
<li role="none">
- <h6 className={clsx("dropdown-header", action && "dropdown-header-with-action")}>
+ <h6 className={clsx("dropdown-header", hasActions && "tn-menu-header-with-actions")}>
<span>{text}</span>
- {action}
+ {hasActions && (
+ <span
+ className="tn-menu-header-actions"
+ // As over a row, the pointer closes the submenu open at this level.
+ onPointerMove={(e) => {
+ if (menu?.open[level] && pointerMoved(e)) menu.openSubmenu(level);
+ }}
+ // A press keeps focus where it was, as on a row.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ {shownActions.map(({ icon, caption, callback }, index) => (
+ <ActionButton
+ key={index} icon={icon} text={caption} titlePosition="top"
+ onClick={(e) => {
+ menu?.close();
+ callback(e);
+ }}
+ />
+ ))}
+ </span>
+ )}
</h6>
</li>
);
diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsx
index a66c275569..f06f6d9bc1 100644
--- a/apps/client/src/widgets/react/Menu.spec.tsx
+++ b/apps/client/src/widgets/react/Menu.spec.tsx
@@ -3,7 +3,7 @@ import { render } from "preact";
import { useState } from "preact/hooks";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import type { MenuItem } from "../../menus/context_menu";
+import type { MenuHeaderAction, MenuHeaderActions, MenuItem } from "../../menus/context_menu";
import { formatShortcut, joinShortcut } from "../../services/keyboard_shortcut_display";
import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem } from "./FormList";
import Menu, { bottomUpOrder, MenuItemRows, type MenuProps } from "./Menu";
@@ -472,6 +472,90 @@ describe("Menu with an action row", () => {
});
});
+describe("Menu with heading actions", () => {
+ const host = document.createElement("div");
+ document.body.append(host);
+ afterEach(() => render(null, host));
+
+ function renderMenu() {
+ const calls: string[] = [];
+ const onSelect = vi.fn();
+ const action = (caption: string, icon: string): MenuHeaderAction =>
+ ({ caption, icon, callback: (e) => calls.push(`${caption} ${e.type}`) });
+ // Four, as a script can pass, past the three the type allows.
+ const actions = [ action("Help", "bx bx-help-circle"), action("Options", "bx bx-cog"),
+ action("Reset", "bx bx-reset"), action("Extra", "bx bx-plus") ];
+ const items: MenuItem<string>[] = [
+ { kind: "header", title: "Sort", actions: actions as MenuHeaderActions },
+ { title: "By title", command: "title" },
+ { title: "More", items: [ { title: "Inner", command: "inner" } ] }
+ ];
+ render(<Menu
+ anchor={{ x: 10, y: 10 }} items={items} onSelect={onSelect}
+ onClose={() => calls.push("close")}
+ />, host);
+
+ const menu = document.querySelector<HTMLElement>(".tn-popup.tn-menu");
+ const buttons = [ ...menu?.querySelectorAll<HTMLButtonElement>(
+ "h6.dropdown-header > .tn-menu-header-actions > button") ?? [] ];
+ if (!menu || !buttons.length) throw new Error("expected the menu and the heading's actions");
+ return { menu, buttons, calls, onSelect };
+ }
+
+ const key = (menu: HTMLElement, name: string) =>
+ menu.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true }));
+
+ it("draws at most three icon buttons after the title, named by tooltips and skipped by the keys", async () => {
+ const { menu, buttons } = renderMenu();
+ const tooltipText = (button: HTMLElement) => {
+ const tooltip = Tooltip.getInstance(button);
+ if (!tooltip) return undefined;
+ tooltip.show();
+ const text = document.querySelector(".tooltip:last-of-type .tooltip-inner")?.textContent;
+ tooltip.hide();
+ return text;
+ };
+
+ expect(menu.querySelector("h6.dropdown-header")?.textContent).toBe("Sort");
+ expect(buttons.map((button) => [ ...button.classList ].join(" "))).toEqual([
+ "icon-action bx bx-help-circle",
+ "icon-action bx bx-cog",
+ "icon-action bx bx-reset"
+ ]);
+ await vi.waitFor(() => expect(buttons.map(tooltipText)).toEqual([ "Help", "Options", "Reset" ]));
+
+ key(menu, "ArrowDown");
+ await vi.waitFor(() => expect(menu.querySelector("li.tn-menu-active > span")?.textContent).toBe("By title"));
+ });
+
+ it("closes the menu, then runs the action, keeping the focus and running no row", () => {
+ const { buttons, calls, onSelect } = renderMenu();
+ const [ , options ] = buttons;
+ if (!options) throw new Error("expected the Options action");
+
+ const press = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
+ options.dispatchEvent(press);
+ options.click();
+
+ expect(press.defaultPrevented).toBe(true);
+ expect(calls).toEqual([ "close", "Options click" ]);
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+
+ it("closes a row's submenu once the pointer turns to the heading's actions", async () => {
+ const { menu, buttons: [ help ] } = renderMenu();
+ const layers = () => menu.querySelectorAll(":scope > div.dropdown-submenu > .dropdown-menu").length;
+ const more = [ ...menu.querySelectorAll<HTMLElement>("li.dropdown-item") ]
+ .find((row) => row.querySelector(":scope > span")?.textContent === "More");
+ if (!help || !more) throw new Error("expected the Help action and the More row");
+
+ more.dispatchEvent(new PointerEvent("pointerenter"));
+ await vi.waitFor(() => expect(layers()).toBe(1));
+ help.dispatchEvent(new PointerEvent("pointermove", { bubbles: true, movementX: 3 }));
+ await vi.waitFor(() => expect(layers()).toBe(0));
+ });
+});
+
describe("bottomUpOrder", () => {
const header = (title: string): MenuItem<unknown> => ({ kind: "header", title });
const separator: MenuItem<unknown> = { kind: "separator" };
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 9f55e3d156..1c9c542ff6 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -555,7 +555,7 @@ function MenuItemRow<T>({ row, onSelect }: { row: MenuItem<T>, onSelect: MenuPro
if ("kind" in row) {
if (row.kind === "separator") return <FormDropdownDivider />;
// Its title is text, as it can be a name the user wrote.
- if (row.kind === "header") return <FormListHeader text={row.title} />;
+ if (row.kind === "header") return <FormListHeader text={row.title} actions={row.actions} />;
if (row.kind === "actions") return <MenuActions items={row.items} className={row.className} onSelect={onSelect} />;
return <FormListCustomItem><row.componentFn /></FormListCustomItem>;
}
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
index 65e7ff3017..d9699e2bdd 100644
--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx
@@ -431,13 +431,11 @@ export default function ChatInputBar({
<Fragment key={group.id}>
<FormListHeader
text={group.name}
- action={
- <ActionButton
- icon="bx bx-edit"
- text={t("llm_chat.edit_models")}
- onClick={() => openEditModels(group.id)}
- />
- }
+ actions={[ {
+ icon: "bx bx-edit",
+ caption: t("llm_chat.edit_models"),
+ callback: () => openEditModels(group.id)
+ } ]}
/>
{group.models.length > 0 ? group.models.map(model => (
<FormListItem