Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion config/eslint/eslint.seatbelt.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1329,7 +1329,6 @@
"../../src/pages/settings/Wallet/UnshareBankAccount/UnshareBankAccount.tsx" "no-restricted-imports" 1
"../../src/pages/settings/Wallet/UpdatePersonalBankAccountPage.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1
"../../src/pages/settings/Wallet/UpdatePersonalBankAccountPage.tsx" "no-restricted-imports" 1
"../../src/pages/settings/Wallet/WalletPage/index.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2
"../../src/pages/settings/Wallet/WalletPage/index.tsx" "no-restricted-imports" 2
"../../src/pages/settings/Wallet/WalletPage/index.tsx" "react-hooks/set-state-in-effect" 1
"../../src/pages/Share/ShareDetailsPage.tsx" "no-restricted-imports" 1
Expand Down
28 changes: 23 additions & 5 deletions src/components/ThreeDotsMenu/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import KeyboardUtils from '@src/utils/keyboard';

import type {ComponentRef} from 'react';

import debounce from 'lodash/debounce';
import React, {useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState} from 'react';
import {View} from 'react-native';

Expand Down Expand Up @@ -89,6 +90,13 @@ function ThreeDotsMenu({

const getMenuPosition = shouldSelfPosition ? calculateAndSetThreeDotsMenuPosition : getAnchorPosition;

// Most callers pass an inline `anchorAlignment`/`getAnchorPosition`, so `getMenuPosition` gets a new identity on
// every render. It is held in a ref so the reposition effect below can depend on the viewport size alone.
const getMenuPositionRef = useRef(getMenuPosition);
useLayoutEffect(() => {
getMenuPositionRef.current = getMenuPosition;
});

const onThreeDotsPress = () => {
if (isPopupMenuVisible) {
hidePopoverMenu();
Expand Down Expand Up @@ -137,14 +145,24 @@ function ThreeDotsMenu({
}, [hidePopoverMenu, isBehindModal, isPopupMenuVisible, isContainerFocused]);

useLayoutEffect(() => {
if (!getMenuPosition || !isPopupMenuVisible) {
if (!getMenuPositionRef.current || !isPopupMenuVisible) {
return;
}

getMenuPosition?.().then((value) => {
setPosition(value);
});
}, [windowWidth, windowHeight, shouldSelfPosition, getMenuPosition, isPopupMenuVisible]);
// The anchor is re-measured after a debounce so that surrounding layout which settles asynchronously after a
// viewport change (virtualized list cells, for instance) has finished moving the anchor. Measuring immediately
// can read pre-resize coordinates and pin the menu to a stale position.
const debouncedRepositionMenu = debounce(() => {
getMenuPositionRef.current?.().then((value) => {
// Keep the previous object when the measurement is unchanged, so an unchanged position doesn't cascade
// into a re-render of the open menu.
setPosition((previousPosition) => (previousPosition?.horizontal === value.horizontal && previousPosition?.vertical === value.vertical ? previousPosition : value));
});
}, CONST.TIMING.RESIZE_DEBOUNCE_TIME);
debouncedRepositionMenu();

return () => debouncedRepositionMenu.cancel();
}, [windowWidth, windowHeight, isPopupMenuVisible]);

const getIconFill = () => {
if (!shouldChangeFillOnOpen) {
Expand Down
10 changes: 3 additions & 7 deletions src/pages/settings/Wallet/WalletPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ import {hasSeenTourSelector} from '@selectors/Onboarding';
import {isCollectingDepositAccountsSelector} from '@selectors/Policy';
import debounce from 'lodash/debounce';
import isEmpty from 'lodash/isEmpty';
import React, {useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
import React, {useCallback, useContext, useEffect, useMemo, useState} from 'react';
import {View} from 'react-native';

import type {CardPressHandlerParams, PaymentMethodPressHandlerParams} from './types';
Expand Down Expand Up @@ -146,7 +146,6 @@ function WalletPage() {
const {paymentMethod, setPaymentMethod, resetSelectedPaymentMethodData} = usePaymentMethodState();
const {showConfirmModal} = useConfirmModal();
const [shouldShowLoadingSpinner, setShouldShowLoadingSpinner] = useState(false);
const paymentMethodButtonRef = useRef<HTMLDivElement | null>(null);
const [selectedCard, setSelectedCard] = useState<OnyxTypes.Card | undefined>(undefined);
const [shouldShowShareButton, setShouldShowShareButton] = useState(false);
const [shouldShowUnshareButton, setShouldShowUnshareButton] = useState(false);
Expand Down Expand Up @@ -177,9 +176,7 @@ function WalletPage() {
/**
* Display the delete/default menu, or the add payment method menu
*/
const paymentMethodPressed = ({event, accountData, accountType, methodID, isDefault, icon, description}: PaymentMethodPressHandlerParams) => {
paymentMethodButtonRef.current = event?.currentTarget as HTMLDivElement;

const paymentMethodPressed = ({accountData, accountType, methodID, isDefault, icon, description}: PaymentMethodPressHandlerParams) => {
if (accountData?.state === CONST.BANK_ACCOUNT.STATE.LOCKED && accountData?.bankAccountID) {
if (nvpLockedVbaUnlockRequested?.[`${ONYXKEYS.COLLECTION.NVP_LOCKED_VBA_UNLOCK_REQUESTED}${accountData.bankAccountID}`]) {
showUnlockAlreadyRequestedModal(showConfirmModal, translate);
Expand Down Expand Up @@ -270,8 +267,7 @@ function WalletPage() {
navigateToBankAccountRoute({bankAccountID, backTo: ROUTES.SETTINGS_WALLET});
};

const assignedCardPressed = ({event, cardData, icon, cardID}: CardPressHandlerParams) => {
paymentMethodButtonRef.current = event?.currentTarget as HTMLDivElement;
const assignedCardPressed = ({cardData, icon, cardID}: CardPressHandlerParams) => {
setSelectedCard(cardData);
const isCSVImportCard = cardData?.bank === CONST.COMPANY_CARD.FEED_BANK_NAME.UPLOAD;
const cardTitle = isCSVImportCard ? (cardData?.nameValuePairs?.cardTitle ?? cardData?.cardName) : maskCardNumber(cardData?.cardName, cardData?.bank);
Expand Down
137 changes: 137 additions & 0 deletions tests/unit/ThreeDotsMenuRepositionTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import {act, fireEvent, render, screen} from '@testing-library/react-native';

import ThreeDotsMenu from '@components/ThreeDotsMenu';

import CONST from '@src/CONST';

import type {ReactNode} from 'react';

import React from 'react';

type MockPopoverMenuProps = {isVisible?: boolean; anchorPosition?: {horizontal: number; vertical: number}};

const mockMeasuredAnchor = {horizontal: 0, vertical: 0, width: 40, height: 40};
const mockWindowDimensions = {windowWidth: 1400, windowHeight: 900};
const mockMeasureCount = {current: 0};

/** Records every `PopoverMenu` render so assertions can read the `anchorPosition` it was last given while open. */
const mockPopoverRender = jest.fn<void, [MockPopoverMenuProps]>();

jest.mock('@hooks/useWindowDimensions', () => () => mockWindowDimensions);

jest.mock('@hooks/usePopoverPosition', () => () => ({
calculatePopoverPosition: () => {
mockMeasureCount.current++;
return Promise.resolve({...mockMeasuredAnchor});
},
}));

jest.mock('@hooks/useOnyx', () => () => [undefined, {status: 'loaded'}]);

jest.mock('@components/PopoverMenu', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- jest.requireActual returns an untyped module; standard RN-mock pattern in this repo.
const {View: RNView} = jest.requireActual('react-native');
function MockPopoverMenu({isVisible, anchorPosition}: MockPopoverMenuProps) {
mockPopoverRender({isVisible, anchorPosition});
return <RNView testID={isVisible ? 'popover-open' : 'popover-closed'} />;
}
return MockPopoverMenu;
});

jest.mock('@components/Icon', () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- jest.requireActual returns an untyped module; standard RN-mock pattern in this repo.
const {View: RNView} = jest.requireActual('react-native');
function MockIcon() {
return <RNView />;
}
return MockIcon;
});

jest.mock('@components/Tooltip/PopoverAnchorTooltip', () => {
function MockTooltip({children}: {children?: ReactNode}) {
return children;
}
return MockTooltip;
});

jest.mock('@components/Tooltip/EducationalTooltip', () => {
function MockEducationalTooltip({children}: {children?: ReactNode}) {
return children;
}
return MockEducationalTooltip;
});

const setMeasuredAnchor = (horizontal: number, vertical: number) => {
mockMeasuredAnchor.horizontal = horizontal;
mockMeasuredAnchor.vertical = vertical;
};

const menuElement = (
<ThreeDotsMenu
shouldSelfPosition
testID="three-dots-menu"
menuItems={[{text: 'Delete', onSelected: () => {}}]}
/>
);

/** The `anchorPosition` from the most recent render in which the popover was open. */
const lastOpenAnchorPosition = () => mockPopoverRender.mock.calls.map(([props]) => props).findLast((props) => props.isVisible)?.anchorPosition;

/** Lets a pending `calculatePopoverPosition` promise settle without running the reposition debounce. */
const flushPendingMeasurements = () =>
act(async () => {
jest.advanceTimersByTime(0);
});

describe('ThreeDotsMenu repositioning', () => {
beforeEach(() => {
jest.useFakeTimers();
setMeasuredAnchor(1000, 300);
mockWindowDimensions.windowWidth = 1400;
mockWindowDimensions.windowHeight = 900;
mockPopoverRender.mockClear();
mockMeasureCount.current = 0;
});

afterEach(() => {
jest.useRealTimers();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add Given/When/Then sections to each new test

Both added it blocks omit the required literal // Given, // When, and // Then sections explaining why their setup, action, and assertions exist. Add all three documented sections to each test so this regression coverage follows the repository's mandatory test-documentation convention.

AGENTS.md reference: AGENTS.md:L1-L3

Useful? React with 👍 / 👎.


it('re-measures the anchor only after the layout has settled following a viewport change', async () => {
const {rerender} = render(menuElement);

fireEvent.press(screen.getByTestId('three-dots-menu'));
await flushPendingMeasurements();

expect(screen.getByTestId('popover-open')).toBeOnTheScreen();
expect(lastOpenAnchorPosition()?.horizontal).toBe(1000);

// The viewport shrinks. Surrounding layout (a virtualized list, for instance) has not repositioned the
// anchor yet, so measuring at this point would still report the pre-resize coordinates.
mockWindowDimensions.windowWidth = 1000;
rerender(menuElement);
await flushPendingMeasurements();

// The surrounding layout settles and moves the anchor to its post-resize position.
setMeasuredAnchor(700, 300);

await act(async () => {
jest.advanceTimersByTime(CONST.TIMING.RESIZE_DEBOUNCE_TIME);
});

expect(lastOpenAnchorPosition()?.horizontal).toBe(700);
});

it('does not re-measure the anchor while the menu is closed', async () => {
const {rerender} = render(menuElement);
mockMeasureCount.current = 0;

mockWindowDimensions.windowWidth = 1000;
rerender(menuElement);
await act(async () => {
jest.advanceTimersByTime(CONST.TIMING.RESIZE_DEBOUNCE_TIME);
});

expect(mockMeasureCount.current).toBe(0);
});
});
Loading