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(dropdown): show a dropdown's content in its popup, with Bootstrap's behaviour around it
Elian Doran916f51cb6aca
diff --git a/apps/client/src/widgets/collections/board/group_by.spec.tsx b/apps/client/src/widgets/collections/board/group_by.spec.tsxindex 1e922dee99..5d797f6c90 100644--- a/apps/client/src/widgets/collections/board/group_by.spec.tsx+++ b/apps/client/src/widgets/collections/board/group_by.spec.tsx@@ -170,14 +170,14 @@ describe("BoardGroupBy", () => {// Bootstrap does not open a menu under happy-dom, and the items are drawn only once it is.await act(async () => {- $(mountPoint.querySelector(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ $(mountPoint.querySelector(".dropdown") as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");});return { mountPoint, onSelect };}const items = (mountPoint: HTMLElement) =>- [ ...mountPoint.querySelectorAll(".dropdown-menu .dropdown-item") ];+ [ ...document.querySelectorAll(".dropdown-menu .dropdown-item") ];it("offers making a grouping after the ones the board has, behind a divider", async () => {const { mountPoint } = await setup();@@ -186,7 +186,7 @@ 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 = [ ...(mountPoint.querySelector(".dropdown-menu")?.children ?? []) ];+ const menu = [ ...(document.querySelector(".dropdown-menu")?.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);@@ -216,7 +216,7 @@ describe("BoardGroupBy", () => {const { mountPoint } = await setup();await act(async () => {- mountPoint.querySelector<HTMLElement>(".board-group-by-create")?.click();+ document.querySelector<HTMLElement>(".board-group-by-create")?.click();});expect(mocks.detail.opts).toMatchObject({@@ -240,7 +240,7 @@ describe("BoardGroupBy", () => {const { mountPoint, onSelect } = await setup();await act(async () => {- mountPoint.querySelector<HTMLElement>(".board-group-by-create")?.click();+ document.querySelector<HTMLElement>(".board-group-by-create")?.click();});const made: Attribute = {@@ -269,7 +269,7 @@ describe("BoardGroupBy", () => {const { mountPoint, onSelect } = await setup();await act(async () => {- mountPoint.querySelector<HTMLElement>(".board-group-by-create")?.click();+ document.querySelector<HTMLElement>(".board-group-by-create")?.click();});await act(async () => {@@ -294,7 +294,7 @@ describe("BoardGroupBy", () => {const { mountPoint, onSelect } = await setup();await act(async () => {- mountPoint.querySelector<HTMLElement>(".board-group-by-create")?.click();+ document.querySelector<HTMLElement>(".board-group-by-create")?.click();});await act(async () => {diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex f6cd471ec5..83dc140848 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -2498,7 +2498,7 @@ describe("Board column rename", () => {await act(async () => {pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));- $(pill.closest(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ $(pill.closest(".dropdown") as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");await flush();});@@ -2525,7 +2525,7 @@ describe("Board column rename", () => {// Picking closes the menu, as any dropdown item click does; open it again to read the tick.await act(async () => {pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));- $(pill.closest(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ $(pill.closest(".dropdown") as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");await flush();});const reopened = [ ...document.querySelectorAll<HTMLElement>(".card-template-pill") ].at(-1);@@ -2569,7 +2569,7 @@ describe("Board column rename", () => {await act(async () => {pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));- $(pill.closest(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ $(pill.closest(".dropdown") as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");editor.dispatchEvent(new FocusEvent("blur"));editor.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));await flush();@@ -2758,7 +2758,7 @@ describe("Board column rename", () => {if (!pill) throw new Error("expected the template pill");await act(async () => {pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));- $(pill.closest(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ $(pill.closest(".dropdown") as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");await flush();});@@ -2868,7 +2868,7 @@ describe("Board column rename", () => {await act(async () => {pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));- $(pill.closest(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ $(pill.closest(".dropdown") as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");await flush();});@@ -4530,11 +4530,11 @@ describe("Board properties from the note menu", () => {const options = cog?.closest(".dropdown");if (!options) throw new Error("expected a settings menu on the collection bar");await act(async () => {- $(options as HTMLElement).trigger("show.bs.dropdown");+ $(options as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");await flush();});- const entry = [ ...options.querySelectorAll<HTMLElement>(".dropdown-item") ].at(-1);+ const entry = [ ...document.querySelectorAll<HTMLElement>(".tn-popup .dropdown-item") ].at(-1);if (!entry) throw new Error("expected an entry in the settings menu");expect(entry.textContent).toContain("board_view.properties");expect(entry.previousElementSibling?.className).toContain("dropdown-divider");diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsxindex 32e10641bb..e5bcc3bd1f 100644--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx@@ -117,10 +117,10 @@ describe("TemplateNoteTypes", () => {const dropdown = container.querySelector(".dropdown");expect(dropdown).not.toBeNull();await act(async () => {- if (dropdown) window.$(dropdown).trigger("show.bs.dropdown");+ if (dropdown) window.$(dropdown).children("button:not([aria-expanded=true])").trigger("click");});- expect(container.textContent).toContain("Meeting Notes");- expect(container.textContent).not.toContain("[protected]");+ expect(document.body.textContent).toContain("Meeting Notes");+ expect(document.body.textContent).not.toContain("[protected]");serverGetSpy.mockRestore();});diff --git a/apps/client/src/widgets/note_icon.spec.tsx b/apps/client/src/widgets/note_icon.spec.tsxindex 5e32e277e2..6246f1f091 100644--- a/apps/client/src/widgets/note_icon.spec.tsx+++ b/apps/client/src/widgets/note_icon.spec.tsx@@ -8,35 +8,7 @@ import attributes from "../services/attributes";import { renderInto } from "../test/render";import { ReactWrappedWidget } from "./basic_widget";-const { dropdownInstances, getOrCreateInstance } = vi.hoisted(() => {- const dropdownInstances: Array<{- show: ReturnType<typeof vi.fn>;- hide: ReturnType<typeof vi.fn>;- update: ReturnType<typeof vi.fn>;- dispose: ReturnType<typeof vi.fn>;- _menu: HTMLElement | null;- }> = [];- const instancesByToggle = new Map<HTMLElement, typeof dropdownInstances[number]>();- const getOrCreateInstance = vi.fn((toggle: HTMLElement) => {- let instance = instancesByToggle.get(toggle);- if (!instance) {- instance = {- show: vi.fn(),- hide: vi.fn(),- update: vi.fn(),- dispose: vi.fn(),- _menu: null- };- instancesByToggle.set(toggle, instance);- dropdownInstances.push(instance);- }- return instance;- });- return { dropdownInstances, getOrCreateInstance };-});-vi.mock("bootstrap", () => ({- Dropdown: { getOrCreateInstance },Tooltip: class {}}));@@ -156,14 +128,8 @@ describe("NoteIcon", () => {const dropdown = container.querySelector<HTMLElement>(".dropdown");expect(toggle).not.toBeNull();expect(dropdown).not.toBeNull();- const pickerDropdown = dropdownInstances.at(-1);- expect(pickerDropdown).toBeTruthy();-- void act(() => {- toggle?.dispatchEvent(new Event("pointerdown", { bubbles: true }));- });void act(() => {- $(dropdown as HTMLElement).trigger("show.bs.dropdown");+ $(dropdown as HTMLElement).children("button:not([aria-expanded=true])").trigger("click");});expect(document.body.querySelector(".tn-dropdown-portal .icon-picker")).not.toBeNull();@@ -173,14 +139,12 @@ describe("NoteIcon", () => {expect(toggle?.classList.contains("bx-updated")).toBe(true);expect(toggle?.classList.contains("show")).toBe(true);expect(toggle?.getAttribute("aria-expanded")).toBe("true");- expect(pickerDropdown?.dispose).not.toHaveBeenCalled();expect(document.body.querySelector(".tn-dropdown-portal .icon-picker")).not.toBeNull();void act(() => noteContext.setNote?.(buildNote("note-b")));expect(container.querySelector("button")?.classList.contains("bx-note-b")).toBe(true);expect(container.querySelector("button")).not.toBe(toggle);- expect(pickerDropdown?.dispose).toHaveBeenCalledTimes(1);expect(document.body.querySelector(".tn-dropdown-portal .icon-picker")).toBeNull();});});diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsxindex 55d4b32811..27040e9f6c 100644--- a/apps/client/src/widgets/react/Dropdown.spec.tsx+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx@@ -1,9 +1,13 @@-import { render } from "preact";+import { type ComponentChildren, render } from "preact";import { useRef } from "preact/hooks";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import Dropdown, { type DropdownHandle, type DropdownProps } from "./Dropdown";+// A dialog's focus trap would pull focus out of a menu portaled over it.+const focusTraps = vi.hoisted(() => ({ suspend: vi.fn(() => () => {}) }));+vi.mock("./modal_focustrap", () => ({ suspendModalFocusTraps: focusTraps.suspend }));+describe("Dropdown", () => {const host = document.createElement("div");document.body.append(host);@@ -20,14 +24,14 @@ describe("Dropdown", () => {vi.restoreAllMocks();});- function renderDropdown(props: Partial<DropdownProps> = {}) {+ function renderDropdown(props: Partial<DropdownProps> = {}, content: ComponentChildren = <li className="dropdown-item">By title</li>) {let handle: { current: DropdownHandle | null } = { current: null };function Harness() {const dropdownRef = useRef<DropdownHandle | null>(null);handle = dropdownRef;return (<Dropdown text="Sort" dropdownRef={dropdownRef} dropdownContainerClassName="sort-menu" {...props}>- <li className="dropdown-item">By title</li>+ {content}</Dropdown>);}@@ -48,14 +52,18 @@ describe("Dropdown", () => {it("opens a popup below its toggle on a click, and closes it on another", async () => {const onShown = vi.fn();const onHidden = vi.fn();- const { toggle } = renderDropdown({ onShown, onHidden });+ const { toggle } = renderDropdown({ onShown, onHidden, className: "sort-dropdown" });expect(popup()).toBeNull();expect(toggle.getAttribute("aria-expanded")).toBe("false");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" ]);+ expect([ ...opened?.classList ?? [] ]).toEqual([ "tn-popup", "dropdown-menu", "show", "tn-dropdown-menu", "sort-menu", "tn-dropdown-list" ]);+ expect(opened?.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);// 2px below the toggle, as Bootstrap's dropdowns stood.expect([ opened?.style.left, opened?.style.top ]).toEqual([ "100px", "82px" ]);expect(toggle.getAttribute("aria-expanded")).toBe("true");@@ -109,4 +117,100 @@ describe("Dropdown", () => {const disabledToggle = host.querySelector<HTMLButtonElement>("button");expect(disabledToggle?.disabled).toBe(true);});++ describe("content", () => {+ const items = <>+ <li className="dropdown-item" tabIndex={0}>By title</li>+ <li className="dropdown-item disabled" tabIndex={0}>By size</li>+ {/* As `FormListToggleableItem`, which stops its click so the menu stays up. */}+ <li className="dropdown-item" tabIndex={0} onClick={(e) => e.stopPropagation()}>Descending</li>+ <li><input className="filter" /></li>+ <li className="dropdown-item" tabIndex={0}>By date</li>+ </>;+ const item = (title: string) => {+ const found = [ ...popup()?.querySelectorAll<HTMLElement>("li") ?? [] ].find((li) => li.textContent === title);+ if (!found) throw new Error(`expected an item titled ${title}`);+ return found;+ };++ it("closes on a click on an item, but not on one the item stops, in a field, or on the menu itself", async () => {+ const { toggle } = renderDropdown({}, items);+ click(toggle);+ await vi.waitFor(() => expect(popup()).not.toBeNull());++ item("Descending").click();+ popup()?.querySelector<HTMLElement>("input")?.click();+ popup()?.click();+ expect(popup()).not.toBeNull();++ item("By title").click();+ await vi.waitFor(() => expect(popup()).toBeNull());+ });++ it("stays up for a click inside when it closes only on one outside", async () => {+ const { toggle } = renderDropdown({ dropdownOptions: { autoClose: "outside" } }, items);+ click(toggle);+ await vi.waitFor(() => expect(popup()).not.toBeNull());++ item("By title").click();+ expect(popup()).not.toBeNull();+ document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ await vi.waitFor(() => expect(popup()).toBeNull());+ });++ it("opens above its toggle when asked to", async () => {+ const { toggle } = renderDropdown({ dropdownOptions: { popperConfig: { placement: "top" } } });+ vi.spyOn(toggle, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x: 100, y: 500, width: 80, height: 30 }));+ click(toggle);+ // Centered over the toggle, and ending 2px above it: 500 - 100 - 2.+ await vi.waitFor(() => expect([ popup()?.style.left, popup()?.style.top ]).toEqual([ "40px", "398px" ]));+ });++ 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);+ const key = (target: Element, name: string) =>+ target.dispatchEvent(new KeyboardEvent("keydown", { key: name, bubbles: true, cancelable: true }));++ toggle.focus();+ key(toggle, "ArrowDown");+ await vi.waitFor(() => expect(document.activeElement?.textContent).toBe("By title"));+ // Bootstrap reacts on a toggle only with `data-bs-toggle`, which this one does not carry.+ bootstrapHeard.mockClear();++ // Past the disabled item, round from the last to the first, and back.+ key(item("By title"), "ArrowDown");+ expect(document.activeElement?.textContent).toBe("Descending");+ key(item("Descending"), "ArrowDown");+ expect(document.activeElement?.textContent).toBe("By date");+ key(item("By date"), "ArrowDown");+ expect(document.activeElement?.textContent).toBe("By title");+ key(item("By title"), "ArrowUp");+ expect(document.activeElement?.textContent).toBe("By date");+ expect(bootstrapHeard).not.toHaveBeenCalled();++ // A field keeps its own arrows.+ const field = popup()?.querySelector("input");+ if (!field) throw new Error("expected the field");+ key(field, "ArrowDown");+ expect(bootstrapHeard).toHaveBeenCalledTimes(1);+ document.removeEventListener("keydown", bootstrapHeard, true);+ });++ it("suspends the focus traps of the dialogs under it while it is up, and restores them after", async () => {+ const restore = vi.fn();+ focusTraps.suspend.mockReturnValue(restore);+ const { toggle } = renderDropdown();++ click(toggle);+ await vi.waitFor(() => expect(popup()).not.toBeNull());+ expect(focusTraps.suspend).toHaveBeenCalledTimes(1);+ expect(restore).not.toHaveBeenCalled();++ click(toggle);+ await vi.waitFor(() => expect(popup()).toBeNull());+ expect(restore).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsxindex 62c7dfd25b..aaeb68ffd5 100644--- a/apps/client/src/widgets/react/Dropdown.tsx+++ b/apps/client/src/widgets/react/Dropdown.tsx@@ -1,10 +1,12 @@+import type { Placement } from "@floating-ui/dom";import type { Dropdown as BootstrapDropdown, Tooltip } from "bootstrap";import clsx from "clsx";import { ComponentChildren, HTMLAttributes } from "preact";import { CSSProperties, HTMLProps } from "preact/compat";-import { MutableRef, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";+import { MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";import { useTooltip, useUniqueName } from "./hooks";+import { suspendModalFocusTraps } from "./modal_focustrap";import Popup from "./Popup";type DataAttributes = {@@ -95,10 +97,18 @@ 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, title, text, dropdownContainerStyle, dropdownContainerClassName, dropdownContainerRef: externalContainerRef, hideToggleArrow, iconAction, disabled, noSelectButtonStyle, forceShown, onShown, onHidden, buttonProps, dropdownRef, titlePosition, titleOptions }: 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 }: DropdownProps) {const containerRef = useRef<HTMLDivElement | null>(null);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. */+ const pendingFocus = useRef<"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;+ const popperConfig = dropdownOptions?.popperConfig;+ const placement = toFloatingPlacement(popperConfig && typeof popperConfig === "object" ? popperConfig.placement : undefined);// Memoized so useTooltip's effect (keyed on config identity) doesn't dispose and recreate the// Bootstrap tooltip on every re-render — only when the title (or positioning) actually changes.@@ -113,6 +123,24 @@ export default function Dropdown({ id, className, buttonClassName, title, text,// On the wrapper, and silenced while the popup is up, so the title does not hang over it.const { hideTooltip } = useTooltip(containerRef, tooltipConfig, !shown);+ // Every open and close goes through here, which says so at once, as Bootstrap's events did+ // within the press: a caller holding something open for the menu's sake, such as the board's+ // card editor, must know before the focus the press moves reaches it.+ const shownRef = useRef(shown);+ const callbacks = useRef({ onShown, onHidden, hideTooltip });+ callbacks.current = { onShown, onHidden, hideTooltip };+ const setOpen = useCallback((open: boolean) => {+ if (shownRef.current === open) return;+ shownRef.current = open;+ setShown(open);+ if (open) {+ callbacks.current.hideTooltip();+ callbacks.current.onShown?.();+ } else {+ callbacks.current.onHidden?.();+ }+ }, []);+useLayoutEffect(() => {if (externalContainerRef) externalContainerRef.current = containerRef.current;}, [ externalContainerRef ]);@@ -120,29 +148,47 @@ export default function Dropdown({ id, className, buttonClassName, title, text,useLayoutEffect(() => {if (!dropdownRef) return;dropdownRef.current = {- show: () => setShown(true),- hide: () => setShown(false),- toggle: () => setShown((current) => !current)+ show: () => setOpen(true),+ hide: () => setOpen(false),+ toggle: () => setOpen(!shownRef.current)};}, [ dropdownRef ]);// A disabled toggle cannot be pressed to close its popup, so disabling it closes the popup.useLayoutEffect(() => {- if (disabled) setShown(false);+ if (disabled) setOpen(false);}, [ disabled ]);- const everShown = useRef(false);+ // One shown from the start says so once it is mounted. `shown` is the first render's here.useEffect(() => {- if (shown) {- everShown.current = true;- hideTooltip();- onShown?.();- } else if (everShown.current) {- onHidden?.();- }+ if (shown) callbacks.current.onShown?.();+ }, []);++ // A dialog's focus trap would pull focus out of a popup that stands outside the dialog.+ useEffect(() => {+ if (!shown) return;+ 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.+ useEffect(() => {+ if (!shown) return;+ const onKeyDown = (e: KeyboardEvent) => {+ const popup = popupRef.current;+ const target = e.target as Element;+ if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return;+ if (!popup?.contains(target) || /input|textarea/i.test(target.tagName)) return;+ e.preventDefault();+ e.stopPropagation();+ focusItem(popup, e.key === "ArrowDown" ? "next" : "previous", target);+ };+ window.addEventListener("keydown", onKeyDown, true);+ return () => window.removeEventListener("keydown", onKeyDown, true);}, [ shown ]);const ariaId = useUniqueName("button");+ const toggleId = id ?? ariaId;return (// `title` stands in only for the moment before the tooltip is wired: Bootstrap moves the@@ -161,11 +207,24 @@ export default function Dropdown({ id, className, buttonClassName, title, text,type="button"aria-haspopup="true"aria-expanded={shown}- id={id ?? ariaId}+ id={toggleId}disabled={disabled}onClick={(e) => {buttonProps?.onClick?.(e);- setShown((current) => !current);+ setOpen(!shownRef.current);+ }}+ // Up or Down on the toggle opens the popup at its first or last item.+ onKeyDown={(e) => {+ buttonProps?.onKeyDown?.(e);+ 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);+ } else {+ pendingFocus.current = edge;+ setOpen(true);+ }}}>{text}@@ -175,17 +234,64 @@ export default function Dropdown({ id, className, buttonClassName, title, text,{shown && triggerRef.current && (<Popupanchor={triggerRef.current}+ placement={placement}offset={TOGGLE_GAP}- className={clsx("dropdown-menu show tn-dropdown-menu", dropdownContainerClassName)}+ // Bootstrap's dropdowns grew past the viewport, and a `FormDropdownSubmenu`+ // nested in the menu would be clipped by a menu that scrolls.+ capHeight={false}+ // In a wrapper with the dropdown's classes, so CSS scoped under them still+ // applies to the menu in the page's body. style.css stacks a portaled menu by+ // `tn-dropdown-portal`.+ portalClassName={clsx("tn-dropdown-portal", className)}+ elementRef={popupRef}+ className={clsx("dropdown-menu show tn-dropdown-menu", isStatic && "static", dropdownContainerClassName,+ !noDropdownListStyle && "tn-dropdown-list")}+ style={dropdownContainerStyle}+ aria-labelledby={toggleId}+ onPlaced={() => {+ const edge = pendingFocus.current;+ 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);+ }}onDismiss={(reason) => {- setShown(false);+ if (reason === "outside" && (autoClose === "inside" || autoClose === false)) return;+ setOpen(false);if (reason === "escape") triggerRef.current?.focus();}}>- {/* The popup holds nothing yet; the menu comes next. */}- <div aria-labelledby={ariaId} style={dropdownContainerStyle} />+ {children}</Popup>)}</div>);}++/**+ * Focuses an enabled item of `popup`'s own, not one in a submenu nested in it: the first or the+ * last, or the one after or before `from`, going round at either end, as Bootstrap's did.+ */+function focusItem(popup: HTMLElement, where: "first" | "last" | "next" | "previous", from?: Element) {+ const items = [ ...popup.querySelectorAll<HTMLElement>(".dropdown-item:not(.disabled):not(:disabled)") ]+ .filter((item) => item.parentElement?.closest(".dropdown-menu") === popup);+ if (!items.length) return;++ const current = from?.closest<HTMLElement>(".dropdown-item");+ const index = current ? items.indexOf(current) : -1;+ let target: HTMLElement | undefined;+ if (where === "first" || (where === "next" && index < 0)) target = items[0];+ else if (where === "last" || (where === "previous" && index < 0)) target = items.at(-1);+ else target = items[(index + (where === "next" ? 1 : -1) + items.length) % items.length];+ target?.focus();+}++/** A placement as Popper names it, as Floating UI does; Popper's `auto` ones fall back to the default. */+function toFloatingPlacement(placement: string | undefined): Placement | undefined {+ return placement && !placement.startsWith("auto") ? placement as Placement : undefined;+}diff --git a/apps/client/src/widgets/react/Dropdown_legacy.tsx b/apps/client/src/widgets/react/Dropdown_legacy.tsxindex 4f117d4a78..c4025ccd12 100644--- a/apps/client/src/widgets/react/Dropdown_legacy.tsx+++ b/apps/client/src/widgets/react/Dropdown_legacy.tsx@@ -4,11 +4,9 @@import type { Dropdown as BootstrapDropdown, Tooltip } from "bootstrap";import { ComponentChildren, HTMLAttributes } from "preact";import { createPortal, CSSProperties, HTMLProps } from "preact/compat";-import { MutableRef, useCallback, useEffect, useRef, useState } from "preact/hooks";+import { MutableRef, useCallback, useEffect, useState } from "preact/hooks";import { isMobile } from "../../services/utils";-import { useUniqueName } from "./hooks";-import { suspendModalFocusTraps } from "./modal_focustrap";type DataAttributes = {[key: `data-${string}`]: string | number | boolean | undefined;@@ -88,9 +86,8 @@ export interface DropdownProps extends Pick<HTMLProps<HTMLDivElement>, "id" | "cbackdrop?: boolean;}-export default function Dropdown({ className, isStatic, children, dropdownContainerStyle, dropdownContainerClassName, noDropdownListStyle, onShown: externalOnShown, onHidden: externalOnHidden, mobileBackdrop: mobileBackdropProp, portalToBody: portalToBodyProp, mobileBottomSheet, backdrop }: DropdownProps) {- // Not yet in `Dropdown`: `dropdownOptions` — `popperConfig.placement: "top"` (1 caller),- // `autoClose: "outside"` (2), `display: "static"` (1).+export default function Dropdown({ className, children, onShown: externalOnShown, onHidden: externalOnHidden, mobileBackdrop: mobileBackdropProp, portalToBody: portalToBodyProp, mobileBottomSheet, backdrop }: DropdownProps) {+ // Not yet in `Dropdown`: `dropdownOptions.display: "static"` (1 caller).// The sheet is three things at once — placed by the app's own rule, dimming what is behind it,// and lifted out of whatever opened it — so it is asked for as one thing and unpacked here.@@ -98,7 +95,6 @@ export default function Dropdown({ className, isStatic, children, dropdownContaiconst mobileBackdrop = mobileBackdropProp || bottomSheet;const portalToBody = portalToBodyProp || bottomSheet;- const dropdownContainerRef = useRef<HTMLUListElement | null>(null);const [ shown ] = useState(false);const onShown = useCallback(() => {@@ -120,37 +116,13 @@ export default function Dropdown({ className, isStatic, children, dropdownContaielse onHidden();}, [ shown ]);- // A portaled menu lives in `document.body`, outside any modal that opened it. That modal's focus-trap- // would keep yanking focus back into the modal, so an input in the menu (e.g. the note-icon picker's- // search box) could never hold focus. Suspend the shown modals' traps while the menu is open.- useEffect(() => {- if (!portalToBody || !shown) return;- return suspendModalFocusTraps();- }, [ portalToBody, shown ]);-- const ariaId = useUniqueName("button");-const menu = (- <ul- class={`dropdown-menu tn-dropdown-menu ${isStatic ? "static" : ""} ${dropdownContainerClassName ?? ""} ${bottomSheet ? "mobile-bottom-menu" : ""} ${!noDropdownListStyle ? "tn-dropdown-list" : ""}`}- style={dropdownContainerStyle}- aria-labelledby={ariaId}- ref={dropdownContainerRef}- onClick={(e) => {- // Prevent clicks directly inside the dropdown from closing.- if (e.target === dropdownContainerRef.current) {- e.stopPropagation();- }- }}- >+ <ul class={`dropdown-menu ${bottomSheet ? "mobile-bottom-menu" : ""}`}>{shown && children}</ul>);return portalToBody- // Keep the `className` scope on the portaled wrapper so CSS scoped under it (e.g.- // `.note-icon-widget .icon-list`) still applies even though the menu now lives in body.- // `tn-dropdown-portal` beside it carries the z-index a menu needs out here (style.css).? createPortal((<div class={`tn-dropdown-portal ${className ?? ""}`}>{backdrop && shown && <div class="tn-dropdown-backdrop" />}diff --git a/apps/client/src/widgets/react/FormDropdownList.spec.tsx b/apps/client/src/widgets/react/FormDropdownList.spec.tsxindex d28d42c43b..9c77833bf7 100644--- a/apps/client/src/widgets/react/FormDropdownList.spec.tsx+++ b/apps/client/src/widgets/react/FormDropdownList.spec.tsx@@ -74,7 +74,7 @@ describe("FormDropdownList", () => {expect(button?.querySelector("small")?.textContent).toBe("abc");expect(button?.querySelector(".bx-text")).not.toBeNull();- const items = [ ...container.querySelectorAll(".dropdown-item") ];+ const items = [ ...document.querySelectorAll(".dropdown-item") ];expect(items.map((item) => item.textContent?.replace(/\s+/g, " ").trim())).toEqual([ "Text abcAny text", "Number", "Relation" ]);// A check mark would take the icon's slot, so the current item is highlighted instead.@@ -83,7 +83,7 @@ describe("FormDropdownList", () => {expect(items[0].querySelector(".bx-text")).not.toBeNull();// Only the item that starts a group is preceded by a rule.- expect(container.querySelectorAll(".dropdown-divider")).toHaveLength(1);+ expect(document.querySelectorAll(".dropdown-divider")).toHaveLength(1);expect(items[2].previousElementSibling?.className).toContain("dropdown-divider");act(() => (items[1] as HTMLElement).click());@@ -102,7 +102,7 @@ describe("FormDropdownList", () => {/>);expect(container.querySelector("button")?.textContent).toBe("");- expect([ ...container.querySelectorAll(".dropdown-item") ].some((item) => item.className.includes("active")))+ expect([ ...document.querySelectorAll(".dropdown-item") ].some((item) => item.className.includes("active"))).toBe(false);renderOpened(@@ -114,11 +114,11 @@ describe("FormDropdownList", () => {onChange={vi.fn()}/>);- const items = [ ...container.querySelectorAll(".dropdown-item") ];+ const items = [ ...document.querySelectorAll(".dropdown-item") ];expect(items[1].querySelector(".bx-check")).not.toBeNull();expect(items[1].className).not.toContain("active");// Without a property to read it from, no item starts a group of its own.- expect(container.querySelectorAll(".dropdown-divider")).toHaveLength(0);+ expect(document.querySelectorAll(".dropdown-divider")).toHaveLength(0);});/** The menu only renders its items once Bootstrap reports it open, which nothing does here. */@@ -126,7 +126,7 @@ describe("FormDropdownList", () => {act(() => render(vnode, container));const dropdown = container.querySelector(".dropdown");act(() => {- if (dropdown) $(dropdown).trigger("show.bs.dropdown");+ if (dropdown) $(dropdown).children("button:not([aria-expanded=true])").trigger("click");});}});diff --git a/apps/client/src/widgets/react/Popup.spec.tsx b/apps/client/src/widgets/react/Popup.spec.tsxindex b5ac588fe5..16cf63e08d 100644--- a/apps/client/src/widgets/react/Popup.spec.tsx+++ b/apps/client/src/widgets/react/Popup.spec.tsx@@ -71,6 +71,18 @@ describe("Popup", () => {expect(tall.style.maxHeight).toBe(`${800 - 330 - 5}px`);});+ it("grows past the viewport without its height cap, stands in a wrapper it is given, and says when it is placed", async () => {+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(1000);+ anchorAt(100, 300);+ const onPlaced = vi.fn();+ const popup = await open({ capHeight: false, portalClassName: "tn-dropdown-portal note-actions", onPlaced });++ expect(popup.style.maxHeight).toBe("");+ expect(popup.parentElement?.className).toBe("tn-dropdown-portal note-actions");+ expect(popup.parentElement?.parentElement).toBe(document.body);+ expect(onPlaced).toHaveBeenCalledTimes(1);+ });+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.tsxindex 335b01c5ec..a37b7063bd 100644--- a/apps/client/src/widgets/react/Popup.tsx+++ b/apps/client/src/widgets/react/Popup.tsx@@ -4,14 +4,14 @@ import { autoUpdate, computePosition, flip, offset, type Placement, type Referenimport clsx from "clsx";import type { ComponentChildren, HTMLAttributes } from "preact";import { createPortal } from "preact/compat";-import { useLayoutEffect, useRef } from "preact/hooks";+import { type MutableRef, useLayoutEffect, useRef } from "preact/hooks";/*** A surface that stands beside something rather than in the page's flow: a dropdown's menu, and* anything else that pops up from a control or at a point. It knows nothing of what it holds; it* places itself, keeps inside the viewport, and says when it is dismissed.*/-export interface PopupProps {+export interface PopupProps extends Pick<HTMLAttributes<HTMLDivElement>, "id" | "className" | "role" | "style" | "onClick" | "aria-labelledby"> {/** What it stands beside: an element, or a point in the viewport such as where a right-click landed. */anchor: HTMLElement | { x: number, y: number };/**@@ -21,22 +21,34 @@ export interface PopupProps {placement?: Placement;/** The gap, in pixels, it keeps from its anchor. */offset?: number;+ /**+ * Caps its height to the room on the side it takes, for content that scrolls in it. Without,+ * it grows past the viewport, as content that must not be clipped needs.+ */+ capHeight?: boolean;+ /**+ * Classes for an element it stands in, in the page's body, so the CSS scoped under the+ * classes of what opened it still applies there.+ */+ portalClassName?: string;+ elementRef?: MutableRef<HTMLDivElement | null>;+ /** Called once it is first placed and shown: a browser focuses nothing inside it before. */+ onPlaced?(): void;/*** Called on a press outside it and its anchor, and on Escape. A press on the anchor is left to* the anchor, as a dropdown's toggle closes its own popup.*/onDismiss(reason: "outside" | "escape"): void;- id?: string;- className?: string;- role?: HTMLAttributes<HTMLDivElement>["role"];children?: ComponentChildren;}/** How many pixels it keeps from the edges of the viewport. */const VIEWPORT_PADDING = 5;-export default function Popup({ anchor, placement = "bottom-start", offset: gap = 0, onDismiss, id, className, role, children }: PopupProps) {- const popupRef = useRef<HTMLDivElement>(null);+export default function Popup({ anchor, placement = "bottom-start", offset: gap = 0, capHeight = true, portalClassName, elementRef, onPlaced, onDismiss, className, children, ...elementProps }: PopupProps) {+ const popupRef = useRef<HTMLDivElement | null>(null);+ const placed = useRef(onPlaced);+ placed.current = onPlaced;const anchorX = "x" in anchor ? anchor.x : undefined;const anchorY = "y" in anchor ? anchor.y : undefined;@@ -44,9 +56,14 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gapconst popup = popupRef.current;if (!popup) return;const reference = anchor instanceof HTMLElement ? anchor : pointAt(anchor.x, anchor.y);+ let shown = false;// Places it now, and again whenever its anchor moves or the viewport or it changes size.- return autoUpdate(reference, popup, () => void placePopup(popup, reference, placement, gap));- }, [ anchor instanceof HTMLElement ? anchor : undefined, anchorX, anchorY, placement, gap ]);+ return autoUpdate(reference, popup, () => void placePopup(popup, reference, placement, gap, capHeight).then(() => {+ if (shown) return;+ shown = true;+ placed.current?.();+ }));+ }, [ anchor instanceof HTMLElement ? anchor : undefined, anchorX, anchorY, placement, gap, capHeight ]);const dismiss = useRef(onDismiss);dismiss.current = onDismiss;@@ -76,19 +93,28 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap// Out of any ancestor that would clip it or, with a transform or a filter, place its fixed// position against itself. A browser showing an element fullscreen paints only that element.- return createPortal((- <div ref={popupRef} id={id} role={role} className={clsx("tn-popup", className)}>+ const popup = (+ <div+ {...elementProps}+ ref={(element) => {+ popupRef.current = element;+ if (elementRef) elementRef.current = element;+ }}+ className={clsx("tn-popup", className)}+ >{children}</div>- ), document.fullscreenElement ?? document.body);+ );+ return createPortal(portalClassName ? <div className={portalClassName}>{popup}</div> : popup,+ document.fullscreenElement ?? document.body);}/*** Positions `popup` beside `anchor`, preferring `placement` and flipping to the other side where- * that has no room, and caps its height to the room on the side it takes. It stays hidden until- * placed, so it never paints at a stale position.+ * that has no room, and with `capHeight` caps its height to the room on the side it takes. It+ * stays hidden until placed, so it never paints at a stale position.*/-async function placePopup(popup: HTMLElement, anchor: ReferenceElement, placement: Placement, gap: number) {+async function placePopup(popup: HTMLElement, anchor: ReferenceElement, placement: Placement, gap: number, capHeight: boolean) {const { x, y } = await computePosition(anchor, popup, {strategy: "fixed",placement,@@ -98,7 +124,7 @@ async function placePopup(popup: HTMLElement, anchor: ReferenceElement, placemen// Over a point it can also move across the side it stands on, as a popup wider than// the room on either side of the point must; an element it must not cover.shift({ crossAxis: !(anchor instanceof HTMLElement), padding: VIEWPORT_PADDING }),- size({+ capHeight && size({padding: VIEWPORT_PADDING,apply({ availableHeight }) {popup.style.maxHeight = `${availableHeight}px`;diff --git a/apps/client/src/widgets/react/SegmentedChoice.spec.tsx b/apps/client/src/widgets/react/SegmentedChoice.spec.tsxindex 88d46067ce..38def609df 100644--- a/apps/client/src/widgets/react/SegmentedChoice.spec.tsx+++ b/apps/client/src/widgets/react/SegmentedChoice.spec.tsx@@ -188,7 +188,7 @@ describe("SegmentedChoice", () => {act(() => render(vnode, container));const dropdown = container.querySelector(".dropdown");act(() => {- if (dropdown) $(dropdown).trigger("show.bs.dropdown");+ if (dropdown) $(dropdown).children("button:not([aria-expanded=true])").trigger("click");});}diff --git a/apps/client/src/widgets/type_widgets/file/MediaPlayer.spec.tsx b/apps/client/src/widgets/type_widgets/file/MediaPlayer.spec.tsxindex acc29c2da6..7afb62f34e 100644--- a/apps/client/src/widgets/type_widgets/file/MediaPlayer.spec.tsx+++ b/apps/client/src/widgets/type_widgets/file/MediaPlayer.spec.tsx@@ -65,7 +65,7 @@ const input = (el: Element | null, value: string) =>/** A Dropdown only mounts its items once Bootstrap announces the open, which is what this stands in for. */const openDropdown = () =>- act(() => { $(container.querySelector(".dropdown") as HTMLElement).trigger("show.bs.dropdown"); });+ act(() => { $(container.querySelector(".dropdown") as HTMLElement).children("button:not([aria-expanded=true])").trigger("click"); });/** Lets a chain of promises inside the component settle, then flushes the renders and effects it caused. */const settle = async () => {@@ -253,7 +253,7 @@ describe("VolumeControl", () => {});describe("PlaybackSpeed", () => {- const items = () => Array.from(container.querySelectorAll(".dropdown-item"));+ const items = () => Array.from(document.querySelectorAll(".dropdown-item"));it("offers the speeds, marking the element's current one", () => {const mediaRef = fakeMedia();@@ -329,7 +329,7 @@ describe("PlayModeButton", () => {act(() => render(<PlayModeButton mode="loop" onSelectMode={onSelectMode} />, container));openDropdown();- const items = Array.from(container.querySelectorAll(".dropdown-item"));+ const items = Array.from(document.querySelectorAll(".dropdown-item"));expect(items).toHaveLength(3);const active = items.find(el => el.classList.contains("active"));expect(active?.querySelector(".bx-repeat")).not.toBeNull();