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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 19 additions & 15 deletions src/components/Search/SearchAutocompleteList.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type {ForwardedRef, RefObject} from 'react';
import React, {useContext, useEffect, useMemo, useRef, useState} from 'react';
import React, {useEffect, useMemo, useRef, useState} from 'react';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import {OptionsListStateContext, useOptionsList} from '@components/OptionListContextProvider';
import OptionsListSkeletonView from '@components/OptionsListSkeletonView';
import type {AnimatedTextInputRef} from '@components/RNTextInput';
import type {ListItem as NewListItem, UserListItemProps} from '@components/SelectionList/ListItem/types';
Expand All @@ -13,6 +12,7 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'
import useDebounce from '@hooks/useDebounce';
import useDebouncedAccessibilityAnnouncement from '@hooks/useDebouncedAccessibilityAnnouncement';
import useFeedKeysWithAssignedCards from '@hooks/useFeedKeysWithAssignedCards';
import useFilteredOptions from '@hooks/useFilteredOptions';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
Expand Down Expand Up @@ -94,6 +94,11 @@ const defaultListOptions = {
categoryOptions: [],
};

const emptyOptionList = {
reports: [],
personalDetails: [],
};

const setPerformanceTimersEnd = () => {
endSpan(CONST.TELEMETRY.SPAN_OPEN_SEARCH_ROUTER);
};
Expand Down Expand Up @@ -165,7 +170,7 @@ function SearchAutocompleteList({
const expensifyIcons = useMemoizedLazyExpensifyIcons(['History', 'MagnifyingGlass']);
const taxRates = getAllTaxRates(policies);

const {options, areOptionsInitialized} = useOptionsList();
const {options: listOptions, isLoading: isLoadingOptions} = useFilteredOptions({enabled: true, isSearching: !!autocompleteQueryValue.trim(), betas: betas ?? []});

const isRecentSearchesDataLoaded = !isLoadingOnyxValue(recentSearchesMetadata);

Expand All @@ -175,25 +180,24 @@ function SearchAutocompleteList({
};
}, []);

const {areOptionsInitialized: contextAreOptionsInitialized} = useContext(OptionsListStateContext);
const coldStartAttributeSet = useRef(false);
useEffect(() => {
if (coldStartAttributeSet.current) {
return;
}
const parentSpan = getSpan(CONST.TELEMETRY.SPAN_OPEN_SEARCH_ROUTER);
if (parentSpan) {
parentSpan.setAttribute(CONST.TELEMETRY.ATTRIBUTE_COLD_START, !contextAreOptionsInitialized);
parentSpan.setAttribute(CONST.TELEMETRY.ATTRIBUTE_COLD_START, isLoadingOptions);
coldStartAttributeSet.current = true;
}
}, [contextAreOptionsInitialized]);
}, [isLoadingOptions]);

const searchOptions = (() => {
if (!areOptionsInitialized) {
if (listOptions === null) {
return defaultListOptions;
}
return getSearchOptions({
options,
options: listOptions,
draftComments,
nvpDismissedProductTraining,
betas: betas ?? [],
Expand Down Expand Up @@ -277,7 +281,7 @@ function SearchAutocompleteList({
autocompleteQueryValue,
allCards,
allFeeds,
options,
options: listOptions ?? emptyOptionList,
draftComments,
nvpDismissedProductTraining,
betas,
Expand Down Expand Up @@ -357,7 +361,7 @@ function SearchAutocompleteList({
const reasonAttributes: SkeletonSpanReasonAttributes = {
context: 'SearchAutocompleteList',
isRecentSearchesDataLoaded,
areOptionsInitialized,
isLoadingOptions,
};

/* Sections generation */
Expand Down Expand Up @@ -404,7 +408,7 @@ function SearchAutocompleteList({
} as AutocompleteListItem;
});

if (areOptionsInitialized) {
if (!isLoadingOptions) {
pushSection({
title: autocompleteQueryValue.trim() === '' ? translate('search.recentChats') : undefined,
data: nextStyledRecentReports,
Expand All @@ -423,7 +427,7 @@ function SearchAutocompleteList({
reasonAttributes={{
context: 'SearchAutocompleteList',
isRecentSearchesDataLoaded,
areOptionsInitialized,
isLoadingOptions,
}}
/>
),
Expand Down Expand Up @@ -458,7 +462,7 @@ function SearchAutocompleteList({
searchQueryItem,
styles,
translate,
areOptionsInitialized,
isLoadingOptions,
isRecentSearchesDataLoaded,
]);

Expand Down Expand Up @@ -500,13 +504,13 @@ function SearchAutocompleteList({
// because useState(initialFocusedIndex) in useArrowKeyFocusManager only reads the initial value.
// Imperatively focus the first recent report once options become available (desktop only).
useEffect(() => {
if (shouldUseNarrowLayout || !areOptionsInitialized || hasSetInitialFocusRef.current || firstRecentReportFlatIndex === -1) {
if (shouldUseNarrowLayout || isLoadingOptions || hasSetInitialFocusRef.current || firstRecentReportFlatIndex === -1) {
return;
}
hasSetInitialFocusRef.current = true;

innerListRef.current?.updateAndScrollToFocusedIndex(firstRecentReportFlatIndex, false);
}, [areOptionsInitialized, firstRecentReportFlatIndex, shouldUseNarrowLayout]);
}, [isLoadingOptions, firstRecentReportFlatIndex, shouldUseNarrowLayout]);

useEffect(() => {
const targetText = autocompleteQueryValue;
Expand Down
10 changes: 5 additions & 5 deletions src/hooks/useFilteredOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ type UseFilteredOptionsConfig = {
batchSize?: number;
/** Whether to enable dynamic loading/pagination (default: true) */
enablePagination?: boolean;
/** Search term for filtering - when present, builds full report map for personal details (default: '') */
searchTerm?: string;
/** Whether search mode is active - when true, builds full report map for personal details (default: false) */
isSearching?: boolean;
/** Beta features the user has access to */
betas?: OnyxEntry<Beta[]>;
};
Expand Down Expand Up @@ -66,7 +66,7 @@ type UseFilteredOptionsResult = {
* />
*/
function useFilteredOptions(config: UseFilteredOptionsConfig = {}): UseFilteredOptionsResult {
const {maxRecentReports = 500, enabled = true, includeP2P = true, batchSize = 100, searchTerm = '', betas} = config;
const {maxRecentReports = 500, enabled = true, includeP2P = true, batchSize = 100, isSearching = false, betas} = config;

const [reportsLimit, setReportsLimit] = useState(maxRecentReports);

Expand All @@ -86,11 +86,11 @@ function useFilteredOptions(config: UseFilteredOptionsConfig = {}): UseFilteredO
? createFilteredOptionList(allPersonalDetails, allReports, reportAttributesDerived, privateIsArchivedMap, allPolicies, {
maxRecentReports: reportsLimit,
includeP2P,
searchTerm,
isSearching,
betas,
})
: null,
[enabled, allReports, allPersonalDetails, reportAttributesDerived, privateIsArchivedMap, allPolicies, reportsLimit, includeP2P, searchTerm, betas],
[enabled, allReports, allPersonalDetails, reportAttributesDerived, privateIsArchivedMap, allPolicies, reportsLimit, includeP2P, isSearching, betas],
);

const hasMore = options ? reportsLimit < totalReports : false;
Expand Down
5 changes: 2 additions & 3 deletions src/libs/OptionsListUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@
*/

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

Check warning on line 217 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 +230,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 233 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 +280,7 @@
});

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

Check warning on line 283 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 @@ -1536,14 +1536,13 @@
options: {
maxRecentReports?: number;
includeP2P?: boolean;
searchTerm?: string;
isSearching?: boolean;
betas?: OnyxEntry<Beta[]>;
} = {},
policyTags?: OnyxCollection<PolicyTagLists>,
visibleReportActionsData: VisibleReportActionsDerivedValue = {},
) {
const {maxRecentReports = 500, includeP2P = true, searchTerm = ''} = options;
const isSearching = !!searchTerm?.trim();
const {maxRecentReports = 500, includeP2P = true, isSearching = false} = options;
const reportMapForAccountIDs: Record<number, Report> = {};

// Step 1: Pre-filter reports to avoid processing thousands
Expand Down
2 changes: 1 addition & 1 deletion src/pages/NewChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ function useOptions(reportAttributesDerived: ReportAttributesDerivedValue['repor
includeP2P: true,
batchSize: 100,
enablePagination: true,
searchTerm: debouncedSearchTerm,
isSearching: !!debouncedSearchTerm.trim(),
betas,
});

Expand Down
2 changes: 1 addition & 1 deletion src/pages/Share/ShareTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ function ShareTab({ref}: ShareTabProps) {
const {options: listOptions, isLoading} = useFilteredOptions({
enabled: didScreenTransitionEnd,
betas: betas ?? [],
searchTerm: debouncedTextInputValue,
isSearching: !!debouncedTextInputValue.trim(),
});
const areOptionsInitialized = !isLoading;
const [isSearchingForReports] = useOnyx(ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS);
Expand Down
10 changes: 5 additions & 5 deletions tests/perf-test/OptionsListUtils.perf-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,26 +274,26 @@ describe('OptionsListUtils', () => {
await measureFunction(() =>
createFilteredOptionList(personalDetails, mockedReportsMap, undefined, EMPTY_PRIVATE_IS_ARCHIVED_MAP, undefined, {
maxRecentReports: 500,
searchTerm: '',
isSearching: false,
}),
);
});

test('[OptionsListUtils] createFilteredOptionList with searchTerm', async () => {
test('[OptionsListUtils] createFilteredOptionList with isSearching is true', async () => {
await waitForBatchedUpdates();
await measureFunction(() =>
createFilteredOptionList(personalDetails, mockedReportsMap, undefined, EMPTY_PRIVATE_IS_ARCHIVED_MAP, undefined, {
maxRecentReports: 500,
searchTerm: SEARCH_VALUE,
isSearching: true,
}),
);
});

test('[OptionsListUtils] getSearchOptions with searchTerm', async () => {
test('[OptionsListUtils] getSearchOptions with isSearching is true', async () => {
await waitForBatchedUpdates();
const optionLists = createFilteredOptionList(personalDetails, mockedReportsMap, undefined, EMPTY_PRIVATE_IS_ARCHIVED_MAP, undefined, {
maxRecentReports: 500,
searchTerm: SEARCH_VALUE,
isSearching: true,
});

await measureFunction(() =>
Expand Down
26 changes: 14 additions & 12 deletions tests/ui/components/SearchAutocompleteListTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,20 @@ jest.mock('@hooks/useResponsiveLayout', () => ({
})),
}));

jest.mock('@components/OptionListContextProvider', () => {
const ActualReact = jest.requireActual<typeof React>('react');
return {
useOptionsList: jest.fn(() => ({
options: {},
areOptionsInitialized: true,
})),
OptionsListStateContext: ActualReact.createContext({
areOptionsInitialized: true,
}),
};
});
jest.mock('@hooks/useFilteredOptions', () => ({
// eslint-disable-next-line @typescript-eslint/naming-convention
__esModule: true,
default: jest.fn(() => ({
options: {
reports: [],
personalDetails: [],
},
isLoading: false,
loadMore: jest.fn(),
hasMore: false,
isLoadingMore: false,
})),
}));

jest.mock('@libs/OptionsListUtils', () => ({
getSearchOptions: jest.fn(() => ({
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/OptionsListUtilsTest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7045,22 +7045,22 @@ describe('OptionsListUtils', () => {
expect(result).toBeDefined();
});

it('should handle searchTerm filtering', () => {
const result = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, undefined, {}, undefined, {searchTerm: 'Spider'});
it('should handle isSearching filtering', () => {
const result = createFilteredOptionList(PERSONAL_DETAILS, REPORTS, undefined, {}, undefined, {isSearching: true});

expect(result).toBeDefined();
expect(result.reports.length).toBe(Object.keys(REPORTS).length);
});

it('should return all reports when searchTerm is provided (isSearching is true)', () => {
it('should return all reports when isSearching is true', () => {
const result = createFilteredOptionList(
PERSONAL_DETAILS,
REPORTS,
undefined,
{},
{},
{
searchTerm: 'Report',
isSearching: true,
maxRecentReports: 2,
},
);
Expand Down
Loading