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
fix(menu): follow the layout when a tablet turns while a menu is open
Elian Dorand03daee8805b
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.tsindex 1711c1030f..cf050d18d0 100644--- a/apps/client/src/menus/context_menu.spec.ts+++ b/apps/client/src/menus/context_menu.spec.ts@@ -7,11 +7,22 @@ vi.mock("../services/keyboard_actions", () => ({effectiveShortcuts: name === "copyNotesToClipboard" ? [ "Ctrl+C", "Ctrl+Insert" ] : []})}));-const layout = vi.hoisted(() => ({ onMobile: false, narrow: true }));+const layout = vi.hoisted(() => ({+ onMobile: false,+ narrow: true,+ onChange: new Set<() => void>()+}));vi.mock("../services/utils", async (importOriginal) => {const original = await importOriginal<typeof import("../services/utils")>();// `Menu` imports `isMobile()` by name, `contextMenu` through the default export.- const overrides = { isMobile: () => layout.onMobile, isNarrowLayout: () => layout.narrow };+ const overrides = {+ isMobile: () => layout.onMobile,+ isNarrowLayout: () => layout.narrow,+ onNarrowLayoutChange: (listener: () => void) => {+ layout.onChange.add(listener);+ return () => layout.onChange.delete(listener);+ }+ };return { ...original, ...overrides, default: { ...original.default, ...overrides } };});const focusTraps = vi.hoisted(() => ({ restore: vi.fn(), suspend: vi.fn() }));@@ -1098,6 +1109,20 @@ describe("contextMenu", () => {expect(menu?.style.maxHeight).not.toBe("");});+ it("closes as a tablet turns past the phone layout's width", async () => {+ layout.onMobile = true;+ buildPage();+ const contextMenu = await buildContextMenu();+ await contextMenu.show({ x: 10, y: 20, items, selectMenuItemHandler: () => {} });+ expect(menuElement()).not.toBeNull();++ layout.narrow = false;+ for (const listener of [ ...layout.onChange ]) listener();+ await vi.waitFor(() => expect(menuElement()).toBeNull());+ expect(contextMenu.isShown).toBe(false);+ expect(layout.onChange.size).toBe(0);+ });+it("opens at the pointer instead when the caller asks", async () => {layout.onMobile = true;buildPage();diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex 2f93f93f2c..d1373e4f6a 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -95,6 +95,8 @@ class ContextMenu {private lastInputWasKey = false;/** Counts `show()` calls, so that only the latest one mounts a menu. */private lastShowRequest = 0;+ /** Stops closing the menu when the layout changes; see `show()`. */+ private stopFollowingLayout?: () => void;constructor() {this.cover = utils.isMobile() ? document.getElementById("context-menu-cover") : null;@@ -148,6 +150,11 @@ class ContextMenu {(document.fullscreenElement ?? document.body).append(this.host);this.cover?.classList.add("show");document.body.classList.add("context-menu-shown");+ // A mobile menu is a sheet or placed at the press depending on the layout, decided here,+ // so it closes when a tablet turns past that width.+ if (utils.isMobile() && !options.forcePositionOnMobile) {+ this.stopFollowingLayout = utils.onNarrowLayoutChange(() => void this.hide());+ }render(h(Menu<T>, {// The id and classes the stylesheets, themes and `floating_layers` know this menu by.@@ -188,6 +195,8 @@ class ContextMenu {async hide() {const options = this.options;this.options = undefined;+ this.stopFollowingLayout?.();+ this.stopFollowingLayout = undefined;this.cover?.classList.remove("show");document.body.classList.remove("context-menu-shown");diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex b6a4edf5de..fc30f22082 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -314,9 +314,18 @@ export function isMobile() {* around the `.mobile-bottom-menu` rules in style.css.*/export function isNarrowLayout() {- return window.matchMedia("(max-width: 991px)").matches;+ return window.matchMedia(NARROW_LAYOUT).matches;}+/** Calls `onChange` whenever {@link isNarrowLayout} changes, until the returned function runs. */+export function onNarrowLayoutChange(onChange: () => void) {+ const query = window.matchMedia(NARROW_LAYOUT);+ query.addEventListener("change", onChange);+ return () => query.removeEventListener("change", onChange);+}++const NARROW_LAYOUT = "(max-width: 991px)";+/*** Returns true if the client device is an Apple iOS one (iPad, iPhone, iPod).* Does not check if the user requested the mobile or desktop layout, use {@link isMobile} for that.@@ -990,6 +999,7 @@ export default {randomString,isMobile,isNarrowLayout,+ onNarrowLayoutChange,isDesktop,setCookie,getNoteTypeClass,diff --git a/apps/client/src/widgets/react/Dropdown.spec.tsx b/apps/client/src/widgets/react/Dropdown.spec.tsxindex 269abfd37f..de8d83bc7a 100644--- a/apps/client/src/widgets/react/Dropdown.spec.tsx+++ b/apps/client/src/widgets/react/Dropdown.spec.tsx@@ -9,7 +9,11 @@ import { FormDropdownSubmenu, FormListItem } from "./FormList";const focusTraps = vi.hoisted(() => ({ suspend: vi.fn(() => () => {}) }));vi.mock("./modal_focustrap", () => ({ suspendModalFocusTraps: focusTraps.suspend }));-const layout = vi.hoisted(() => ({ onMobile: false, narrow: true }));+const layout = vi.hoisted(() => ({+ onMobile: false,+ narrow: true,+ onChange: new Set<() => void>()+}));vi.mock("../../services/utils", async (importOriginal) => ({...(await importOriginal<typeof import("../../services/utils")>()),isMobile: () => layout.onMobile@@ -26,7 +30,12 @@ describe("Dropdown", () => {vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(100);// A phone's width unless a spec says otherwise; happy-dom's window is 1024px wide.vi.spyOn(window, "matchMedia").mockImplementation((media) => ({- matches: layout.narrow, media, addEventListener() {}, removeEventListener() {}+ matches: layout.narrow,+ media,+ addEventListener: (_: string, listener: () => void) => layout.onChange.add(listener),+ removeEventListener: (_: string, listener: () => void) => {+ layout.onChange.delete(listener);+ }}) as unknown as MediaQueryList);});@@ -35,6 +44,7 @@ describe("Dropdown", () => {vi.restoreAllMocks();layout.onMobile = false;layout.narrow = true;+ layout.onChange.clear();});/** Renders a `Dropdown`, or a `DropdownPanel` for `panel`. */@@ -420,6 +430,28 @@ describe("Dropdown", () => {cover.remove();});+ it("turns into a placed menu and back as a tablet turns while it is open", async () => {+ layout.onMobile = true;+ const turn = (narrow: boolean) => {+ layout.narrow = narrow;+ for (const listener of layout.onChange) listener();+ };+ const { toggle } = renderDropdown({ mobileBottomSheet: true });+ click(toggle);+ await vi.waitFor(() => expect(popup()?.classList).toContain("mobile-bottom-menu"));++ turn(false);+ await vi.waitFor(() => expect(popup()?.style.top).toBe("82px"));+ expect(popup()?.classList.contains("mobile-bottom-menu")).toBe(false);+ expect(popup()?.style.maxHeight).not.toBe("");++ // Back to the sheet, with nothing inline left for its rules to contend with.+ turn(true);+ await vi.waitFor(() => expect(popup()?.classList).toContain("mobile-bottom-menu"));+ const { left, top, maxHeight } = popup()?.style ?? {};+ expect([ left, top, maxHeight ]).toEqual([ "", "", "" ]);+ });+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 });diff --git a/apps/client/src/widgets/react/Dropdown.tsx b/apps/client/src/widgets/react/Dropdown.tsxindex 1d8bc60916..e6fcd312d5 100644--- a/apps/client/src/widgets/react/Dropdown.tsx+++ b/apps/client/src/widgets/react/Dropdown.tsx@@ -5,7 +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, isNarrowLayout } from "../../services/utils";+import { isMobile, isNarrowLayout, onNarrowLayoutChange } from "../../services/utils";import { focusListItem } from "./FormList";import { useTooltip, useUniqueName } from "./hooks";import { suspendModalFocusTraps } from "./modal_focustrap";@@ -159,8 +159,15 @@ function DropdownToggle({ id, className, buttonClassName, title, text, dropdownCpopup(slot: PopupSlot): ComponentChildren;}) {// 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() && isNarrowLayout();+ // one thing and unpacked here. It follows the layout, as a tablet can turn while it is open.+ const followsLayout = !!mobileBottomSheet && isMobile();+ const [ narrow, setNarrow ] = useState(isNarrowLayout);+ useEffect(() => {+ if (!followsLayout) return;+ setNarrow(isNarrowLayout());+ return onNarrowLayoutChange(() => setNarrow(isNarrowLayout()));+ }, [ followsLayout ]);+ const bottomSheet = followsLayout && narrow;const mobileBackdrop = (!!mobileBackdropProp || !!mobileBottomSheet) && isMobile();const containerRef = useRef<HTMLDivElement | null>(null);const triggerRef = useRef<HTMLButtonElement | null>(null);diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsxindex b4ee09a1ee..b46e356a72 100644--- a/apps/client/src/widgets/react/Popup.tsx+++ b/apps/client/src/widgets/react/Popup.tsx@@ -97,10 +97,13 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gapconst anchorX = "x" in anchor ? anchor.x : undefined;const anchorY = "y" in anchor ? anchor.y : undefined;+ const stylesheetPlaces = useRef(placedByStylesheet);+ stylesheetPlaces.current = placedByStylesheet;useLayoutEffect(() => {const popup = popupRef.current;if (!popup) return;if (placedByStylesheet) {+ clearPlacement(popup);popup.style.visibility = "visible";reportPlaced();return;@@ -112,6 +115,8 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gapconst options = { placement, offset: gap, capHeight, shiftAcross: !(anchor instanceof HTMLElement) };const stopUpdating = autoUpdate(reference, popup, () => void placeFloating(popup, reference, options).then(() => {if (!closed) reportPlaced();+ // Resolved after the stylesheet took over, so what it wrote goes again.+ else if (stylesheetPlaces.current) clearPlacement(popup);}));return () => {closed = true;@@ -193,6 +198,13 @@ function swallowStrayClick(pressed: Node) {window.addEventListener("pointerdown", stop, true);}+/** Removes what `placeFloating()` wrote on `popup`, so the stylesheet places it. */+function clearPlacement(popup: HTMLElement) {+ popup.style.removeProperty("left");+ popup.style.removeProperty("top");+ popup.style.removeProperty("max-height");+}+/** A popup, as the one it opened inside knows it. */interface Layer {/** Whether `target` is in the popup or in a popup opened inside it. */diff --git a/apps/client/src/widgets/react/SegmentedChoice.spec.tsx b/apps/client/src/widgets/react/SegmentedChoice.spec.tsxindex 78bed7917c..ee410b2e18 100644--- a/apps/client/src/widgets/react/SegmentedChoice.spec.tsx+++ b/apps/client/src/widgets/react/SegmentedChoice.spec.tsx@@ -161,8 +161,9 @@ describe("SegmentedChoice", () => {it("comes up from the bottom of the screen, out of the dialog and over a backdrop", () => {isMobileMock.mockReturnValue(true);// A phone's width; happy-dom's window is 1024px wide, a tablet's.+ const phone = { matches: true, addEventListener() {}, removeEventListener() {} };const narrow = vi.spyOn(window, "matchMedia")- .mockReturnValue({ matches: true } as MediaQueryList);+ .mockReturnValue(phone as unknown as MediaQueryList);renderOpened(<SegmentedChoice options={iconOptions} currentValue="dark" onChange={() => {}} collapseOnMobile />);// Placed by the app's own bottom-sheet rule rather than by Popper, which mobile's forced