diff --git a/src/components/Search/FilterComponents/InSelector.tsx b/src/components/Search/FilterComponents/InSelector.tsx
index 86772faf292e..acfae321da0d 100644
--- a/src/components/Search/FilterComponents/InSelector.tsx
+++ b/src/components/Search/FilterComponents/InSelector.tsx
@@ -54,6 +54,8 @@ function InSelector({value = [], selectionListTextInputStyle, selectionListStyle
const {options, isLoading} = useFilteredOptions({
enabled: ready,
isSearching: !!debouncedSearchTerm.trim(),
+ // The sections below read recentReports and never personalDetails, so contacts would never reach the list.
+ includeP2P: false,
});
const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx
index 812bd1f1ff2c..ee0f3235b27b 100644
--- a/src/components/Search/SearchAutocompleteList.tsx
+++ b/src/components/Search/SearchAutocompleteList.tsx
@@ -225,6 +225,7 @@ function SearchAutocompleteList({
} = useFilteredOptions({
enabled: true,
isSearching: !!autocompleteQueryValue.trim(),
+ includeP2P: true,
// The empty-query state renders only recent searches and recent reports (no standalone contacts),
// so contacts can be deferred until the user types a query.
deferContactsUntilSearch: true,
diff --git a/src/hooks/useFilteredOptions.ts b/src/hooks/useFilteredOptions.ts
index fa5952bd6b11..e924ac2887ab 100644
--- a/src/hooks/useFilteredOptions.ts
+++ b/src/hooks/useFilteredOptions.ts
@@ -18,8 +18,8 @@ type UseFilteredOptionsConfig = {
maxRecentReports?: number;
/** Whether the hook should be enabled (default: true) */
enabled?: boolean;
- /** Whether to include P2P personal details (default: true) */
- includeP2P?: boolean;
+ /** Whether to build contact shells. This value must match the downstream `includeP2P` value. */
+ includeP2P: boolean;
/** Number of reports to load per batch when paginating (default: 100) */
batchSize?: number;
/** Whether to enable dynamic loading/pagination (default: true) */
@@ -68,6 +68,7 @@ type UseFilteredOptionsResult = {
* const {options, isLoading} = useFilteredOptions({
* maxRecentReports: 500,
* enabled: didScreenTransitionEnd,
+ * includeP2P: true,
* });
*
*
*/
-function useFilteredOptions(config: UseFilteredOptionsConfig = {}): UseFilteredOptionsResult {
- const {maxRecentReports = 500, enabled = true, includeP2P = true, batchSize = 100, isSearching = false, deferContactsUntilSearch = false} = config;
+function useFilteredOptions(config: UseFilteredOptionsConfig): UseFilteredOptionsResult {
+ const {maxRecentReports = 500, enabled = true, includeP2P, batchSize = 100, isSearching = false, deferContactsUntilSearch = false} = config;
const [reportsLimit, setReportsLimit] = useState(maxRecentReports);
diff --git a/src/hooks/useSearchSelector/base.ts b/src/hooks/useSearchSelector/base.ts
index 66ca0e59e240..4d0bda7c9253 100644
--- a/src/hooks/useSearchSelector/base.ts
+++ b/src/hooks/useSearchSelector/base.ts
@@ -156,6 +156,11 @@ type UseSearchSelectorReturn = {
const emptyOptionList: OptionList = {reports: [], personalDetails: []};
+const CONTEXTS_APPLYING_GET_VALID_OPTIONS_CONFIG: ReadonlySet = new Set([
+ CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_GENERAL,
+ CONST.SEARCH_SELECTOR.SEARCH_CONTEXT_ATTENDEES,
+]);
+
const doOptionsMatch = (option1: OptionData, option2: OptionData) => {
return (
(option1.accountID && option1.accountID === option2.accountID) || // eslint-disable-line @typescript-eslint/prefer-nullish-coalescing -- this is boolean comparison
@@ -212,6 +217,12 @@ function useSearchSelectorBase({
// Searching bypasses the recent-reports pre-filter so a typed query can still match reports outside the top 500 most recently active ones.
const isSearchingOptions = !!debouncedSearchTerm.trim();
+
+ // Keep option-list contact building aligned with downstream includeP2P filtering.
+ const appliesGetValidOptionsConfig = CONTEXTS_APPLYING_GET_VALID_OPTIONS_CONFIG.has(searchContext);
+ const includeP2P = !appliesGetValidOptionsConfig || (getValidOptionsConfig.includeP2P ?? true);
+ const appliedGetValidOptionsConfig = appliesGetValidOptionsConfig ? getValidOptionsConfig : CONST.EMPTY_OBJECT;
+
const {
options: filteredOptions,
isLoading: isLoadingOptions,
@@ -220,6 +231,7 @@ function useSearchSelectorBase({
} = useFilteredOptions({
enabled: shouldInitialize,
isSearching: isSearchingOptions,
+ includeP2P,
batchSize: maxResultsPerPage,
});
const areOptionsInitialized = !isLoadingOptions;
@@ -229,7 +241,6 @@ function useSearchSelectorBase({
if (!contactOptions?.length || !areOptionsInitialized) {
return defaultOptions;
}
-
// Imported contacts get a generated accountID, so one sharing a login with a real Onyx user would show a duplicate
// row and be treated as a new invite. Track already-represented logins and drop contacts whose login is present.
const existingLogins = new Set();
@@ -261,7 +272,8 @@ function useSearchSelectorBase({
return {
...defaultOptions,
- personalDetails: defaultOptions.personalDetails.concat(dedupedContactOptions),
+ // Imported contacts are already hydrated.
+ personalDetails: defaultOptions.personalDetails.concat(dedupedContactOptions.map((contact) => ({...contact, isHydrated: true as const}))),
};
})();
@@ -328,7 +340,7 @@ function useSearchSelectorBase({
allPolicyTags,
sortedActions,
isTrackIntentUser,
- ...getValidOptionsConfig,
+ ...appliedGetValidOptionsConfig,
},
translate,
);
@@ -365,6 +377,7 @@ function useSearchSelectorBase({
allPolicyTags,
sortedActions,
isTrackIntentUser,
+ ...appliedGetValidOptionsConfig,
},
translate,
);
@@ -399,7 +412,7 @@ function useSearchSelectorBase({
allPolicyTags,
sortedActions,
isTrackIntentUser,
- ...getValidOptionsConfig,
+ ...appliedGetValidOptionsConfig,
},
translate,
);
diff --git a/src/libs/OptionsListUtils/index.ts b/src/libs/OptionsListUtils/index.ts
index 33a557b3ebdf..0312700df6cc 100644
--- a/src/libs/OptionsListUtils/index.ts
+++ b/src/libs/OptionsListUtils/index.ts
@@ -12,7 +12,7 @@ import filterArrayByMatch from '@libs/filterArrayByMatch';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import {isReportMessageAttachment} from '@libs/isReportMessageAttachment';
import {formatPhoneNumber as formatPhoneNumberPhoneUtils} from '@libs/LocalePhoneNumber';
-import {translateLocal} from '@libs/Localize';
+import {translate as translateWithLocale, translateLocal} from '@libs/Localize';
import {appendCountryCode, getPhoneNumberWithoutSpecialChars} from '@libs/LoginUtils';
import MaxHeap from '@libs/MaxHeap';
import MinHeap from '@libs/MinHeap';
@@ -214,7 +214,9 @@ import type {
GetOptionsConfig,
GetUserToInviteConfig,
GetValidReportsConfig,
+ HydratedPersonalDetailOption,
IsValidReportsConfig,
+ LazyHydrationContext,
MemberForList,
OptionList,
Options,
@@ -222,6 +224,9 @@ import type {
OrderOptionsConfig,
OrderReportOptionsConfig,
PayeePersonalDetails,
+ PersonalDetailFilterRankFields,
+ PersonalDetailOptionOrShell,
+ PersonalDetailShell,
PreviewConfig,
ReportAndPersonalDetailOptions,
SearchOption,
@@ -303,6 +308,23 @@ Onyx.connect({
callback: (value) => (activePolicyID = value),
});
+/** Single-account lookup without the allocations required by the plural helper. */
+function getPersonalDetailForAccountID(accountID: number, personalDetails: OnyxInputOrEntry): PersonalDetails | undefined {
+ const cleanAccountID = Number(accountID);
+ if (!personalDetails || !cleanAccountID) {
+ return undefined;
+ }
+
+ const personalDetail: PersonalDetails = personalDetails[accountID] ?? ({} as PersonalDetails);
+
+ if (cleanAccountID === CONST.ACCOUNT_ID.CONCIERGE) {
+ personalDetail.avatar = CONST.CONCIERGE_ICON_URL;
+ }
+
+ personalDetail.accountID = cleanAccountID;
+ return personalDetail;
+}
+
/**
* Returns the personal details for an array of accountIDs
* @returns keys of the object are emails, values are PersonalDetails objects.
@@ -314,21 +336,11 @@ function getPersonalDetailsForAccountIDs(accountIDs: number[] | undefined, perso
}
if (accountIDs) {
for (const accountID of accountIDs) {
- const cleanAccountID = Number(accountID);
- if (!cleanAccountID) {
- continue;
- }
- let personalDetail: OnyxEntry = personalDetails[accountID] ?? undefined;
+ const personalDetail = getPersonalDetailForAccountID(accountID, personalDetails);
if (!personalDetail) {
- personalDetail = {} as PersonalDetails;
- }
-
- if (cleanAccountID === CONST.ACCOUNT_ID.CONCIERGE) {
- personalDetail.avatar = CONST.CONCIERGE_ICON_URL;
+ continue;
}
-
- personalDetail.accountID = cleanAccountID;
- personalDetailsForAccountIDs[cleanAccountID] = personalDetail;
+ personalDetailsForAccountIDs[personalDetail.accountID] = personalDetail;
}
}
return personalDetailsForAccountIDs;
@@ -1134,6 +1146,26 @@ type CreateOptionParams = {
currentUserAccountID?: number;
};
+/** Shared by createOption and shells so filtering uses the final display text. */
+type GetPersonalDetailOptionTextProps = {
+ accountID: number | undefined;
+ hasReport: boolean;
+ personalDetails: OnyxEntry;
+ login: string | undefined;
+ translate: LocalizedTranslate;
+};
+
+function getPersonalDetailOptionText({accountID, hasReport, personalDetails, login, translate}: GetPersonalDetailOptionTextProps): string {
+ return (
+ getDisplayNameForParticipant({
+ accountID,
+ personalDetailsData: hasReport ? undefined : (personalDetails ?? undefined),
+ formatPhoneNumber: formatPhoneNumberPhoneUtils,
+ translate,
+ }) || formatPhoneNumberPhoneUtils(login ?? '')
+ );
+}
+
/**
* Creates a report list option - optimized for SearchOption context
*/
@@ -1276,17 +1308,10 @@ function createOption({
: '');
reportName = showPersonalDetails
- ? getDisplayNameForParticipant({accountID: accountIDs.at(0), formatPhoneNumber: formatPhoneNumberPhoneUtils, translate: translateFn}) ||
- formatPhoneNumberPhoneUtils(personalDetail?.login ?? '')
+ ? getPersonalDetailOptionText({accountID: accountIDs.at(0), hasReport: true, personalDetails, login: personalDetail?.login, translate: translateFn})
: computedReportName;
} else {
- reportName =
- getDisplayNameForParticipant({
- accountID: accountIDs.at(0),
- personalDetailsData: personalDetails ?? undefined,
- formatPhoneNumber: formatPhoneNumberPhoneUtils,
- translate: translateFn,
- }) || formatPhoneNumberPhoneUtils(personalDetail?.login ?? '');
+ reportName = getPersonalDetailOptionText({accountID: accountIDs.at(0), hasReport: false, personalDetails, login: personalDetail?.login, translate: translateFn});
result.keyForList = String(accountIDs.at(0));
result.alternateText = formatPhoneNumberPhoneUtils(personalDetails?.[accountIDs[0]]?.login ?? '');
@@ -1673,35 +1698,14 @@ const reportSortComparator = (report: Report, privateIsArchivedMap: PrivateIsArc
return `${isSelfDM ? 1 : 0}_${isArchived ? 0 : 1}_${report.lastVisibleActionCreated ?? ''}`;
};
-/**
- * Creates an optimized option list with smart pre-filtering.
- *
- * Performance optimization approach:
- * 1. Pre-filters reports using shouldReportBeInOptionList with correct parameters (betas, etc.)
- * 2. Default (`options.isSearching` false): pre-computes each report's sort key once, then uses a heap to
- * select the top N reports (`maxRecentReports`) by self-DM status, archived status, and recency. Only
- * those reports are processed in step 4, avoiding work on thousands of reports while ensuring correct filtering.
- * 3. Search mode (`options.isSearching` true): uses the full pre-filtered report list with no recency sort and
- * no `maxRecentReports` cap, so search can include all eligible reports.
- *
- * @param options.isSearching - When true, skips the sort and top-N limit in step 2; when false, applies them.
- *
- * @remarks In search mode, sorting by last visible action is skipped because the UI needs the full eligible set.
- *
- * Use this for screens that need recent reports (NewChatPage, WorkspaceInvitePage, etc.)
- */
-// Shared stable default so an omitted `visibleReportActionsData` keeps a constant reference across calls,
-// which the cache below relies on for hits.
+/** Builds an option list with pre-filtered reports and lazy contact shells. */
+// Stable default used by the cache when no report-action data is provided.
const EMPTY_VISIBLE_REPORT_ACTIONS: VisibleReportActionsDerivedValue = {};
-// Cache keyed by the options signature so each selection screen configuration (SearchRouter, NewChatPage,
-// ShareTab, etc.) keeps its own entry and reopening one screen is not evicted by opening another.
-// An entry is reused only while its Onyx inputs are referentially unchanged.
+// Each configuration gets its own entry and is reused while its Onyx inputs are unchanged.
const filteredOptionListCache = new Map();
-// One slot per active screen configuration (~7 distinct callers) plus a small buffer.
-// The LRU bound prevents a paginating screen from flooding the cache with one entry
-// per distinct maxRecentReports value and evicting entries for other screens.
+// Bound the LRU cache so pagination cannot evict every other screen's entry.
const FILTERED_OPTION_LIST_CACHE_MAX_ENTRIES = 8;
/** Builds the cache key from the option values that define a distinct screen configuration. */
@@ -1709,12 +1713,7 @@ function buildFilteredOptionListCacheKey(args: Array)
return args.join('_');
}
-// Consumers (e.g. getValidOptions) mutate option objects in place (isBold/isSelected/brickRoadIndicator),
-// so the cache keeps a pristine copy and every caller receives its own shallow clones, matching the
-// per-call fresh objects they would get without the cache.
-// NOTE: this is a shallow clone — the top-level fields consumers mutate today are all scalars. Nested
-// objects (icons, participantsList, item, allReportErrors) stay shared with the cached entry, so any new
-// consumer that mutates those in place would corrupt the cache and must clone them first.
+// Clone top-level options because consumers mutate their marks. Nested values and shell hydrators stay shared.
function cloneOptionList(optionList: OptionList): OptionList {
return {
reports: optionList.reports.map((option) => ({...option})),
@@ -1722,15 +1721,7 @@ function cloneOptionList(optionList: OptionList): OptionList {
};
}
-// Enforces the cloneOptionList invariant in dev: the cached entry's nested objects are shared with every
-// clone handed out, so freezing them makes a consumer that mutates one throw immediately instead of
-// silently corrupting the cache for other screens. The clones' top-level objects stay mutable because
-// spreading a frozen object produces a new unfrozen one — which covers all mutations consumers do today.
-//
-// `item` and the members of `participantsList` are exempt: they are Onyx snapshot objects shared with the
-// whole app, not structures this cache created, and existing code still writes to them in place (e.g.
-// getPersonalDetailsForAccountIDs sets accountID during every option build), so freezing them would crash
-// unrelated flows in dev. Mutating them corrupts app-wide Onyx state, which is beyond this cache's invariant.
+// Freeze cached values in dev, except shared Onyx snapshots.
function deepFreeze(value: unknown) {
if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {
return;
@@ -1759,6 +1750,97 @@ function clearFilteredOptionListCache() {
// account, so drop them on sign-out instead of holding them until the next call.
registerSessionCleanupCallback(() => filteredOptionListCache.clear());
+/** Builds the display option from the shell's captured inputs. */
+function buildFullOption(accountID: number, item: PersonalDetails | null, report: Report | undefined, context: LazyHydrationContext): HydratedPersonalDetailOption {
+ const {
+ personalDetails,
+ policiesCollection,
+ reportAttributesDerived,
+ policyTags,
+ visibleReportActionsData,
+ privateIsArchivedMap,
+ conciergeReportID,
+ currentUserAccountID,
+ dateFnsLocale,
+ translate,
+ } = context;
+ const privateIsArchived = report ? privateIsArchivedMap[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report.reportID}`] : undefined;
+ const policy = policiesCollection?.[`${ONYXKEYS.COLLECTION.POLICY}${report?.policyID}`];
+ const reportPolicyTags = policyTags?.[`${ONYXKEYS.COLLECTION.POLICY_TAGS}${getNonEmptyStringOnyxID(report?.policyID)}`];
+
+ const built: HydratedPersonalDetailOption = {
+ item,
+ ...createOption({
+ dateFnsLocale,
+ accountIDs: [accountID],
+ personalDetails,
+ report,
+ policy,
+ privateIsArchived,
+ conciergeReportID,
+ config: {showPersonalDetails: true},
+ reportAttributesDerived,
+ policyTags: reportPolicyTags,
+ visibleReportActionsData,
+ currentUserAccountID,
+ translate,
+ }),
+ isHydrated: true,
+ };
+
+ // Freeze the shared value. Callers receive mutable top-level copies.
+ if (__DEV__) {
+ deepFreeze(built);
+ }
+
+ return built;
+}
+
+/**
+ * Step 5 of createFilteredOptionList: one lightweight shell per personal detail.
+ * Only filter/rank fields are computed here. getValidOptions hydrates survivors via hydrateContactOption.
+ */
+function buildPersonalDetailsOptions(reportMapForAccountIDs: Record, context: LazyHydrationContext): PersonalDetailShell[] {
+ const {personalDetails, translate} = context;
+ return Object.values(personalDetails ?? {}).map((personalDetail) => {
+ const accountID = personalDetail?.accountID ?? CONST.DEFAULT_NUMBER_ID;
+ const report = reportMapForAccountIDs[accountID];
+ // Match createOption's personal-details lookup.
+ const detail = getPersonalDetailForAccountID(accountID, personalDetails);
+ // Keep shell text identical to the hydrated option.
+ const text = getPersonalDetailOptionText({accountID, hasReport: !!report, personalDetails, login: detail?.login, translate});
+
+ // Do not capture the shell: getValidOptions mutates its transient marks.
+ let built: HydratedPersonalDetailOption | undefined;
+ const hydrate = () => (built ??= buildFullOption(accountID, personalDetail, report, context));
+
+ return {
+ item: personalDetail,
+ isHydrated: false,
+ hydrate,
+ // Keep the falsy default expected by existing callers.
+ // eslint-disable-next-line rulesdir/no-default-id-values
+ reportID: report?.reportID ?? '',
+ keyForList: report ? String(report.reportID) : String(accountID),
+ text,
+ login: detail?.login,
+ accountID: Number(detail?.accountID),
+ participantsList: detail ? [detail] : [],
+ isSelected: false,
+ selected: false,
+ };
+ });
+}
+
+/** Hydrates a shell, reusing its memoized display option. */
+function hydrateContactOption(option: PersonalDetailOptionOrShell): HydratedPersonalDetailOption {
+ if (option.isHydrated) {
+ return option;
+ }
+
+ return {...option.hydrate(), isHydrated: true};
+}
+
function createFilteredOptionList(
personalDetails: OnyxEntry,
reports: OnyxCollection,
@@ -1770,6 +1852,7 @@ function createFilteredOptionList(
dateFnsLocale: DateFnsLocale | undefined;
conciergeReportID: string | undefined;
maxRecentReports?: number;
+ /** Whether to build contact shells. */
includeP2P?: boolean;
isSearching?: boolean;
/**
@@ -1789,14 +1872,17 @@ function createFilteredOptionList(
): OptionList {
const {currentUserAccountID, conciergeReportID, maxRecentReports = 500, includeP2P = true, isSearching = false, deferContactsUntilSearch = false, locale} = options;
+ // Use the cache-key locale for translated contact fields.
+ const activeLocale = locale ?? IntlStore.getCurrentLocale();
+ const translateInActiveLocale: LocalizedTranslate = (path, ...parameters) => translateWithLocale(activeLocale, path, ...parameters);
+
// Contacts are expensive to build on large accounts (one option per personal detail). When a screen
// opts into deferral and is not actively searching, skip building them entirely; the empty state
// does not display standalone contacts, and typing flips `isSearching` which rebuilds the full set.
const areContactsDeferred = deferContactsUntilSearch && !isSearching;
const shouldBuildContacts = includeP2P && !areContactsDeferred;
- // Search-mode results contain an option for every report and contact, so caching them would retain
- // full-account-sized arrays until sign-out — and any Onyx change invalidates them anyway.
+ // Avoid caching search results, which can contain every report and contact.
const shouldUseCache = !isSearching;
const cacheEntryKey = buildFilteredOptionListCacheKey([maxRecentReports, includeP2P, isSearching, deferContactsUntilSearch]);
@@ -1810,9 +1896,9 @@ function createFilteredOptionList(
visibleReportActionsData,
isTrackIntentUser,
conciergeReportID,
- // Option building translates strings imperatively (translateLocal) and formats dates, so both the active locale and the
+ // Option building translates strings and formats dates, so both the active locale and the
// date-fns locale are part of the output.
- locale ?? IntlStore.getCurrentLocale(),
+ activeLocale,
options.dateFnsLocale,
// The RAM_ONLY_SORTED_REPORT_ACTIONS derived value produces a new object on every recompute,
// so its reference signals that the underlying report actions changed.
@@ -1900,38 +1986,25 @@ function createFilteredOptionList(
}
}
- // Step 5: Process personal details (all of them when built - needed for search functionality)
+ // Build contact shells; display fields are added after filtering.
const personalDetailsOptions = shouldBuildContacts
- ? Object.values(personalDetails ?? {}).map((personalDetail) => {
- const accountID = personalDetail?.accountID ?? CONST.DEFAULT_NUMBER_ID;
-
- const report = reportMapForAccountIDs[accountID];
- const privateIsArchived = privateIsArchivedMap[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`];
- const policy = policiesCollection?.[`${ONYXKEYS.COLLECTION.POLICY}${report?.policyID}`];
- const reportPolicyTags = policyTags?.[`${ONYXKEYS.COLLECTION.POLICY_TAGS}${getNonEmptyStringOnyxID(report?.policyID)}`];
- return {
- item: personalDetail,
- ...createOption({
- dateFnsLocale: options.dateFnsLocale,
- accountIDs: [accountID],
- personalDetails,
- report: reportMapForAccountIDs[accountID],
- policy,
- privateIsArchived,
- conciergeReportID,
- config: {showPersonalDetails: true},
- reportAttributesDerived,
- policyTags: reportPolicyTags,
- visibleReportActionsData,
- currentUserAccountID,
- }),
- };
+ ? buildPersonalDetailsOptions(reportMapForAccountIDs, {
+ personalDetails,
+ policiesCollection,
+ reportAttributesDerived,
+ policyTags,
+ visibleReportActionsData,
+ privateIsArchivedMap,
+ conciergeReportID,
+ currentUserAccountID,
+ dateFnsLocale: options.dateFnsLocale,
+ translate: translateInActiveLocale,
})
: [];
const result: OptionList = {
reports: reportOptions,
- personalDetails: personalDetailsOptions as Array>,
+ personalDetails: personalDetailsOptions,
};
if (!shouldUseCache) {
@@ -2006,7 +2079,13 @@ function createOptionFromReport({
};
}
-function orderPersonalDetailsOptions(options: T[]): T[] {
+/**
+ * What personalDetailsComparator reads: the filter/rank subset both halves of PersonalDetailOptionOrShell
+ * satisfy, plus the `alternateText` fallback that only PersonalDetailOptionData needs.
+ */
+type PersonalDetailSortFields = PersonalDetailFilterRankFields & Pick;
+
+function orderPersonalDetailsOptions(options: T[]): T[] {
// PersonalDetails should be ordered Alphabetically by default - https://github.com/Expensify/App/issues/8220#issuecomment-1104009435
// Keep this aligned with `getValidOptions` ordering (`optionsOrderBy(..., personalDetailsComparator, ...)`)
// so upstream and downstream sorting use the same key (text -> alternateText -> login).
@@ -2021,10 +2100,8 @@ function orderReportOptions(options: SearchOptionData[]) {
return lodashOrderBy(options, [sortComparatorReportOptionByArchivedStatus, sortComparatorReportOptionByDate], ['asc', 'desc']);
}
-/**
- * Sort personal details by displayName or login in alphabetical order
- */
-function personalDetailsComparator(personalDetail: SearchOptionData | PersonalDetailOptionData) {
+/** Sort personal details using the same text key for shells and hydrated options. */
+function personalDetailsComparator(personalDetail: PersonalDetailSortFields) {
const name = personalDetail.text ?? personalDetail.alternateText ?? personalDetail.login ?? '';
return name.toLowerCase();
}
@@ -2251,13 +2328,13 @@ function sortComparatorReportOptionByDate(options: SearchOptionData) {
/**
* Sorts reports and personal details independently.
*/
-function orderOptions(options: ReportAndPersonalDetailOptions): ReportAndPersonalDetailOptions;
+function orderOptions(options: ReportAndPersonalDetailOptions): ReportAndPersonalDetailOptions;
/**
* Sorts reports and personal details independently, but prioritizes the search value.
*/
-function orderOptions(options: ReportAndPersonalDetailOptions, searchValue: string, config?: OrderReportOptionsConfig): ReportAndPersonalDetailOptions;
-function orderOptions(options: ReportAndPersonalDetailOptions, searchValue?: string, config?: OrderReportOptionsConfig): ReportAndPersonalDetailOptions {
+function orderOptions(options: ReportAndPersonalDetailOptions, searchValue: string, config?: OrderReportOptionsConfig): ReportAndPersonalDetailOptions;
+function orderOptions(options: ReportAndPersonalDetailOptions, searchValue?: string, config?: OrderReportOptionsConfig): ReportAndPersonalDetailOptions {
let orderedReportOptions: SearchOptionData[];
if (searchValue) {
orderedReportOptions = orderReportOptionsWithSearch(options.recentReports, searchValue, config);
@@ -2669,9 +2746,7 @@ function prepareReportOptionsForDisplay(
return validOptions;
}
-/**
- * Options are reports and personal details. This function filters out the options that are not valid to be displayed.
- */
+/** Filters reports and contacts; deferred contacts must be hydrated before rendering. */
function getValidOptions(
options: OptionList,
policiesCollection: OnyxCollection,
@@ -2770,7 +2845,11 @@ function getValidOptions(
searchText += participantsSearchText;
}
searchText = deburr(searchText.toLocaleLowerCase());
- return searchTerms.every((term) => searchText.includes(term));
+
+ // Keep the pre-filter a superset of filterReports(). The canonical matcher handles apostrophes,
+ // hyphens, zero-width characters, diacritics, and email searches without dots that this cheap
+ // substring check may miss. Run it only when the cheap check does not find a match.
+ return searchTerms.every((term) => searchText.includes(term)) || filterReports([report], searchTerms).length > 0;
};
const filteringFunction = (report: SearchOption) => {
@@ -2925,9 +3004,9 @@ function getValidOptions(
}
// Get valid personal details and check if we can find the current user:
- let personalDetailsOptions: SearchOptionData[] = [];
+ let personalDetailsOptions: HydratedPersonalDetailOption[] = [];
const currentUserRef = {
- current: undefined as SearchOptionData | undefined,
+ current: undefined as HydratedPersonalDetailOption | undefined,
};
if (includeP2P) {
@@ -2954,6 +3033,12 @@ function getValidOptions(
if (personalDetailLoginsToExclude[personalDetail.login]) {
return false;
}
+
+ // Keep this pre-filter a superset of filterPersonalDetails().
+ if (searchTerms.length > 0 && filterPersonalDetails([personalDetail], searchTerms, currentUserAccountID).length > 0) {
+ return true;
+ }
+
return searchTerms.every((term) =>
doesPersonalDetailMatchSearchTerm(personalDetail, currentUserAccountID, term, {
useLocaleLowerCase: true,
@@ -2969,7 +3054,8 @@ function getValidOptions(
? Math.max(maxElements - recentReportOptions.length - workspaceChats.length - (!selfDMChat ? 1 : 0), MIN_PERSONAL_DETAILS_SLOTS)
: undefined;
const groupedPersonalDetails = optionsOrderBy(options.personalDetails, personalDetailsComparator, maxPersonalDetailsElements, filteringFunction, true);
- personalDetailsOptions = groupedPersonalDetails.options;
+ // Only the top-N survivors of the heap are hydrated. The shells filtered out above never pay the build cost.
+ personalDetailsOptions = groupedPersonalDetails.options.map(hydrateContactOption);
hasMore = hasMore || groupedPersonalDetails.hasMore;
@@ -2984,11 +3070,7 @@ function getValidOptions(
}
}
- for (let i = 0; i < personalDetailsOptions.length; i++) {
- const personalDetail = personalDetailsOptions.at(i);
- if (!personalDetail) {
- continue;
- }
+ for (const personalDetail of personalDetailsOptions) {
if (!!currentUserEmail && personalDetail?.login === currentUserEmail) {
currentUserRef.current = personalDetail;
}
@@ -3351,7 +3433,7 @@ function formatSectionsFromSearchTerm(
/**
* Remove the personal details for the DMs that are already in the recent reports so that we don't show duplicates.
*/
-function filteredPersonalDetailsOfRecentReports(recentReports: SearchOptionData[], personalDetails: SearchOptionData[]) {
+function filteredPersonalDetailsOfRecentReports(recentReports: SearchOptionData[], personalDetails: T[]): T[] {
const excludedLogins = new Set(recentReports.map((report) => report.login));
return personalDetails.filter((personalDetail) => !excludedLogins.has(personalDetail.login));
}
@@ -3414,7 +3496,7 @@ function filterWorkspaceChats(reports: SearchOptionData[], searchTerms: string[]
return filteredReports;
}
-function filterPersonalDetails(personalDetails: SearchOptionData[], searchTerms: string[], currentUserAccountID: number): SearchOptionData[] {
+function filterPersonalDetails(personalDetails: T[], searchTerms: string[], currentUserAccountID: number): T[] {
return searchTerms.reduceRight(
(items, term) =>
filterArrayByMatch(items, term, (item) => {
@@ -3425,8 +3507,8 @@ function filterPersonalDetails(personalDetails: SearchOptionData[], searchTerms:
);
}
-function filterCurrentUserOption(currentUserOption: SearchOptionData | null | undefined, searchTerms: string[]): SearchOptionData | null | undefined {
- return searchTerms.reduceRight((item, term) => {
+function filterCurrentUserOption(currentUserOption: T | null | undefined, searchTerms: string[]): T | null | undefined {
+ return searchTerms.reduceRight((item, term) => {
if (!item) {
return null;
}
@@ -3478,37 +3560,11 @@ function filterUserToInvite(
}
function filterSelfDMChat(report: SearchOptionData, searchTerms: string[]): SearchOptionData | undefined {
- const isMatch = searchTerms.every((term) => {
- const values: string[] = [];
-
- if (report.text) {
- values.push(report.text);
- }
- if (report.login) {
- values.push(report.login);
- values.push(report.login.replace(CONST.EMAIL_SEARCH_REGEX, ''));
- }
- if (report.isThread) {
- if (report.alternateText) {
- values.push(report.alternateText);
- }
- } else if (!!report.isChatRoom || !!report.isPolicyExpenseChat) {
- if (report.subtitle) {
- values.push(report.subtitle);
- }
- }
-
- // Remove duplicate values and check if the term matches any value
- return uniqFast(values)
- .map((val) => val.toLocaleLowerCase())
- .some((value) => value.includes(term.toLocaleLowerCase()));
- });
-
- return isMatch ? report : undefined;
+ return filterReports([report], searchTerms).at(0);
}
-function filterOptions(
- options: Options,
+function filterOptions(
+ options: Options,
searchInputValue: string,
countryCode: number,
loginList: OnyxEntry,
@@ -3516,7 +3572,7 @@ function filterOptions(
currentUserAccountID: number,
personalDetailsCollection: OnyxEntry,
config?: FilterUserToInviteConfig,
-): Options {
+): Options {
const trimmedSearchInput = searchInputValue.trim();
const searchInputValueForInvite = config?.searchInputValue ?? trimmedSearchInput;
@@ -3567,11 +3623,11 @@ type FilterAndOrderConfig = FilterUserToInviteConfig & AllOrderConfigs;
* Personal details will be filtered out if they are part of the recent reports.
* Additional configs can be applied.
*/
-function combineOrderingOfReportsAndPersonalDetails(
- options: ReportAndPersonalDetailOptions,
+function combineOrderingOfReportsAndPersonalDetails(
+ options: ReportAndPersonalDetailOptions,
searchInputValue: string,
{maxRecentReportsToShow, sortByReportTypeInSearch, ...orderReportOptionsConfig}: AllOrderConfigs = {},
-): ReportAndPersonalDetailOptions {
+): ReportAndPersonalDetailOptions {
// sortByReportTypeInSearch will show the personal details as part of the recent reports
if (sortByReportTypeInSearch) {
const personalDetailsWithoutDMs = filteredPersonalDetailsOfRecentReports(options.recentReports, options.personalDetails);
@@ -3597,8 +3653,8 @@ function combineOrderingOfReportsAndPersonalDetails(
* Filters and orders the options based on the search input value.
* Note that personal details that are part of the recent reports will always be shown as part of the recent reports (ie. DMs).
*/
-function filterAndOrderOptions(
- options: Options,
+function filterAndOrderOptions(
+ options: Options,
searchInputValue: string,
countryCode: number,
loginList: OnyxEntry,
@@ -3606,7 +3662,7 @@ function filterAndOrderOptions(
currentUserAccountID: number,
personalDetails: OnyxEntry,
config?: FilterAndOrderConfig,
-): Options {
+): Options {
let filterResult = options;
if (searchInputValue.trim().length > 0) {
filterResult = filterOptions(options, searchInputValue, countryCode, loginList, currentUserEmail, currentUserAccountID, personalDetails, config);
@@ -3670,6 +3726,7 @@ export {
combineOrderingOfReportsAndPersonalDetails,
createOptionFromReport,
createFilteredOptionList,
+ hydrateContactOption,
createOption,
filterAndOrderOptions,
filterReports,
@@ -3714,4 +3771,15 @@ export {
processSearchString,
};
-export type {GetOptionsConfig, MemberForList, Option, OptionList, OptionTree, Options, SearchOption, SearchOptionData} from './types';
+export type {
+ GetOptionsConfig,
+ HydratedPersonalDetailOption,
+ MemberForList,
+ Option,
+ OptionList,
+ OptionTree,
+ Options,
+ PersonalDetailOptionOrShell,
+ SearchOption,
+ SearchOptionData,
+} from './types';
diff --git a/src/libs/OptionsListUtils/searchMatchUtils.ts b/src/libs/OptionsListUtils/searchMatchUtils.ts
index e04a6fded835..ccbc947d8e03 100644
--- a/src/libs/OptionsListUtils/searchMatchUtils.ts
+++ b/src/libs/OptionsListUtils/searchMatchUtils.ts
@@ -2,7 +2,7 @@ import {translateLocal} from '@libs/Localize';
import CONST from '@src/CONST';
-import type {SearchOptionData} from './types';
+import type {PersonalDetailFilterRankFields} from './types';
type SearchMatchConfig = {
/** Whether to use toLocaleLowerCase() instead of toLowerCase(), defaults to false */
@@ -22,7 +22,7 @@ type SearchMatchConfig = {
* @returns Raw (not lowercased) terms: display text, login,
* login with dots stripped before @, and translated "You"/"Me".
*/
-function getCurrentUserSearchTerms(item: Partial) {
+function getCurrentUserSearchTerms(item: PersonalDetailFilterRankFields) {
return [item.text ?? item.displayName ?? '', item.login ?? '', item.login?.replace(CONST.EMAIL_SEARCH_REGEX, '') ?? '', translateLocal('common.you'), translateLocal('common.me')];
}
@@ -33,7 +33,7 @@ function getCurrentUserSearchTerms(item: Partial) {
*
* @returns Raw (not lowercased) terms the person is searchable by.
*/
-function getPersonalDetailSearchTerms(item: Partial, currentUserAccountID: number) {
+function getPersonalDetailSearchTerms(item: PersonalDetailFilterRankFields, currentUserAccountID: number) {
if (item.accountID === currentUserAccountID) {
return getCurrentUserSearchTerms(item);
}
@@ -47,7 +47,7 @@ function getPersonalDetailSearchTerms(item: Partial, currentUs
* Expects `searchTerm` to already be lowercased and trimmed.
*/
function doesPersonalDetailMatchSearchTerm(
- item: Partial,
+ item: PersonalDetailFilterRankFields,
currentUserAccountID: number,
searchTerm: string,
{useLocaleLowerCase = false, transformSearchText}: SearchMatchConfig = {},
diff --git a/src/libs/OptionsListUtils/types.ts b/src/libs/OptionsListUtils/types.ts
index d9ab2d5bd36e..bb3a6d6f6702 100644
--- a/src/libs/OptionsListUtils/types.ts
+++ b/src/libs/OptionsListUtils/types.ts
@@ -1,5 +1,8 @@
+import type {LocalizedTranslate} from '@components/LocaleContextProvider';
import type {Section as SelectionListSection} from '@components/SelectionList/SelectionListWithSections/types';
+import type {PrivateIsArchivedMap} from '@hooks/usePrivateIsArchivedMap';
+
import type {OptionData} from '@libs/ReportUtils';
import type {AvatarSource} from '@libs/UserAvatarUtils';
@@ -9,6 +12,7 @@ import type {
Login,
PersonalDetails,
PersonalDetailsList,
+ Policy,
PolicyTagLists,
Report,
ReportAction,
@@ -98,13 +102,68 @@ type SearchOptionData = Pick<
| 'selected' // Duplicate of isSelected, kept for backwards compatibility
>;
+/** Inputs captured by shell hydrators for one option-list build. */
+type LazyHydrationContext = {
+ personalDetails: OnyxEntry;
+ policiesCollection: OnyxCollection;
+ reportAttributesDerived: ReportAttributesDerivedValue['reports'] | undefined;
+ policyTags: OnyxCollection;
+ visibleReportActionsData: VisibleReportActionsDerivedValue;
+ privateIsArchivedMap: PrivateIsArchivedMap;
+ conciergeReportID: string | undefined;
+ currentUserAccountID: number;
+
+ /** Date-fns locale used when the option list was built. */
+ dateFnsLocale: DateFnsLocale | undefined;
+
+ /** Locale used when the option list was built. */
+ translate: LocalizedTranslate;
+};
+
type SearchOption = SearchOptionData & {
item: T;
};
+/** Filter/rank fields for a contact. Hydrate before rendering. */
+type PersonalDetailShell = Pick<
+ SearchOptionData,
+ // Identity
+ | 'reportID'
+ | 'keyForList'
+ | 'login'
+ | 'accountID'
+ | 'text'
+ | 'displayName'
+ | 'participantsList'
+ | 'isOptimisticPersonalDetail'
+
+ // Initialized to their falsy defaults by the shell builder; getValidOptions marks the hydrated copy.
+ | 'isSelected'
+ | 'selected'
+> & {
+ item: PersonalDetails | null;
+
+ /** Discriminates a shell from a display-ready option. */
+ isHydrated: false;
+
+ /** Builds the memoized display option. */
+ hydrate: () => HydratedPersonalDetailOption;
+};
+
+type HydratedPersonalDetailOption = SearchOption & {isHydrated: true};
+
+type PersonalDetailOptionOrShell = PersonalDetailShell | HydratedPersonalDetailOption;
+
+/**
+ * The only fields filtering, ranking and de-duping read off a contact option. Both halves of
+ * PersonalDetailOptionOrShell satisfy it, so helpers typed against it accept shells without claiming the
+ * display fields exist.
+ */
+type PersonalDetailFilterRankFields = Pick;
+
type OptionList = {
reports: Array>;
- personalDetails: Array>;
+ personalDetails: PersonalDetailOptionOrShell[];
};
type Option = Partial;
@@ -265,11 +324,12 @@ type SectionForSearchTerm = {
type SelectionListSections = Array>;
-type Options = {
+/** Keeps the shell/display union until the caller hydrates before rendering. */
+type Options = {
recentReports: SearchOptionData[];
- personalDetails: SearchOptionData[];
+ personalDetails: TPersonalDetail[];
userToInvite: SearchOptionData | null;
- currentUserOption: SearchOptionData | null | undefined;
+ currentUserOption: TPersonalDetail | null | undefined;
workspaceChats?: SearchOptionData[];
selfDMChat?: SearchOptionData | undefined;
};
@@ -307,10 +367,10 @@ type OrderReportOptionsConfig = {
preferRecentExpenseReports?: boolean;
};
-type ReportAndPersonalDetailOptions = Pick;
+type ReportAndPersonalDetailOptions = Pick, 'recentReports' | 'personalDetails' | 'workspaceChats'>;
-type OptionsResult = {
- options: Options;
+type OptionsResult = {
+ options: Options;
hasMore?: boolean;
};
@@ -319,6 +379,8 @@ export type {
GetOptionsConfig,
GetUserToInviteConfig,
GetValidReportsConfig,
+ HydratedPersonalDetailOption,
+ LazyHydrationContext,
MemberForList,
Option,
OptionWithKey,
@@ -328,6 +390,9 @@ export type {
OrderOptionsConfig,
OrderReportOptionsConfig,
PayeePersonalDetails,
+ PersonalDetailFilterRankFields,
+ PersonalDetailOptionOrShell,
+ PersonalDetailShell,
PreviewConfig,
ReportAndPersonalDetailOptions,
SearchOption,
diff --git a/src/pages/Share/ShareTab.tsx b/src/pages/Share/ShareTab.tsx
index 219d3e6603b0..ea980e7fad8c 100644
--- a/src/pages/Share/ShareTab.tsx
+++ b/src/pages/Share/ShareTab.tsx
@@ -61,6 +61,7 @@ function ShareTab() {
const {options: listOptions, isLoading} = useFilteredOptions({
enabled: didScreenTransitionEnd,
isSearching: !!debouncedTextInputValue.trim(),
+ includeP2P: true,
});
const areOptionsInitialized = !isLoading;
const [isSearchingForReports] = useOnyx(ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS);
diff --git a/tests/unit/OptionsListUtilsTest.tsx b/tests/unit/OptionsListUtilsTest.tsx
index 3ad1188fa3fa..a88ed8798b74 100644
--- a/tests/unit/OptionsListUtilsTest.tsx
+++ b/tests/unit/OptionsListUtilsTest.tsx
@@ -13,7 +13,7 @@ import {getAddAgentRuleMessage, getDeleteAgentRuleMessage, getUpdateAgentRuleMes
import DateUtils from '@libs/DateUtils';
import {translate} from '@libs/Localize';
import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute';
-import type {OptionList, Options, SearchOption, SearchOptionData} from '@libs/OptionsListUtils';
+import type {HydratedPersonalDetailOption, OptionList, Options, PersonalDetailOptionOrShell, SearchOption, SearchOptionData} from '@libs/OptionsListUtils';
import {
canCreateOptimisticPersonalDetailOption,
clearFilteredOptionListCache,
@@ -38,6 +38,7 @@ import {
getSearchValueForPhoneOrEmail,
getUserToInviteOption,
getValidOptions,
+ hydrateContactOption,
optionsOrderAndGroupBy,
optionsOrderBy,
orderOptions,
@@ -1335,6 +1336,67 @@ describe('OptionsListUtils', () => {
expect(results.recentReports).toEqual(expect.arrayContaining([expect.objectContaining({login: 'concierge@expensify.com'})]));
});
+ it.each([
+ {
+ description: 'Vietnamese diacritics',
+ // cspell:disable-next-line
+ displayName: 'Trần Hải',
+ searchString: 'tran',
+ },
+ {
+ description: 'Vietnamese extended diacritics',
+ // cspell:disable-next-line
+ displayName: 'Nguyễn Văn A',
+ searchString: 'nguyen',
+ },
+ {
+ description: 'a zero-width space',
+ displayName: 'Jo\u200Bhn',
+ searchString: 'john',
+ },
+ ])('should preserve a contact when the canonical matcher finds $description', ({displayName, searchString}) => {
+ const accountID = 1003;
+ const personalDetails: PersonalDetailsList = {
+ [accountID]: {
+ accountID,
+ displayName,
+ login: 'contact1003@example.com',
+ keyForList: 'contact1003@example.com',
+ reportID: '',
+ },
+ };
+ const optionList = createFilteredOptionList(personalDetails, {}, undefined, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ isSearching: true,
+ });
+
+ const {options: preFilteredOptions} = getValidOptions(
+ optionList,
+ allPolicies,
+ {},
+ loginList,
+ CURRENT_USER_ACCOUNT_ID,
+ CURRENT_USER_EMAIL,
+ undefined,
+ {
+ dateFnsLocale: undefined,
+ includeRecentReports: false,
+ personalDetails,
+ searchString,
+ },
+ translateLocal,
+ );
+
+ // The contact must survive getValidOptions' pre-filter so the final filter can return it.
+ expect(preFilteredOptions.personalDetails).toEqual(expect.arrayContaining([expect.objectContaining({login: 'contact1003@example.com'})]));
+
+ const filteredOptions = filterAndOrderOptions(preFilteredOptions, searchString, COUNTRY_CODE, loginList, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, personalDetails);
+
+ expect(filteredOptions.personalDetails).toEqual([expect.objectContaining({login: 'contact1003@example.com'})]);
+ });
+
it('should exclude Concierge when excludedLogins is specified', () => {
// Given a set of reports and personalDetails that includes Concierge and a config object that excludes Concierge
// When we call getValidOptions()
@@ -1735,6 +1797,700 @@ describe('OptionsListUtils', () => {
});
});
+ describe('getValidOptions() with lazy contact options', () => {
+ const hydrateAllPersonalDetails = (list: OptionList): OptionList => ({
+ ...list,
+ personalDetails: list.personalDetails.map(hydrateContactOption),
+ });
+
+ // NOTE: `eagerList` is NOT a correctness baseline for what hydration produces — both sides of every
+ // comparison below run through hydrateContactOption, so a dropped hydration input would
+ // change both and still pass. What these tests prove is that getValidOptions handles the two halves of
+ // PersonalDetailOptionOrShell identically (filtering, ranking, the top-N heap, marking).
+ // The non-circular check — hydration output vs. a direct createOption call with non-default inputs —
+ // lives in 'lazy contact hydration vs. a direct createOption build' below.
+ const buildOptionLists = () => {
+ const lazyList = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ isSearching: true,
+ });
+ const eagerList = hydrateAllPersonalDetails(lazyList);
+ return {eagerList, lazyList};
+ };
+
+ it('should defer the full option build for every contact', () => {
+ // Given an option list from createFilteredOptionList
+ const {lazyList} = buildOptionLists();
+
+ // Then every contact option is a lightweight one: it is not hydrated and skips expensive fields like icons
+ expect(lazyList.personalDetails.length).toBeGreaterThan(0);
+ expect(lazyList.personalDetails.every((option) => !option.isHydrated)).toBe(true);
+ expect(lazyList.personalDetails.every((option) => !('icons' in option))).toBe(true);
+ });
+
+ it('should produce results identical to eagerly built options after hydration', () => {
+ // Given the same data as lightweight shells and as fully hydrated options
+ const {eagerList, lazyList} = buildOptionLists();
+
+ // When both lists go through getValidOptions with a top-N cap that exercises the heap
+ const config = {dateFnsLocale: undefined, maxElements: 3, personalDetails: PERSONAL_DETAILS};
+ const {options: eagerResults} = getValidOptions(eagerList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const {options: lazyResults} = getValidOptions(lazyList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+
+ // Then the surviving contacts are hydrated (createOption ran for them) and match the eager results exactly
+ expect(lazyResults.personalDetails.length).toBeGreaterThan(0);
+ expect(lazyResults.personalDetails.every((option) => option.icons !== undefined)).toBe(true);
+ expect(lazyResults.personalDetails.every((option) => !('hydrate' in option))).toBe(true);
+ expect(lazyResults.personalDetails).toEqual(eagerResults.personalDetails);
+ });
+
+ it('should produce results identical to eagerly built options when searching', () => {
+ // Given the same data as lightweight shells and as fully hydrated options
+ const {eagerList, lazyList} = buildOptionLists();
+
+ // When both lists go through getValidOptions with a search string (contact filtering reads text/login/participantsList)
+ const config = {dateFnsLocale: undefined, searchString: 'spider', personalDetails: PERSONAL_DETAILS};
+ const {options: eagerResults} = getValidOptions(eagerList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const {options: lazyResults} = getValidOptions(lazyList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+
+ // Then filtering and ordering are unchanged and the hydrated results match
+ expect(lazyResults.personalDetails).toEqual(eagerResults.personalDetails);
+ });
+
+ it.each([
+ {
+ description: 'an apostrophe',
+ reportText: "Don't forget",
+ searchText: 'dont',
+ },
+ {
+ description: 'a hyphen',
+ reportText: 'Foo-Bar',
+ searchText: 'foobar',
+ },
+ {
+ description: 'diacritics',
+ // cspell:disable-next-line
+ reportText: 'Café Zürich',
+ searchText: 'cafe zurich',
+ },
+ {
+ description: 'a zero-width character',
+ reportText: 'Foo\u200BBar',
+ searchText: 'foobar',
+ },
+ {
+ description: 'dots omitted from an email address',
+ reportText: 'Test User',
+ reportLogin: 'test.user@example.com',
+ searchText: 'testuser@example.com',
+ },
+ {
+ description: 'a formatted phone number',
+ reportText: 'Phone Contact',
+ reportLogin: '+12345678901',
+ searchText: '+1 (234) 567-8901',
+ },
+ ])('should preserve a report match through the pre-filter and final filter for $description', ({reportText, reportLogin, searchText}) => {
+ // Given a report option with a search-sensitive display value
+ const sourceReport = OPTIONS.reports.find((report) => !!report.login);
+ expect(sourceReport).toBeDefined();
+ if (!sourceReport) {
+ return;
+ }
+
+ const report = {
+ ...sourceReport,
+ text: reportText,
+ login: reportLogin ?? sourceReport.login,
+ };
+
+ // When getValidOptions receives the NewChat-style normalized search value and the result is
+ // filtered again with the raw search value, as it is in NewChatPage
+ const searchString = getSearchValueForPhoneOrEmail(searchText, COUNTRY_CODE);
+ const {options} = getValidOptions(
+ {reports: [report], personalDetails: []},
+ allPolicies,
+ {},
+ loginList,
+ CURRENT_USER_ACCOUNT_ID,
+ CURRENT_USER_EMAIL,
+ undefined,
+ {dateFnsLocale: undefined, searchString, includeP2P: true},
+ translateLocal,
+ );
+ const filteredOptions = filterAndOrderOptions(options, searchText, COUNTRY_CODE, loginList, CURRENT_USER_EMAIL, CURRENT_USER_ACCOUNT_ID, PERSONAL_DETAILS);
+
+ // Then the report must survive both filtering stages
+ expect(filteredOptions.recentReports).toEqual(expect.arrayContaining([expect.objectContaining({reportID: report.reportID, text: reportText})]));
+ });
+
+ it('should keep every shell filter and sort field identical to the hydrated option', () => {
+ // Given lightweight shells from createFilteredOptionList
+ const {eagerList, lazyList} = buildOptionLists();
+
+ // Then each shell carries the exact values the downstream filter (login/accountID/participantsList/text)
+ // and the heap comparator key read on the hydrated option, which also guarantees identical
+ // tie-breaking for contacts with equal comparator keys
+ expect(lazyList.personalDetails.length).toBe(eagerList.personalDetails.length);
+ for (const [index, eagerOption] of eagerList.personalDetails.entries()) {
+ const shell = lazyList.personalDetails.at(index);
+ expect(shell?.text).toBe(eagerOption.text);
+ expect(shell?.login).toBe(eagerOption.login);
+ expect(shell?.accountID).toBe(eagerOption.accountID);
+ expect(shell?.participantsList).toEqual(eagerOption.participantsList);
+ }
+ });
+
+ it('should not let createOption drift from the lazy shell on any filter- or rank-relevant field', () => {
+ // Drift guard for the lazy shell: it hand-reproduces the subset of createOption's showPersonalDetails
+ // output that getValidOptions filters and ranks on. If createOption ever changes how one of those
+ // values is derived - or starts populating a new one (e.g. displayName / isOptimisticPersonalDetail,
+ // currently undefined on both paths) - the shell must be updated in lockstep or filtering/ranking
+ // will diverge from what is displayed after hydration. This asserts exact parity across every such
+ // field so that a one-sided change to createOption fails here.
+ //
+ // When you add a field that the personal-details filter (see getValidOptions -> filteringFunction
+ // / doesPersonalDetailMatchSearchTerm) or the heap comparator (personalDetailsComparator) reads,
+ // add it to this list AND reproduce it in buildPersonalDetailsOptions.
+ const FILTER_AND_RANK_FIELDS = ['text', 'login', 'accountID', 'participantsList', 'displayName', 'isOptimisticPersonalDetail'] as const;
+
+ // Given lightweight shells and their hydrated counterparts
+ const {eagerList, lazyList} = buildOptionLists();
+
+ // Then every shell reproduces every filter/rank field exactly, and the resolved comparator key matches
+ expect(lazyList.personalDetails.length).toBe(eagerList.personalDetails.length);
+ expect(lazyList.personalDetails.length).toBeGreaterThan(0);
+ for (const [index, eagerOption] of eagerList.personalDetails.entries()) {
+ const shell = lazyList.personalDetails.at(index);
+ for (const field of FILTER_AND_RANK_FIELDS) {
+ expect(shell?.[field]).toEqual(eagerOption[field]);
+ }
+ // personalDetailsComparator ranks on `text ?? alternateText ?? login`. Both paths always populate
+ // `text` with a string, so the fallbacks are unreachable for personal details and the shells
+ // getValidOptions ranks cannot order differently from the hydrated options orderOptions ranks
+ // later. Assert that invariant directly: if createOption ever leaves `text` nullish, the two
+ // passes would silently diverge (the shell has no alternateText to fall back to, by design).
+ expect(typeof shell?.text).toBe('string');
+ expect(typeof eagerOption.text).toBe('string');
+ }
+ });
+
+ it('should produce results identical to eagerly built options with custom exclusions', () => {
+ // Given the same data as lightweight shells and as fully hydrated options
+ const {eagerList, lazyList} = buildOptionLists();
+
+ // When both lists go through getValidOptions with a custom exclusion (filter reads shell.login)
+ const config = {dateFnsLocale: undefined, excludeLogins: {'peterparker@expensify.com': true}, personalDetails: PERSONAL_DETAILS};
+ const {options: eagerResults} = getValidOptions(eagerList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const {options: lazyResults} = getValidOptions(lazyList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+
+ // Then the excluded contact is dropped from both and the remaining results match
+ expect(lazyResults.personalDetails.some((option) => option.login === 'peterparker@expensify.com')).toBe(false);
+ expect(lazyResults.personalDetails).toEqual(eagerResults.personalDetails);
+ });
+
+ it('should handle empty personal details', () => {
+ // Given a lazily built option list with no personal details
+ const lazyList = createFilteredOptionList({}, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ isSearching: true,
+ });
+
+ // When it goes through getValidOptions
+ const {options: results} = getValidOptions(
+ lazyList,
+ allPolicies,
+ {},
+ loginList,
+ CURRENT_USER_ACCOUNT_ID,
+ CURRENT_USER_EMAIL,
+ undefined,
+ {dateFnsLocale: undefined},
+ translateLocal,
+ );
+
+ // Then no contacts are produced and nothing throws
+ expect(lazyList.personalDetails).toEqual([]);
+ expect(results.personalDetails).toEqual([]);
+ });
+
+ it('should hydrate every rendering-critical property on surviving contacts', () => {
+ // Given a lazily built option list
+ const {lazyList} = buildOptionLists();
+
+ // When it goes through getValidOptions
+ const {options: results} = getValidOptions(
+ lazyList,
+ allPolicies,
+ {},
+ loginList,
+ CURRENT_USER_ACCOUNT_ID,
+ CURRENT_USER_EMAIL,
+ undefined,
+ {
+ dateFnsLocale: undefined,
+ personalDetails: PERSONAL_DETAILS,
+ },
+ translateLocal,
+ );
+
+ // Then every surviving contact has the properties SelectionList rendering and selection rely on,
+ // so the deferred build introduces no missing fields
+ expect(results.personalDetails.length).toBeGreaterThan(0);
+ for (const option of results.personalDetails) {
+ expect(option.icons).toBeDefined();
+ expect(option.keyForList).toBeTruthy();
+ expect(option.text).toBeDefined();
+ expect(option.alternateText).toBeDefined();
+ expect(option.login).toBeDefined();
+ expect(option.accountID).toBeDefined();
+ expect(typeof option.isSelected).toBe('boolean');
+ }
+ });
+
+ it('should produce results identical to eagerly built options when searching with a top-N cap', () => {
+ // Given the same data as lightweight shells and as fully hydrated options
+ const {eagerList, lazyList} = buildOptionLists();
+
+ // When both lists go through getValidOptions with search + maxElements together
+ // (filter selects matches, then the heap keeps only the top-N survivors to hydrate)
+ const config = {dateFnsLocale: undefined, searchString: 'man', maxElements: 3, personalDetails: PERSONAL_DETAILS};
+ const {options: eagerResults} = getValidOptions(eagerList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const {options: lazyResults} = getValidOptions(lazyList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+
+ // Then filtering, ranking, and hydration match the eager path
+ expect(lazyResults.personalDetails.length).toBeGreaterThan(0);
+ expect(lazyResults.personalDetails.every((option) => option.icons !== undefined)).toBe(true);
+ expect(lazyResults.personalDetails.every((option) => !('hydrate' in option))).toBe(true);
+ expect(lazyResults.personalDetails).toEqual(eagerResults.personalDetails);
+ });
+
+ it('should hydrate correctly after a filtered option list cache hit', () => {
+ // Given lazy contact options built while not searching (the only mode that uses the option-list cache)
+ clearFilteredOptionListCache();
+ const firstLazyList = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ });
+ const cachedLazyList = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ });
+ const eagerList = hydrateAllPersonalDetails(firstLazyList);
+
+ // Then the cache hit still returns shells
+ expect(cachedLazyList.personalDetails.every((option) => !option.isHydrated)).toBe(true);
+
+ // And the clone from the cache hit shares each shell's hydration closure, so the expensive build is
+ // reused rather than re-run per clone. cloneOptionList allocates a new shell object on every return,
+ // so a memo keyed on shell identity would start empty here and rebuild the whole visible page.
+ const freshShell = firstLazyList.personalDetails.at(0);
+ const cachedShell = cachedLazyList.personalDetails.at(0);
+ expect(freshShell).toBeDefined();
+ expect(cachedShell).toBeDefined();
+ expect(cachedShell).not.toBe(freshShell);
+ if (freshShell && cachedShell) {
+ expect(hydrateContactOption(cachedShell).icons).toBe(hydrateContactOption(freshShell).icons);
+ }
+
+ // When both the fresh and cached lazy lists go through getValidOptions
+ const config = {dateFnsLocale: undefined, maxElements: 3, personalDetails: PERSONAL_DETAILS};
+ const {options: firstResults} = getValidOptions(firstLazyList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const {options: cachedResults} = getValidOptions(cachedLazyList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const {options: eagerResults} = getValidOptions(eagerList, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+
+ // Then hydration from the cached clone matches the fresh lazy build and the eager path
+ expect(cachedResults.personalDetails).toEqual(firstResults.personalDetails);
+ expect(cachedResults.personalDetails).toEqual(eagerResults.personalDetails);
+ });
+
+ it('should hydrate with the build-time inputs, keeping brickRoadIndicator without any caller-provided data', () => {
+ // Given a contact whose 1:1 DM report has a brick road status in the derived report attributes
+ const {lazyList: baseList} = buildOptionLists();
+ const dmReportID = baseList.personalDetails.find((option) => option.reportID)?.reportID;
+ expect(dmReportID).toBeTruthy();
+ const attributesWithError: Record = {
+ ...MOCK_REPORT_ATTRIBUTES_DERIVED,
+ [String(dmReportID)]: {
+ ...MOCK_REPORT_ATTRIBUTES_DERIVED[String(dmReportID)],
+ brickRoadStatus: CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR,
+ },
+ };
+ const lazyList = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, attributesWithError, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ isSearching: true,
+ });
+ const shell = lazyList.personalDetails.find((option) => option.reportID === dmReportID);
+ expect(shell).toBeDefined();
+ if (!shell) {
+ return;
+ }
+
+ // When the shell is hydrated (hydration reads the inputs captured at build time, so no consumer
+ // - e.g. a getSearchOptions caller without report attributes in scope - can drop display data)
+ const hydrated = hydrateContactOption(shell);
+
+ // Then the RBR indicator matches what the eager build would have produced
+ expect(hydrated.brickRoadIndicator).toBe(CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR);
+ });
+
+ it('should reuse the built option per shell while still returning a fresh object every time', () => {
+ // Given a shell hydrated once (screens like NewChatPage re-run getValidOptions on every keystroke,
+ // so re-running createOption for every surviving contact would be slower than the eager build)
+ const {lazyList} = buildOptionLists();
+ const shell = lazyList.personalDetails.at(0);
+ expect(shell).toBeDefined();
+ if (!shell) {
+ return;
+ }
+ const first = hydrateContactOption(shell);
+
+ // When the same shell is hydrated again
+ const second = hydrateContactOption(shell);
+
+ // Then the expensive parts are shared, but the option itself is a new object so consumers marking it
+ // in place (isSelected/isBold) cannot leak into other callers and list rows still see a changed reference
+ expect(second).not.toBe(first);
+ expect(second).toEqual(first);
+ expect(second.icons).toBe(first.icons);
+
+ // And mutating one copy leaves later hydrations of the same shell untouched
+ first.isSelected = true;
+ expect(hydrateContactOption(shell).isSelected).toBe(false);
+ });
+
+ it('should hydrate lazy shells when mixed with fully-built device contacts', () => {
+ // Given a fully-built device contact appended onto eager and lazy lists as the hydrated half of the
+ // union, matching useSearchSelector's contactOptions concat path
+ const deviceContactLogin = '+15551234567';
+ const deviceContact: HydratedPersonalDetailOption = {
+ item: {
+ accountID: 9999,
+ displayName: 'Device Contact Jane',
+ login: deviceContactLogin,
+ },
+ reportID: '',
+ keyForList: '9999',
+ text: 'Device Contact Jane',
+ alternateText: deviceContactLogin,
+ login: deviceContactLogin,
+ accountID: 9999,
+ participantsList: [
+ {
+ accountID: 9999,
+ displayName: 'Device Contact Jane',
+ login: deviceContactLogin,
+ },
+ ],
+ icons: [
+ {
+ source: '',
+ name: 'Device Contact Jane',
+ type: CONST.ICON_TYPE_AVATAR,
+ id: 9999,
+ },
+ ],
+ isSelected: false,
+ selected: false,
+ brickRoadIndicator: null,
+ isHydrated: true,
+ };
+
+ const {eagerList, lazyList} = buildOptionLists();
+ const eagerWithContacts: OptionList = {
+ ...eagerList,
+ personalDetails: eagerList.personalDetails.concat(deviceContact),
+ };
+ const lazyWithContacts: OptionList = {
+ ...lazyList,
+ personalDetails: lazyList.personalDetails.concat(deviceContact),
+ };
+
+ // When both mixed lists are filtered for the device contact
+ const config = {dateFnsLocale: undefined, searchString: 'Device Contact Jane', personalDetails: PERSONAL_DETAILS};
+ const {options: eagerResults} = getValidOptions(eagerWithContacts, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const {options: lazyResults} = getValidOptions(lazyWithContacts, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+
+ // Then the device contact survives hydrate unchanged, lazy shells hydrate, and results match eager
+ expect(lazyResults.personalDetails.some((option) => option.login === deviceContactLogin)).toBe(true);
+ expect(lazyResults.personalDetails.find((option) => option.login === deviceContactLogin)?.icons).toBeDefined();
+ expect(lazyResults.personalDetails.every((option) => !('hydrate' in option))).toBe(true);
+ expect(lazyResults.personalDetails).toEqual(eagerResults.personalDetails);
+ });
+ });
+
+ describe('lazy contact hydration vs. a direct createOption build', () => {
+ // A self-contained fixture so every hydration input can be set to a non-default value and the output
+ // field it drives can be asserted individually. Comparing hydration against another hydration cannot
+ // catch a dropped input; comparing it against a direct createOption call can.
+ const PARITY_ACCOUNT_ID = 77;
+ const PARITY_REPORT_ID = '7700';
+ const PARITY_LOGIN = 'parity@expensify.com';
+
+ const PARITY_PERSONAL_DETAILS: PersonalDetailsList = {
+ '77': {
+ accountID: PARITY_ACCOUNT_ID,
+ displayName: 'Parity Contact',
+ login: PARITY_LOGIN,
+ keyForList: PARITY_LOGIN,
+ reportID: PARITY_REPORT_ID,
+ },
+ };
+ const PARITY_PERSONAL_DETAIL = PARITY_PERSONAL_DETAILS['77'] ?? null;
+
+ // A plain 1:1 DM, so createFilteredOptionList maps it onto the contact above.
+ const PARITY_REPORT: Report = {
+ reportID: PARITY_REPORT_ID,
+ type: CONST.REPORT.TYPE.CHAT,
+ reportName: 'Parity Contact',
+ lastVisibleActionCreated: '2024-01-01 00:00:00.000',
+ participants: {
+ [CURRENT_USER_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS},
+ [PARITY_ACCOUNT_ID]: {notificationPreference: CONST.REPORT.NOTIFICATION_PREFERENCE.ALWAYS},
+ },
+ };
+ const PARITY_REPORTS: OnyxCollection = {[PARITY_REPORT_ID]: PARITY_REPORT};
+
+ // Non-default hydration inputs. Each one drives a different field of the built option, asserted below.
+ const PARITY_ATTRIBUTES: Record = {
+ [PARITY_REPORT_ID]: {
+ reportName: 'Parity Contact',
+ isEmpty: false,
+ brickRoadStatus: CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR,
+ requiresAttention: true,
+ reportErrors: {},
+ },
+ };
+ const PARITY_ARCHIVED_MAP: PrivateIsArchivedMap = {
+ [`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${PARITY_REPORT_ID}`]: true,
+ };
+
+ const buildParityShell = () => {
+ clearFilteredOptionListCache();
+ const list = createFilteredOptionList(PARITY_PERSONAL_DETAILS, PARITY_REPORTS, PARITY_ATTRIBUTES, PARITY_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ isSearching: true,
+ });
+ const shell = list.personalDetails.at(0);
+ expect(shell).toBeDefined();
+ // Guard against a vacuous pass: the DM has to be mapped onto the contact, or none of the
+ // report-derived inputs below would reach createOption on either side.
+ expect(shell?.reportID).toBe(PARITY_REPORT_ID);
+ return shell;
+ };
+
+ it('should produce exactly what createOption produces from the same inputs', () => {
+ // Given a shell built from a fixture where every report-derived hydration input is non-default
+ const shell = buildParityShell();
+ if (!shell) {
+ return;
+ }
+
+ // When it is hydrated
+ const hydrated = hydrateContactOption(shell);
+
+ // Then it matches an option built by calling createOption directly with those same inputs.
+ // Dropping any input from the hydration path makes this diverge, because this side names them all.
+ const expected: HydratedPersonalDetailOption = {
+ item: PARITY_PERSONAL_DETAIL,
+ ...createOption({
+ dateFnsLocale: undefined,
+ accountIDs: [PARITY_ACCOUNT_ID],
+ personalDetails: PARITY_PERSONAL_DETAILS,
+ report: PARITY_REPORT,
+ policy: undefined,
+ privateIsArchived: true,
+ conciergeReportID: undefined,
+ config: {showPersonalDetails: true},
+ reportAttributesDerived: PARITY_ATTRIBUTES,
+ policyTags: undefined,
+ visibleReportActionsData: {},
+ }),
+ isHydrated: true,
+ };
+
+ expect(hydrated).toEqual(expected);
+ });
+
+ it('should carry the brick road status from reportAttributesDerived into the built option', () => {
+ // Given reportAttributesDerived marking the mapped DM with an error brick road
+ const shell = buildParityShell();
+ if (!shell) {
+ return;
+ }
+
+ // Then hydration surfaces it, so a caller with no report attributes in scope cannot lose it
+ expect(hydrateContactOption(shell).brickRoadIndicator).toBe(CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR);
+ });
+
+ it('should carry the archived state from privateIsArchivedMap into the built option', () => {
+ // Given a privateIsArchivedMap marking the mapped DM as archived
+ const shell = buildParityShell();
+ if (!shell) {
+ return;
+ }
+
+ // Then hydration reflects it
+ expect(hydrateContactOption(shell).private_isArchived).toBe(true);
+ });
+
+ it('should carry conciergeReportID into the built option', () => {
+ // Given the mapped DM is the Concierge report
+ clearFilteredOptionListCache();
+ const list = createFilteredOptionList(PARITY_PERSONAL_DETAILS, PARITY_REPORTS, PARITY_ATTRIBUTES, PARITY_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: PARITY_REPORT_ID,
+ isSearching: true,
+ });
+ const shell = list.personalDetails.at(0);
+ expect(shell).toBeDefined();
+ if (!shell) {
+ return;
+ }
+
+ // Then hydration builds the same option a direct createOption call with that conciergeReportID does,
+ // rather than the one it would build with conciergeReportID dropped
+ const hydrated = hydrateContactOption(shell);
+ const withConcierge = createOption({
+ dateFnsLocale: undefined,
+ accountIDs: [PARITY_ACCOUNT_ID],
+ personalDetails: PARITY_PERSONAL_DETAILS,
+ report: PARITY_REPORT,
+ policy: undefined,
+ privateIsArchived: true,
+ conciergeReportID: PARITY_REPORT_ID,
+ config: {showPersonalDetails: true},
+ reportAttributesDerived: PARITY_ATTRIBUTES,
+ policyTags: undefined,
+ visibleReportActionsData: {},
+ });
+
+ expect(hydrated).toEqual({item: PARITY_PERSONAL_DETAIL, ...withConcierge, isHydrated: true});
+ });
+ });
+
+ describe('lazy contact options on the warm path', () => {
+ // createOption is called through a module-local binding, so a jest spy on the export never sees it.
+ // buildFullOption allocates a fresh `icons` array per build instead, so sharing that array by reference
+ // is exactly "no createOption ran": a rebuild could not produce the same array object.
+ const buildIdentity = (option: PersonalDetailOptionOrShell) => hydrateContactOption(option).icons;
+
+ it('should not rebuild any contact option when the second option list comes from the entry cache', () => {
+ // Given two identical createFilteredOptionList calls, the second served from the entry cache
+ clearFilteredOptionListCache();
+ const first = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ });
+ const second = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ });
+ expect(first.personalDetails.length).toBeGreaterThan(0);
+ expect(second.personalDetails.length).toBe(first.personalDetails.length);
+
+ // When both are run through getValidOptions (the first pass builds, the second must not)
+ const config = {dateFnsLocale: undefined, personalDetails: PERSONAL_DETAILS};
+ const firstBuilds = first.personalDetails.map(buildIdentity);
+ const {options: firstResults} = getValidOptions(first, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const {options: secondResults} = getValidOptions(second, allPolicies, {}, loginList, CURRENT_USER_ACCOUNT_ID, CURRENT_USER_EMAIL, undefined, config, translateLocal);
+ const secondBuilds = second.personalDetails.map(buildIdentity);
+
+ // Then every contact on the second pass reused the first pass's build.
+ // cloneOptionList hands out fresh shell objects on every return, so a memo keyed on shell identity
+ // starts empty for each clone and rebuilds the whole visible page — slower than the eager build it
+ // replaced. Keying the memo inside the shell's own closure is what makes the warm path free.
+ expect(secondBuilds).toHaveLength(firstBuilds.length);
+ for (let i = 0; i < firstBuilds.length; i++) {
+ expect(secondBuilds.at(i)).toBe(firstBuilds.at(i));
+ }
+
+ // And the two passes still produce equal output
+ expect(secondResults.personalDetails).toEqual(firstResults.personalDetails);
+ });
+
+ it('should freeze the memoized build in dev while leaving the copy handed to callers writable', () => {
+ // Given a hydrated contact option
+ clearFilteredOptionListCache();
+ const list = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ isSearching: true,
+ });
+ const shell = list.personalDetails.at(0);
+ expect(shell).toBeDefined();
+ if (!shell) {
+ return;
+ }
+ const hydrated = hydrateContactOption(shell);
+ const icons = hydrated.icons;
+ expect(icons?.length).toBeGreaterThan(0);
+
+ // Then its nested objects — shared with every other caller that hydrates the same contact — are
+ // locked, so a consumer that mutates one cannot silently corrupt what the next caller reads.
+ // NOTE: jest runs this file in sloppy mode, where assigning to a frozen property fails silently
+ // instead of throwing, so assert the freeze itself plus a mutation that throws in either mode.
+ expect(Object.isFrozen(icons)).toBe(true);
+ expect(Object.isFrozen(icons?.at(0))).toBe(true);
+ const originalSource = icons?.at(0)?.source;
+ const icon = icons?.at(0);
+ if (icon) {
+ icon.source = '';
+ }
+ expect(icons?.at(0)?.source).toBe(originalSource);
+ expect(() => icons?.pop()).toThrow(TypeError);
+
+ // While the top-level copy stays writable, because getValidOptions marks options in place
+ hydrated.isBold = true;
+ expect(hydrated.isBold).toBe(true);
+ expect(Object.isFrozen(hydrated)).toBe(false);
+ });
+ });
+
+ describe('PersonalDetailOptionOrShell typing', () => {
+ it('should not let a display field be read without narrowing on isHydrated', () => {
+ clearFilteredOptionListCache();
+ const list = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, MOCK_REPORT_ATTRIBUTES_DERIVED, EMPTY_PRIVATE_IS_ARCHIVED_MAP, allPolicies, {
+ currentUserAccountID: CURRENT_USER_ACCOUNT_ID,
+ dateFnsLocale: undefined,
+ conciergeReportID: undefined,
+ isSearching: true,
+ });
+ const option = list.personalDetails.at(0);
+ expect(option).toBeDefined();
+ if (!option) {
+ return;
+ }
+
+ // The display fields only exist on the hydrated half of the union, so reading one off the union is
+ // a compile error rather than an `undefined` that reaches a rendered row.
+ // @ts-expect-error icons is not readable without narrowing on isHydrated
+ const {icons} = option;
+ // @ts-expect-error subtitle is not readable without narrowing on isHydrated
+ const {subtitle} = option;
+ expect(icons).toBeUndefined();
+ expect(subtitle).toBeUndefined();
+
+ // Narrowing (or hydrating) is what makes them readable
+ expect(hydrateContactOption(option).icons).toBeDefined();
+ });
+ });
+
describe('getValidOptions() for chat room', () => {
it('should include all reports by default', () => {
// Given a set of reports and personalDetails that includes workspace rooms
@@ -3918,9 +4674,10 @@ describe('OptionsListUtils', () => {
isSearching: true,
});
- // Then the personal detail option for account 1 (Mister Fantastic) should have private_isArchived set
+ // Then the hydrated personal detail option for account 1 (Mister Fantastic) should have private_isArchived set
const misterFantasticOption = result.personalDetails.find((pd) => pd.item?.accountID === 1);
- expect(misterFantasticOption?.private_isArchived).toBe(true);
+ const hydratedMisterFantasticOption = misterFantasticOption ? hydrateContactOption(misterFantasticOption) : undefined;
+ expect(hydratedMisterFantasticOption?.private_isArchived).toBe(true);
});
it('should not set private_isArchived on personal details options when privateIsArchivedMap is empty', () => {
@@ -3936,8 +4693,8 @@ describe('OptionsListUtils', () => {
isSearching: true,
});
- // Then no personal details options should have private_isArchived set
- const optionsWithArchived = result.personalDetails.filter((pd) => pd.private_isArchived);
+ // Then no personal details options should have private_isArchived set once hydrated
+ const optionsWithArchived = result.personalDetails.map(hydrateContactOption).filter((pd) => pd.private_isArchived);
expect(optionsWithArchived.length).toBe(0);
});
@@ -3957,12 +4714,14 @@ describe('OptionsListUtils', () => {
isSearching: true,
});
- // Then the personal detail options should have the correct private_isArchived values
+ // Then the hydrated personal detail options should have the correct private_isArchived values
const misterFantasticOption = result.personalDetails.find((pd) => pd.item?.accountID === 1);
const invisibleWomanOption = result.personalDetails.find((pd) => pd.item?.accountID === 5);
+ const hydratedMisterFantasticOption = misterFantasticOption ? hydrateContactOption(misterFantasticOption) : undefined;
+ const hydratedInvisibleWomanOption = invisibleWomanOption ? hydrateContactOption(invisibleWomanOption) : undefined;
- expect(misterFantasticOption?.private_isArchived).toBe(true);
- expect(invisibleWomanOption?.private_isArchived).toBe(true);
+ expect(hydratedMisterFantasticOption?.private_isArchived).toBe(true);
+ expect(hydratedInvisibleWomanOption?.private_isArchived).toBe(true);
});
it('should set private_isArchived on report options when privateIsArchivedMap is provided', () => {
@@ -4226,6 +4985,59 @@ describe('OptionsListUtils', () => {
// Then the returned value should match the search term
expect(filteredReports).toEqual(reports);
});
+
+ it.each([
+ {
+ description: 'an apostrophe',
+ reportText: "Don't forget",
+ searchText: 'dont',
+ },
+ {
+ description: 'a hyphen',
+ reportText: 'Foo-Bar',
+ searchText: 'foobar',
+ },
+ {
+ description: 'a zero-width character',
+ reportText: 'Foo\u200BBar',
+ searchText: 'foobar',
+ },
+ ])('should match report text containing $description', ({reportText, searchText}) => {
+ // Given a report whose display text contains characters normalized by report search
+ const report: OptionData = {text: reportText, reportID: 'normalized', keyForList: 'normalized'};
+
+ // When the report is filtered with the normalized search value
+ const filteredReports = filterReports([report], [searchText]);
+
+ // Then the report should remain in the results
+ expect(filteredReports).toEqual([report]);
+ });
+
+ it('should match a report by email when dots are omitted from the search', () => {
+ const report: OptionData = {
+ text: 'Test User',
+ login: 'test.user@example.com',
+ reportID: 'email',
+ keyForList: 'email',
+ };
+
+ const filteredReports = filterReports([report], ['testuser@example.com']);
+
+ expect(filteredReports).toEqual([report]);
+ });
+
+ it('should match a report by its normalized phone number', () => {
+ const report: OptionData = {
+ text: 'Phone Contact',
+ login: '+12345678901',
+ reportID: 'phone',
+ keyForList: 'phone',
+ };
+
+ const filteredReports = filterReports([report], [getSearchValueForPhoneOrEmail('+1 (234) 567-8901', COUNTRY_CODE)]);
+
+ expect(filteredReports).toEqual([report]);
+ });
});
describe('getMostRecentOptions()', () => {
@@ -10056,9 +10868,11 @@ describe('OptionsListUtils', () => {
const secondOption = second.personalDetails.at(0);
// Same cache entry (nested objects are shared between clones), but each caller gets fresh top-level objects.
- expect(secondOption?.icons).toBe(firstOption?.icons);
+ // Personal detail shells share participantsList; report options share icons.
+ expect(secondOption?.participantsList).toBe(firstOption?.participantsList);
expect(secondOption).not.toBe(firstOption);
expect(secondOption?.isSelected).toBeFalsy();
+ expect(second.reports.at(0)?.icons).toBe(first.reports.at(0)?.icons);
});
// conciergeReportID affects the Concierge option's subtitle/alternate text, so a change must
@@ -10075,8 +10889,11 @@ describe('OptionsListUtils', () => {
conciergeReportID: '1',
});
- // A cache hit would share nested objects between clones (see the pristine-cache test above).
- expect(second.personalDetails.at(0)?.icons).not.toBe(first.personalDetails.at(0)?.icons);
+ // A cache hit copies each shell's `hydrate` by reference between clones (see the pristine-cache test
+ // above), so a fresh closure is what proves the entry was rebuilt rather than served.
+ const getHydrate = (option: PersonalDetailOptionOrShell | undefined) => (option && !option.isHydrated ? option.hydrate : undefined);
+ expect(getHydrate(first.personalDetails.at(0))).toBeDefined();
+ expect(getHydrate(second.personalDetails.at(0))).not.toBe(getHydrate(first.personalDetails.at(0)));
});
// The cached entry is frozen in dev, so a consumer that mutates a nested object shared with the
@@ -10087,7 +10904,8 @@ describe('OptionsListUtils', () => {
dateFnsLocale: undefined,
conciergeReportID: undefined,
});
- const icons = result.personalDetails.at(0)?.icons;
+ // Report options still carry fully-built icons; personal detail shells do not.
+ const icons = result.reports.at(0)?.icons;
expect(icons?.length).toBeGreaterThan(0);
expect(() => icons?.pop()).toThrow(TypeError);
@@ -10108,6 +10926,13 @@ describe('OptionsListUtils', () => {
expect(Object.isFrozen(personalDetailItem)).toBe(false);
expect(reportItem).toBeDefined();
expect(Object.isFrozen(reportItem)).toBe(false);
+
+ // Hydration freezes the option it memoizes, and it reads shared Onyx Reports out of its captured
+ // build inputs — those must survive unfrozen too.
+ const hydrated = result.personalDetails.map(hydrateContactOption);
+ expect(hydrated.length).toBeGreaterThan(0);
+ expect(hydrated.every((option) => !Object.isFrozen(option))).toBe(true);
+ expect(Object.values(REPORTS).every((report) => !Object.isFrozen(report))).toBe(true);
});
});
describe('getValidOptions() with recentAttendees', () => {
@@ -10988,6 +11813,8 @@ describe('OptionsListUtils', () => {
});
expect(results.recentReports.length).toBe(1);
+ expect(results.recentReports.at(0)?.isUnread).toBe(true);
+ expect(results.recentReports.at(0)?.isBold).toBe(true);
});
});
});