Skip to content

Build your personal knowledge base with Trilium Notes

client/ui/cards/item creation button: add support for dropdown menu

Adorian Doran554fc188dd3d
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index 4cbec59195..38acbcc3ba 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -1615,6 +1615,39 @@ describe("contextMenu", () => {
expect([ menu.style.left, menu.style.top ]).toEqual([ "5px", "20px" ]);
});
+ it("opens below or above the element it is anchored to, centered on request", async () => {
+ buildPage();
+ const contextMenu = await buildContextMenu();
+ vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);
+ vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(800);
+ vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(200);
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(300);
+ const button = document.createElement("button");
+ document.body.append(button);
+ let buttonRect = DOMRect.fromRect({ x: 100, y: 200, width: 400, height: 30 });
+ vi.spyOn(button, "getBoundingClientRect").mockImplementation(() => buttonRect);
+
+ /** Where the menu is placed against `button`, which it is hidden again after. */
+ async function placedAt(centered?: boolean) {
+ await contextMenu.show({
+ anchor: button, centered, items, selectMenuItemHandler: () => {}
+ });
+ const menu = menuElement();
+ if (!menu) throw new Error("expected the menu to render");
+ await vi.waitFor(() => expect(menu.style.visibility).toBe("visible"));
+ const position = [ menu.style.left, menu.style.top ];
+ await contextMenu.hide();
+ return position;
+ }
+
+ expect(await placedAt()).toEqual([ "100px", "230px" ]);
+ expect(await placedAt(true)).toEqual([ "200px", "230px" ]);
+
+ buttonRect = DOMRect.fromRect({ x: 100, y: 600, width: 400, height: 30 });
+ expect(await placedAt()).toEqual([ "100px", "300px" ]);
+ expect(await placedAt(true)).toEqual([ "200px", "300px" ]);
+ });
+
it("caps its height to the viewport so that it scrolls", async () => {
const menu = await place({ x: 10, y: 20, width: 200, height: 2000 });
expect(menu.style.maxHeight).toBe("790px");
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.ts
index 087766b9ba..b26462b8c9 100644
--- a/apps/client/src/menus/context_menu.ts
+++ b/apps/client/src/menus/context_menu.ts
@@ -7,10 +7,20 @@ import type { NotePresetId } from "../services/note_presets.js";
import utils from "../services/utils.js";
import { suspendModalFocusTraps } from "../widgets/react/modal_focustrap";
-export interface ContextMenuOptions<T> {
- x: number;
- y: number;
- orientation?: "left";
+/**
+ * Where the menu opens: beside a point, towards the right unless `orientation` says otherwise, or
+ * below an element, and above it where there is no room below. Along the element, it lines up with
+ * the element's start unless `centered` is set.
+ */
+export type ContextMenuOptions<T> = ContextMenuBaseOptions<T> & (
+ | { x: number; y: number; orientation?: "left"; anchor?: undefined; centered?: undefined }
+ | {
+ anchor: HTMLElement; centered?: boolean;
+ x?: undefined; y?: undefined; orientation?: undefined;
+ }
+);
+
+interface ContextMenuBaseOptions<T> {
selectMenuItemHandler: MenuHandler<T>;
items: MenuItem<T>[];
/** Offers an input at the top of the menu that filters its items. */
@@ -208,8 +218,12 @@ class ContextMenu {
// The id and classes the stylesheets, themes and `floating_layers` know this menu by.
id: "context-menu-container",
className: "dropdown-menu-sm dropend",
- anchor: { x: options.x, y: options.y },
- placement: options.orientation === "left" ? "left-start" : "right-start",
+ ...(options.anchor
+ ? { anchor: options.anchor, placement: options.centered ? "bottom" : undefined }
+ : {
+ anchor: { x: options.x, y: options.y },
+ placement: options.orientation === "left" ? "left-start" : "right-start"
+ }),
// Already where the screen shows it: see the host above.
container: this.host,
bottomSheet: utils.isMobile() && utils.isNarrowLayout()
diff --git a/apps/client/src/widgets/react/Button.tsx b/apps/client/src/widgets/react/Button.tsx
index 967dcc2e49..a3b85aa1a3 100644
--- a/apps/client/src/widgets/react/Button.tsx
+++ b/apps/client/src/widgets/react/Button.tsx
@@ -16,7 +16,8 @@ import { renderShortcutKbds } from "./shortcut_kbd";
const cachedIsMobile = isMobile();
-export interface ButtonProps extends Pick<ButtonHTMLAttributes<HTMLButtonElement>, "tabIndex" | "aria-pressed"> {
+export interface ButtonProps extends Pick<ButtonHTMLAttributes<HTMLButtonElement>,
+ "tabIndex" | "aria-pressed" | "aria-haspopup" | "aria-expanded"> {
name?: string;
/** Reference to the button element. Mostly useful for requesting focus. */
buttonRef?: RefObject<HTMLButtonElement | null>;
diff --git a/apps/client/src/widgets/react/Card.spec.tsx b/apps/client/src/widgets/react/Card.spec.tsx
index bb5866ee71..1086ef7423 100644
--- a/apps/client/src/widgets/react/Card.spec.tsx
+++ b/apps/client/src/widgets/react/Card.spec.tsx
@@ -2,10 +2,21 @@ import { ComponentChild } from "preact";
import { act } from "preact/test-utils";
import { describe, expect, it, vi } from "vitest";
+import contextMenu, { type ContextMenuOptions, type MenuItem } from "../../menus/context_menu";
import { renderInto } from "../../test/render";
-import { Card, CardFrame, CardSection, OptionCardSection } from "./Card";
+import { Card, CardFrame, CardSection, ItemCreationRow, OptionCardSection } from "./Card";
import { FilterProvider } from "./filter";
+const menuState = vi.hoisted(() => ({ dismissedByLastPress: false }));
+vi.mock("../../menus/context_menu", () => ({
+ default: {
+ show: vi.fn(),
+ get dismissedByLastPress() {
+ return menuState.dismissedByLastPress;
+ }
+ }
+}));
+
describe("Card", () => {
it("carries a heading, a sentence and controls of its own, and drops the heading line with nothing on it", () => {
const withHeading = renderInto(
@@ -330,6 +341,67 @@ describe("under a filter", () => {
}
});
+describe("ItemCreationRow", () => {
+ const show = vi.mocked(contextMenu.show);
+ const items: MenuItem<string>[] = [ { title: "Alpha", handler: vi.fn() } ];
+
+ it("opens a button's menu against it on any press, marked open meanwhile", async () => {
+ show.mockClear();
+ const onClick = vi.fn();
+ const container = renderInto(<ItemCreationRow buttons={[
+ { label: "Add", onClick },
+ { label: "Add from", menu: items }
+ ]} />);
+ const [ plain, withMenu ] = container.querySelectorAll<HTMLButtonElement>(".tn-card-adder");
+ expect(plain.hasAttribute("aria-haspopup")).toBe(false);
+ expect(withMenu.getAttribute("aria-haspopup")).toBe("menu");
+ expect(withMenu.getAttribute("aria-expanded")).toBe("false");
+
+ await press(withMenu, 1);
+ const options = show.mock.lastCall?.[0] as ContextMenuOptions<string>;
+ expect(options).toMatchObject({ anchor: withMenu, centered: true, items });
+ expect(options.x).toBeUndefined();
+ act(() => options.onShow?.(document.createElement("div")));
+ expect(withMenu.getAttribute("aria-expanded")).toBe("true");
+ act(() => options.onHide?.());
+ expect(withMenu.getAttribute("aria-expanded")).toBe("false");
+
+ await press(withMenu, 0);
+ expect(show.mock.lastCall?.[0]).toMatchObject({ anchor: withMenu });
+
+ await press(plain, 1);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(show).toHaveBeenCalledTimes(2);
+ });
+
+ it("leaves its menu closed after the press that put it away", async () => {
+ show.mockClear();
+ const container = renderInto(
+ <ItemCreationRow buttons={[ { label: "Add from", menu: items } ]} />);
+ const button = container.querySelector<HTMLButtonElement>(".tn-card-adder");
+ if (!button) throw new Error("No button.");
+
+ menuState.dismissedByLastPress = true;
+ try {
+ await press(button, 1);
+ expect(show).not.toHaveBeenCalled();
+ } finally {
+ menuState.dismissedByLastPress = false;
+ }
+
+ await press(button, 1);
+ expect(show).toHaveBeenCalledTimes(1);
+ });
+
+ /** Clicks `button`, letting the menu module load. A `detail` of 0 is a click from a key. */
+ async function press(button: HTMLButtonElement, detail: number) {
+ await act(async () => {
+ button.dispatchEvent(new MouseEvent("click", { bubbles: true, detail }));
+ await import("../../menus/context_menu");
+ });
+ }
+});
+
function classesOf(container: HTMLElement, selector: string) {
return container.querySelector(selector)?.className;
}
diff --git a/apps/client/src/widgets/react/Card.tsx b/apps/client/src/widgets/react/Card.tsx
index c8fdf2e22a..c261dd7200 100644
--- a/apps/client/src/widgets/react/Card.tsx
+++ b/apps/client/src/widgets/react/Card.tsx
@@ -4,6 +4,7 @@ import { JSX, HTMLAttributes, type RefObject } from "preact";
import { useCallback, useContext, useLayoutEffect, useRef, useState } from "preact/hooks";
import clsx from "clsx";
+import type { MenuItem } from "../../menus/context_menu";
import Button from "./Button";
import {
type FilterRole, FilterPassthrough, filterRoleClass, useFilterMatch, useIsFiltering
@@ -272,8 +273,7 @@ function holdsSmallControl(element: HTMLElement) {
// #region Item Creation Row
-/** One button of an {@link ItemCreationRow}. */
-export interface ItemCreationRowButton {
+interface ItemCreationRowButtonBase {
label: string;
/** An icon class, `bx` prefix included. */
icon?: string;
@@ -281,9 +281,17 @@ export interface ItemCreationRowButton {
disabled?: boolean;
/** The button's `name` attribute, which tests find it by. */
name?: string;
- onClick: (event: MouseEvent) => void;
}
+/**
+ * One button of an {@link ItemCreationRow}: one that creates the entry on a press, or one that
+ * opens a context menu of the entries it can create.
+ */
+export type ItemCreationRowButton = ItemCreationRowButtonBase & (
+ | { onClick: (event: MouseEvent) => void; menu?: undefined }
+ | { menu: MenuItem<string>[]; onClick?: undefined }
+);
+
interface ItemCreationRowProps {
buttons: ItemCreationRowButton[];
elementRef?: RefObject<HTMLElement | null>;
@@ -295,28 +303,59 @@ interface ItemCreationRowProps {
* the card rather than as a button, so the row reads as the foot of the list above it.
*/
export function ItemCreationRow({ buttons, elementRef, onKeyDown }: ItemCreationRowProps) {
+ // The position of the button whose menu is open.
+ const [ openMenuIndex, setOpenMenuIndex ] = useState<number>();
+
return (
// Transparent: each button paints itself, and the gaps show the card through.
<section ref={elementRef} className="tn-card-section tn-card-adders" onKeyDown={onKeyDown}>
- {buttons.map((button, index) => (
- <Button
- // The position in the row: two buttons can share a label.
- key={index}
- name={button.name}
- // Not a command button: the theme gives those a background, a shadow and a
- // minimum width, none of which suit a segment.
- kind="lowProfile"
- className="tn-card-adder"
- text={<>
- {button.icon && <Icon icon={button.icon} />}
- <span>{button.label}</span>
- </>}
- disabled={button.disabled}
- onClick={button.onClick}
- />
- ))}
+ {buttons.map((button, index) => {
+ const { menu } = button;
+ return (
+ <Button
+ // The position in the row: two buttons can share a label.
+ key={index}
+ name={button.name}
+ // Not a command button: the theme gives those a background, a shadow and a
+ // minimum width, none of which suit a segment.
+ kind="lowProfile"
+ className="tn-card-adder"
+ text={<>
+ {button.icon && <Icon icon={button.icon} />}
+ <span>{button.label}</span>
+ </>}
+ disabled={button.disabled}
+ aria-haspopup={menu ? "menu" : undefined}
+ aria-expanded={menu ? openMenuIndex === index : undefined}
+ onClick={menu
+ ? (event) => void openItemCreationMenu(event.currentTarget, menu, {
+ onShow: () => setOpenMenuIndex(index),
+ onHide: () => setOpenMenuIndex(undefined)
+ })
+ : button.onClick}
+ />
+ );
+ })}
</section>
);
}
+/**
+ * Opens `items` as a context menu centered below `button`, or above it where there is no room
+ * below. The press that put the menu away opens nothing.
+ */
+async function openItemCreationMenu(
+ button: HTMLButtonElement,
+ items: MenuItem<string>[],
+ { onShow, onHide }: { onShow: () => void; onHide: () => void }
+) {
+ // Loaded on demand: the login and setup pages show cards but no menus.
+ const { default: contextMenu } = await import("../../menus/context_menu");
+ if (contextMenu.dismissedByLastPress) return;
+
+ await contextMenu.show({
+ anchor: button, centered: true, items, selectMenuItemHandler: () => {}, onShow, onHide
+ });
+}
+
// #endregion
\ No newline at end of file