Skip to content

Build your personal knowledge base with Trilium Notes

feat(dropdown): draw a dropdown's rows as a menu, which shrinks with the viewport

Elian Doran02b1072edf77
diff --git a/apps/client/src/widgets/EmbeddedNotePane.tsx b/apps/client/src/widgets/EmbeddedNotePane.tsx
index 7a02d2a970..ba1d5cfd41 100644
--- a/apps/client/src/widgets/EmbeddedNotePane.tsx
+++ b/apps/client/src/widgets/EmbeddedNotePane.tsx
@@ -336,6 +336,7 @@ export function MaximizeToQuickEditAction({ note, onClose }: { note: FNote; onCl
export function NoteColorAction({ note, title }: { note: FNote; title: string }) {
return (
<Dropdown
+ panel
className="tn-embedded-note-color"
buttonClassName="bx bx-palette"
title={title}
diff --git a/apps/client/src/widgets/collections/board/group_by.spec.tsx b/apps/client/src/widgets/collections/board/group_by.spec.tsx
index 5d797f6c90..879f4c1479 100644
--- a/apps/client/src/widgets/collections/board/group_by.spec.tsx
+++ b/apps/client/src/widgets/collections/board/group_by.spec.tsx
@@ -186,7 +186,8 @@ describe("BoardGroupBy", () => {
"Status", "Priority", "promoted_attributes.create_attribute"
]);
// Set apart from the groupings above it: the entry makes one rather than picking one.
- const menu = [ ...(document.querySelector(".dropdown-menu")?.children ?? []) ];
+ // The rows scroll inside the menu, in its `.tn-menu-scroll`.
+ const menu = [ ...(document.querySelector(".dropdown-menu > .tn-menu-scroll")?.children ?? []) ];
const divider = menu.findIndex(child => child.classList.contains("dropdown-divider"));
const create = menu.findIndex(child => child.classList.contains("board-group-by-create"));
expect(divider).toBeGreaterThan(0);
diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsx
index 83dc140848..98984c498b 100644
--- a/apps/client/src/widgets/collections/board/index.spec.tsx
+++ b/apps/client/src/widgets/collections/board/index.spec.tsx
@@ -2581,7 +2581,7 @@ describe("Board column rename", () => {
// Once the menu is done with, the field has the focus again.
await act(async () => {
- $(pill.closest(".dropdown") as HTMLElement).trigger("hide.bs.dropdown");
+ $(pill.closest(".dropdown") as HTMLElement).children("button[aria-expanded=true]").trigger("click");
await flush();
});
expect(document.activeElement).toBe(editor);
diff --git a/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx b/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx
index 6a94152a2f..be404a13fc 100644
--- a/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx
+++ b/apps/client/src/widgets/collections/calendar/RecurrenceEditor.tsx
@@ -60,6 +60,7 @@ export default function RecurrenceEditor({ note }: { note: FNote }) {
return (
<EventField name={t("calendar.recurrence.repeats")}>
<Dropdown
+ panel
className="calendar-recurrence-dropdown"
text={modelTitle(model)}
noDropdownListStyle
diff --git a/apps/client/src/widgets/launch_bar/launch_bar_widgets.tsx b/apps/client/src/widgets/launch_bar/launch_bar_widgets.tsx
index fb9c2523a5..07913d8599 100644
--- a/apps/client/src/widgets/launch_bar/launch_bar_widgets.tsx
+++ b/apps/client/src/widgets/launch_bar/launch_bar_widgets.tsx
@@ -57,6 +57,7 @@ export function LaunchBarDropdownButton({ children, icon, dropdownOptions, launc
return (
<Dropdown
+ panel
className="right-dropdown-widget"
buttonClassName="right-dropdown-button launcher-button"
hideToggleArrow
diff --git a/apps/client/src/widgets/layout/StatusBar.tsx b/apps/client/src/widgets/layout/StatusBar.tsx
index 908da20657..c1aa977221 100644
--- a/apps/client/src/widgets/layout/StatusBar.tsx
+++ b/apps/client/src/widgets/layout/StatusBar.tsx
@@ -264,6 +264,7 @@ export function NoteInfoBadge(context: NoteInfoContext) {
return (enabled &&
<StatusBarDropdown
+ panel
icon="bx bx-info-circle"
title={t("status_bar.note_info_title")}
dropdownRef={dropdownRef}
@@ -340,6 +341,7 @@ function BacklinksBadge({ note, viewScope }: StatusBarContext) {
return (note && count > 0 &&
<StatusBarDropdown
+ panel
className="backlinks-badge"
icon="bx bx-link"
text={t("status_bar.backlinks", { count })}
@@ -482,6 +484,7 @@ function NotePaths({ note, hoistedNoteId, notePath }: StatusBarContext) {
return (
<StatusBarDropdown
+ panel
className="note-paths-button"
icon="bx bx-directions"
title={t("status_bar.note_paths_title")}
diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsx
index 78a24e2e28..9bbef4ac04 100644
--- a/apps/client/src/widgets/react/Dropdown.spec.tsx
+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx
@@ -3,6 +3,7 @@ import { useRef } from "preact/hooks";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import Dropdown, { type DropdownHandle, type DropdownProps } from "./Dropdown";
+import { FormDropdownSubmenu, FormListItem } from "./FormList";
// A dialog's focus trap would pull focus out of a menu portaled over it.
const focusTraps = vi.hoisted(() => ({ suspend: vi.fn(() => () => {}) }));
@@ -66,8 +67,10 @@ describe("Dropdown", () => {
click(toggle);
await vi.waitFor(() => expect(popup()?.style.visibility).toBe("visible"));
const opened = popup();
- expect([ ...opened?.classList ?? [] ]).toEqual([ "tn-popup", "dropdown-menu", "show", "tn-dropdown-menu", "sort-menu", "tn-dropdown-list" ]);
- expect(opened?.textContent).toBe("By title");
+ // A menu, which lays its rows out in a scroller of its own.
+ expect([ ...opened?.classList ?? [] ]).toEqual([ "tn-popup", "dropdown-menu", "show", "tn-menu", "tn-dropdown-menu", "sort-menu" ]);
+ expect(opened?.getAttribute("role")).toBe("menu");
+ expect(opened?.querySelector(":scope > .tn-menu-scroll")?.textContent).toBe("By title");
// In the page's body, in a wrapper with the dropdown's class, so CSS scoped under it applies.
expect(opened?.parentElement?.className).toBe("tn-dropdown-portal sort-dropdown");
expect(opened?.getAttribute("aria-labelledby")).toBe(toggle.id);
@@ -92,9 +95,9 @@ describe("Dropdown", () => {
document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
await vi.waitFor(() => expect(popup()).toBeNull());
+ // The menu takes focus as it shows, and gives it back to the toggle as Escape closes it.
click(toggle);
- await vi.waitFor(() => expect(popup()).not.toBeNull());
- document.body.focus();
+ await vi.waitFor(() => expect(document.activeElement).toBe(popup()));
popup()?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
await vi.waitFor(() => expect(popup()).toBeNull());
expect(document.activeElement).toBe(toggle);
@@ -176,7 +179,8 @@ describe("Dropdown", () => {
it("moves focus over the items with Up and Down, keeping them from Bootstrap, and opens from the toggle", async () => {
const bootstrapHeard = vi.fn();
document.addEventListener("keydown", bootstrapHeard, true);
- const { toggle } = renderDropdown({}, items);
+ // A panel, whose items are no rows of a menu, moves focus over them as Bootstrap's did.
+ const { toggle } = renderDropdown({ panel: true }, items);
const key = (target: Element, name: string) =>
target.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true }));
@@ -221,6 +225,52 @@ describe("Dropdown", () => {
});
});
+ describe("as a menu", () => {
+ it("caps its height to the room below its toggle, its rows scrolling inside, as the context menu does", async () => {
+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(1000);
+ const { toggle } = renderDropdown();
+
+ click(toggle);
+ await vi.waitFor(() => expect(popup()?.style.visibility).toBe("visible"));
+ // Below the toggle's bottom (80) and its 2px gap, less the 5px kept from the viewport's edge.
+ expect(popup()?.style.maxHeight).toBe(`${800 - 82 - 5}px`);
+ expect(popup()?.querySelector(":scope > .tn-menu-scroll")).not.toBeNull();
+ });
+
+ it("closes on a row's click, but not on one the row stopped, as a toggle does to stay up", async () => {
+ const picked: string[] = [];
+ const { toggle } = renderDropdown({}, <>
+ <FormListItem onClick={(e) => { picked.push("wrap"); e.stopPropagation(); }}>Wrap lines</FormListItem>
+ <FormListItem onClick={() => picked.push("title")}>By title</FormListItem>
+ </>);
+ const row = (title: string) => [ ...document.querySelectorAll<HTMLElement>(".tn-popup li.dropdown-item") ]
+ .find((item) => item.textContent === title);
+
+ click(toggle);
+ await vi.waitFor(() => expect(row("Wrap lines")).toBeTruthy());
+ row("Wrap lines")?.click();
+ expect(popup()).not.toBeNull();
+
+ row("By title")?.click();
+ await vi.waitFor(() => expect(popup()).toBeNull());
+ expect(picked).toEqual([ "wrap", "title" ]);
+ });
+
+ it("opens a nested submenu as a layer of its own, beside the scroller rather than in it", async () => {
+ const { toggle } = renderDropdown({}, (
+ <FormDropdownSubmenu icon="bx bx-chip" title="Advanced">
+ <FormListItem>Show log</FormListItem>
+ </FormDropdownSubmenu>
+ ));
+
+ click(toggle);
+ await vi.waitFor(() => expect(popup()?.querySelector("li.dropdown-submenu")).not.toBeNull());
+ popup()?.querySelector("li.dropdown-submenu")?.dispatchEvent(new PointerEvent("pointerenter"));
+ await vi.waitFor(() => expect(popup()?.querySelector(":scope > div.dropdown-submenu > .dropdown-menu")?.textContent)
+ .toBe("Show log"));
+ });
+ });
+
describe("as a sheet or over a backdrop", () => {
/** The dimmed cover the shell keeps for menus on a phone. */
function addCover() {
diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsx
index 3bf800b491..38eed3a5cf 100644
--- a/apps/client/src/widgets/react/Dropdown.tsx
+++ b/apps/client/src/widgets/react/Dropdown.tsx
@@ -8,6 +8,7 @@ import { MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, u
import { isMobile } from "../../services/utils";
import { useTooltip, useUniqueName } from "./hooks";
import { suspendModalFocusTraps } from "./modal_focustrap";
+import Menu from "./Menu";
import Popup from "./Popup";
type DataAttributes = {
@@ -86,6 +87,12 @@ export interface DropdownProps extends Pick<HTMLProps<HTMLDivElement>, "id" | "c
* {@link portalToBody} for that, and does nothing without it.
*/
backdrop?: boolean;
+ /**
+ * Holds something other than a menu's rows, such as a picker or a form, which stands in a
+ * plain popup: a menu would take the keys its fields need, and tell assistive technology it is
+ * a menu.
+ */
+ panel?: boolean;
}
/** Opens and closes a dropdown from outside it, for a caller that decides when. */
@@ -98,7 +105,7 @@ export interface DropdownHandle {
/** The gap, in pixels, between the toggle and its popup, as Bootstrap's dropdowns kept. */
const TOGGLE_GAP = 2;
-export default function Dropdown({ id, className, buttonClassName, isStatic, children, title, text, dropdownContainerStyle, dropdownContainerClassName, dropdownContainerRef: externalContainerRef, hideToggleArrow, iconAction, disabled, noSelectButtonStyle, noDropdownListStyle, forceShown, onShown, onHidden, dropdownOptions, buttonProps, dropdownRef, titlePosition, titleOptions, mobileBackdrop: mobileBackdropProp, mobileBottomSheet, backdrop }: DropdownProps) {
+export default function Dropdown({ id, className, buttonClassName, isStatic, children, title, text, dropdownContainerStyle, dropdownContainerClassName, dropdownContainerRef: externalContainerRef, hideToggleArrow, iconAction, disabled, noSelectButtonStyle, noDropdownListStyle, forceShown, onShown, onHidden, dropdownOptions, buttonProps, dropdownRef, titlePosition, titleOptions, mobileBackdrop: mobileBackdropProp, mobileBottomSheet, backdrop, panel }: DropdownProps) {
// The sheet is placed by the app's own rule and dims what is behind it, so it is asked for as
// one thing and unpacked here.
const bottomSheet = !!mobileBottomSheet && isMobile();
@@ -107,8 +114,9 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
const triggerRef = useRef<HTMLButtonElement | null>(null);
const popupRef = useRef<HTMLDivElement | null>(null);
const [ shown, setShown ] = useState(!!forceShown && !disabled);
- /** The item to focus once the popup shows, for a popup a key on the toggle opened. */
+ /** The item to start at once the popup shows, for a popup a key on the toggle opened. */
const pendingFocus = useRef<"first" | "last">();
+ const [ startAt, setStartAt ] = useState<"first" | "last">();
// As Bootstrap's `autoClose`: `true` closes on a click inside and a press outside, "inside" and
// "outside" on that one alone, `false` on neither. Escape closes it whatever this says.
const autoClose = dropdownOptions?.autoClose ?? true;
@@ -137,6 +145,10 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
const setOpen = useCallback((open: boolean) => {
if (shownRef.current === open) return;
shownRef.current = open;
+ // Focus that the popup holds goes back to the toggle, as a native menu button's does; a
+ // command that moved it elsewhere keeps it there.
+ if (!open && popupRef.current?.contains(document.activeElement)) triggerRef.current?.focus();
+ if (!open) setStartAt(undefined);
setShown(open);
if (open) {
callbacks.current.hideTooltip();
@@ -184,10 +196,11 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
return suspendModalFocusTraps();
}, [ shown ]);
- // Up and Down move between the items, as Bootstrap's did. Captured at the window, so its
- // handler for keys in a `.dropdown-menu`, which finds no toggle beside a popup, never sees them.
+ // In a panel, Up and Down move between its items, as Bootstrap's did; a menu has its own keys.
+ // Captured at the window, so Bootstrap's handler for keys in a `.dropdown-menu`, which finds
+ // no toggle beside a popup, never sees them.
useEffect(() => {
- if (!shown) return;
+ if (!shown || !panel) return;
const onKeyDown = (e: KeyboardEvent) => {
const popup = popupRef.current;
const target = e.target as Element;
@@ -199,11 +212,20 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
};
window.addEventListener("keydown", onKeyDown, true);
return () => window.removeEventListener("keydown", onKeyDown, true);
- }, [ shown ]);
+ }, [ shown, panel ]);
const ariaId = useUniqueName("button");
const toggleId = id ?? ariaId;
+ /** Closes it on a click inside, as Bootstrap's `autoClose` did, for content that is no row of a menu. */
+ function closeOnClickInside(e: MouseEvent) {
+ if (autoClose === "outside" || autoClose === false) return;
+ const target = e.target as Element;
+ // Neither the menu's own padding nor a field in it closes it.
+ if (target === e.currentTarget || /input|select|option|textarea|form/i.test(target.tagName)) return;
+ setOpen(false);
+ }
+
return (
// `title` stands in only for the moment before the tooltip is wired: Bootstrap moves the
// attribute into the tooltip and drops it, so the browser's own doesn't double up with ours.
@@ -219,7 +241,7 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
)}
ref={triggerRef}
type="button"
- aria-haspopup="true"
+ aria-haspopup={panel ? "true" : "menu"}
aria-expanded={shown}
id={toggleId}
disabled={disabled}
@@ -233,10 +255,11 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;
e.preventDefault();
const edge = e.key === "ArrowDown" ? "first" : "last";
- if (shown && popupRef.current) {
- focusItem(popupRef.current, edge);
+ if (shown) {
+ if (panel && popupRef.current) focusItem(popupRef.current, edge);
} else {
pendingFocus.current = edge;
+ setStartAt(edge);
setOpen(true);
}
}}
@@ -245,7 +268,32 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
<span className="caret" />
</button>
- {shown && triggerRef.current && (
+ {shown && triggerRef.current && !panel && (
+ <Menu
+ anchor={triggerRef.current}
+ placement={placement}
+ offset={TOGGLE_GAP}
+ bottomSheet={bottomSheet}
+ startAt={startAt}
+ elementRef={popupRef}
+ isWanted={() => shownRef.current}
+ // In a wrapper with the dropdown's classes, so CSS scoped under them still
+ // applies to the menu in the page's body.
+ portalClassName={clsx("tn-dropdown-portal", className)}
+ backdropClassName={backdrop ? "tn-dropdown-backdrop" : undefined}
+ className={clsx("tn-dropdown-menu", isStatic && "static", dropdownContainerClassName)}
+ style={dropdownContainerStyle}
+ aria-labelledby={toggleId}
+ onClick={closeOnClickInside}
+ onDismiss={() => {
+ if (autoClose !== "inside" && autoClose !== false) setOpen(false);
+ }}
+ onClose={() => setOpen(false)}
+ >
+ {children}
+ </Menu>
+ )}
+ {shown && triggerRef.current && panel && (
<Popup
anchor={triggerRef.current}
placement={placement}
@@ -270,17 +318,10 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi
pendingFocus.current = undefined;
if (edge && popupRef.current) focusItem(popupRef.current, edge);
}}
- onClick={(e) => {
- if (autoClose === "outside" || autoClose === false) return;
- const target = e.target as Element;
- // Neither the menu's own padding nor a field in it closes it, as in Bootstrap's.
- if (target === e.currentTarget || /input|select|option|textarea|form/i.test(target.tagName)) return;
- setOpen(false);
- }}
+ onClick={closeOnClickInside}
onDismiss={(reason) => {
if (reason === "outside" && (autoClose === "inside" || autoClose === false)) return;
setOpen(false);
- if (reason === "escape") triggerRef.current?.focus();
}}
>
{children}
diff --git a/apps/client/src/widgets/react/FormList.tsx b/apps/client/src/widgets/react/FormList.tsx
index 8717d746b6..87a3b8f4a1 100644
--- a/apps/client/src/widgets/react/FormList.tsx
+++ b/apps/client/src/widgets/react/FormList.tsx
@@ -143,7 +143,7 @@ export interface FormListItemOpts {
*/
checkable?: boolean;
/**
- * Inside a menu, whether running the row closes the menu before its {@link onClick} runs. It
+ * Inside a menu, whether running the row closes the menu after its {@link onClick} runs. It
* does unless this is `false`, for a caller that decides for itself, as `contextMenu` does.
*/
closeOnSelect?: boolean;
@@ -177,13 +177,22 @@ export function FormListItem({ className, icon, iconClassName, value, title, act
const id = useUniqueName("menu-row");
const isActive = menu?.active?.id === id;
+ /**
+ * Runs the row, then closes the menu it stands in, as Bootstrap's dropdowns did, unless
+ * {@link closeOnSelect} is `false` or the row's handler stopped the click: a row that stays up
+ * to be worked again, such as a toggle, stops it.
+ */
+ function run(e: MouseEvent) {
+ onClick?.(e);
+ if (closeOnSelect !== false && !e.cancelBubble) menu?.close();
+ }
+
/**
* Runs the row for the keys, as a click would, with the modifiers of the key that ran it, so
* Ctrl+Enter does what a Ctrl+click does.
*/
function select(e: MouseEvent | KeyboardEvent) {
- if (closeOnSelect !== false) menu?.close();
- onClick?.(new MouseEvent("click", { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey, altKey: e.altKey, metaKey: e.metaKey }));
+ run(new MouseEvent("click", { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey, altKey: e.altKey, metaKey: e.metaKey }));
}
function onPointed(e: { currentTarget: HTMLLIElement }) {
@@ -234,9 +243,7 @@ export function FormListItem({ className, icon, iconClassName, value, title, act
}}
// The row runs on the release, so a press can still be taken back by moving off.
onClick={(e) => {
- if (disabled) return;
- if (closeOnSelect !== false) menu?.close();
- onClick?.(e);
+ if (!disabled) run(e);
}}
data-trigger-command={triggerCommand}
dir={rtl ? "rtl" : undefined}
diff --git a/apps/client/src/widgets/react/HelpDropdown.tsx b/apps/client/src/widgets/react/HelpDropdown.tsx
index baeb59d592..98272f244d 100644
--- a/apps/client/src/widgets/react/HelpDropdown.tsx
+++ b/apps/client/src/widgets/react/HelpDropdown.tsx
@@ -33,6 +33,7 @@ interface HelpDropdownProps {
export default function HelpDropdown({ children, helpPage, openInPopup, className, onShown }: HelpDropdownProps) {
return (
<Dropdown
+ panel
onShown={onShown}
className={`help-dropdown ${className ?? ""}`}
buttonClassName="bx bx-help-circle"
diff --git a/apps/client/src/widgets/react/HelpRemoveButtons.tsx b/apps/client/src/widgets/react/HelpRemoveButtons.tsx
index 79c0a138f7..16f759f632 100644
--- a/apps/client/src/widgets/react/HelpRemoveButtons.tsx
+++ b/apps/client/src/widgets/react/HelpRemoveButtons.tsx
@@ -13,6 +13,7 @@ export default function HelpRemoveButtons({ help, removeText, onRemove }: HelpRe
<td className="button-column">
{help && <>
<Dropdown
+ panel
className="help-dropdown"
buttonClassName="bx bx-help-circle icon-action"
hideToggleArrow
diff --git a/apps/client/src/widgets/react/IconPicker.tsx b/apps/client/src/widgets/react/IconPicker.tsx
index b65479dcba..f6f29b768e 100644
--- a/apps/client/src/widgets/react/IconPicker.tsx
+++ b/apps/client/src/widgets/react/IconPicker.tsx
@@ -170,6 +170,7 @@ function IconPickerDropdownButton({
return (
<Dropdown
+ panel
// The legacy class dresses the menu the picker sits in, which the themes and the
// picker's own stylesheet reach through it.
className={clsx("note-icon-widget", className)}
diff --git a/apps/client/src/widgets/react/Menu.spec.tsx b/apps/client/src/widgets/react/Menu.spec.tsx
index 699d53b36e..3751dea108 100644
--- a/apps/client/src/widgets/react/Menu.spec.tsx
+++ b/apps/client/src/widgets/react/Menu.spec.tsx
@@ -113,7 +113,7 @@ describe("Menu with declared rows", () => {
expect(calls).toEqual([]);
});
- it("closes the menu before running a row, but not for a row that opens a submenu or is disabled", async () => {
+ it("closes the menu after running a row, but not for a row that opens a submenu or is disabled", async () => {
const { menu, calls } = renderMenu();
press(rowTitled("Delete"));
@@ -121,8 +121,9 @@ describe("Menu with declared rows", () => {
await vi.waitFor(() => expect(layers(menu)).toHaveLength(1));
expect(calls).toEqual([]);
+ // The row runs first, as in Bootstrap's dropdowns, so a row that stops its click stays up.
press(rowTitled("Show log"));
- expect(calls).toEqual([ "close", "log" ]);
+ expect(calls).toEqual([ "log", "close" ]);
});
it("walks the rows as they are drawn, into a declared submenu and back, skipping what cannot run", async () => {
@@ -148,6 +149,6 @@ describe("Menu with declared rows", () => {
key(menu, "ArrowRight");
await vi.waitFor(() => expect(active()).toBe("Show log"));
key(menu, "Enter");
- expect(calls).toEqual([ "close", "log" ]);
+ expect(calls).toEqual([ "log", "close" ]);
});
});
diff --git a/apps/client/src/widgets/react/Menu.tsx b/apps/client/src/widgets/react/Menu.tsx
index 4bceec3f41..a051fe0ec9 100644
--- a/apps/client/src/widgets/react/Menu.tsx
+++ b/apps/client/src/widgets/react/Menu.tsx
@@ -20,7 +20,7 @@ import Popup, { type PopupProps } from "./Popup";
* `FormDropdownSubmenu`, `FormDropdownDivider`, `FormListHeader` and `FormListCustomItem`.
*/
export interface MenuProps<T> extends Pick<PopupProps, "anchor" | "offset" | "container" | "portalClassName"
- | "backdropClassName" | "style" | "aria-labelledby"> {
+ | "backdropClassName" | "style" | "onClick" | "elementRef" | "aria-labelledby"> {
id?: string;
className?: string;
/** The side of its anchor it prefers: beside a point towards the right, or below an element. */
@@ -34,6 +34,11 @@ export interface MenuProps<T> extends Pick<PopupProps, "anchor" | "offset" | "co
startAt?: "first" | "last";
/** Called on a press outside the menu and its anchor. It answers Escape itself, with {@link onClose}. */
onDismiss?(): void;
+ /**
+ * Whether its owner still wants it, asked as it is first placed, which can come after the owner
+ * closed it: a menu no longer wanted leaves focus where it is.
+ */
+ isWanted?(): boolean;
items?: MenuItem<T>[];
/** Called when one of {@link items} is pressed with the primary button, or run from the keyboard. */
onSelect?(item: MenuCommandItem<T>, e: MouseEvent | KeyboardEvent): void;
@@ -49,14 +54,16 @@ const KEYS_LEAVING_CUSTOM_ROW = new Set([ "ArrowUp", "ArrowDown", "Escape", "Tab
/** How long typed letters keep adding to the text a row is looked up by. */
const TYPEAHEAD_TIMEOUT = 500;
-export default function Menu<T>({ id, className, anchor, placement, bottomSheet, startAt, items, onSelect, children, onClose, onDismiss, ...popupProps }: MenuProps<T>) {
+export default function Menu<T>({ id, className, anchor, placement, bottomSheet, startAt, items, onSelect, children, onClose, onDismiss, isWanted, elementRef, ...popupProps }: MenuProps<T>) {
const menuRef = useRef<HTMLDivElement | null>(null);
// The submenus' layers render into the menu element, which rows reach through the context.
const [ layerHost, setLayerHost ] = useState<HTMLElement | null>(null);
const setMenuElement = useCallback((element: HTMLDivElement | null) => {
menuRef.current = element;
setLayerHost(element);
- }, []);
+ if (typeof elementRef === "function") elementRef(element);
+ else if (elementRef) elementRef.current = element;
+ }, [ elementRef ]);
const [ open, setOpen ] = useState<OpenSubmenu[]>([]);
const openSubmenu = useCallback((level: number, rowId?: string, anchor?: HTMLElement, chosen = false) => {
@@ -74,6 +81,12 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
const typeahead = useRef({ text: "", timeout: 0 });
/** Whether the keys moved the menu since the pointer last did. See `Menu.css`. */
const [ keyboardDriven, setKeyboardDriven ] = useState(false);
+ /** Whether the menu has asked to close, which it does once. */
+ const closed = useRef(false);
+ const close = useCallback(() => {
+ closed.current = true;
+ onClose();
+ }, [ onClose ]);
const setActive = useCallback((level: number, rowId: string) => {
setActiveRow({ level, id: rowId });
@@ -95,7 +108,7 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
});
}, [ rows ]);
const context: MenuContextValue = {
- open, openSubmenu, active, setActive, rows, registerRow, keyboardDriven, close: onClose, layerHost
+ open, openSubmenu, active, setActive, rows, registerRow, keyboardDriven, close, layerHost
};
/** The ids of the rows the keys can stand on at `level`, in the order they stand in. */
@@ -216,7 +229,7 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
case "Escape":
// One level at a time, then the menu itself.
if (open.length) closeLevel(open.length);
- else onClose();
+ else close();
break;
// Focus stays in the menu until it closes.
case "Tab": break;
@@ -246,6 +259,8 @@ export default function Menu<T>({ id, className, anchor, placement, bottomSheet,
// browser does not focus an element under `visibility: hidden`, so the menu takes focus only
// once it is shown.
function takeFocus() {
+ // A menu already closing, as one whose row ran before it was placed, leaves focus alone.
+ if (closed.current || isWanted?.() === false) return;
menuRef.current?.focus({ preventScroll: true });
if (!startAt) return;
const rowIds = navigableRows(0);
diff --git a/apps/client/src/widgets/react/Popup.spec.tsx b/apps/client/src/widgets/react/Popup.spec.tsx
index 16cf63e08d..fb5f6704f1 100644
--- a/apps/client/src/widgets/react/Popup.spec.tsx
+++ b/apps/client/src/widgets/react/Popup.spec.tsx
@@ -83,6 +83,17 @@ describe("Popup", () => {
expect(onPlaced).toHaveBeenCalledTimes(1);
});
+ it("says nothing of a placement that settles once it has closed", async () => {
+ anchorAt(100, 50);
+ const onPlaced = vi.fn();
+ render(<Popup anchor={anchor} onPlaced={onPlaced}>content</Popup>, host);
+ // Closed before the placement it started has settled, as a row picked at once closes a menu.
+ render(null, host);
+
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(onPlaced).not.toHaveBeenCalled();
+ });
+
it("opens at a point, as a menu opened where a right-click landed does", async () => {
const popup = await open({ anchor: { x: 300, y: 200 }, placement: "right-start" });
diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsx
index 915dcbae77..a1e594005b 100644
--- a/apps/client/src/widgets/react/Popup.tsx
+++ b/apps/client/src/widgets/react/Popup.tsx
@@ -70,6 +70,13 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
}, [ elementRef ]);
const placed = useRef(onPlaced);
placed.current = onPlaced;
+ /** Whether it has said it is placed, which it says once, however often it is placed again. */
+ const hasPlaced = useRef(false);
+ const reportPlaced = () => {
+ if (hasPlaced.current) return;
+ hasPlaced.current = true;
+ placed.current?.();
+ };
const anchorX = "x" in anchor ? anchor.x : undefined;
const anchorY = "y" in anchor ? anchor.y : undefined;
@@ -78,18 +85,21 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap
if (!popup) return;
if (placedByStylesheet) {
popup.style.visibility = "visible";
- placed.current?.();
+ reportPlaced();
return;
}
const reference = anchor instanceof HTMLElement ? anchor : pointAt(anchor.x, anchor.y);
- let shown = false;
+ // A placement settles after the fact, by which time it can have closed.
+ let closed = false;
// Places it now, and again whenever its anchor moves or the viewport or it changes size.
const options = { placement, offset: gap, capHeight, shiftAcross: !(anchor instanceof HTMLElement) };
- return autoUpdate(reference, popup, () => void placeFloating(popup, reference, options).then(() => {
- if (shown) return;
- shown = true;
- placed.current?.();
+ const stopUpdating = autoUpdate(reference, popup, () => void placeFloating(popup, reference, options).then(() => {
+ if (!closed) reportPlaced();
}));
+ return () => {
+ closed = true;
+ stopUpdating();
+ };
}, [ anchor instanceof HTMLElement ? anchor : undefined, anchorX, anchorY, placement, gap, capHeight, placedByStylesheet ]);
const dismiss = useRef(onDismiss);
diff --git a/apps/client/src/widgets/type_widgets/SqlConsole.tsx b/apps/client/src/widgets/type_widgets/SqlConsole.tsx
index 9c4108003b..8aadc595f0 100644
--- a/apps/client/src/widgets/type_widgets/SqlConsole.tsx
+++ b/apps/client/src/widgets/type_widgets/SqlConsole.tsx
@@ -157,7 +157,7 @@ export function SqlTableSchemas({ note }: TypeWidgetProps) {
<span class="sql-table-schemas">
{schemas.map(({ name, columns }) => (
- <Dropdown key={name} text={name} noSelectButtonStyle hideToggleArrow>
+ <Dropdown key={name} text={name} noSelectButtonStyle hideToggleArrow panel>
<table className="table-schema">
{columns.map(column => (
<tr key={column.name}>
diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
index 1a1088b08f..b63631250b 100644
--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.tsx
@@ -589,6 +589,7 @@ export function useMediaPlayMode(noteContext: NoteContext | undefined, mediaRef:
export function PlayModeButton({ mode, onSelectMode }: { mode: MediaPlayMode, onSelectMode: (mode: MediaPlayMode) => void }) {
return (
<Dropdown
+ panel
iconAction
hideToggleArrow
className="play-mode-dropdown"
@@ -637,6 +638,7 @@ export function PlaybackSpeed({ mediaRef }: { mediaRef: RefObject<HTMLVideoEleme
return (
<Dropdown
+ panel
iconAction
hideToggleArrow
buttonClassName="speed-dropdown"