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): open dropdowns in a Popup of their own instead of Bootstrap's
Elian Doran8011e17a6bd9
diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsxindex 0cedb96998..55d4b32811 100644--- a/apps/client/src/widgets/react/Dropdown.spec.tsx+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx@@ -1,296 +1,112 @@-import $ from "jquery";import { render } from "preact";-import { act } from "preact/test-utils";+import { useRef } from "preact/hooks";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-// A single fake Bootstrap dropdown instance so the component wiring (dropdownRef, `_menu`-// re-pointing, dispose-on-unmount) can be asserted without real Bootstrap/Popper.-const { instance, getOrCreateInstance } = vi.hoisted(() => {- const instance = {- show: vi.fn(),- hide: vi.fn(),- update: vi.fn(),- dispose: vi.fn(),- _menu: null as HTMLElement | null- };- return { instance, getOrCreateInstance: vi.fn(() => instance) };-});--vi.mock("bootstrap", () => ({- Dropdown: { getOrCreateInstance },- Tooltip: class {}-}));--// Stub only the Bootstrap-Tooltip hook; keep the rest of the hooks module real. The stubs must be-// referentially stable across renders — onShown/onHidden depend on hideTooltip's identity.-const tooltipStub = vi.hoisted(() => ({ showTooltip: vi.fn(), hideTooltip: vi.fn() }));-vi.mock("./hooks", async (importOriginal) => ({- ...(await importOriginal<typeof import("./hooks")>()),- useTooltip: () => tooltipStub-}));--// `mobileBottomSheet` only takes effect on a mobile layout, which has to be answerable per test.-const isMobileMock = vi.hoisted(() => vi.fn(() => false));-vi.mock("../../services/utils", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../services/utils")>()),- isMobile: () => isMobileMock()-}));--import Dropdown from "./Dropdown";--// happy-dom has no ResizeObserver; the component only needs observe/disconnect to exist.-class ResizeObserverStub {- observe() {}- unobserve() {}- disconnect() {}-}-globalThis.ResizeObserver = globalThis.ResizeObserver ?? (ResizeObserverStub as unknown as typeof ResizeObserver);--let container: HTMLDivElement | undefined;-function renderInto(vnode: preact.ComponentChild) {- const el = document.createElement("div");- container = el;- document.body.appendChild(el);- void act(() => render(vnode, el));- return el;-}--function getToggle() {- const button = container?.querySelector("button");- expect(button).toBeTruthy();- return button as HTMLButtonElement;-}--function fire(target: EventTarget, eventName: string) {- void act(() => {- target.dispatchEvent(new Event(eventName, { bubbles: true }));- });-}+import Dropdown, { type DropdownHandle, type DropdownProps } from "./Dropdown";describe("Dropdown", () => {+ const host = document.createElement("div");+ document.body.append(host);+beforeEach(() => {- vi.clearAllMocks();- isMobileMock.mockReturnValue(false);- instance._menu = null;+ 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(100);});afterEach(() => {- if (container) {- const el = container;- void act(() => render(null, el));- el.remove();- container = undefined;- }- });-- it("renders a non-portaled menu inline, exposes the instance via dropdownRef and disposes it on unmount", () => {- const dropdownRef = { current: null };- const el = renderInto(<Dropdown dropdownRef={dropdownRef}>item</Dropdown>);-- // Menu is nested next to the toggle, not in the body.- expect(el.querySelector(".dropdown .dropdown-menu")).toBeTruthy();- expect(dropdownRef.current).toBe(instance);-- void act(() => render(null, el));- expect(instance.dispose).toHaveBeenCalledTimes(1);- });-- it("preserves Bootstrap's open marker when the button class changes", () => {- const el = renderInto(<Dropdown buttonClassName="bx bx-note">item</Dropdown>);- const dropdownEl = el.querySelector(".dropdown");- expect(dropdownEl).toBeTruthy();-- void act(() => {- $(dropdownEl as HTMLElement).trigger("show.bs.dropdown");- });- getToggle().classList.add("show");- expect(getToggle().classList.contains("show")).toBe(true);-- void act(() => render(<Dropdown buttonClassName="bx bx-star">item</Dropdown>, el));-- expect(getToggle().classList.contains("bx-star")).toBe(true);- expect(getToggle().classList.contains("show")).toBe(true);- expect(getToggle().getAttribute("aria-expanded")).toBe("true");- });-- it("closes an open menu before disabling the toggle", () => {- const el = renderInto(<Dropdown>item</Dropdown>);- const dropdownEl = el.querySelector(".dropdown");- expect(dropdownEl).toBeTruthy();- void act(() => {- $(dropdownEl as HTMLElement).trigger("show.bs.dropdown");- });-- // Bootstrap's hide() returns early on a disabled toggle, so the state at call time matters.- let disabledAtHide: boolean | undefined;- instance.hide.mockImplementationOnce(() => {- disabledAtHide = getToggle().disabled;- });- void act(() => render(<Dropdown disabled>item</Dropdown>, el));- expect(instance.hide).toHaveBeenCalledTimes(1);- expect(disabledAtHide).toBe(false);-- void act(() => {- $(dropdownEl as HTMLElement).trigger("hide.bs.dropdown");- });- expect(getToggle().disabled).toBe(true);- expect(getToggle().getAttribute("aria-expanded")).toBe("false");-- // A closed dropdown takes the attribute at once and has nothing to hide.- void act(() => render(null, el));- el.remove();- instance.hide.mockClear();- const closedEl = renderInto(<Dropdown disabled>item</Dropdown>);- expect(instance.hide).not.toHaveBeenCalled();- expect(getToggle().disabled).toBe(true);-- // `forceShown` does not open a disabled dropdown, so the toggle keeps the attribute.- void act(() => render(null, closedEl));- closedEl.remove();- instance.show.mockClear();- renderInto(<Dropdown disabled forceShown>item</Dropdown>);- expect(instance.show).not.toHaveBeenCalled();- expect(getToggle().disabled).toBe(true);+ render(null, host);+ vi.restoreAllMocks();});- it("mounts the portaled menu on arm (pointerdown/focus), wires _menu, and tears down on blur without open", () => {- renderInto(<Dropdown portalToBody className="my-scope" text="btn">item</Dropdown>);-- // Not mounted while idle — no empty wrapper left in the body.- expect(document.body.querySelector(":scope > .my-scope")).toBeNull();-- // Pointer press arms it: the wrapper + menu mount in the body and _menu is re-pointed.- fire(getToggle(), "pointerdown");- const menu = document.body.querySelector(":scope > .my-scope > .dropdown-menu");- expect(menu).toBeTruthy();- expect(instance._menu).toBe(menu);- // `tn-dropdown-portal` is what style.css hangs the out-of-modal z-index on; without it a- // portaled menu paints under whatever dialog it was opened from.- expect(menu?.parentElement?.classList.contains("tn-dropdown-portal")).toBe(true);-- // Releasing focus without opening tears the empty menu back down.- fire(getToggle(), "focusout");- expect(document.body.querySelector(":scope > .my-scope")).toBeNull();-- // Focusing the toggle (keyboard path) arms it too.- fire(getToggle(), "focusin");- expect(document.body.querySelector(":scope > .my-scope > .dropdown-menu")).toBeTruthy();- });+ function renderDropdown(props: Partial<DropdownProps> = {}) {+ 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>+ </Dropdown>+ );+ }+ render(<Harness />, host);+ const toggle = host.querySelector<HTMLButtonElement>("button");+ if (!toggle) throw new Error("expected the toggle to render");+ vi.spyOn(toggle, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x: 100, y: 50, width: 80, height: 30 }));+ return { toggle, handle: () => handle.current };+ }++ const popup = () => document.querySelector<HTMLElement>(".tn-popup");+ const click = (element: HTMLElement) => {+ // A press comes before its click, and would reach the popup's dismissal first.+ element.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ element.click();+ };- it("keeps an open portaled menu mounted through blur and unmounts it on hide", () => {+ 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 el = renderInto(- <Dropdown portalToBody className="my-scope" onShown={onShown} onHidden={onHidden}>- <li>entry</li>- </Dropdown>- );-- fire(getToggle(), "pointerdown");-- // Bootstrap opens the dropdown: children render and blur no longer unmounts.- const dropdownEl = el.querySelector(".dropdown");- expect(dropdownEl).toBeTruthy();- void act(() => {- $(dropdownEl as HTMLElement).trigger("show.bs.dropdown");- });+ const { toggle } = renderDropdown({ onShown, onHidden });+ 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" ]);+ // 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");+ expect(toggle.classList.contains("show")).toBe(true);expect(onShown).toHaveBeenCalledTimes(1);- expect(document.body.querySelector(":scope > .my-scope li")).toBeTruthy();-- fire(getToggle(), "focusout");- expect(document.body.querySelector(":scope > .my-scope > .dropdown-menu")).toBeTruthy();- // Hiding resets both `shown` and `armed`, unmounting the portaled menu.- void act(() => {- $(dropdownEl as HTMLElement).trigger("hide.bs.dropdown");- });+ // The toggle's own press is not a press outside, so its click closes rather than reopens.+ click(toggle);+ await vi.waitFor(() => expect(popup()).toBeNull());+ expect(toggle.getAttribute("aria-expanded")).toBe("false");expect(onHidden).toHaveBeenCalledTimes(1);- expect(document.body.querySelector(":scope > .my-scope")).toBeNull();});- /**- * A menu that is a task of its own dims the page behind it. The cover is drawn inside the same- * portal, before the menu, so what covers what is document order rather than two z-index scales- * meeting; and only while the menu is actually open, an armed but closed one covering nothing.- */- it("draws a backdrop under a portaled menu while it is open", () => {- const el = renderInto(- <Dropdown portalToBody backdrop className="my-scope">- <li>entry</li>- </Dropdown>- );+ it("closes on a press outside, and on Escape, which hands focus back to the toggle", async () => {+ const { toggle } = renderDropdown();- fire(getToggle(), "pointerdown");- expect(document.body.querySelector(":scope > .my-scope > .tn-dropdown-backdrop")).toBeNull();+ click(toggle);+ await vi.waitFor(() => expect(popup()).not.toBeNull());+ document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ await vi.waitFor(() => expect(popup()).toBeNull());- const dropdownEl = el.querySelector(".dropdown");- void act(() => {- $(dropdownEl as HTMLElement).trigger("show.bs.dropdown");- });-- const wrapper = document.body.querySelector<HTMLElement>(":scope > .my-scope");- const drawn = [ ...(wrapper?.children ?? []) ].map(child => child.className.split(" ")[0]);- expect(drawn).toEqual([ "tn-dropdown-backdrop", "dropdown-menu" ]);-- void act(() => {- $(dropdownEl as HTMLElement).trigger("hide.bs.dropdown");- });- expect(document.body.querySelector(":scope > .my-scope")).toBeNull();- });-- it("leaves a menu without the prop undimmed", () => {- const el = renderInto(- <Dropdown portalToBody className="my-scope"><li>entry</li></Dropdown>- );-- fire(getToggle(), "pointerdown");- void act(() => {- $(el.querySelector(".dropdown") as HTMLElement).trigger("show.bs.dropdown");- });-- expect(document.body.querySelector(":scope > .my-scope > .tn-dropdown-backdrop")).toBeNull();+ click(toggle);+ await vi.waitFor(() => expect(popup()).not.toBeNull());+ document.body.focus();+ popup()?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ await vi.waitFor(() => expect(popup()).toBeNull());+ expect(document.activeElement).toBe(toggle);});- it("leaves a mobileBottomSheet menu alone on a desktop layout", () => {- const el = renderInto(<Dropdown mobileBottomSheet forceShown>item</Dropdown>);-- // Nested next to the toggle, unclassed and undimmed: the sheet is a mobile arrangement only.- expect(el.querySelector(".dropdown > .dropdown-menu")).toBeTruthy();- expect(el.querySelector(".mobile-bottom-menu")).toBeNull();- });-- it("makes a mobileBottomSheet menu a bottom sheet on mobile: classed, portaled out and over the backdrop", () => {- isMobileMock.mockReturnValue(true);- const cover = document.createElement("div");- cover.id = "context-menu-cover";- document.body.appendChild(cover);-- const el = renderInto(<Dropdown mobileBottomSheet>item</Dropdown>);- const dropdownEl = el.querySelector(".dropdown");- void act(() => {- $(dropdownEl as HTMLElement).trigger("show.bs.dropdown");- });-- // The one prop stands in for all three pieces the arrangement needs.- expect(instance._menu?.classList.contains("mobile-bottom-menu")).toBe(true);- expect(el.contains(instance._menu)).toBe(false);- expect(instance._menu?.closest("body")).toBeTruthy();- expect(cover.classList.contains("show")).toBe(true);-- void act(() => {- $(dropdownEl as HTMLElement).trigger("hide.bs.dropdown");- });- expect(cover.classList.contains("show")).toBe(false);- cover.remove();+ it("opens, closes and toggles through its handle, for a caller that decides when", async () => {+ const { handle } = renderDropdown();+ await vi.waitFor(() => expect(handle()).not.toBeNull());++ handle()?.show();+ await vi.waitFor(() => expect(popup()).not.toBeNull());+ handle()?.hide();+ await vi.waitFor(() => expect(popup()).toBeNull());+ handle()?.toggle();+ await vi.waitFor(() => expect(popup()).not.toBeNull());+ handle()?.toggle();+ await vi.waitFor(() => expect(popup()).toBeNull());});- it("mounts and shows a forceShown portaled dropdown immediately", () => {- // No className: the portaled wrapper falls back to an empty class.- renderInto(<Dropdown portalToBody forceShown>item</Dropdown>);+ it("closes an open popup once it is disabled, and does not open while it is", async () => {+ const { toggle } = renderDropdown();+ click(toggle);+ await vi.waitFor(() => expect(popup()).not.toBeNull());- expect(instance.show).toHaveBeenCalledTimes(1);- // The menu was mounted into the body (via the class-less wrapper) and wired as _menu.- expect(instance._menu?.classList.contains("dropdown-menu")).toBe(true);- expect(instance._menu?.closest("body")).toBeTruthy();+ renderDropdown({ disabled: true });+ await vi.waitFor(() => expect(popup()).toBeNull());+ const disabledToggle = host.querySelector<HTMLButtonElement>("button");+ expect(disabledToggle?.disabled).toBe(true);});});diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsxindex 603dd39d42..62c7dfd25b 100644--- a/apps/client/src/widgets/react/Dropdown.tsx+++ b/apps/client/src/widgets/react/Dropdown.tsx@@ -1,12 +1,11 @@-import { Dropdown as BootstrapDropdown, Tooltip } from "bootstrap";+import type { Dropdown as BootstrapDropdown, Tooltip } from "bootstrap";import clsx from "clsx";import { ComponentChildren, HTMLAttributes } from "preact";-import { createPortal, CSSProperties, HTMLProps } from "preact/compat";-import { MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";+import { CSSProperties, HTMLProps } from "preact/compat";+import { MutableRef, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";-import { isMobile } from "../../services/utils";import { useTooltip, useUniqueName } from "./hooks";-import { suspendModalFocusTraps } from "./modal_focustrap";+import Popup from "./Popup";type DataAttributes = {[key: `data-${string}`]: string | number | boolean | undefined;@@ -48,7 +47,7 @@ export interface DropdownProps extends Pick<HTMLProps<HTMLDivElement>, "id" | "conShown?: () => void;onHidden?: () => void;dropdownOptions?: Partial<BootstrapDropdown.Options>;- dropdownRef?: MutableRef<BootstrapDropdown | null>;+ dropdownRef?: MutableRef<DropdownHandle | null>;titlePosition?: "top" | "right" | "bottom" | "left";titleOptions?: Partial<Tooltip.Options>;mobileBackdrop?: boolean;@@ -86,177 +85,71 @@ export interface DropdownProps extends Pick<HTMLProps<HTMLDivElement>, "id" | "cbackdrop?: boolean;}-export default function Dropdown({ id, className, buttonClassName, isStatic, children, title, text, dropdownContainerStyle, dropdownContainerClassName, dropdownContainerRef: externalContainerRef, hideToggleArrow, iconAction, disabled, noSelectButtonStyle, noDropdownListStyle, forceShown, onShown: externalOnShown, onHidden: externalOnHidden, dropdownOptions, buttonProps, dropdownRef, titlePosition, titleOptions, mobileBackdrop: mobileBackdropProp, portalToBody: portalToBodyProp, mobileBottomSheet, backdrop }: DropdownProps) {- // 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.- const bottomSheet = !!mobileBottomSheet && isMobile();- const mobileBackdrop = mobileBackdropProp || bottomSheet;- const portalToBody = portalToBodyProp || bottomSheet;+/** Opens and closes a dropdown from outside it, for a caller that decides when. */+export interface DropdownHandle {+ show(): void;+ hide(): void;+ toggle(): void;+}++/** 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) {const containerRef = useRef<HTMLDivElement | null>(null);const triggerRef = useRef<HTMLButtonElement | null>(null);- const dropdownContainerRef = useRef<HTMLUListElement | null>(null);+ const [ shown, setShown ] = useState(!!forceShown && !disabled);// 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.const tooltipConfig = useMemo<Partial<Tooltip.Options>>(() => ({...titleOptions,- // Drive the tooltip from config, not just the `title` attribute: Bootstrap reads the attribute once- // on init, so a dynamic title (e.g. the media play-mode button) would otherwise go stale (`title` is- // a dependency of this memo, so a change recreates the tooltip, keeping it in sync). Prefer the- // `title` prop, then a `titleOptions.title` escape-hatch, then "" (Bootstrap rejects `undefined`;- // "" shows no tooltip).+ // Bootstrap reads the `title` attribute once, so a dynamic title is driven from config.+ // Bootstrap rejects `undefined`; "" shows no tooltip.title: title ?? titleOptions?.title ?? "",placement: titlePosition ?? "bottom",fallbackPlacements: [ titlePosition ?? "bottom" ]- }), [title, titleOptions, titlePosition]);- const [ shown, setShown ] = useState(false);- // On the wrapper, not on the toggle: Bootstrap keeps one component instance per element and the toggle- // is already the dropdown's own, so a tooltip put there is refused registration and can never be- // disposed — it goes on showing its title with nothing left to take it down.- //- // Triggering is Bootstrap's, though, rather than driven from the toggle's mouseenter/mouseleave as it- // once was: only Bootstrap's own listeners keep the hover state it decides by, and a tooltip shown- // around it is liable to be taken away again under the pointer. What that arrangement was for — the- // wrapper holding the open menu too, so the title hung over the menu the pointer had moved into — is- // answered by silencing the tooltip for as long as the menu is up.+ }), [ title, titleOptions, titlePosition ]);+ // On the wrapper, and silenced while the popup is up, so the title does not hang over it.const { hideTooltip } = useTooltip(containerRef, tooltipConfig, !shown);- // A portaled menu lives in `document.body`, detached from the toggle's subtree. Mounting it eagerly- // for every instance leaves an empty menu wrapper in the body for every note context/tab, so only- // mount it while it's actually needed: open (`shown`), about to open (`armed` — set on interaction- // with the toggle, see the button handlers below), or forced open. Non-portaled menus stay inline- // next to the toggle and are always mounted, as before.- const [ armed, setArmed ] = useState(false);- const menuMounted = !portalToBody || shown || armed || !!forceShown;- const dropdownInstanceRef = useRef<BootstrapDropdown | null>(null);-- // Create/wire the Bootstrap dropdown. Re-runs whenever the (portaled) menu remounts so `_menu` gets- // re-pointed at the fresh element. useLayoutEffect so the wiring lands synchronously after the- // interaction that mounts the menu but before Bootstrap's click handler opens it.useLayoutEffect(() => {- if (!triggerRef.current) return;-- const dropdown = BootstrapDropdown.getOrCreateInstance(triggerRef.current, dropdownOptions);- dropdownInstanceRef.current = dropdown;- if (dropdownRef) {- dropdownRef.current = dropdown;- }-- // When the menu is portaled to `document.body` it is no longer a sibling of the toggle, so- // Bootstrap fails to locate it (it searches the toggle's wrapper). Wire it up by hand —- // Bootstrap only ever positions/toggles whatever `_menu` points at, regardless of where it- // lives in the DOM, and the popper reference stays the toggle button.- if (portalToBody && dropdownContainerRef.current) {- (dropdown as unknown as { _menu: HTMLElement })._menu = dropdownContainerRef.current;- }-- // React to popup container size changes, which can affect the positioning.- let resizeObserver: ResizeObserver | undefined;- if (dropdownContainerRef.current) {- resizeObserver = new ResizeObserver(() => dropdown.update());- resizeObserver.observe(dropdownContainerRef.current);- }-- return () => resizeObserver?.disconnect();- }, [ menuMounted ]);+ if (externalContainerRef) externalContainerRef.current = containerRef.current;+ }, [ externalContainerRef ]);- // Show a forced-open dropdown once mounted, and dispose the instance only when the component truly- // unmounts (not on every menu remount driven by the effect above).- useEffect(() => {- if (forceShown && !disabled) {- dropdownInstanceRef.current?.show();- setShown(true);- }- return () => {- dropdownInstanceRef.current?.dispose();- dropdownInstanceRef.current = null;+ useLayoutEffect(() => {+ if (!dropdownRef) return;+ dropdownRef.current = {+ show: () => setShown(true),+ hide: () => setShown(false),+ toggle: () => setShown((current) => !current)};- }, []);-- const onShown = useCallback(() => {- setShown(true);- externalOnShown?.();- hideTooltip();- if (mobileBackdrop && isMobile()) {- document.getElementById("context-menu-cover")?.classList.add("show", "global-menu-cover");- }- }, [ hideTooltip, mobileBackdrop ]);-- const onHidden = useCallback(() => {- setShown(false);- setArmed(false);- externalOnHidden?.();- if (mobileBackdrop && isMobile()) {- document.getElementById("context-menu-cover")?.classList.remove("show", "global-menu-cover");- }- }, [ mobileBackdrop ]);+ }, [ dropdownRef ]);- // Bootstrap's `hide()` and `clearMenus()` skip a disabled toggle, so this effect closes the- // menu first. The toggle takes the `disabled` attribute only once `shown` is false.+ // A disabled toggle cannot be pressed to close its popup, so disabling it closes the popup.useLayoutEffect(() => {- if (disabled && shown) {- dropdownInstanceRef.current?.hide();- }- }, [ disabled, shown ]);+ if (disabled) setShown(false);+ }, [ disabled ]);- // 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.+ const everShown = useRef(false);useEffect(() => {- if (!portalToBody || !shown) return;- return suspendModalFocusTraps();- }, [ portalToBody, shown ]);-- useEffect(() => {- if (!containerRef.current) return;- if (externalContainerRef) externalContainerRef.current = containerRef.current;-- const $dropdown = $(containerRef.current);- $dropdown.on("show.bs.dropdown", (e) => {- // Stop propagation causing multiple shows for nested dropdowns.- e.stopPropagation();- onShown();- });- $dropdown.on("hide.bs.dropdown", (e) => {- // Stop propagation causing multiple hides for nested dropdowns.- e.stopPropagation();- onHidden();- });-- // Add proper cleanup- return () => {- $dropdown.off("show.bs.dropdown", onShown);- $dropdown.off("hide.bs.dropdown", onHidden);- };- }, [ onShown, onHidden ]);+ if (shown) {+ everShown.current = true;+ hideTooltip();+ onShown?.();+ } else if (everShown.current) {+ onHidden?.();+ }+ }, [ 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();- }- }}- >- {shown && children}- </ul>- );-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.<div ref={containerRef} class={`dropdown ${className ?? ""}`} style={{ display: "flex" }} title={title}><button- // `buttonClassName` updates rewrite the class list.- // `shown` keeps Bootstrap's marker on later renders.+ {...buttonProps}className={clsx(iconAction ? "icon-action" : "btn",!noSelectButtonStyle && "select-button",@@ -266,38 +159,33 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi)}ref={triggerRef}type="button"- data-bs-toggle="dropdown"- data-bs-display={ isStatic ? "static" : undefined }aria-haspopup="true"aria-expanded={shown}id={id ?? ariaId}- disabled={disabled && !shown}- // Mount the portaled menu just before it can open: any interaction that leads to a- // Bootstrap open (pointer press, or focusing the toggle ahead of a keyboard open) is- // preceded by one of these, so `_menu` is wired by the time the click/keydown fires.- // Releasing focus without opening tears the empty menu back down.- onPointerDown={portalToBody ? () => setArmed(true) : undefined}- onFocus={portalToBody ? () => setArmed(true) : undefined}- onBlur={portalToBody ? () => { if (!shown) setArmed(false); } : undefined}- {...buttonProps}+ disabled={disabled}+ onClick={(e) => {+ buttonProps?.onClick?.(e);+ setShown((current) => !current);+ }}>{text}<span className="caret" /></button>- {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).- // Only mount it while needed (see `menuMounted`) so closed pickers don't each leave an- // empty menu wrapper in the body.- ? (menuMounted && createPortal((- <div class={`tn-dropdown-portal ${className ?? ""}`}>- {backdrop && shown && <div class="tn-dropdown-backdrop" />}- {menu}- </div>- ), document.body))- : menu}+ {shown && triggerRef.current && (+ <Popup+ anchor={triggerRef.current}+ offset={TOGGLE_GAP}+ className={clsx("dropdown-menu show tn-dropdown-menu", dropdownContainerClassName)}+ onDismiss={(reason) => {+ setShown(false);+ if (reason === "escape") triggerRef.current?.focus();+ }}+ >+ {/* The popup holds nothing yet; the menu comes next. */}+ <div aria-labelledby={ariaId} style={dropdownContainerStyle} />+ </Popup>+ )}</div>);}diff --git a/apps/client/src/widgets/react/Dropdown_legacy.tsx b/apps/client/src/widgets/react/Dropdown_legacy.tsxnew file mode 100644index 0000000000..4f117d4a78--- /dev/null+++ b/apps/client/src/widgets/react/Dropdown_legacy.tsx@@ -0,0 +1,161 @@+// Reference copy of the Bootstrap-driven Dropdown from before the `Popup` rewrite. Nothing imports it.+// Delete a piece once `Dropdown` covers it, and the file once the two reach parity.++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 { isMobile } from "../../services/utils";+import { useUniqueName } from "./hooks";+import { suspendModalFocusTraps } from "./modal_focustrap";++type DataAttributes = {+ [key: `data-${string}`]: string | number | boolean | undefined;+};++export interface DropdownProps extends Pick<HTMLProps<HTMLDivElement>, "id" | "className"> {+ buttonClassName?: string;+ buttonProps?: Partial<HTMLAttributes<HTMLButtonElement> & DataAttributes>;+ isStatic?: boolean;+ children: ComponentChildren;+ title?: string;+ dropdownContainerStyle?: CSSProperties;+ dropdownContainerClassName?: string;+ dropdownContainerRef?: MutableRef<HTMLDivElement | null>;+ hideToggleArrow?: boolean;+ /** If set to true, then the dropdown button will be considered an icon action (without normal border and sized for icons only). */+ iconAction?: boolean;+ noSelectButtonStyle?: boolean;+ /**+ * Drop the `tn-dropdown-list` class the menu otherwise carries by default.+ *+ * That class exists for **scrollable** menus: it moves the theme's backdrop blur off the menu's+ * `::before` layer — which a scrollable menu would scroll away with its content — and onto the+ * menu element itself. The element-level filter is the fragile one, though: opened over note+ * content it blurs nothing at all, leaving the menu merely translucent and reading as+ * see-through over anything dark.+ *+ * So set this on any menu that doesn't scroll (i.e. nearly every action menu) to keep it on the+ * working pseudo-element layer.+ */+ noDropdownListStyle?: boolean;+ /**+ * The only supported way to disable the toggle. Bootstrap cannot close a menu whose toggle is+ * disabled through `buttonProps` or a `disabled` class.+ */+ disabled?: boolean;+ text?: ComponentChildren;+ forceShown?: boolean;+ onShown?: () => void;+ onHidden?: () => void;+ dropdownOptions?: Partial<BootstrapDropdown.Options>;+ dropdownRef?: MutableRef<BootstrapDropdown | null>;+ titlePosition?: "top" | "right" | "bottom" | "left";+ titleOptions?: Partial<Tooltip.Options>;+ mobileBackdrop?: boolean;+ /**+ * Render the dropdown menu into `document.body` instead of nesting it next to the toggle.+ *+ * Use this when an ancestor establishes a containment/backdrop root (e.g. `container-type`,+ * `transform`, `filter`) which would otherwise flatten the menu's `backdrop-filter` blur into a+ * flat tint. The menu is wrapped in a `<div class="tn-dropdown-portal {className}">` so any CSS+ * scoped under that class keeps applying even though the menu no longer lives inside the+ * toggle's wrapper, and so the menu outranks whatever stacking context it was lifted out of.+ */+ portalToBody?: boolean;+ /**+ * On a phone, show the menu as a sheet rising from the bottom of the screen over a dimmed page,+ * the way the app's other mobile menus appear. No effect on a desktop layout.+ *+ * Prefer this to setting the pieces by hand. A menu left to place itself on mobile lands as a+ * narrow box adrift in the middle of the page — Popper computes an offset that the app's own+ * `body.mobile .dropdown-menu { position: fixed }` then measures from somewhere else — and one+ * opened inside a dialog needs {@link portalToBody} besides, since a transformed `.modal-dialog`+ * is both the box a fixed menu is placed against and a stacking context the backdrop, painting+ * above the whole modal, would otherwise dim the menu through.+ */+ mobileBottomSheet?: boolean;+ /**+ * Dim the page behind the menu on any screen, for a menu that is a task of its own rather than+ * a list of actions: the icon picker, which holds a search field and a grid of a thousand+ * icons.+ *+ * Drawn inside the same portal as the menu, immediately before it, so what covers what is a+ * matter of document order and one z-index rather than of two scales meeting. Needs+ * {@link portalToBody} for that, and does nothing without it.+ */+ backdrop?: 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).++ // 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.+ const bottomSheet = !!mobileBottomSheet && isMobile();+ const mobileBackdrop = mobileBackdropProp || bottomSheet;+ const portalToBody = portalToBodyProp || bottomSheet;++ const dropdownContainerRef = useRef<HTMLUListElement | null>(null);+ const [ shown ] = useState(false);++ const onShown = useCallback(() => {+ externalOnShown?.();+ if (mobileBackdrop && isMobile()) {+ document.getElementById("context-menu-cover")?.classList.add("show", "global-menu-cover");+ }+ }, [ mobileBackdrop ]);++ const onHidden = useCallback(() => {+ externalOnHidden?.();+ if (mobileBackdrop && isMobile()) {+ document.getElementById("context-menu-cover")?.classList.remove("show", "global-menu-cover");+ }+ }, [ mobileBackdrop ]);++ useEffect(() => {+ if (shown) onShown();+ else 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();+ }+ }}+ >+ {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" />}+ {menu}+ </div>+ ), document.body)+ : menu;+}diff --git a/apps/client/src/widgets/react/Popup.css b/apps/client/src/widgets/react/Popup.cssnew file mode 100644index 0000000000..4e0f8d019e--- /dev/null+++ b/apps/client/src/widgets/react/Popup.css@@ -0,0 +1,13 @@+/*+ * `body` outranks the position a class it is given sets, such as Bootstrap's `.dropdown-menu`.+ * `placePopup()` shows it once it has a position.+ */+body .tn-popup {+ position: fixed;+ top: 0;+ left: 0;+ /* As a portaled dropdown menu: over a modal (1055) and a stacked quick-edit popup (1100), under+ the prompts (2000) it can summon. */+ z-index: 1200;+ visibility: hidden;+}diff --git a/apps/client/src/widgets/react/Popup.spec.tsx b/apps/client/src/widgets/react/Popup.spec.tsxnew file mode 100644index 0000000000..b5ac588fe5--- /dev/null+++ b/apps/client/src/widgets/react/Popup.spec.tsx@@ -0,0 +1,117 @@+import { render } from "preact";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import Popup, { type PopupProps } from "./Popup";++describe("Popup", () => {+ const host = document.createElement("div");+ document.body.append(host);+ let anchor: HTMLButtonElement;++ beforeEach(() => {+ anchor = document.createElement("button");+ document.body.append(anchor);+ // Floating UI reads the viewport from the root element's client size, and the popup's own+ // size from its offset size; happy-dom lays out nothing.+ 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(100);+ });++ afterEach(() => {+ render(null, host);+ anchor.remove();+ vi.restoreAllMocks();+ Object.defineProperty(document, "fullscreenElement", { value: null, configurable: true });+ });++ function anchorAt(x: number, y: number) {+ vi.spyOn(anchor, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect({ x, y, width: 80, height: 30 }));+ }++ /** Renders the popup and waits for it to be placed, which is when it shows. */+ async function open(props: Partial<PopupProps> = {}) {+ render(<Popup anchor={anchor} onDismiss={() => {}} {...props}><span>content</span></Popup>, host);+ const popup = document.querySelector<HTMLElement>(".tn-popup");+ if (!popup) throw new Error("expected the popup to render");+ await vi.waitFor(() => expect(popup.style.visibility).toBe("visible"));+ return popup;+ }++ it("stands in the page's body, below its anchor and lined up with its start", async () => {+ anchorAt(100, 50);+ const popup = await open({ className: "dropdown-menu", role: "menu" });++ expect(popup.parentElement).toBe(document.body);+ expect([ ...popup.classList ]).toEqual([ "tn-popup", "dropdown-menu" ]);+ expect(popup.getAttribute("role")).toBe("menu");+ expect(popup.textContent).toBe("content");+ expect([ popup.style.left, popup.style.top ]).toEqual([ "100px", "80px" ]);+ });++ it("keeps the gap it is given from its anchor", async () => {+ anchorAt(100, 50);+ const popup = await open({ offset: 2 });++ expect(popup.style.top).toBe("82px");+ });++ it("flips above its anchor where there is no room below, and caps its height to the room it has", async () => {+ anchorAt(100, 740);+ const popup = await open();+ // 740 - 100: it ends where the anchor starts.+ expect(popup.style.top).toBe("640px");++ render(null, host);+ vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(1000);+ anchorAt(100, 300);+ const tall = await open();+ // The side with the most room, less the gap it keeps from the viewport's edges.+ expect(tall.style.maxHeight).toBe(`${800 - 330 - 5}px`);+ });++ 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" });++ expect([ popup.style.left, popup.style.top ]).toEqual([ "300px", "200px" ]);+ });++ it("stands inside whatever has the screen, which is all a browser paints then", async () => {+ const fullscreen = document.createElement("div");+ document.body.append(fullscreen);+ Object.defineProperty(document, "fullscreenElement", { value: fullscreen, configurable: true });+ anchorAt(100, 50);++ const popup = await open();+ expect(popup.parentElement).toBe(fullscreen);+ fullscreen.remove();+ });++ it("is dismissed by a press outside it and its anchor, and by Escape, which goes no further", async () => {+ anchorAt(100, 50);+ const onDismiss = vi.fn();+ const popup = await open({ onDismiss });+ const pressOn = (target: Element) => target.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ // As the note tree stops its own presses.+ const outside = document.createElement("div");+ outside.addEventListener("pointerdown", (e) => e.stopPropagation());+ document.body.append(outside);++ pressOn(popup.firstElementChild ?? popup);+ // The anchor is a dropdown's toggle, which opens and closes the popup itself.+ pressOn(anchor);+ expect(onDismiss).not.toHaveBeenCalled();++ pressOn(outside);+ expect(onDismiss).toHaveBeenCalledWith("outside");++ const dialogHeard = vi.fn();+ document.addEventListener("keydown", dialogHeard);+ popup.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));+ expect(onDismiss).toHaveBeenLastCalledWith("escape");+ expect(dialogHeard).not.toHaveBeenCalled();+ document.removeEventListener("keydown", dialogHeard);+ outside.remove();+ });+});diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsxnew file mode 100644index 0000000000..335b01c5ec--- /dev/null+++ b/apps/client/src/widgets/react/Popup.tsx@@ -0,0 +1,120 @@+import "./Popup.css";++import { autoUpdate, computePosition, flip, offset, type Placement, type ReferenceElement, shift, size } from "@floating-ui/dom";+import clsx from "clsx";+import type { ComponentChildren, HTMLAttributes } from "preact";+import { createPortal } from "preact/compat";+import { 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 {+ /** 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 };+ /**+ * The side of the anchor it prefers, flipped to the other side where that one has no room.+ * Below the anchor, lined up with its start, by default.+ */+ placement?: Placement;+ /** The gap, in pixels, it keeps from its anchor. */+ offset?: number;+ /**+ * 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);+ const anchorX = "x" in anchor ? anchor.x : undefined;+ const anchorY = "y" in anchor ? anchor.y : undefined;++ useLayoutEffect(() => {+ const popup = popupRef.current;+ if (!popup) return;+ const reference = anchor instanceof HTMLElement ? anchor : pointAt(anchor.x, anchor.y);+ // 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 ]);++ const dismiss = useRef(onDismiss);+ dismiss.current = onDismiss;+ useLayoutEffect(() => {+ // Captured at the window, so a host that stops its own presses, as the note tree does,+ // cannot keep them from here, and so Escape arrives before Bootstrap's handler for keys in+ // a `.dropdown-menu`, which looks for a toggle beside the popup and crashes without one.+ const onPointerDown = (e: PointerEvent) => {+ const target = e.target as Node;+ if (popupRef.current?.contains(target)) return;+ if (anchor instanceof HTMLElement && anchor.contains(target)) return;+ dismiss.current("outside");+ };+ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key !== "Escape") return;+ // A dialog under it stays open.+ e.stopPropagation();+ dismiss.current("escape");+ };+ window.addEventListener("pointerdown", onPointerDown, true);+ window.addEventListener("keydown", onKeyDown, true);+ return () => {+ window.removeEventListener("pointerdown", onPointerDown, true);+ window.removeEventListener("keydown", onKeyDown, true);+ };+ }, [ anchor ]);++ // 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)}>+ {children}+ </div>+ ), 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.+ */+async function placePopup(popup: HTMLElement, anchor: ReferenceElement, placement: Placement, gap: number) {+ const { x, y } = await computePosition(anchor, popup, {+ strategy: "fixed",+ placement,+ middleware: [+ offset(gap),+ flip({ padding: VIEWPORT_PADDING }),+ // 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({+ padding: VIEWPORT_PADDING,+ apply({ availableHeight }) {+ popup.style.maxHeight = `${availableHeight}px`;+ }+ })+ ]+ });++ popup.style.left = `${x}px`;+ popup.style.top = `${y}px`;+ popup.style.visibility = "visible";+}++/** A zero-size anchor at a point in the viewport. */+function pointAt(x: number, y: number): ReferenceElement {+ return {+ getBoundingClientRect: () => DOMRect.fromRect({ x, y, width: 0, height: 0 })+ };+}