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
3 changes: 2 additions & 1 deletion src/hooks/useSearchSelector.base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import type {PermissionStatus} from 'react-native-permissions';
import {usePersonalDetails} from '@components/OnyxListItemProvider';
import {useOptionsList} from '@components/OptionListContextProvider';
import type {GetOptionsConfig, Option, Options, SearchOption} from '@libs/OptionsListUtils';
import {getEmptyOptions, getPersonalDetailSearchTerms, getSearchOptions, getSearchValueForPhoneOrEmail, getValidOptions} from '@libs/OptionsListUtils';
import {getEmptyOptions, getSearchOptions, getSearchValueForPhoneOrEmail, getValidOptions} from '@libs/OptionsListUtils';
import {getPersonalDetailSearchTerms} from '@libs/OptionsListUtils/searchMatchUtils';
import type {OptionData} from '@libs/ReportUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
Expand Down
27 changes: 8 additions & 19 deletions src/libs/OptionsListUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@
} from '@src/types/onyx';
import type {Attendee, Participant} from '@src/types/onyx/IOU';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import {getCurrentUserSearchTerms, getPersonalDetailSearchTerms, isPersonalDetailMatchingSearchTerm} from './searchMatchUtils';
import type {
FilterUserToInviteConfig,
GetOptionsConfig,
Expand Down Expand Up @@ -214,7 +215,7 @@
*/

let allReports: OnyxCollection<Report>;
Onyx.connect({

Check warning on line 218 in src/libs/OptionsListUtils/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => {
Expand All @@ -230,7 +231,7 @@
const deprecatedCachedOneTransactionThreadReportIDs: Record<string, string | undefined> = {};
/** @deprecated Use sortedReportActionsData from ONYXKEYS.DERIVED.RAM_ONLY_SORTED_REPORT_ACTIONS instead. Will be removed once all flows are migrated. */
let deprecatedAllReportActions: OnyxCollection<ReportActions>;
Onyx.connect({

Check warning on line 234 in src/libs/OptionsListUtils/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.COLLECTION.REPORT_ACTIONS,
waitForCollectionCallback: true,
callback: (actions) => {
Expand Down Expand Up @@ -280,7 +281,7 @@
});

let activePolicyID: OnyxEntry<string>;
Onyx.connect({

Check warning on line 284 in src/libs/OptionsListUtils/index.ts

View workflow job for this annotation

GitHub Actions / Changed files ESLint check

Onyx.connect() is deprecated. Use useOnyx() hook instead and pass the data as parameters to a pure function
key: ONYXKEYS.NVP_ACTIVE_POLICY_ID,
callback: (value) => (activePolicyID = value),
});
Expand Down Expand Up @@ -2660,10 +2661,12 @@
if (personalDetailLoginsToExclude[personalDetail.login]) {
return false;
}
const personalDetailSearchTerms = getPersonalDetailSearchTerms(personalDetail, currentUserAccountID);
const searchText = deburr(`${personalDetailSearchTerms.join(' ')} ${personalDetail.text ?? ''}`.toLocaleLowerCase());

return searchTerms.every((term) => searchText.includes(term));
return searchTerms.every((term) =>
isPersonalDetailMatchingSearchTerm(personalDetail, currentUserAccountID, term, {
useLocaleLowerCase: true,
transformSearchText: (concatenatedSearchTerms) => deburr(`${concatenatedSearchTerms} ${personalDetail.text ?? ''}`),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep transformed search text case-insensitive

This callback appends personalDetail.text after isPersonalDetailMatchingSearchTerm() has already lowercased the base terms, so any uppercase characters in personalDetail.text are now matched case-sensitively. Before this refactor, the whole concatenated string (terms + text) was lowercased first, so lowercase queries would still match. In cases where the relevant token exists only in text (not in participantsList/displayName/login), search can now miss valid results.

Useful? React with 👍 / 👎.

}),
);
};

// when we expect that function return eg. 50 elements and we already found 40 recent reports, we should adjust the max personal details number
Expand Down Expand Up @@ -2995,7 +2998,7 @@
// This will add them to the list of options, deduping them if they already exist in the other lists
const selectedParticipantsWithoutDetails = selectedOptions.filter((participant) => {
const accountID = participant.accountID ?? null;
const isPartOfSearchTerm = getPersonalDetailSearchTerms(participant, currentUserAccountID).join(' ').toLowerCase().includes(cleanSearchTerm);
const isPartOfSearchTerm = isPersonalDetailMatchingSearchTerm(participant, currentUserAccountID, cleanSearchTerm);
const isReportInRecentReports = filteredRecentReports.some((report) => report.accountID === accountID) || filteredWorkspaceChats.some((report) => report.accountID === accountID);
const isReportInPersonalDetails = filteredPersonalDetails.some((personalDetail) => personalDetail.accountID === accountID);

Expand Down Expand Up @@ -3023,18 +3026,6 @@
};
}

function getPersonalDetailSearchTerms(item: Partial<SearchOptionData>, currentUserAccountID: number) {
if (item.accountID === currentUserAccountID) {
return getCurrentUserSearchTerms(item);
}
return [item.participantsList?.[0]?.displayName ?? item.displayName ?? '', item.login ?? '', item.login?.replace(CONST.EMAIL_SEARCH_REGEX, '') ?? ''];
}

function getCurrentUserSearchTerms(item: Partial<SearchOptionData>) {
// eslint-disable-next-line @typescript-eslint/no-deprecated
return [item.text ?? item.displayName ?? '', item.login ?? '', item.login?.replace(CONST.EMAIL_SEARCH_REGEX, '') ?? '', translateLocal('common.you'), translateLocal('common.me')];
}

/**
* Remove the personal details for the DMs that are already in the recent reports so that we don't show duplicates.
*/
Expand Down Expand Up @@ -3417,7 +3408,6 @@
formatSectionsFromSearchTerm,
getAlternateText,
getFilteredRecentAttendees,
getCurrentUserSearchTerms,
getEmptyOptions,
getHeaderMessage,
getHeaderMessageForNonUserList,
Expand All @@ -3429,7 +3419,6 @@
getLastMessageTextForReport,
getManagerMcTestParticipant,
getParticipantsOption,
getPersonalDetailSearchTerms,
getPersonalDetailsForAccountIDs,
getPolicyExpenseReportOption,
getReportDisplayOption,
Expand Down
53 changes: 53 additions & 0 deletions src/libs/OptionsListUtils/searchMatchUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// eslint-disable-next-line @typescript-eslint/no-deprecated
import {translateLocal} from '@libs/Localize';
import CONST from '@src/CONST';
import type {SearchOptionData} from './types';

type SearchMatchConfig = {
/** Use toLocaleLowerCase() instead of toLowerCase(). Default: false */
useLocaleLowerCase?: boolean;

/**
* Optional callback to transform the concatenated search terms before matching.
* Receives the joined terms string (already lowercased).
* Return the final string to match against.
*/
transformSearchText?: (concatenatedSearchTerms: string) => string;
};

function getCurrentUserSearchTerms(item: Partial<SearchOptionData>) {
// eslint-disable-next-line @typescript-eslint/no-deprecated
return [item.text ?? item.displayName ?? '', item.login ?? '', item.login?.replace(CONST.EMAIL_SEARCH_REGEX, '') ?? '', translateLocal('common.you'), translateLocal('common.me')];
}

function getPersonalDetailSearchTerms(item: Partial<SearchOptionData>, currentUserAccountID: number) {
if (item.accountID === currentUserAccountID) {
return getCurrentUserSearchTerms(item);
}
return [item.participantsList?.[0]?.displayName ?? item.displayName ?? '', item.login ?? '', item.login?.replace(CONST.EMAIL_SEARCH_REGEX, '') ?? ''];
}

/**
* Checks whether a personal detail option matches a single search term
* by comparing against the option's searchable fields (displayName, login, etc.).
*
* Expects `searchTerm` to already be lowercased and trimmed.
*/
function isPersonalDetailMatchingSearchTerm(
item: Partial<SearchOptionData>,
currentUserAccountID: number,
searchTerm: string,
{useLocaleLowerCase = false, transformSearchText}: SearchMatchConfig = {},
): boolean {
const terms = getPersonalDetailSearchTerms(item, currentUserAccountID).join(' ');
let searchText = useLocaleLowerCase ? terms.toLocaleLowerCase() : terms.toLowerCase();

if (transformSearchText) {
searchText = transformSearchText(searchText);
}

return searchText.includes(searchTerm);
}

export {getCurrentUserSearchTerms, getPersonalDetailSearchTerms, isPersonalDetailMatchingSearchTerm};
export type {SearchMatchConfig};
37 changes: 9 additions & 28 deletions src/pages/NewChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,15 @@ import useIsFocusedRef from '@hooks/useIsFocusedRef';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useOnyx from '@hooks/useOnyx';
import usePrivateIsArchivedMap from '@hooks/usePrivateIsArchivedMap';
import useSafeAreaInsets from '@hooks/useSafeAreaInsets';
import useSingleExecution from '@hooks/useSingleExecution';
import useThemeStyles from '@hooks/useThemeStyles';
import {navigateToAndOpenReport, searchInServer, setGroupDraft} from '@libs/actions/Report';
import {canUseTouchScreen} from '@libs/DeviceCapabilities';
import Log from '@libs/Log';
import Navigation from '@libs/Navigation/Navigation';
import {
filterAndOrderOptions,
filterSelectedOptions,
formatSectionsFromSearchTerm,
getHeaderMessage,
getPersonalDetailSearchTerms,
getUserToInviteOption,
getValidOptions,
} from '@libs/OptionsListUtils';
import {filterAndOrderOptions, filterSelectedOptions, getHeaderMessage, getUserToInviteOption, getValidOptions} from '@libs/OptionsListUtils';
import {isPersonalDetailMatchingSearchTerm} from '@libs/OptionsListUtils/searchMatchUtils';
import type {OptionWithKey} from '@libs/OptionsListUtils/types';
import type {OptionData} from '@libs/ReportUtils';
import variables from '@styles/variables';
Expand Down Expand Up @@ -139,7 +131,7 @@ function useOptions(reportAttributesDerived: ReportAttributesDerivedValue['repor
!!options.userToInvite,
debouncedSearchTerm.trim(),
countryCode,
selectedOptions.some((participant) => getPersonalDetailSearchTerms(participant, currentUserAccountID).join(' ').toLowerCase?.().includes(cleanSearchTerm)),
selectedOptions.some((participant) => isPersonalDetailMatchingSearchTerm(participant, currentUserAccountID, cleanSearchTerm)),
);

useFocusEffect(() => {
Expand Down Expand Up @@ -245,19 +237,16 @@ function NewChatPage({ref}: NewChatPageProps) {
const personalData = useCurrentUserPersonalDetails();
const currentUserAccountID = personalData.accountID;
const {top} = useSafeAreaInsets();
const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
const [isSearchingForReports] = useOnyx(ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS);
const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED);
const [betas] = useOnyx(ONYXKEYS.BETAS);
const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector});
const privateIsArchivedMap = usePrivateIsArchivedMap();
const selectionListRef = useRef<SelectionListWithSectionsHandle | null>(null);

const [reportAttributesDerivedFull] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES);

const reportAttributesDerived = reportAttributesDerivedFull?.reports;

const allPersonalDetails = usePersonalDetails();
const {singleExecution} = useSingleExecution();

useImperativeHandle(ref, () => ({
Expand All @@ -280,20 +269,12 @@ function NewChatPage({ref}: NewChatPageProps) {

const sections: Array<Section<OptionWithKey>> = [];

const formatResults = formatSectionsFromSearchTerm(
debouncedSearchTerm,
selectedOptions as OptionData[],
recentReports,
personalDetails,
privateIsArchivedMap,
currentUserAccountID,
allPolicies,
allPersonalDetails,
undefined,
undefined,
reportAttributesDerived,
);
sections.push({...formatResults.section, title: undefined, sectionIndex: 0});
const selectedSection =
debouncedSearchTerm === ''
? selectedOptions
: selectedOptions.filter((participant) => isPersonalDetailMatchingSearchTerm(participant, currentUserAccountID, debouncedSearchTerm.trim().toLowerCase()));

sections.push({data: selectedSection, title: undefined, sectionIndex: 0});

sections.push({
title: translate('common.recents'),
Expand Down
4 changes: 2 additions & 2 deletions src/pages/iou/request/MoneyRequestAttendeeSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ import {
getFilteredRecentAttendees,
getHeaderMessage,
getParticipantsOption,
getPersonalDetailSearchTerms,
getPolicyExpenseReportOption,
isCurrentUser,
orderOptions,
} from '@libs/OptionsListUtils';
import {isPersonalDetailMatchingSearchTerm} from '@libs/OptionsListUtils/searchMatchUtils';
import {getPersonalDetailByEmail} from '@libs/PersonalDetailsUtils';
import {isPaidGroupPolicy as isPaidGroupPolicyFn} from '@libs/PolicyUtils';
import type {OptionData} from '@libs/ReportUtils';
Expand Down Expand Up @@ -272,7 +272,7 @@ function MoneyRequestAttendeeSelector({attendees = [], onFinish, onAttendeesAdde
!!orderedAvailableOptions?.userToInvite,
cleanSearchTerm,
countryCode,
attendees.some((attendee) => getPersonalDetailSearchTerms(attendee, currentUserAccountID).join(' ').toLowerCase().includes(cleanSearchTerm)),
attendees.some((attendee) => isPersonalDetailMatchingSearchTerm(attendee, currentUserAccountID, cleanSearchTerm)),
);
sections = newSections;
}
Expand Down
5 changes: 3 additions & 2 deletions src/pages/iou/request/MoneyRequestParticipantsSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ import goToSettings from '@libs/goToSettings';
import {isMovingTransactionFromTrackExpense} from '@libs/IOUUtils';
import Navigation from '@libs/Navigation/Navigation';
import type {Option} from '@libs/OptionsListUtils';
import {formatSectionsFromSearchTerm, getHeaderMessage, getParticipantsOption, getPersonalDetailSearchTerms, getPolicyExpenseReportOption, isCurrentUser} from '@libs/OptionsListUtils';
import {formatSectionsFromSearchTerm, getHeaderMessage, getParticipantsOption, getPolicyExpenseReportOption, isCurrentUser} from '@libs/OptionsListUtils';
import {isPersonalDetailMatchingSearchTerm} from '@libs/OptionsListUtils/searchMatchUtils';
import type {OptionWithKey} from '@libs/OptionsListUtils/types';
import {getActiveAdminWorkspaces, isPaidGroupPolicy as isPaidGroupPolicyUtil} from '@libs/PolicyUtils';
import type {OptionData} from '@libs/ReportUtils';
Expand Down Expand Up @@ -264,7 +265,7 @@ function MoneyRequestParticipantsSelector({
!!availableOptions?.userToInvite,
debouncedSearchTerm.trim(),
countryCode,
participants.some((participant) => getPersonalDetailSearchTerms(participant, currentUserAccountID).join(' ').toLowerCase().includes(cleanSearchTerm)),
participants.some((participant) => isPersonalDetailMatchingSearchTerm(participant, currentUserAccountID, cleanSearchTerm)),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[
Expand Down
3 changes: 1 addition & 2 deletions tests/unit/OptionsListUtilsTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,11 @@ import {
filterWorkspaceChats,
formatMemberForList,
formatSectionsFromSearchTerm,
getCurrentUserSearchTerms,
getFilteredRecentAttendees,
getIOUReportIDOfLastAction,
getLastActorDisplayName,
getLastActorDisplayNameFromLastVisibleActions,
getLastMessageTextForReport,
getPersonalDetailSearchTerms,
getPolicyExpenseReportOption,
getReportDisplayOption,
getReportOption,
Expand All @@ -45,6 +43,7 @@ import {
shouldShowLastActorDisplayName,
sortAlphabetically,
} from '@libs/OptionsListUtils';
import {getCurrentUserSearchTerms, getPersonalDetailSearchTerms} from '@libs/OptionsListUtils/searchMatchUtils';
import Parser from '@libs/Parser';
import {
getAddedCardFeedMessage,
Expand Down
Loading