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 a dropdown as a phone's bottom sheet, over the cover or a backdrop
Elian Dorand151b73589b8
diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsxindex 27040e9f6c..78a24e2e28 100644--- a/apps/client/src/widgets/react/Dropdown.spec.tsx+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx@@ -8,6 +8,12 @@ import Dropdown, { type DropdownHandle, type DropdownProps } from "./Dropdown";const focusTraps = vi.hoisted(() => ({ suspend: vi.fn(() => () => {}) }));vi.mock("./modal_focustrap", () => ({ suspendModalFocusTraps: focusTraps.suspend }));+const layout = vi.hoisted(() => ({ onMobile: false }));+vi.mock("../../services/utils", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../services/utils")>()),+ isMobile: () => layout.onMobile+}));+describe("Dropdown", () => {const host = document.createElement("div");document.body.append(host);@@ -22,6 +28,7 @@ describe("Dropdown", () => {afterEach(() => {render(null, host);vi.restoreAllMocks();+ layout.onMobile = false;});function renderDropdown(props: Partial<DropdownProps> = {}, content: ComponentChildren = <li className="dropdown-item">By title</li>) {@@ -213,4 +220,54 @@ describe("Dropdown", () => {expect(restore).toHaveBeenCalledTimes(1);});});++ describe("as a sheet or over a backdrop", () => {+ /** The dimmed cover the shell keeps for menus on a phone. */+ function addCover() {+ const cover = document.createElement("div");+ cover.id = "context-menu-cover";+ document.body.append(cover);+ return cover;+ }++ it("rises from the bottom of a phone's screen, where the stylesheet places it, over the cover", async () => {+ layout.onMobile = true;+ const cover = addCover();+ const { toggle } = renderDropdown({ mobileBottomSheet: true });++ click(toggle);+ await vi.waitFor(() => expect(popup()?.style.visibility).toBe("visible"));+ expect(popup()?.classList.contains("mobile-bottom-menu")).toBe(true);+ // Nothing placed it beside the toggle; the `.mobile-bottom-menu` rules do.+ expect([ popup()?.style.left, popup()?.style.top ]).toEqual([ "", "" ]);+ expect([ ...cover.classList ]).toEqual([ "show", "global-menu-cover" ]);++ // A tap on the cover is one outside the menu.+ cover.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));+ await vi.waitFor(() => expect(popup()).toBeNull());+ expect(cover.classList.contains("show")).toBe(false);+ cover.remove();+ });++ it("is an ordinary menu beside its toggle on a desktop, with no cover", async () => {+ const cover = addCover();+ const { toggle } = renderDropdown({ mobileBottomSheet: true, mobileBackdrop: true });++ click(toggle);+ await vi.waitFor(() => expect(popup()?.style.visibility).toBe("visible"));+ expect(popup()?.classList.contains("mobile-bottom-menu")).toBe(false);+ expect(popup()?.style.top).toBe("82px");+ expect(cover.classList.contains("show")).toBe(false);+ cover.remove();+ });++ it("dims the page under it when asked to, drawn just before it", async () => {+ const { toggle } = renderDropdown({ backdrop: true, className: "icon-picker-dropdown" });++ click(toggle);+ await vi.waitFor(() => expect(popup()).not.toBeNull());+ const drawn = [ ...popup()?.parentElement?.children ?? [] ].map((child) => child.classList[0]);+ expect(drawn).toEqual([ "tn-dropdown-backdrop", "tn-popup" ]);+ });+ });});diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsxindex aaeb68ffd5..3bf800b491 100644--- a/apps/client/src/widgets/react/Dropdown.tsx+++ b/apps/client/src/widgets/react/Dropdown.tsx@@ -5,6 +5,7 @@ import { ComponentChildren, HTMLAttributes } from "preact";import { CSSProperties, HTMLProps } from "preact/compat";import { MutableRef, useCallback, 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";@@ -97,7 +98,11 @@ 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 }: 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 }: 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();+ const mobileBackdrop = (!!mobileBackdropProp || bottomSheet) && isMobile();const containerRef = useRef<HTMLDivElement | null>(null);const triggerRef = useRef<HTMLButtonElement | null>(null);const popupRef = useRef<HTMLDivElement | null>(null);@@ -164,6 +169,15 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chiif (shown) callbacks.current.onShown?.();}, []);+ // On a phone the shell's cover dims the page under the popup; a tap on it closes the popup,+ // being one outside it.+ useEffect(() => {+ if (!shown || !mobileBackdrop) return;+ const cover = document.getElementById("context-menu-cover");+ cover?.classList.add("show", "global-menu-cover");+ return () => cover?.classList.remove("show", "global-menu-cover");+ }, [ shown, mobileBackdrop ]);+// A dialog's focus trap would pull focus out of a popup that stands outside the dialog.useEffect(() => {if (!shown) return;@@ -243,9 +257,12 @@ export default function Dropdown({ id, className, buttonClassName, isStatic, chi// 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)}+ placedByStylesheet={bottomSheet}+ // style.css stacks it just under a portaled menu.+ backdropClassName={backdrop ? "tn-dropdown-backdrop" : undefined}elementRef={popupRef}className={clsx("dropdown-menu show tn-dropdown-menu", isStatic && "static", dropdownContainerClassName,- !noDropdownListStyle && "tn-dropdown-list")}+ bottomSheet && "mobile-bottom-menu", !noDropdownListStyle && "tn-dropdown-list")}style={dropdownContainerStyle}aria-labelledby={toggleId}onPlaced={() => {diff --git a/apps/client/src/widgets/react/Dropdown_legacy.tsx b/apps/client/src/widgets/react/Dropdown_legacy.tsxdeleted file mode 100644index c4025ccd12..0000000000--- a/apps/client/src/widgets/react/Dropdown_legacy.tsx+++ /dev/null@@ -1,133 +0,0 @@-// 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, useState } from "preact/hooks";--import { isMobile } from "../../services/utils";--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, 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.- const bottomSheet = !!mobileBottomSheet && isMobile();- const mobileBackdrop = mobileBackdropProp || bottomSheet;- const portalToBody = portalToBodyProp || bottomSheet;-- 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 ]);-- const menu = (- <ul class={`dropdown-menu ${bottomSheet ? "mobile-bottom-menu" : ""}`}>- {shown && children}- </ul>- );-- return portalToBody- ? 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.tsx b/apps/client/src/widgets/react/Popup.tsxindex a37b7063bd..7beeb414be 100644--- a/apps/client/src/widgets/react/Popup.tsx+++ b/apps/client/src/widgets/react/Popup.tsx@@ -31,6 +31,13 @@ export interface PopupProps extends Pick<HTMLAttributes<HTMLDivElement>, "id" |* classes of what opened it still applies there.*/portalClassName?: string;+ /**+ * Leaves it where the stylesheet puts it rather than beside its anchor, as a sheet along the+ * bottom of a phone's screen is.+ */+ placedByStylesheet?: boolean;+ /** Classes for an element drawn just before it, which dims the page under it. */+ backdropClassName?: string;elementRef?: MutableRef<HTMLDivElement | null>;/** Called once it is first placed and shown: a browser focuses nothing inside it before. */onPlaced?(): void;@@ -45,7 +52,7 @@ export interface PopupProps extends Pick<HTMLAttributes<HTMLDivElement>, "id" |/** 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, capHeight = true, portalClassName, elementRef, onPlaced, onDismiss, className, children, ...elementProps }: PopupProps) {+export default function Popup({ anchor, placement = "bottom-start", offset: gap = 0, capHeight = true, portalClassName, placedByStylesheet, backdropClassName, elementRef, onPlaced, onDismiss, className, children, ...elementProps }: PopupProps) {const popupRef = useRef<HTMLDivElement | null>(null);const placed = useRef(onPlaced);placed.current = onPlaced;@@ -55,6 +62,11 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gapuseLayoutEffect(() => {const popup = popupRef.current;if (!popup) return;+ if (placedByStylesheet) {+ popup.style.visibility = "visible";+ placed.current?.();+ 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.@@ -63,7 +75,7 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gapshown = true;placed.current?.();}));- }, [ anchor instanceof HTMLElement ? anchor : undefined, anchorX, anchorY, placement, gap, capHeight ]);+ }, [ anchor instanceof HTMLElement ? anchor : undefined, anchorX, anchorY, placement, gap, capHeight, placedByStylesheet ]);const dismiss = useRef(onDismiss);dismiss.current = onDismiss;@@ -105,7 +117,11 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gap{children}</div>);- return createPortal(portalClassName ? <div className={portalClassName}>{popup}</div> : popup,+ const drawn = <>+ {backdropClassName && <div className={backdropClassName} />}+ {popup}+ </>;+ return createPortal(portalClassName ? <div className={portalClassName}>{drawn}</div> : drawn,document.fullscreenElement ?? document.body);}