diff --git a/src/components/DropdownField.tsx b/src/components/DropdownField.tsx index 9f8608a29309..6637ff6d6fe1 100644 --- a/src/components/DropdownField.tsx +++ b/src/components/DropdownField.tsx @@ -1,4 +1,5 @@ import useContentHeaderHeight from '@hooks/useContentHeaderHeight'; +import useRemeasureOnWindowResize from '@hooks/useRemeasureOnWindowResize'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useSafeAreaInsets from '@hooks/useSafeAreaInsets'; import useWindowDimensions from '@hooks/useWindowDimensions'; @@ -11,6 +12,7 @@ import type AnchorAlignment from '@src/types/utils/AnchorAlignment'; import type {ComponentRef, ReactNode, Ref} from 'react'; import type {View} from 'react-native'; +import {shallowEqual} from 'fast-equals'; import React, {useImperativeHandle, useRef, useState} from 'react'; import type {DropdownFieldRowProps} from './DropdownFieldRow'; @@ -42,7 +44,7 @@ const ANCHOR_ALIGNMENT_ABOVE: AnchorAlignment = { vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.BOTTOM, }; -/** Where and how big the container is, measured off the row each time it opens */ +/** Where and how big the container is, measured off the row each time it opens and again whenever the window changes size under it */ type DropdownLayout = { horizontal: number; vertical: number; @@ -139,6 +141,27 @@ function DropdownField({renderDropdown, shouldOpenInDropdown, onPress, listHeade const closeDropdown = () => updateVisibility(false); + /** Measures the row and hands back where the container goes, and whether that side has room for a list */ + const measureLayout = (onMeasured: (measuredLayout: DropdownLayout, hasUsableHeight: boolean) => void) => { + anchorRef.current?.measureInWindow((x, y, width, height) => { + const spaceBelow = windowHeight - (y + height + CONTAINER_GAP); + const spaceAbove = y - CONTAINER_GAP - (safeAreaTop + contentHeaderHeight); + const shouldOpenAbove = spaceBelow < maxContainerHeight && spaceAbove > spaceBelow; + const availableHeight = (shouldOpenAbove ? spaceAbove : spaceBelow) - CONTAINER_BORDER; + + onMeasured( + { + horizontal: x, + vertical: shouldOpenAbove ? y - CONTAINER_GAP : y + height + CONTAINER_GAP, + width, + height: Math.min(maxContainerHeight, availableHeight), + shouldOpenAbove, + }, + availableHeight >= minUsableHeight, + ); + }); + }; + const openDropdown = () => { if (isSmallScreenWidth) { setHasEverOpened(true); @@ -146,29 +169,35 @@ function DropdownField({renderDropdown, shouldOpenInDropdown, onPress, listHeade return; } - anchorRef.current?.measureInWindow((x, y, width, height) => { - const spaceBelow = windowHeight - (y + height + CONTAINER_GAP); - const spaceAbove = y - CONTAINER_GAP - (safeAreaTop + contentHeaderHeight); - const shouldOpenAbove = spaceBelow < maxContainerHeight && spaceAbove > spaceBelow; - const availableHeight = (shouldOpenAbove ? spaceAbove : spaceBelow) - CONTAINER_BORDER; - - if (availableHeight < minUsableHeight && onPress) { + measureLayout((measuredLayout, hasUsableHeight) => { + if (!hasUsableHeight && onPress) { onPress(); return; } - setLayout({ - horizontal: x, - vertical: shouldOpenAbove ? y - CONTAINER_GAP : y + height + CONTAINER_GAP, - width, - height: Math.min(maxContainerHeight, availableHeight), - shouldOpenAbove, - }); + setLayout(measuredLayout); setHasEverOpened(true); updateVisibility(true); }); }; + const remeasureOpenDropdown = (isStale: () => boolean) => { + measureLayout((measuredLayout, hasUsableHeight) => { + if (isStale()) { + return; + } + // Pressing the row here would have opened its page instead, but a resize is no reason to navigate, so the list just closes. + if (!hasUsableHeight && onPress) { + closeDropdown(); + return; + } + setLayout((currentLayout) => (shallowEqual(currentLayout, measuredLayout) ? currentLayout : measuredLayout)); + }); + }; + + // The row moves and resizes with the window, so an open pop-over is placed off it again. A bottom sheet doesn't hang off the row. + useRemeasureOnWindowResize(isVisible && !isSmallScreenWidth, remeasureOpenDropdown); + const handlePress = () => { if (!shouldOpenInDropdown) { onPress?.(); diff --git a/src/components/PopoverWithMeasuredContent/PopoverWithMeasuredContentBase.tsx b/src/components/PopoverWithMeasuredContent/PopoverWithMeasuredContentBase.tsx index 7a62ce15a88a..80be901962c5 100644 --- a/src/components/PopoverWithMeasuredContent/PopoverWithMeasuredContentBase.tsx +++ b/src/components/PopoverWithMeasuredContent/PopoverWithMeasuredContentBase.tsx @@ -72,7 +72,10 @@ function PopoverWithMeasuredContentBase({ const hasStaticDimensions = popoverDimensions.width > 0 && popoverDimensions.height > 0; const modalId = ComposerFocusManager.getId(); - // Static dimensions skip `onLayout`, so sync height changes from the prop. + // Static dimensions skip `onLayout`, so sync size changes from the prop. + if (hasStaticDimensions && popoverWidth !== popoverDimensions.width) { + setPopoverWidth(popoverDimensions.width); + } if (hasStaticDimensions && popoverHeight !== popoverDimensions.height) { setPopoverHeight(popoverDimensions.height); } diff --git a/src/hooks/useRemeasureOnWindowResize/index.native.ts b/src/hooks/useRemeasureOnWindowResize/index.native.ts new file mode 100644 index 000000000000..83ff90a7d418 --- /dev/null +++ b/src/hooks/useRemeasureOnWindowResize/index.native.ts @@ -0,0 +1,9 @@ +import type UseRemeasureOnWindowResize from './types'; + +/** + * A native window can't be dragged to a new size. It only changes size on rotation, split view or, on Android, when the + * keyboard shows, and re-measuring then would move or close a list while its search is being typed in. + */ +const useRemeasureOnWindowResize: UseRemeasureOnWindowResize = () => {}; + +export default useRemeasureOnWindowResize; diff --git a/src/hooks/useRemeasureOnWindowResize/index.ts b/src/hooks/useRemeasureOnWindowResize/index.ts new file mode 100644 index 000000000000..bb7ec749caa6 --- /dev/null +++ b/src/hooks/useRemeasureOnWindowResize/index.ts @@ -0,0 +1,34 @@ +import useWindowDimensions from '@hooks/useWindowDimensions'; + +import CONST from '@src/CONST'; + +import {useEffect, useEffectEvent} from 'react'; + +import type UseRemeasureOnWindowResize from './types'; + +/** + * Keeps something anchored to an element in place while the browser window is resized, e.g. a pop-over under a row in + * the RHP, which follows the window's right edge. The RHP only takes the new width after its own layout pass, so a + * measurement on the same frame still sees the element a step behind: it keeps the pop-over close while the window is + * dragged, and the element is measured once more after the resize settles. The first run also happens as soon as the + * hook turns active. + */ +const useRemeasureOnWindowResize: UseRemeasureOnWindowResize = (isActive, remeasure) => { + const {windowWidth, windowHeight} = useWindowDimensions(); + const onRemeasure = useEffectEvent(remeasure); + + useEffect(() => { + if (!isActive) { + return; + } + let isStale = false; + onRemeasure(() => isStale); + const settledRemeasureTimeout = setTimeout(() => onRemeasure(() => isStale), CONST.TIMING.RESIZE_DEBOUNCE_TIME); + return () => { + isStale = true; + clearTimeout(settledRemeasureTimeout); + }; + }, [isActive, windowWidth, windowHeight]); +}; + +export default useRemeasureOnWindowResize; diff --git a/src/hooks/useRemeasureOnWindowResize/types.ts b/src/hooks/useRemeasureOnWindowResize/types.ts new file mode 100644 index 000000000000..05bb6347f8f6 --- /dev/null +++ b/src/hooks/useRemeasureOnWindowResize/types.ts @@ -0,0 +1,12 @@ +/** + * Measures the anchor again and applies the result. Call `isStale` once the measurement comes back: it is true when the + * window changed again or the hook went inactive in the meantime, and the result should then be dropped. + */ +type UseRemeasureOnWindowResizeCallback = (isStale: () => boolean) => void; + +/** + * Calls `remeasure` while `isActive`, whenever the window changes size. The callback doesn't need to be stable. + */ +type UseRemeasureOnWindowResize = (isActive: boolean, remeasure: UseRemeasureOnWindowResizeCallback) => void; + +export default UseRemeasureOnWindowResize; diff --git a/tests/unit/PopoverWithMeasuredContentPositionTest.tsx b/tests/unit/PopoverWithMeasuredContentPositionTest.tsx index 73d65efc76b3..8f188aa3bb16 100644 --- a/tests/unit/PopoverWithMeasuredContentPositionTest.tsx +++ b/tests/unit/PopoverWithMeasuredContentPositionTest.tsx @@ -17,9 +17,10 @@ const POPOVER_HEIGHT = 400; const POPOVER_WIDTH = 300; const WINDOW_MARGIN = CONST.MODAL.POPOVER_MENU_PADDING; +const mockWindowWidth = 1000; let mockAnchorPosition: PopoverAnchorPosition | undefined; -jest.mock('@hooks/useWindowDimensions', () => () => ({windowWidth: 1000, windowHeight: 600})); +jest.mock('@hooks/useWindowDimensions', () => () => ({windowWidth: mockWindowWidth, windowHeight: 600})); jest.mock('@components/Popover', () => { const MockPopover = ({anchorPosition, children}: {anchorPosition: PopoverAnchorPosition; children: ReactNode}) => { @@ -48,6 +49,33 @@ function renderPopoverAt(vertical: number, verticalAlignment: ValueOf { + it('positions the popover by its current width when a static width changes while it is open', () => { + // Given an open popover as wide as its anchor row, which ends a gutter short of the window's right edge + const ROW_RIGHT_EDGE = mockWindowWidth - 20; + const buildPopover = (width: number) => ( + {}} + anchorRef={createRef>()} + anchorPosition={{horizontal: ROW_RIGHT_EDGE - width, vertical: 100}} + anchorAlignment={{horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT, vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.TOP}} + popoverDimensions={{height: POPOVER_HEIGHT, width}} + > + content + + ); + const {rerender} = render(buildPopover(POPOVER_WIDTH)); + + // When the row gets narrower and the popover is given the new width and left edge + const narrowerWidth = POPOVER_WIDTH - 100; + rerender(buildPopover(narrowerWidth)); + + // Then it stays on the row's left edge, since the width it opened with would look like an overflow and shift it left + expect(mockAnchorPosition?.left).toBe(ROW_RIGHT_EDGE - narrowerWidth); + }); +}); + describe('PopoverWithMeasuredContentBase vertical positioning', () => { describe('BOTTOM alignment (popover opens above the anchor)', () => { it('pins the popover bottom edge to the anchor when the popover fits above it', () => { diff --git a/tests/unit/components/DropdownField.test.tsx b/tests/unit/components/DropdownField.test.tsx index b1027e1949d8..641a68480684 100644 --- a/tests/unit/components/DropdownField.test.tsx +++ b/tests/unit/components/DropdownField.test.tsx @@ -23,10 +23,13 @@ import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates'; let mockIsSmallScreenWidth = false; jest.mock('@hooks/useResponsiveLayout', () => jest.fn(() => ({isSmallScreenWidth: mockIsSmallScreenWidth, shouldUseNarrowLayout: mockIsSmallScreenWidth}))); // Read lazily so a test can shrink the viewport, leaving the row short of room on both sides at once. -let mockWindowHeight = 800; -jest.mock('@hooks/useWindowDimensions', () => jest.fn(() => ({windowWidth: 1280, windowHeight: mockWindowHeight}))); - const WINDOW_HEIGHT = 800; +const WINDOW_WIDTH = 1280; +let mockWindowHeight = WINDOW_HEIGHT; +let mockWindowWidth = WINDOW_WIDTH; +jest.mock('@hooks/useWindowDimensions', () => jest.fn(() => ({windowWidth: mockWindowWidth, windowHeight: mockWindowHeight}))); +// Jest resolves the native no-op, but a window is only dragged to a new size on web, which is what these tests cover. +jest.mock('@hooks/useRemeasureOnWindowResize', () => jest.requireActual>('@hooks/useRemeasureOnWindowResize/index.ts')); const FIELD_NAME = 'Category'; const ROW_TEST_ID = 'category-row'; @@ -44,11 +47,10 @@ const pressRow = () => fireEvent.press(screen.getByTestId(ROW_TEST_ID), {nativeE * Stands in for the measurement the row does when it opens: the container is positioned off the row's real * geometry, which the test renderer never lays out, so each test says where the row sits instead. */ -const mockRowAt = (rowTop: number) => { +const mockRowAt = (rowTop: number, rowX = ROW_X, rowWidth = ROW_WIDTH) => jest.spyOn(View.prototype, 'measureInWindow').mockImplementation((callback) => { - callback(ROW_X, rowTop, ROW_WIDTH, ROW_HEIGHT); + callback(rowX, rowTop, rowWidth, ROW_HEIGHT); }); -}; describe('DropdownField', () => { let renderedProps: DropdownFieldRenderProps | undefined; @@ -68,6 +70,7 @@ describe('DropdownField', () => { renderedProps = undefined; renderCount = 0; mockWindowHeight = WINDOW_HEIGHT; + mockWindowWidth = WINDOW_WIDTH; mockIsSmallScreenWidth = false; await Onyx.clear(); await waitForBatchedUpdates(); @@ -77,18 +80,19 @@ describe('DropdownField', () => { jest.restoreAllMocks(); }); - const renderField = (shouldOpenInDropdown = true, onPress: () => void = jest.fn(), listHeaderHeight?: number) => - render( - , - ); + const buildField = (shouldOpenInDropdown = true, onPress: () => void = jest.fn(), listHeaderHeight?: number) => ( + + ); + + const renderField = (shouldOpenInDropdown = true, onPress: () => void = jest.fn(), listHeaderHeight?: number) => render(buildField(shouldOpenInDropdown, onPress, listHeaderHeight)); describe('with a header above the list', () => { const HEADER_HEIGHT = variables.componentSizeNormal; @@ -334,6 +338,145 @@ describe('DropdownField', () => { expect(onPress).not.toHaveBeenCalled(); }); + describe('when the window is resized', () => { + // A narrower window, and the row moved and narrowed along with it + const RESIZE_DELTA = 40; + const RESIZED_WINDOW_WIDTH = WINDOW_WIDTH - RESIZE_DELTA; + const RESIZED_ROW_X = ROW_X + RESIZE_DELTA; + const RESIZED_ROW_WIDTH = ROW_WIDTH - RESIZE_DELTA; + + // The row is measured once more after a resize settles, so these tests step the clock past that wait + const waitForResizeToSettle = () => act(() => jest.advanceTimersByTime(CONST.TIMING.RESIZE_DEBOUNCE_TIME)); + + // Opening the list schedules that same settled measurement, so it is let run first and can't stand in for the one a resize schedules + const openListAndSettle = () => { + act(() => pressRow()); + waitForResizeToSettle(); + }; + + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + + it('follows the row to its new place and width once the resize settles', () => { + // Given a field whose list is open, pinned to where the row sat when it was pressed + const onPress = jest.fn(); + mockRowAt(ROW_TOP); + const {rerender} = renderField(true, onPress); + openListAndSettle(); + + // When the window narrows, and the row only reaches its new place and width a moment later, once the RHP has laid + // itself out at the new size + mockWindowWidth = RESIZED_WINDOW_WIDTH; + rerender(buildField(true, onPress)); + mockRowAt(ROW_TOP, RESIZED_ROW_X, RESIZED_ROW_WIDTH); + waitForResizeToSettle(); + + // Then the pop-over is placed off where the row ended up, instead of where it was on the frame the window changed + expect(renderedProps?.popoverWidth).toBe(RESIZED_ROW_WIDTH); + expect(renderedProps?.anchorPosition.horizontal).toBe(RESIZED_ROW_X); + }); + + it('follows the row while the window is still being resized', () => { + // Given a field whose list is open + const onPress = jest.fn(); + mockRowAt(ROW_TOP); + const {rerender} = renderField(true, onPress); + openListAndSettle(); + + // When the window narrows and the row has already moved, with the resize not settled yet, as on every step of a drag + mockWindowWidth = RESIZED_WINDOW_WIDTH; + mockRowAt(ROW_TOP, RESIZED_ROW_X, RESIZED_ROW_WIDTH); + rerender(buildField(true, onPress)); + + // Then the pop-over is placed off the row right away, so it doesn't hang where the drag started until the window stops + expect(renderedProps?.popoverWidth).toBe(RESIZED_ROW_WIDTH); + expect(renderedProps?.anchorPosition.horizontal).toBe(RESIZED_ROW_X); + }); + + it('places a list opened as a bottom sheet under the row once the layout turns wide', () => { + // Given a narrow layout, where the list opened as a bottom sheet without measuring the row + const onPress = jest.fn(); + mockIsSmallScreenWidth = true; + mockRowAt(ROW_TOP); + const {rerender} = renderField(true, onPress); + act(() => pressRow()); + + // When the window widens past the breakpoint while the list is still open + mockIsSmallScreenWidth = false; + rerender(buildField(true, onPress)); + waitForResizeToSettle(); + + // Then the pop-over is placed and sized off the row, not in the window's corner at the default width + expect(renderedProps?.popoverWidth).toBe(ROW_WIDTH); + expect(renderedProps?.anchorPosition.horizontal).toBe(ROW_X); + }); + + it('leaves a bottom sheet open and unmeasured when the window gets shorter', () => { + // Given a narrow layout, where the list is open as a bottom sheet + const onPress = jest.fn(); + mockIsSmallScreenWidth = true; + const measureSpy = mockRowAt(120); + const {rerender} = renderField(true, onPress); + act(() => pressRow()); + // The spy sits on the shared View prototype, so it starts this test with calls from earlier ones + measureSpy.mockClear(); + + // When the window gets so short that a pop-over would have no room next to the row + mockWindowHeight = 300; + rerender(buildField(true, onPress)); + waitForResizeToSettle(); + + // Then the sheet stays open, since it is docked to the bottom of the window and doesn't depend on where the row is + expect(screen.getByText(DROPDOWN_TEXT)).toBeTruthy(); + expect(measureSpy).not.toHaveBeenCalled(); + }); + + it('closes the list instead of opening the page when the window leaves no room for it', () => { + // Given a field whose list is open below the row + const onPress = jest.fn(); + mockRowAt(120); + const {rerender} = renderField(true, onPress); + openListAndSettle(); + + // When the window gets so short that neither side of the row has room for a list + mockWindowHeight = 300; + rerender(buildField(true, onPress)); + waitForResizeToSettle(); + + // Then the list closes rather than shrinking to nothing, and the page does not open, since a resize is no reason to navigate + expect(screen.queryByText(DROPDOWN_TEXT)).toBeNull(); + expect(onPress).not.toHaveBeenCalled(); + }); + + it('ignores a measurement that lands after the list closed', () => { + // Given an open list, and a row that answers its measurements later, as it does on native + const onPress = jest.fn(); + mockRowAt(ROW_TOP); + const {rerender} = renderField(true, onPress); + openListAndSettle(); + let answerMeasurement: (() => void) | undefined; + jest.spyOn(View.prototype, 'measureInWindow').mockImplementation((callback) => { + answerMeasurement = () => callback(RESIZED_ROW_X, ROW_TOP, RESIZED_ROW_WIDTH, ROW_HEIGHT); + }); + + // When the window narrows, and the list closes before the last measurement comes back + mockWindowWidth = RESIZED_WINDOW_WIDTH; + rerender(buildField(true, onPress)); + waitForResizeToSettle(); + act(() => pressRow()); + act(() => answerMeasurement?.()); + + // Then the closed list keeps the layout it had, instead of taking a measurement meant for an open one + expect(renderedProps?.isVisible).toBe(false); + expect(renderedProps?.popoverWidth).toBe(ROW_WIDTH); + }); + }); + it('closes the list when the row is pressed again', () => { // Given a field whose list is already open mockRowAt(ROW_TOP);