diff --git a/src/components/ApproverSelectionList.tsx b/src/components/ApproverSelectionList.tsx index cbe431e5762d..2775c1edf2ab 100644 --- a/src/components/ApproverSelectionList.tsx +++ b/src/components/ApproverSelectionList.tsx @@ -1,4 +1,5 @@ import useDebouncedState from '@hooks/useDebouncedState'; +import useInitialSelection from '@hooks/useInitialSelection'; import {useMemoizedLazyIllustrations} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; @@ -7,6 +8,7 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {canUseTouchScreen} from '@libs/DeviceCapabilities'; import {getSearchValueForPhoneOrEmail, sortAlphabetically} from '@libs/OptionsListUtils'; import {goBackFromInvalidPolicy, isPendingDeletePolicy, isPolicyAdmin} from '@libs/PolicyUtils'; +import moveInitialSelectionToTop from '@libs/SelectionListOrderUtils'; import tokenizedSearch from '@libs/tokenizedSearch'; import variables from '@styles/variables'; @@ -33,7 +35,6 @@ type ApproverSelectionListPageProps = { policy?: Policy; isLoadingReportData?: boolean; onBackButtonPress: () => void; - initiallyFocusedOptionKey?: string; shouldShowNotFoundView?: boolean; shouldShowNotFoundViewLink?: boolean; listEmptyContentSubtitle?: string; @@ -52,7 +53,7 @@ type ApproverSelectionListPageProps = { }; type SelectionListApprover = ListItem & { - value?: number; + value?: number | string; }; function ApproverSelectionList({ @@ -62,7 +63,6 @@ function ApproverSelectionList({ isLoadingReportData, policy, onBackButtonPress, - initiallyFocusedOptionKey, shouldShowTextInput: shouldShowTextInputProp, shouldShowNotFoundView: shouldShowNotFoundViewProp = false, shouldShowNotFoundViewLink = true, @@ -96,18 +96,20 @@ function ApproverSelectionList({ ); const selectedMembers = useMemo(() => allApprovers.filter((approver) => approver.isSelected), [allApprovers]); + const selectedApproverKeys = useMemo(() => selectedMembers.map((approver) => approver.value?.toString() ?? '').filter(Boolean), [selectedMembers]); + const initialSelectedApproverKeys = useInitialSelection(selectedApproverKeys, {isVisible: !shouldShowLoadingPlaceholder && allApprovers.length > 0, resetOnFocus: true}); + const initiallyFocusedApproverKey = allApprovers.find((approver) => initialSelectedApproverKeys.includes(String(approver.value)))?.keyForList; + const selectionListKey = initialSelectedApproverKeys.join(','); const shouldShowNotFoundView = (isEmptyObject(policy) && !isLoadingReportData) || (shouldRequirePolicyAdmin && !isPolicyAdmin(policy)) || isPendingDeletePolicy(policy) || shouldShowNotFoundViewProp; const data = useMemo(() => { - const filteredApprovers = - debouncedSearchTerm !== '' - ? tokenizedSearch(allApprovers, getSearchValueForPhoneOrEmail(debouncedSearchTerm, countryCode), (option) => [option.text ?? '', option.login ?? '']) - : allApprovers; + const sortedApprovers = sortAlphabetically(allApprovers, 'text', localeCompare); + const orderedApprovers = moveInitialSelectionToTop(sortedApprovers, initialSelectedApproverKeys); - return sortAlphabetically(filteredApprovers, 'text', localeCompare); - }, [allApprovers, debouncedSearchTerm, countryCode, localeCompare]); + return tokenizedSearch(orderedApprovers, getSearchValueForPhoneOrEmail(debouncedSearchTerm, countryCode), (option) => [option.text ?? '', option.login ?? '']); + }, [allApprovers, debouncedSearchTerm, countryCode, localeCompare, initialSelectedApproverKeys]); const shouldShowListEmptyContent = !debouncedSearchTerm && !data.length && shouldShowListEmptyContentProp; @@ -172,6 +174,7 @@ function ApproverSelectionList({ /> {subtitle} diff --git a/src/libs/SelectionListOrderUtils.ts b/src/libs/SelectionListOrderUtils.ts index 6976d64f338e..a5f9777dbe52 100644 --- a/src/libs/SelectionListOrderUtils.ts +++ b/src/libs/SelectionListOrderUtils.ts @@ -1,6 +1,6 @@ import CONST from '@src/CONST'; -function moveInitialSelectionToTop(items: T[], initialSelectedValues: string[]): T[] { +function moveInitialSelectionToTop(items: T[], initialSelectedValues: string[]): T[] { if (initialSelectedValues.length === 0 || items.length < CONST.STANDARD_LIST_ITEM_LIMIT) { return items; } @@ -10,7 +10,7 @@ function moveInitialSelectionToTop(items: T[], initia const remaining: T[] = []; for (const item of items) { - if (selectedValues.has(item.value)) { + if (item.value !== undefined && selectedValues.has(String(item.value))) { selected.push(item); continue; } diff --git a/src/pages/ReportAddApproverPage.tsx b/src/pages/ReportAddApproverPage.tsx index 5272f28acb5e..d53219ba6663 100644 --- a/src/pages/ReportAddApproverPage.tsx +++ b/src/pages/ReportAddApproverPage.tsx @@ -146,7 +146,6 @@ function ReportAddApproverPage({report, isLoadingReportData, policy}: ReportAddA subtitle={{translate('iou.changeApprover.addApprover.subtitle')}} isLoadingReportData={isLoadingReportData} policy={policy} - initiallyFocusedOptionKey={selectedApproverEmail} shouldShowNotFoundViewLink={false} shouldShowNotFoundView={shouldShowNotFoundView} allApprovers={allApprovers} diff --git a/src/pages/Search/SearchAddApproverPage.tsx b/src/pages/Search/SearchAddApproverPage.tsx index 2cf7e98fed18..02261cfd94a1 100644 --- a/src/pages/Search/SearchAddApproverPage.tsx +++ b/src/pages/Search/SearchAddApproverPage.tsx @@ -202,7 +202,6 @@ function SearchAddApproverPage() { } isLoadingReportData={false} policy={allPolicies?.[`${ONYXKEYS.COLLECTION.POLICY}${selectedReports.at(0)?.policyID}`]} - initiallyFocusedOptionKey={selectedApproverEmail} shouldShowNotFoundViewLink={false} shouldShowNotFoundView={false} allApprovers={allApprovers} diff --git a/src/pages/workspace/WorkspaceInviteMessageApproverPage.tsx b/src/pages/workspace/WorkspaceInviteMessageApproverPage.tsx index 8a648e0f411f..277edb737e63 100644 --- a/src/pages/workspace/WorkspaceInviteMessageApproverPage.tsx +++ b/src/pages/workspace/WorkspaceInviteMessageApproverPage.tsx @@ -87,6 +87,7 @@ function WorkspaceInviteMessageApproverPage({policy, personalDetails, isLoadingR keyForList: email, isSelected: selectedApprover === email, login: email, + value: email, icons: [{source: avatar ?? icons.FallbackAvatar, type: CONST.ICON_TYPE_AVATAR, name: displayName, id: accountID}], rightElement: ( ; @@ -67,7 +67,6 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe const personalDetailLogins = useMemo(() => Object.fromEntries(Object.entries(personalDetails ?? {}).map(([id, details]) => [id, details?.login])), [personalDetails]); const isLoadingApprovalWorkflow = isLoadingOnyxValue(approvalWorkflowResults); - const [selectedMembers, setSelectedMembers] = useState([]); const canWriteApprovals = canMemberWrite(policy, currentUserLogin, CONST.POLICY.POLICY_FEATURE.WORKFLOWS_APPROVALS); // Set true when nextStep navigates to the invite-message page so the cleanup // effect below knows to leave the draft intact for that page to consume. @@ -119,73 +118,69 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe return map; })(); - useEffect(() => { + const selectedMembers = ((): SelectionListApprover[] => { if (!approvalWorkflow?.members) { - return; + return []; } - // Intentional: derives the selected-members list from the approval workflow data. - // This effect synchronizes local component state with the Onyx-sourced workflow when it changes. - // eslint-disable-next-line react-hooks/set-state-in-effect - setSelectedMembers( - approvalWorkflow.members - .filter((member) => { - const isPolicyMember = !!policy?.employeeList?.[normalizeLogin(member.email)]; - // Keep policy members. For non-policy members, only keep if they're - // in the invite draft (meaning an invite flow is actively in progress). - // This mirrors the card flow's handleBackButtonPress cleanup pattern. - return isPolicyMember || invitedEmailsToAccountIDsDraft?.[member.email] != null; - }) - .map((member) => { - let accountID = Number(policyMemberEmailsToAccountIDs[normalizeLogin(member.email)] ?? ''); - const isPolicyMember = !!policy?.employeeList?.[normalizeLogin(member.email)]; - - const personalDetail = getPersonalDetailByEmail(member.email); - - // Fall back when getMemberAccountIDsForWorkspace can't resolve an accountID — for - // example a freshly invited user whose personal details haven't fully synced yet - // (the helper requires personalDetail.login). Without a real accountID, - // ReportActionAvatars renders the FallbackAvatar instead of the default avatar - // assigned to that account. - if (!accountID) { - const draftAccountID = invitedEmailsToAccountIDsDraft?.[member.email]; - if (personalDetail?.accountID) { - accountID = personalDetail.accountID; - } else if (draftAccountID) { - accountID = draftAccountID; - } + return approvalWorkflow.members + .filter((member) => { + const isPolicyMember = !!policy?.employeeList?.[normalizeLogin(member.email)]; + // Keep policy members. For non-policy members, only keep if they're + // in the invite draft (meaning an invite flow is actively in progress). + // This mirrors the card flow's handleBackButtonPress cleanup pattern. + return isPolicyMember || invitedEmailsToAccountIDsDraft?.[member.email] != null; + }) + .map((member) => { + let accountID = Number(policyMemberEmailsToAccountIDs[normalizeLogin(member.email)] ?? ''); + const isPolicyMember = !!policy?.employeeList?.[normalizeLogin(member.email)]; + + const personalDetail = getPersonalDetailByEmail(member.email); + + // Fall back when getMemberAccountIDsForWorkspace can't resolve an accountID — for + // example a freshly invited user whose personal details haven't fully synced yet + // (the helper requires personalDetail.login). Without a real accountID, + // ReportActionAvatars renders the FallbackAvatar instead of the default avatar + // assigned to that account. + if (!accountID) { + const draftAccountID = invitedEmailsToAccountIDsDraft?.[member.email]; + if (personalDetail?.accountID) { + accountID = personalDetail.accountID; + } else if (draftAccountID) { + accountID = draftAccountID; } + } - const login = personalDetailLogins?.[accountID] ?? member.email; - const displayName = member.displayName ?? personalDetail?.displayName ?? member.email; - const avatar = member.avatar ?? personalDetail?.avatar; - - return { - text: Str.removeSMSDomain(displayName), - alternateText: member.email, - keyForList: member.email, - isSelected: true, - login: member.email, - icons: [ - { - source: avatar ?? icons.FallbackAvatar, - type: CONST.ICON_TYPE_AVATAR, - name: Str.removeSMSDomain(displayName), - id: accountID, - }, - ], - // Only show right element for policy members - rightElement: isPolicyMember ? ( - - ) : undefined, - }; - }), - ); - }, [approvalWorkflow?.members, icons.FallbackAvatar, invitedEmailsToAccountIDsDraft, personalDetailLogins, policy?.employeeList, policy?.owner, policyMemberEmailsToAccountIDs]); + const login = personalDetailLogins?.[accountID] ?? member.email; + const displayName = member.displayName ?? personalDetail?.displayName ?? member.email; + const avatar = member.avatar ?? personalDetail?.avatar; + + return { + text: Str.removeSMSDomain(displayName), + alternateText: member.email, + keyForList: member.email, + isSelected: true, + login: member.email, + value: member.email, + icons: [ + { + source: avatar ?? icons.FallbackAvatar, + type: CONST.ICON_TYPE_AVATAR, + name: Str.removeSMSDomain(displayName), + id: accountID, + }, + ], + // Only show right element for policy members + rightElement: isPolicyMember ? ( + + ) : undefined, + }; + }); + })(); const workflowApprovers = approvalWorkflow?.approvers; @@ -220,6 +215,7 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe keyForList: member.email, isSelected: false, login: member.email, + value: member.email, icons: [ { source: member.avatar ?? icons.FallbackAvatar, @@ -258,6 +254,7 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe keyForList: userToInvite.login ?? '', isSelected: false, login: userToInvite.login ?? '', + value: userToInvite.login ?? '', icons: userToInvite.icons ?? [], }); } @@ -273,6 +270,7 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe keyForList: option.login ?? '', isSelected: false, login: option.login ?? '', + value: option.login ?? '', icons: option.icons ?? [], }); } @@ -447,10 +445,10 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe const applySelection = (nextMembers: SelectionListApprover[]) => { // Persist non-policy members to the invite draft AND to approvalWorkflow.members // so they survive re-renders triggered by Onyx updates (e.g. personalDetails - // changes from search results). The effect that syncs selectedMembers from - // approvalWorkflow.members filters non-policy members unless they're in the - // invite draft, so both stores must stay in sync to avoid dropping the locally - // selected new member. + // changes from search results). selectedMembers is derived from + // approvalWorkflow.members and only keeps non-policy members that are also in the + // invite draft, so both stores must stay in sync to avoid dropping the newly + // selected member. const nextDraft: Record = {}; const workflowMembers: Member[] = []; for (const member of nextMembers) { @@ -471,7 +469,6 @@ function DynamicWorkspaceWorkflowsApprovalsExpensesFromPage({policy, isLoadingRe } setWorkspaceInviteMembersDraft(route.params.policyID, nextDraft); setApprovalWorkflowMembers(workflowMembers); - setSelectedMembers(nextMembers); }; // Only show warning when creating a new workflow and a member is being added (not removed) diff --git a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApproverPage.tsx b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApproverPage.tsx index d58de1e3e432..9515a7b8bc74 100644 --- a/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApproverPage.tsx +++ b/src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsApproverPage.tsx @@ -118,6 +118,7 @@ function WorkspaceWorkflowsApprovalsApproverPage({policy, personalDetails, isLoa keyForList: email, isSelected: visibleSelectedApproverEmail === email, login: email, + value: email, icons: [{source: avatar ?? icons.FallbackAvatar, type: CONST.ICON_TYPE_AVATAR, name: displayName, id: accountID}], rightElement: ( { + const actualNavigation: typeof ReactNavigation = jest.requireActual('@react-navigation/native'); + const ReactMock = jest.requireActual('react'); + + return { + ...actualNavigation, + useFocusEffect: jest.fn((callback: () => void) => { + ReactMock.useEffect(() => { + if (!mockIsFocused) { + return; + } + + return callback(); + }, [callback, mockIsFocused]); + }), + }; +}); + +jest.mock('@components/SelectionList', () => jest.fn(() => null)); +jest.mock('@components/SelectionList/ListItem/InviteMemberListItem', () => jest.fn(() => null)); +jest.mock('@components/ScreenWrapper', () => jest.fn(({children}: PropsWithChildren) => children)); +jest.mock('@components/HeaderWithBackButton', () => jest.fn(() => null)); +jest.mock('@components/BlockingViews/BlockingView', () => jest.fn(() => null)); +jest.mock('@components/BlockingViews/FullPageNotFoundView', () => jest.fn(({children}: PropsWithChildren) => children)); +jest.mock('@hooks/useDebouncedState', () => + jest.fn((initialValue: string) => { + const [value, setValue] = mockUseState(initialValue); + return [value, value, setValue]; + }), +); +jest.mock('@hooks/useLazyAsset', () => ({ + useMemoizedLazyIllustrations: jest.fn(() => ({TurtleInShell: 'turtle'})), +})); +jest.mock('@hooks/useLocalize', () => + jest.fn(() => ({ + translate: (key: string) => key, + localeCompare: (a: string, b: string) => a.localeCompare(b), + })), +); +jest.mock('@hooks/useOnyx', () => jest.fn(() => ['US'])); +jest.mock('@hooks/useThemeStyles', () => + jest.fn(() => ({ + pb10: {}, + textSupporting: {}, + })), +); +jest.mock('@libs/DeviceCapabilities', () => ({ + canUseTouchScreen: jest.fn(() => false), +})); +jest.mock('@libs/PolicyUtils', () => ({ + goBackFromInvalidPolicy: jest.fn(), + isPendingDeletePolicy: jest.fn(() => false), + isPolicyAdmin: jest.fn(() => true), +})); + +type MockSelectionListProps = { + data: SelectionListApprover[]; + onSelectRow?: (approver: SelectionListApprover) => void; + initiallyFocusedItemKey?: string; + textInputOptions?: { + onChangeText?: (value: string) => void; + }; +}; + +const selectedApprover = 'user9@example.com'; +const updatedApprover = 'user8@example.com'; + +function buildApprovers(selectedLogin: string | null = selectedApprover) { + return Array.from({length: CONST.STANDARD_LIST_ITEM_LIMIT + 2}, (_, index): SelectionListApprover => { + const login = `user${index}@example.com`; + + return { + text: `User ${index}`, + alternateText: login, + keyForList: login, + value: index, + login, + icons: [], + isSelected: login === selectedLogin, + }; + }); +} + +function renderApproverSelectionList(allApprovers = buildApprovers(), shouldShowLoadingPlaceholder = false) { + return render( + , + ); +} + +describe('ApproverSelectionList', () => { + const mockedSelectionList = jest.mocked(SelectionList); + + beforeEach(() => { + mockedSelectionList.mockClear(); + mockIsFocused = true; + }); + + it('pins the initially selected approver to the top on open', () => { + renderApproverSelectionList(); + + const selectionListProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + + expect(selectionListProps?.data.at(0)).toEqual( + expect.objectContaining({ + keyForList: selectedApprover, + isSelected: true, + }), + ); + expect(selectionListProps?.initiallyFocusedItemKey).toBe(selectedApprover); + }); + + it('keeps the initial approver pinned while the live selection changes during the same mount', () => { + const {rerender} = renderApproverSelectionList(); + + rerender( + , + ); + + const selectionListProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + + expect(selectionListProps?.data.at(0)).toEqual( + expect.objectContaining({ + keyForList: selectedApprover, + isSelected: false, + }), + ); + expect(selectionListProps?.data.find((item) => item.keyForList === updatedApprover)).toEqual( + expect.objectContaining({ + keyForList: updatedApprover, + isSelected: true, + }), + ); + expect(selectionListProps?.initiallyFocusedItemKey).toBe(selectedApprover); + }); + + it('pins the selected approver when selection data arrives after list data', () => { + const {rerender} = renderApproverSelectionList(buildApprovers(null), true); + + rerender( + , + ); + + const selectionListProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + + expect(selectionListProps?.data.at(0)).toEqual( + expect.objectContaining({ + keyForList: selectedApprover, + isSelected: true, + }), + ); + expect(selectionListProps?.initiallyFocusedItemKey).toBe(selectedApprover); + }); + + it('does not pin a newly selected approver after user interaction during the same mount', () => { + const {rerender} = renderApproverSelectionList(buildApprovers(null)); + + let selectionListProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + act(() => { + const approverToSelect = selectionListProps?.data.find((item) => item.keyForList === selectedApprover); + if (!approverToSelect) { + return; + } + selectionListProps?.onSelectRow?.(approverToSelect); + }); + + rerender( + , + ); + + selectionListProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + + expect(selectionListProps?.data.at(0)).toEqual( + expect.objectContaining({ + keyForList: 'user0@example.com', + }), + ); + expect(selectionListProps?.data.find((item) => item.keyForList === selectedApprover)).toEqual( + expect.objectContaining({ + keyForList: selectedApprover, + isSelected: true, + }), + ); + expect(selectionListProps?.initiallyFocusedItemKey).toBeUndefined(); + }); + + it('pins the selected approver after returning to the screen', () => { + const {rerender} = renderApproverSelectionList(buildApprovers(null)); + + let selectionListProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + act(() => { + const approverToSelect = selectionListProps?.data.find((item) => item.keyForList === selectedApprover); + if (!approverToSelect) { + return; + } + selectionListProps?.onSelectRow?.(approverToSelect); + }); + + rerender( + , + ); + + selectionListProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + expect(selectionListProps?.data.at(0)).toEqual( + expect.objectContaining({ + keyForList: 'user0@example.com', + }), + ); + + mockIsFocused = false; + rerender( + , + ); + + mockIsFocused = true; + rerender( + , + ); + + selectionListProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + expect(selectionListProps?.data.at(0)).toEqual( + expect.objectContaining({ + keyForList: selectedApprover, + isSelected: true, + }), + ); + expect(selectionListProps?.initiallyFocusedItemKey).toBe(selectedApprover); + }); + + it('keeps initial selection ordering while search is active', () => { + renderApproverSelectionList(); + + const initialProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + + act(() => { + initialProps?.textInputOptions?.onChangeText?.('User'); + }); + + const searchedProps = mockedSelectionList.mock.lastCall?.[0] as MockSelectionListProps | undefined; + + expect(searchedProps?.data.at(0)).toEqual( + expect.objectContaining({ + keyForList: selectedApprover, + isSelected: true, + }), + ); + }); +});