Skip to content
Merged
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
30 changes: 4 additions & 26 deletions src/components/SelectionListWithModal/index.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
import {useIsFocused} from '@react-navigation/native';
import type {ForwardedRef} from 'react';
import React, {useEffect, useMemo, useState} from 'react';
import React, {useMemo, useState} from 'react';
import MenuItem from '@components/MenuItem';
import Modal from '@components/Modal';
import SelectionList from '@components/SelectionList';
import type {ListItem, SelectionListHandle, SelectionListProps} from '@components/SelectionList/types';
import useDebouncedState from '@hooks/useDebouncedState';
import useHandleSelectionMode from '@hooks/useHandleSelectionMode';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useMobileSelectionMode from '@hooks/useMobileSelectionMode';
import useNetwork from '@hooks/useNetwork';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useThemeStyles from '@hooks/useThemeStyles';
import {turnOnMobileSelectionMode} from '@libs/actions/MobileSelectionMode';
import CONST from '@src/CONST';
import {isEmptyValueObject} from '@src/types/utils/EmptyObject';

type SelectionListWithModalProps<TItem extends ListItem> = SelectionListProps<TItem> & {
turnOnSelectionModeOnLongPress?: boolean;
Expand All @@ -37,7 +34,6 @@ function SelectionListWithModal<TItem extends ListItem>({
const [isModalVisible, setIsModalVisible] = useState(false);
const [longPressedItem, setLongPressedItem] = useState<TItem | null>(null);
const {translate} = useLocalize();
const {isOffline} = useNetwork();
const styles = useThemeStyles();
// We need to use isSmallScreenWidth instead of shouldUseNarrowLayout here because there is a race condition that causes shouldUseNarrowLayout to change indefinitely in this component
// See https://github.com/Expensify/App/issues/48675 for more details
Expand All @@ -46,37 +42,19 @@ function SelectionListWithModal<TItem extends ListItem>({
const isFocused = useIsFocused();
const icons = useMemoizedLazyExpensifyIcons(['CheckSquare']);

// Filter out the pending delete item without errors when online to prevent making multiple updates to debouncedData which causes the deleted item is shown again
const filteredData = useMemo(() => {
return data.filter((item) => item.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || isOffline || !isEmptyValueObject(item?.errors));
}, [data, isOffline]);

const isMobileSelectionModeEnabled = useMobileSelectionMode();

// Debounce the data prop to prevent rapid updates that cause FlashList layout errors
// This gives FlashList time to properly update its layout cache when searching/filtering
const [, debouncedData, setDataState] = useDebouncedState<TItem[]>(filteredData, CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME);

// Determine if this is changed by filtering (to limit multiple rerenders)
const isFiltering = filteredData.length < debouncedData.length;

useEffect(() => {
setDataState(filteredData);
}, [filteredData, setDataState]);

const displayData = isFiltering ? debouncedData : filteredData;

const selectedItems = useMemo(
() =>
selectedItemsProp ??
displayData.filter((item) => {
data.filter((item) => {
if (isSelected) {
return isSelected(item);
}
return !!item.isSelected;
}) ??
[],
[isSelected, displayData, selectedItemsProp],
[isSelected, data, selectedItemsProp],
);

useHandleSelectionMode(selectedItems);
Expand Down Expand Up @@ -116,7 +94,7 @@ function SelectionListWithModal<TItem extends ListItem>({
<>
<SelectionList
ref={ref}
data={displayData}
data={data}
addBottomSafeAreaPadding
selectedItems={selectedItemsProp}
onLongPressRow={handleLongPressRow}
Expand Down
14 changes: 7 additions & 7 deletions src/hooks/useSearchResults.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import {useDeferredValue, useEffect, useState} from 'react';
import {useEffect} from 'react';
import CONST from '@src/CONST';
import useDebouncedState from './useDebouncedState';
import usePrevious from './usePrevious';

const stableSortDataDefault = <TValue>(data: TValue[]) => data;

/**
* This hook filters (and optionally sorts) a dataset based on a search parameter.
* It utilizes `useDeferredValue` to allow the searchQuery to change rapidly, while more expensive renders that occur using
* the result of the filtering and sorting are de-prioritized, allowing them to happen in the background.
* The search input updates immediately for instant UI feedback, while the value used for
* filtering is debounced so expensive filter/sort work runs at most once per debounce window.
*
* @param data - The dataset to filter and sort.
* @param filterData - Predicate that decides whether a datum matches the current search input.
Expand All @@ -20,11 +21,10 @@ function useSearchResults<TValue>(
sortData: (data: TValue[]) => TValue[] = stableSortDataDefault,
preFilter?: (datum: TValue) => boolean,
) {
const [inputValue, setInputValue] = useState('');
const deferredInput = useDeferredValue(inputValue);
const [inputValue, debouncedInput, setInputValue] = useDebouncedState('', CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME);
const prevData = usePrevious(data);

const searchQuery = inputValue.trim().length ? deferredInput : '';
const searchQuery = inputValue.trim().length ? debouncedInput : '';

const base = preFilter ? data.filter(preFilter) : data;
const normalizedSearchQuery = searchQuery.trim().toLowerCase();
Expand All @@ -36,7 +36,7 @@ function useSearchResults<TValue>(
return;
}
setInputValue('');
}, [data.length, prevData.length]);
}, [data.length, prevData.length, setInputValue]);

return [inputValue, setInputValue, result] as const;
}
Expand Down
23 changes: 11 additions & 12 deletions src/pages/ReportParticipantsPage.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {useIsFocused} from '@react-navigation/native';
import React, {useEffect, useRef, useState} from 'react';
import React, {useEffect, useRef} from 'react';
// eslint-disable-next-line no-restricted-imports
import {InteractionManager, View} from 'react-native';
import type {TupleToUnion, ValueOf} from 'type-fest';
Expand Down Expand Up @@ -27,6 +27,7 @@ import useReportAttributes from '@hooks/useReportAttributes';
import useReportIsArchived from '@hooks/useReportIsArchived';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useSearchBackPress from '@hooks/useSearchBackPress';
import useSearchResults from '@hooks/useSearchResults';
import useStyleUtils from '@hooks/useStyleUtils';
import useThemeStyles from '@hooks/useThemeStyles';
import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode';
Expand Down Expand Up @@ -90,7 +91,6 @@ function ReportParticipantsPage({report, route}: ReportParticipantsPageProps) {
const isFocused = useIsFocused();
const {isOffline} = useNetwork();
const canSelectMultiple = isGroupChat && isCurrentUserAdmin && (isSmallScreenWidth ? isMobileSelectionModeEnabled : true);
const [searchValue, setSearchValue] = useState('');

const {personalDetailsParticipants, participantsForDisplay} = getReportPersonalDetailsParticipants(report, personalDetails, reportMetadata);
const participantsForDisplayMap = participantsForDisplay.reduce<Record<number, TupleToUnion<typeof participantsForDisplay>>>((acc, participant) => {
Expand All @@ -107,6 +107,13 @@ function ReportParticipantsPage({report, route}: ReportParticipantsPageProps) {

const [selectedMembers, setSelectedMembers] = useFilteredSelection(personalDetailsParticipants, filterParticipants);

const [searchValue, setSearchValue, searchFilteredParticipants] = useSearchResults(
participantsForDisplay,
(participant, search) => isSearchStringMatchUserDetails(participant.details, search),
undefined,
Comment thread
mountiny marked this conversation as resolved.
Resolved
(participant) => isOffline || !participant.isPendingDelete,
);

// Get the active chat members by filtering out the pending members with delete action
const activeParticipants = participantsForDisplay.filter((participant) => isOffline || !participant.isPendingDelete);

Expand Down Expand Up @@ -215,16 +222,8 @@ function ReportParticipantsPage({report, route}: ReportParticipantsPageProps) {

// Build participants list
let participants: MemberOption[] = [];
for (const participantForDisplay of participantsForDisplay) {
const {accountID, details, isDisabled, isPendingDelete, pendingAction, role} = participantForDisplay;

if (searchValue.trim() && !isSearchStringMatchUserDetails(details, searchValue)) {
continue;
}

if (!isOffline && isPendingDelete) {
continue;
}
for (const participantForDisplay of searchFilteredParticipants) {
const {accountID, details, isDisabled, pendingAction, role} = participantForDisplay;

const isAdmin = role === CONST.REPORT.ROLE.ADMIN;

Expand Down
20 changes: 11 additions & 9 deletions src/pages/RoomMembersPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import useReportAttributes from '@hooks/useReportAttributes';
import useReportIsArchived from '@hooks/useReportIsArchived';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useSearchBackPress from '@hooks/useSearchBackPress';
import useSearchResults from '@hooks/useSearchResults';
import useThemeStyles from '@hooks/useThemeStyles';
import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode';
import {clearUserSearchPhrase, updateUserSearchPhrase} from '@libs/actions/RoomMembersUserSearchPhrase';
Expand Down Expand Up @@ -75,7 +76,6 @@ function RoomMembersPage({report, policy}: RoomMembersPageProps) {
const {formatPhoneNumber, translate, localeCompare} = useLocalize();
const {showConfirmModal} = useConfirmModal();
const [userSearchPhrase] = useOnyx(ONYXKEYS.ROOM_MEMBERS_USER_SEARCH_PHRASE);
const [searchValue, setSearchValue] = useState('');
const [didLoadRoomMembers, setDidLoadRoomMembers] = useState(false);
const personalDetails = usePersonalDetails();
const isPolicyExpenseChat = useMemo(() => isPolicyExpenseChatUtils(report), [report]);
Expand All @@ -88,6 +88,11 @@ function RoomMembersPage({report, policy}: RoomMembersPageProps) {
[report, personalDetails, reportMetadata],
);

const [searchValue, setSearchValue, searchFilteredAccountIDs] = useSearchResults(participants, (accountID, search) => {
const details = personalDetails?.[accountID];
return !!details && isSearchStringMatchUserDetails(details, search);
});

const shouldIncludeMember = useCallback(
(participant?: PersonalDetails) => {
if (!participant) {
Expand Down Expand Up @@ -249,7 +254,7 @@ function RoomMembersPage({report, policy}: RoomMembersPageProps) {
return;
}
setSearchValue(userSearchPhrase ?? '');
}, [isFocusedScreen, shouldShowTextInput, userSearchPhrase]);
}, [isFocusedScreen, setSearchValue, shouldShowTextInput, userSearchPhrase]);

useEffect(() => {
updateUserSearchPhrase(searchValue);
Expand Down Expand Up @@ -278,11 +283,9 @@ function RoomMembersPage({report, policy}: RoomMembersPageProps) {
const data = useMemo((): ListItem[] => {
let result: ListItem[] = [];

for (const accountID of participants) {
for (const accountID of searchFilteredAccountIDs) {
const details = personalDetails?.[accountID];

// If search value is provided, filter out members that don't match the search value
if (!details || (searchValue.trim() && !isSearchStringMatchUserDetails(details, searchValue))) {
if (!details) {
continue;
}
const pendingChatMember = reportMetadata?.pendingChatMembers?.findLast((member) => member.accountID === accountID.toString());
Expand Down Expand Up @@ -322,12 +325,11 @@ function RoomMembersPage({report, policy}: RoomMembersPageProps) {
formatPhoneNumber,
localeCompare,
isPolicyExpenseChat,
participants,
searchFilteredAccountIDs,
personalDetails,
policy,
report.ownerAccountID,
reportMetadata?.pendingChatMembers,
searchValue,
selectedMembers,
session?.accountID,
icons.FallbackAvatar,
Expand Down Expand Up @@ -419,7 +421,7 @@ function RoomMembersPage({report, policy}: RoomMembersPageProps) {
onChangeText: setSearchValue,
headerMessage: searchValue.trim() && !data.length ? `${translate('roomMembersPage.memberNotFound')} ${translate('roomMembersPage.useInviteButton')}` : '',
}),
[data.length, searchValue, translate],
[data.length, searchValue, setSearchValue, translate],
);

let subtitleKey: '' | TranslationPaths | undefined;
Expand Down
145 changes: 145 additions & 0 deletions tests/unit/hooks/useSearchResults.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import {act, renderHook} from '@testing-library/react-native';
import useSearchResults from '@hooks/useSearchResults';
import CONST from '@src/CONST';

type Item = {id: number; name: string};

const buildItems = (count: number, prefix = 'item'): Item[] => Array.from({length: count}, (_, i) => ({id: i, name: `${prefix}-${i}`}));

const filterByName = (item: Item, query: string) => item.name.toLowerCase().includes(query);

describe('useSearchResults', () => {
beforeEach(() => {
jest.useFakeTimers();
});

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

it('returns the full list when the input is empty', () => {
const data = buildItems(5);
const {result} = renderHook(() => useSearchResults(data, filterByName));

expect(result.current[0]).toBe('');
expect(result.current[2]).toEqual(data);
});

it('updates the input value immediately but defers filtering until the debounce settles', () => {
const data = buildItems(5);
const {result} = renderHook(() => useSearchResults(data, filterByName));

act(() => {
result.current[1]('item-2');
});

// The typed value is visible right away but the filtered result still reflects the full list.
expect(result.current[0]).toBe('item-2');
expect(result.current[2]).toEqual(data);

act(() => {
jest.advanceTimersByTime(CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME);
});

expect(result.current[2]).toEqual([{id: 2, name: 'item-2'}]);
});

it('restores the full list instantly when the input is cleared, without waiting for the debounce', () => {
const data = buildItems(5);
const {result} = renderHook(() => useSearchResults(data, filterByName));

act(() => {
result.current[1]('item-2');
jest.advanceTimersByTime(CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME);
});
expect(result.current[2]).toHaveLength(1);

act(() => {
result.current[1]('');
});
expect(result.current[2]).toEqual(data);
});

it('applies the sort comparator to the filtered results', () => {
const data: Item[] = [
{id: 1, name: 'banana'},
{id: 2, name: 'apple'},
{id: 3, name: 'cherry'},
];
const sortAlpha = (items: Item[]) => [...items].sort((a, b) => a.name.localeCompare(b.name));
const {result} = renderHook(() => useSearchResults(data, filterByName, sortAlpha));

expect(result.current[2].map((i) => i.name)).toEqual(['apple', 'banana', 'cherry']);
});

it('applies the preFilter before the text filter', () => {
const data: Item[] = [
{id: 1, name: 'apple-good'},
{id: 2, name: 'apple-bad'},
{id: 3, name: 'banana-good'},
];
const preFilter = (item: Item) => item.name.endsWith('-good');
const {result} = renderHook(() => useSearchResults(data, filterByName, undefined, preFilter));

expect(result.current[2].map((i) => i.id)).toEqual([1, 3]);

act(() => {
result.current[1]('apple');
jest.advanceTimersByTime(CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME);
});
expect(result.current[2].map((i) => i.id)).toEqual([1]);
});

describe('auto-clear when data crosses SEARCH_ITEM_LIMIT', () => {
const aboveLimit = CONST.SEARCH_ITEM_LIMIT + 5;
const belowLimit = CONST.SEARCH_ITEM_LIMIT - 5;

it('clears the input when the dataset shrinks from above the limit to at or below the limit', () => {
const {result, rerender} = renderHook(({data}) => useSearchResults(data, filterByName), {
initialProps: {data: buildItems(aboveLimit)},
});

act(() => {
result.current[1]('item');
jest.advanceTimersByTime(CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME);
});
expect(result.current[0]).toBe('item');

rerender({data: buildItems(belowLimit)});

// The search bar is no longer shown for small datasets, so any leftover query must be wiped.
expect(result.current[0]).toBe('');
});

it('does not clear the input when the dataset stays above the limit', () => {
const {result, rerender} = renderHook(({data}) => useSearchResults(data, filterByName), {
initialProps: {data: buildItems(aboveLimit)},
});

act(() => {
result.current[1]('item');
jest.advanceTimersByTime(CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME);
});

rerender({data: buildItems(aboveLimit + 1)});

expect(result.current[0]).toBe('item');
});

it('does not clear the input when the dataset stays at or below the limit', () => {
const {result, rerender} = renderHook(({data}) => useSearchResults(data, filterByName), {
initialProps: {data: buildItems(belowLimit)},
});

act(() => {
result.current[1]('item');
jest.advanceTimersByTime(CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME);
});

rerender({data: buildItems(belowLimit - 1)});

expect(result.current[0]).toBe('item');
});
});
});
Loading