diff --git a/src/CONST/index.ts b/src/CONST/index.ts index e31a30162afd..ec5d82261a51 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2194,6 +2194,8 @@ const CONST = { SEARCH_OPTION_LIST_DEBOUNCE_TIME: 300, ACCESSIBILITY_ANNOUNCEMENT_DEBOUNCE_TIME: 1000, SUGGESTION_DEBOUNCE_TIME: 100, + /** How long the cursor has to rest on an advanced filter row before its content may derive the contact list */ + SEARCH_FILTER_HOVER_INTENT_DELAY: 30, RESIZE_DEBOUNCE_TIME: 100, UNREAD_UPDATE_DEBOUNCE_TIME: 300, USE_DEBOUNCED_STATE_DELAY: 300, @@ -7008,6 +7010,8 @@ const CONST = { RESULTS_PAGE_SIZE: 50, EXITING_ANIMATION_DURATION: 200, ME: 'me', + /** How far the cursor may wander from where it last counted as moving over the advanced filter list and still count as resting */ + HOVER_INTENT_REST_RADIUS_PX: 8, DATA_TYPES: { EXPENSE: 'expense', EXPENSE_REPORT: 'expense-report', diff --git a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx index affa7acd43ef..63001fbc257d 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx @@ -38,6 +38,12 @@ type FilterListProps = FilterItemCallbacks & { selectedFilter?: SearchFilter['key']; style?: StyleProp; contentContainerStyle?: StyleProp; + + /** Called as the cursor travels over the list. Web only - it reports the movement inside a row, which `onHoverIn` only reports entering. */ + onPointerMove?: (event: {clientX: number; clientY: number}) => void; + + /** Called when the cursor leaves the list, so the consumer can settle whatever it was still waiting on for the last row. Web only. */ + onPointerLeave?: (event: {clientX: number}) => void; }; type FilterItemProps = FilterItemCallbacks & { @@ -102,7 +108,7 @@ function FilterItem({filterKey, isSelected, onPress, onHoverIn, onFocus}: Filter ); } -function FilterList({type, policyID, selectedFilter, style, contentContainerStyle, onHoverIn, onFocus, onPress}: FilterListProps) { +function FilterList({type, policyID, selectedFilter, style, contentContainerStyle, onHoverIn, onFocus, onPress, onPointerMove, onPointerLeave}: FilterListProps) { const styles = useThemeStyles(); const typeFiltersKeys = useAdvancedSearchFilters(type, policyID); @@ -111,6 +117,8 @@ function FilterList({type, policyID, selectedFilter, style, contentContainerStyl style={[style]} contentContainerStyle={[contentContainerStyle]} showsVerticalScrollIndicator={false} + onMouseMove={onPointerMove} + onMouseLeave={onPointerLeave} > {typeFiltersKeys.map((section, index) => ( diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index 73d8f5cf404d..b6e516f665dd 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -47,7 +47,8 @@ function UserSelector({value = [], isNegatable, policyID, selectionListTextInput return acc; }, new Set()); - const expensifyTeamExclusions = getExpensifyTeamExclusions(personalDetails, policies, currentUserPersonalDetails.email); + // getExpensifyTeamExclusions walks every personal detail, so it is skipped while the selector withholds its options. + const expensifyTeamExclusions = ready ? getExpensifyTeamExclusions(personalDetails, policies, currentUserPersonalDetails.email) : CONST.EMPTY_OBJECT; // Snapshot the pre-selected accountIDs from when the filter first opened so they can be floated to the // top on first render without repinning rows that are toggled afterwards. diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx index bb02513672fa..f850c4e346ed 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx @@ -1,3 +1,4 @@ +import LoadingIndicator from '@components/LoadingIndicator'; import type {ListFilterContentWrapperProps} from '@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent'; import ListFilterContent from '@components/Search/FilterComponents/ListFilterContent'; @@ -6,12 +7,22 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {isFilterNegatable} from '@libs/SearchQueryUtils'; import React, {useState} from 'react'; +import {View} from 'react-native'; -function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initialIsNegated, type, policyID, onChange}: ListFilterContentWrapperProps) { +function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initialIsNegated, type, policyID, ready, onChange}: ListFilterContentWrapperProps) { const styles = useThemeStyles(); const [isNegated, setIsNegated] = useState(initialIsNegated); const isFilterKeyNegatable = isFilterNegatable(baseFilterKey); + // The filter is its own loading state, so its controls do not render behind the spinner. + if (ready === false) { + return ( + + + + ); + } + return ( ; + + /** The filter values each mounted instance was built from. A revisit compares against it. */ + formAtMount: Partial>>; + + /** The filter values each content was last shown with. It goes on rendering with them while hidden. */ + formWhileHidden: Partial>>; + + /** How many times each content has been remounted. Part of its key, so a bump replaces the instance. */ + contentVersions: Partial>; + + /** The deferred filters now allowed to derive. One left out stands as its own loading state. */ + readyFilters: Array; +}; + +const filterComponents = { + List: ListFilterContentPopupWrapper, + Text: TextInputFilterContentPopupWrapper, + Amount: AmountFilterContentPopupWrapper, + Date: DateFilterContentPopupWrapper, + ReportField: ReportFieldFilterContentPopupWrapper, +} as const; + +/** The filter the popover opens on. */ +const INITIAL_FILTER = CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE; + +/** The filters whose contents are derived from the whole contact list, the one derivation heavy enough to be felt. */ +const DEFERRED_CONTENT_FILTERS = new Set([ + CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, + CONST.SEARCH.SYNTAX_FILTER_KEYS.TO, + CONST.SEARCH.SYNTAX_FILTER_KEYS.ATTENDEE, + CONST.SEARCH.SYNTAX_FILTER_KEYS.ASSIGNEE, +]); + +type MountedFilterContentProps = { + /** The filter whose content this is. */ + filterKey: SearchFilter['key']; + + /** The filter values the content reads. */ + values: Partial | undefined; + + /** Whether the content may derive itself, or has to stand as its own loading state for now. */ + ready: boolean; + + /** Called with the values a change in the content produces. */ + onChange: (values: Partial) => void; +}; + +// React Compiler caches the whole `mountedFilters.map()` in one slot, so every element is rebuilt on each change. Each +// content sits in its own component, so a hover ends the render at the boundary of those whose props did not change. +// `onChange` changes with the form, so an edit still re-renders them all. +function MountedFilterContent({filterKey, values, ready, onChange}: MountedFilterContentProps) { + const styles = useThemeStyles(); + + return ( + + + + ); +} + function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps) { const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const {windowHeight} = useWindowDimensions(); - const [selectedFilter, setSelectedFilter] = useState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE); - const filterContentRef = useRef(null); const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); - + const filterContentRef = useRef(null); + const [mountedFilterState, setMountedFilterState] = useState(() => ({ + activeFilter: INITIAL_FILTER, + mountedFilters: [INITIAL_FILTER], + formAtMount: {[INITIAL_FILTER]: searchAdvancedFiltersForm}, + formWhileHidden: {}, + contentVersions: {}, + readyFilters: [], + })); + const {activeFilter, mountedFilters, formWhileHidden, contentVersions, readyFilters} = mountedFilterState; const {updateFilterQueryParams} = useUpdateFilterQuery(queryJSON); + // Shows a filter's content. A visited one stays mounted, so a return reveals it rather than building it again. + const showFilter = (filterKey: SearchFilter['key']) => { + setMountedFilterState((currentState) => { + if (currentState.activeFilter === filterKey) { + return currentState; + } + + const isMounted = currentState.mountedFilters.includes(filterKey); + // A content decides its selection pinning on mount, so one whose values moved on since it was built is + // remounted rather than revealed. Only the values that content reads count. + const isStale = isMounted && hasFilterContentValuesChanged(filterKey, currentState.formAtMount[filterKey], searchAdvancedFiltersForm); + const isBuilt = !isMounted || isStale; + + return { + activeFilter: filterKey, + mountedFilters: isMounted ? currentState.mountedFilters : [...currentState.mountedFilters, filterKey], + formAtMount: isBuilt ? {...currentState.formAtMount, [filterKey]: searchAdvancedFiltersForm} : currentState.formAtMount, + // The filter being left keeps the values it had while shown, so hiding it costs no render. + formWhileHidden: {...currentState.formWhileHidden, [currentState.activeFilter]: searchAdvancedFiltersForm}, + contentVersions: isStale ? {...currentState.contentVersions, [filterKey]: (currentState.contentVersions[filterKey] ?? 0) + 1} : currentState.contentVersions, + // A remounted content derives itself from scratch, so it waits for the cursor again like a new one. + readyFilters: isStale ? currentState.readyFilters.filter((key) => key !== filterKey) : currentState.readyFilters, + }; + }); + }; + + /** Lets the shown filter derive what it withheld. It reads the filter from the updater, so a wait outlives its render. */ + const markShownFilterReady = () => { + setMountedFilterState((currentState) => { + if (!DEFERRED_CONTENT_FILTERS.has(currentState.activeFilter) || currentState.readyFilters.includes(currentState.activeFilter)) { + return currentState; + } + + return {...currentState, readyFilters: [...currentState.readyFilters, currentState.activeFilter]}; + }); + }; + + // Elapses once the cursor comes to rest on a row. + const {invoke: debouncedMarkShownFilterReady, cancel: cancelReadyWait} = useDebounceWithControls(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + + const hoverFilter = (filterKey: SearchFilter['key']) => { + showFilter(filterKey); + debouncedMarkShownFilterReady(); + }; + + const {trackMovement: trackPointerMovement, stopTracking} = usePointerMovement(CONST.SEARCH.HOVER_INTENT_REST_RADIUS_PX, debouncedMarkShownFilterReady); + + // The direction comes from the last tracked position rather than the exit point, because `SafeTriangle` covers the + // path to the content with an overlay and the cursor leaves the list above it as often as through its edge. + const stopTrackingPointer = (event: {clientX: number}) => { + const lastMovement = stopTracking(); + + if (lastMovement && event.clientX <= lastMovement.x) { + return; + } + + cancelReadyWait(); + markShownFilterReady(); + }; + + // Moving the focus is deliberate and never passes over rows on the way, so nothing is withheld from it. + const focusFilter = (filterKey: SearchFilter['key']) => { + cancelReadyWait(); + showFilter(filterKey); + markShownFilterReady(); + }; + + const mayDeriveContent = (filterKey: SearchFilter['key']) => !DEFERRED_CONTENT_FILTERS.has(filterKey) || readyFilters.includes(filterKey); + return ( @@ -45,26 +197,31 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps style={[styles.typeFiltersPopupContainer]} type={searchAdvancedFiltersForm?.type} policyID={getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, searchAdvancedFiltersForm)} - selectedFilter={selectedFilter} - onHoverIn={setSelectedFilter} - onFocus={setSelectedFilter} + selectedFilter={activeFilter} + onHoverIn={hoverFilter} + onPointerMove={trackPointerMovement} + onPointerLeave={stopTrackingPointer} + onFocus={focusFilter} /> - + {mountedFilters.map((filterKey) => ( + // `Activity` keeps a hidden content mounted while taking it out of layout and unmounting its + // effects, so it holds no Onyx subscriptions until it is shown again. + + + + ))} diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index 76526e7f2de0..ceff0b10e035 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -470,13 +470,17 @@ function SearchAutocompleteList({ // debounce below so they don't fire a server request on every keystroke. const hasUpstreamDebounce = inputQueryValue !== undefined; - const debounceHandleSearch = useDebounce(() => { - if (!handleSearch || !autocompleteQueryWithoutFilters) { - return; - } + const debounceHandleSearch = useDebounce( + () => { + if (!handleSearch || !autocompleteQueryWithoutFilters) { + return; + } - handleSearch(autocompleteQueryWithoutFilters); - }, CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME); + handleSearch(autocompleteQueryWithoutFilters); + }, + CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME, + {maxWait: CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME}, + ); useEffect(() => { if (!handleSearch || !autocompleteQueryWithoutFilters) { diff --git a/src/components/SelectionList/hooks/useSelectionListScroll.ts b/src/components/SelectionList/hooks/useSelectionListScroll.ts index 5165585e73c5..612b3a234274 100644 --- a/src/components/SelectionList/hooks/useSelectionListScroll.ts +++ b/src/components/SelectionList/hooks/useSelectionListScroll.ts @@ -32,7 +32,12 @@ function useSelectionListScroll(listRef: RefObject void; +type DebounceControls = { + /** Calls the debounced function, restarting the wait. */ + invoke: T; + + cancel: () => void; +}; + type UseDebounceOptions = DebounceSettings & { /** * When true, any pending trailing invocation is flushed on component unmount instead of cancelled. @@ -19,7 +26,7 @@ type UseDebounceOptions = DebounceSettings & { * Non-generic implementation so OXC's React Compiler can memoize the hook. * OXC bails on type params inside hooks ("Unsupported declaration type for hoisting"). */ -function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebounceOptions): GenericFunction { +function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebounceOptions): DebounceControls { const debouncedFnRef = useRef | undefined>(undefined); const {leading, maxWait, trailing = true, shouldExecuteOnUnmount = false} = options ?? {}; @@ -35,7 +42,8 @@ function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebou }, [shouldExecuteOnUnmount]); useEffect(() => { - const debouncedFn = lodashDebounce(func, wait, {leading, maxWait, trailing}); + // Lodash checks whether `maxWait` is present, not its value, so `{maxWait: undefined}` would cap the wait at `wait`. + const debouncedFn = maxWait === undefined ? lodashDebounce(func, wait, {leading, trailing}) : lodashDebounce(func, wait, {leading, maxWait, trailing}); debouncedFnRef.current = debouncedFn; @@ -44,32 +52,47 @@ function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebou }; }, [func, wait, leading, maxWait, trailing]); - return (...args: unknown[]) => { - const debouncedFn = debouncedFnRef.current; - - if (debouncedFn) { - debouncedFn(...args); - } + return { + invoke: (...args: unknown[]) => { + debouncedFnRef.current?.(...args); + }, + cancel: () => { + debouncedFnRef.current?.cancel(); + }, }; } +/** + * Same as `useDebounce`, with a `cancel` that drops a pending invocation. See `useDebounce` for the parameters. + * + * Returns an object because OXC's React Compiler fails on a function value whose methods read a ref + * ("Ref type environment did not converge"). + */ +function useDebounceWithControls(func: T, wait: number, options?: UseDebounceOptions): DebounceControls { + return useDebounceImpl(func, wait, options) as DebounceControls; +} + /** * Create and return a debounced function. * * Every time the identity of any of the arguments changes, the debounce operation will restart (canceling any ongoing debounce). * This is especially important in the case of func. To prevent that, pass stable references. * + * Use `useDebounceWithControls` when the wait has to be cancellable. + * * @param func The function to debounce. * @param wait The number of milliseconds to delay. * @param options The options object. * @param options.leading Specify invoking on the leading edge of the timeout. - * @param options.maxWait The maximum time func is allowed to be delayed before it's invoked. + * @param options.maxWait The maximum time func is allowed to be delayed before it's invoked, raised to `wait` when lower. Left out, a burst of calls pushes the wait back without limit. * @param options.trailing Specify invoking on the trailing edge of the timeout. * @param options.shouldExecuteOnUnmount When true, flush pending invocations on unmount instead of cancelling them. * @returns Returns a function to call the debounced function. */ export default function useDebounce(func: T, wait: number, options?: UseDebounceOptions): T { - return useDebounceImpl(func, wait, options) as T; + return useDebounceWithControls(func, wait, options).invoke; } +export {useDebounceWithControls}; + export type {UseDebounceOptions}; diff --git a/src/hooks/useIsScrollLikelyLayoutTriggered.ts b/src/hooks/useIsScrollLikelyLayoutTriggered.ts index 815043eed8a7..bf58df8d0dd2 100644 --- a/src/hooks/useIsScrollLikelyLayoutTriggered.ts +++ b/src/hooks/useIsScrollLikelyLayoutTriggered.ts @@ -16,6 +16,7 @@ export default function useIsScrollLikelyLayoutTriggered() { const debouncedLowerIsScrollLayoutTriggered = useDebounce( useCallback(() => (isScrollLayoutTriggered.current = false), []), 500, + {maxWait: 500}, ); const raiseIsScrollLayoutTriggered = useCallback(() => { diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 232feb4ad940..aefd8f4c04bb 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -1,11 +1,14 @@ +import type {LocaleContextProps} from '@components/LocaleContextProvider'; import {usePersonalDetails} from '@components/OnyxListItemProvider'; +import memoize, {equivalentArgsComparator} from '@libs/memoize'; import {createOptionList, filterPersonalDetailsByLogins} from '@libs/PersonalDetailOptionsListUtils'; import type {OptionData, PrivateIsArchivedMap} from '@libs/PersonalDetailOptionsListUtils/types'; import {isOneOnOneChat, isSelfDM} from '@libs/ReportUtils'; +import {registerSessionCleanupCallback} from '@libs/SessionCleanup'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {Report, ReportAttributesDerivedValue, ReportNameValuePairs} from '@src/types/onyx'; +import type {PersonalDetailsList, Report, ReportAttributesDerivedValue, ReportNameValuePairs} from '@src/types/onyx'; import type {ReportAttributes} from '@src/types/onyx/DerivedValues'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; @@ -102,6 +105,60 @@ const createReportAttributesSelector = return map; }; +/** + * Building an option per personal details entry is the expensive step of this hook and depends only on Onyx values. + * Arguments are compared one level deep because the maps are rebuilt each render from those same unchanged values. + * A single entry is held, so a consumer narrowing the list with `includeLoginsOnly` evicts the whole-list one. + */ +const memoizedCreateOptionList = memoize(createOptionList, { + maxSize: 1, + equality: equivalentArgsComparator, + monitoringName: 'usePersonalDetailOptions.createOptionList', +}); + +/** Releases the cached options. */ +function clearPersonalDetailOptionsCache() { + memoizedCreateOptionList.cache.clear(); +} + +// The cached options describe the signed-in account's contacts. +registerSessionCleanupCallback(clearPersonalDetailOptionsCache); + +type BuildOptionsDataParams = { + accountID: number; + allPersonalDetails: OnyxEntry; + includeLoginsOnly: Set | undefined; + reports: OnyxCollection; + reportAttributes: FilteredReportAttributes | undefined; + reportNameValuePairs: PrivateIsArchivedMap | undefined; + formatPhoneNumber: LocaleContextProps['formatPhoneNumber']; + translate: LocaleContextProps['translate']; + shouldStoreReportErrors: boolean; + shouldShowBrickRoadIndicator: boolean; +}; + +/** Turns the Onyx values into the options list. */ +function buildOptionsData({ + accountID, + allPersonalDetails, + includeLoginsOnly, + reports, + reportAttributes, + reportNameValuePairs, + formatPhoneNumber, + translate, + shouldStoreReportErrors, + shouldShowBrickRoadIndicator, +}: BuildOptionsDataParams) { + const personalDetails = includeLoginsOnly ? filterPersonalDetailsByLogins(allPersonalDetails, includeLoginsOnly) : allPersonalDetails; + const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); + + return memoizedCreateOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, reportAttributes, reportNameValuePairs ?? {}, formatPhoneNumber, translate, { + shouldStoreReportErrors, + shouldShowBrickRoadIndicator, + }); +} + /** * Hook that provides options list for personal details. * @@ -132,18 +189,25 @@ function usePersonalDetailOptions(config: UseFilteredOptionsConfig = {}): UseFil const [reportAttributes, reportAttributesMetadata] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, {selector: reportAttributesSelector}); const [reportNameValuePairs, reportNameValuePairsMetadata] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, {selector: privateIsArchivedSelector}); const allPersonalDetails = usePersonalDetails(); - const personalDetails = includeLoginsOnly ? filterPersonalDetailsByLogins(allPersonalDetails, includeLoginsOnly) : allPersonalDetails; const isLoading = !enabled || isLoadingOnyxValue(reportsMetadata, reportAttributesMetadata, reportNameValuePairsMetadata); - const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); - - const optionsData = !isLoading - ? createOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, reportAttributes, reportNameValuePairs ?? {}, formatPhoneNumber, translate, { + // The whole derivation chain is skipped while loading (or disabled), so a consumer that only holds the Onyx + // subscriptions doesn't rebuild these maps on every collection update. + const optionsData = isLoading + ? undefined + : buildOptionsData({ + accountID, + allPersonalDetails, + includeLoginsOnly, + reports, + reportAttributes, + reportNameValuePairs, + formatPhoneNumber, + translate, shouldStoreReportErrors, shouldShowBrickRoadIndicator, - }) - : undefined; + }); return { options: optionsData?.options, @@ -153,3 +217,4 @@ function usePersonalDetailOptions(config: UseFilteredOptionsConfig = {}): UseFil } export default usePersonalDetailOptions; +export {clearPersonalDetailOptionsCache}; diff --git a/src/hooks/usePersonalDetailSearchSelector/base.ts b/src/hooks/usePersonalDetailSearchSelector/base.ts index 656469e7a086..133e1b4bd01c 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -4,8 +4,10 @@ import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import usePersonalDetailOptions from '@hooks/usePersonalDetailOptions'; +import memoize, {equivalentArgsComparator} from '@libs/memoize'; import {filterOption, getValidOptions} from '@libs/PersonalDetailOptionsListUtils'; import type {OptionData} from '@libs/PersonalDetailOptionsListUtils'; +import {registerSessionCleanupCallback} from '@libs/SessionCleanup'; import {expensifyLoginsSelector} from '@libs/UserUtils'; import CONST from '@src/CONST'; @@ -150,6 +152,43 @@ const defaultListOptions = { selectedOptions: [], }; +/** + * How many option lists the caches below hold. Consumers mount one selector at a time, except the Search filters + * popover, which keeps three people filters alive next to each other (from, to and attendee, on expense searches). + * An eviction in the first cache makes the second one miss, because its result is an identity-compared argument of + * `getValidOptions`. + */ +const MAX_CACHED_OPTION_LISTS = 3; + +/** Filtering the whole option list is a pure derivation of its inputs, so remounting consumers reuse the result. */ +const memoizedGetValidOptions = memoize(getValidOptions, { + maxSize: MAX_CACHED_OPTION_LISTS, + equality: equivalentArgsComparator, + monitoringName: 'usePersonalDetailSearchSelector.getValidOptions', +}); + +/** Marks the options matching the selected accountIDs, so the copy of the list is reused while the inputs are unchanged. */ +const buildSelectedOptions = (options: OptionData[], selectedAccountIDs: Set) => + options.map((option) => ({ + ...option, + isSelected: selectedAccountIDs.has(option.accountID.toString()), + })); + +const memoizedBuildSelectedOptions = memoize(buildSelectedOptions, { + maxSize: MAX_CACHED_OPTION_LISTS, + equality: equivalentArgsComparator, + monitoringName: 'usePersonalDetailSearchSelector.buildSelectedOptions', +}); + +/** Releases the cached lists. */ +function clearPersonalDetailSearchSelectorCaches() { + memoizedGetValidOptions.cache.clear(); + memoizedBuildSelectedOptions.cache.clear(); +} + +// Both caches hold option lists built for the signed-in account. +registerSessionCleanupCallback(clearPersonalDetailSearchSelectorCaches); + /** * Base hook that provides search functionality with selection logic for option lists. * This contains the core logic without platform-specific dependencies. @@ -197,11 +236,18 @@ function usePersonalDetailSearchSelectorBase({ return (defaultOptions ?? []).concat(allowedContactOptions); })(); const areOptionsInitialized = !isPersonalDetailsOptionsLoading; - const transformedOptions: OptionData[] = - optionsWithContacts?.map((option) => ({ - ...option, - isSelected: selectedAccountIDs.has(option.accountID.toString()), - })) ?? []; + + // With nothing selected the options already carry the right state, so the list is passed through instead of a copy + // of every option being built and then held in the cache. + const transformedOptions: OptionData[] = (() => { + if (!optionsWithContacts) { + return []; + } + if (selectedAccountIDs.size === 0) { + return optionsWithContacts; + } + return memoizedBuildSelectedOptions(optionsWithContacts, selectedAccountIDs); + })(); const selectedOptions = (() => { const options: OptionData[] = []; @@ -220,7 +266,7 @@ function usePersonalDetailSearchSelectorBase({ const optionsList = !areOptionsInitialized ? defaultListOptions - : getValidOptions(transformedOptions, currentUserEmail, formatPhoneNumber, countryCode, loginList, { + : memoizedGetValidOptions(transformedOptions, currentUserEmail, formatPhoneNumber, countryCode, loginList, { excludeLogins, excludeFromSuggestionsOnly, includeSelectedOptions: shouldKeepSelectedInAvailableOptions, @@ -335,4 +381,5 @@ function usePersonalDetailSearchSelectorBase({ } export default usePersonalDetailSearchSelectorBase; +export {clearPersonalDetailSearchSelectorCaches}; export type {ContactState, UseSearchSelectorConfig, UseSearchSelectorReturn}; diff --git a/src/hooks/usePointerMovement.ts b/src/hooks/usePointerMovement.ts new file mode 100644 index 000000000000..ef0e5f8bef14 --- /dev/null +++ b/src/hooks/usePointerMovement.ts @@ -0,0 +1,45 @@ +import {useRef} from 'react'; + +type PointerPosition = { + x: number; + y: number; +}; + +type PointerMovement = { + trackMovement: (event: {clientX: number; clientY: number}) => void; + + /** Forgets the tracked position and hands back the one the pointer was last seen moving at. */ + stopTracking: () => PointerPosition | null; +}; + +/** + * Tracks where a pointer moves, ignoring travel shorter than `restRadius`, so a hand shaking on the spot counts as + * still. The first move after mount and after `stopTracking` has nothing to measure against, so it always counts. + * + * `onMove` has to be a stable reference: it keys the memoization of whatever handler the caller builds from + * `trackMovement`. + */ +function usePointerMovement(restRadius: number, onMove: () => void): PointerMovement { + const positionRef = useRef(null); + + return { + trackMovement: (event: {clientX: number; clientY: number}) => { + const position = positionRef.current; + + if (position && Math.hypot(event.clientX - position.x, event.clientY - position.y) < restRadius) { + return; + } + + positionRef.current = {x: event.clientX, y: event.clientY}; + onMove(); + }, + stopTracking: () => { + const position = positionRef.current; + positionRef.current = null; + + return position; + }, + }; +} + +export default usePointerMovement; diff --git a/src/hooks/useReleaseOptionListCaches.ts b/src/hooks/useReleaseOptionListCaches.ts new file mode 100644 index 000000000000..7aee9e61372a --- /dev/null +++ b/src/hooks/useReleaseOptionListCaches.ts @@ -0,0 +1,35 @@ +import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; +import subscribeToRootNavigation from '@libs/Navigation/helpers/subscribeToRootNavigation'; + +import {useEffect} from 'react'; + +import {clearPersonalDetailOptionsCache} from './usePersonalDetailOptions'; +import {clearPersonalDetailSearchSelectorCaches} from './usePersonalDetailSearchSelector/base'; + +/** + * Releases the option lists cached for the people selectors once another tab takes over from Search. The lists are + * derived from Onyx and built again on demand, so holding them beyond that only pins memory - tens of megabytes on an + * account with a large contact list. + */ +function useReleaseOptionListCaches() { + useEffect(() => { + // Search stays mounted while another tab is on top of it, so leaving it shows up as a navigation state change + // rather than as this hook being cleaned up. A right hand pane opening over Search keeps it the topmost tab. + let wasSearchTopmostRoute = isSearchTopmostFullScreenRoute(); + + return subscribeToRootNavigation(() => { + const isSearchTopmostRoute = isSearchTopmostFullScreenRoute(); + const hasLeftSearch = wasSearchTopmostRoute && !isSearchTopmostRoute; + wasSearchTopmostRoute = isSearchTopmostRoute; + + if (!hasLeftSearch) { + return; + } + + clearPersonalDetailOptionsCache(); + clearPersonalDetailSearchSelectorCaches(); + }); + }, []); +} + +export default useReleaseOptionListCaches; diff --git a/src/hooks/useSearchSelector/base.ts b/src/hooks/useSearchSelector/base.ts index c1ee92cafa9d..7e96212b056c 100644 --- a/src/hooks/useSearchSelector/base.ts +++ b/src/hooks/useSearchSelector/base.ts @@ -429,18 +429,23 @@ function useSearchSelectorBase({ // Two independent pagination cursors are checked here on purpose: // - hasMore/maxResults track how many relevance-sorted options are rendered. // - hasMoreReports/loadMoreReports track the raw Onyx report pool size by useFilteredOptions - const onListEndReached = useDebounce(() => { - if (!areOptionsInitialized) { - return; - } + const onListEndReached = useDebounce( + () => { + if (!areOptionsInitialized) { + return; + } - if (hasMore) { - setMaxResults((previous) => previous + maxResultsPerPage); - } - if (hasMoreReports) { - loadMoreReports(); - } - }, CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME); + if (hasMore) { + setMaxResults((previous) => previous + maxResultsPerPage); + } + if (hasMoreReports) { + loadMoreReports(); + } + }, + CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME, + // maxWait keeps pages arriving while the scrolling continues. + {maxWait: CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME}, + ); const isOptionSelected = (option: OptionData) => selectedOptions.some((selected) => doOptionsMatch(selected, option)); diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index c7554ca437d3..404a2fdaee1a 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -99,6 +99,7 @@ import type {TupleToUnion, ValueOf} from 'type-fest'; /* eslint-disable max-lines */ // TODO: Remove this disable once SearchUIUtils is refactored (see dedicated refactor issue) import {addDays, format, parse, subDays} from 'date-fns'; +import {deepEqual} from 'fast-equals'; import type {TransactionPreviewData} from './actions/Search'; import type {CardFeedForDisplay} from './CardFeedUtils'; @@ -6118,6 +6119,46 @@ function getFilterNegatableValue | undefined, + values: Partial | undefined, +): boolean { + if (previousValues === values) { + return false; + } + + if (isAmountFilterKey(baseFilterKey)) { + const modifiers = [CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO, CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN, CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN]; + return modifiers.some((modifier) => previousValues?.[`${baseFilterKey}${modifier}`] !== values?.[`${baseFilterKey}${modifier}`]); + } + + if (isDateFilterKey(baseFilterKey)) { + const modifiers = [CONST.SEARCH.DATE_MODIFIERS.ON, CONST.SEARCH.DATE_MODIFIERS.AFTER, CONST.SEARCH.DATE_MODIFIERS.BEFORE, CONST.SEARCH.DATE_MODIFIERS.RANGE]; + return ( + !!previousValues?.feed !== !!values?.feed || modifiers.some((modifier) => !deepEqual(previousValues?.[`${baseFilterKey}${modifier}`], values?.[`${baseFilterKey}${modifier}`])) + ); + } + + // The report field content is handed the whole form, so anything in it counts. + if (baseFilterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.REPORT_FIELD) { + return !deepEqual(previousValues, values); + } + + if (!deepEqual(getFilterNegatableValue(baseFilterKey, previousValues), getFilterNegatableValue(baseFilterKey, values))) { + return true; + } + + if (isTextFilterKey(baseFilterKey)) { + return false; + } + + // A list content also reads the search type and the workspace filter, which decide the options it offers. + const policyIDKey = CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID; + return previousValues?.type !== values?.type || !deepEqual(getFilterNegatableValue(policyIDKey, previousValues), getFilterNegatableValue(policyIDKey, values)); +} + function getLabelValue(key: SearchAdvancedFiltersKey, labelKey: TranslationPaths | undefined, translate: LocalizedTranslate) { if (!labelKey) { return undefined; @@ -7292,6 +7333,7 @@ export { getDateDisplayValue, getDisplayValue, getFilterNegatableValue, + hasFilterContentValuesChanged, shouldShowFilter, mapFiltersFormToLabelValueList, isTextFilterKey, diff --git a/src/libs/memoize/cache/ArrayCache.ts b/src/libs/memoize/cache/ArrayCache.ts index 209250e47675..229810fca976 100644 --- a/src/libs/memoize/cache/ArrayCache.ts +++ b/src/libs/memoize/cache/ArrayCache.ts @@ -71,6 +71,10 @@ function ArrayCache(config: CacheConfig): Cache { return {value}; }, + clear() { + cache.length = 0; + }, + snapshot: { keys: () => cache.map((entry) => entry[0]), values: () => cache.map((entry) => entry[1]), diff --git a/src/libs/memoize/cache/types.ts b/src/libs/memoize/cache/types.ts index 0cff4932212d..53a2bd83e64c 100644 --- a/src/libs/memoize/cache/types.ts +++ b/src/libs/memoize/cache/types.ts @@ -15,6 +15,8 @@ type Cache = { * @returns The value for the key */ getSet: (key: K, valueProducer: () => V) => BoxedValue; + /** Drops every entry */ + clear: () => void; snapshot: { keys: () => K[]; values: () => V[]; diff --git a/src/libs/memoize/index.ts b/src/libs/memoize/index.ts index c29e4cc4bf8d..1defdfbf289b 100644 --- a/src/libs/memoize/index.ts +++ b/src/libs/memoize/index.ts @@ -1,6 +1,9 @@ import type NonPartial from '@src/types/utils/NonPartial'; import type TakeFirst from '@src/types/utils/TupleOperations'; +import {shallowEqual} from 'fast-equals'; +import lodashIsPlainObject from 'lodash/isPlainObject'; + import type {Callable, ClientOptions, Constructable, IsomorphicFn, IsomorphicParameters, IsomorphicReturnType, MemoizedFn, Stats} from './types'; import ArrayCache from './cache/ArrayCache'; @@ -112,4 +115,33 @@ function memoize => lodashIsPlainObject(value); + +/** + * Two arguments are equivalent when they are shallowly equal, or are plain objects whose values are shallowly equal - + * the second level covers arguments rebuilt from unchanged sources (e.g. a mapped Onyx collection). + */ +const areArgumentsEquivalent = (previousArgument: unknown, nextArgument: unknown) => { + if (shallowEqual(previousArgument, nextArgument)) { + return true; + } + if (!isPlainObject(previousArgument) || !isPlainObject(nextArgument)) { + return false; + } + const previousKeys = Object.keys(previousArgument); + if (previousKeys.length !== Object.keys(nextArgument).length) { + return false; + } + return previousKeys.every((key) => key in nextArgument && shallowEqual(previousArgument[key], nextArgument[key])); +}; + +/** + * Compares memoization keys argument by argument. Use it for functions taking large arguments that are rebuilt on every + * call from unchanged sources, where `'shallow'` always misses and `'deep'` would walk the whole payload. + */ +const equivalentArgsComparator = (previousArgs: Key, nextArgs: Key) => + previousArgs.length === nextArgs.length && previousArgs.every((argument, index) => areArgumentsEquivalent(argument, nextArgs[index])); + export default memoize; +export {equivalentArgsComparator}; diff --git a/src/pages/Search/SearchPage.tsx b/src/pages/Search/SearchPage.tsx index 77a6575c9e0e..2e27ea6b4e23 100644 --- a/src/pages/Search/SearchPage.tsx +++ b/src/pages/Search/SearchPage.tsx @@ -10,6 +10,7 @@ import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; import useOnyx from '@hooks/useOnyx'; import {PaymentContextProvider} from '@hooks/usePaymentContext'; import usePrevious from '@hooks/usePrevious'; +import useReleaseOptionListCaches from '@hooks/useReleaseOptionListCaches'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useSearchOverlay from '@hooks/useSearchOverlay'; import useSearchPageSetup from '@hooks/useSearchPageSetup'; @@ -52,6 +53,7 @@ function SearchPage({route}: SearchPageProps) { useSearchPageSetup(currentSearchQueryJSON); useSeedMyExpensesSearch(); + useReleaseOptionListCaches(); // Adjust state during rendering rather than in a useEffect: the value is consumed in the same // render below (`searchResults = lastNonEmptySearchResults` when sorting), so a useEffect would diff --git a/src/pages/inbox/report/ReportActionCompose/SuggestionEmoji.tsx b/src/pages/inbox/report/ReportActionCompose/SuggestionEmoji.tsx index bafe9c0d7464..216db6990ec8 100644 --- a/src/pages/inbox/report/ReportActionCompose/SuggestionEmoji.tsx +++ b/src/pages/inbox/report/ReportActionCompose/SuggestionEmoji.tsx @@ -223,6 +223,8 @@ function SuggestionEmoji({ [calculateEmojiSuggestion], ), CONST.TIMING.SUGGESTION_DEBOUNCE_TIME, + // maxWait keeps the suggestions refreshing while a key is held down. + {maxWait: CONST.TIMING.SUGGESTION_DEBOUNCE_TIME}, ); useEffect(() => { diff --git a/src/pages/inbox/report/ReportActionCompose/SuggestionMention.tsx b/src/pages/inbox/report/ReportActionCompose/SuggestionMention.tsx index 12ac6635ad33..fdf0a5912769 100644 --- a/src/pages/inbox/report/ReportActionCompose/SuggestionMention.tsx +++ b/src/pages/inbox/report/ReportActionCompose/SuggestionMention.tsx @@ -142,6 +142,7 @@ function SuggestionMention({ } }, [suggestionValues.suggestedMentions.length, suggestionValues.prefixType, suggestionValues.mentionPrefix, policyID, isGroupPolicyReport]), CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME, + {maxWait: CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME}, ); const formatLoginPrivateDomain = useCallback( @@ -562,6 +563,8 @@ function SuggestionMention({ [calculateMentionSuggestion], ), CONST.TIMING.SUGGESTION_DEBOUNCE_TIME, + // maxWait keeps the suggestions refreshing while a key is held down. + {maxWait: CONST.TIMING.SUGGESTION_DEBOUNCE_TIME}, ); useEffect(() => { diff --git a/src/pages/inbox/report/useDebouncedSaveDraft.ts b/src/pages/inbox/report/useDebouncedSaveDraft.ts index 7a70947d1c73..73127f082966 100644 --- a/src/pages/inbox/report/useDebouncedSaveDraft.ts +++ b/src/pages/inbox/report/useDebouncedSaveDraft.ts @@ -28,7 +28,8 @@ function useDebouncedSaveDraftImpl(saveDraftFn: (...args: unknown[]) => void, wa isSavePending.current = false; }, wait, - {shouldExecuteOnUnmount}, + // maxWait writes a draft every `wait` while typing continues. + {shouldExecuteOnUnmount, maxWait: wait}, ); const saveDraft = (...args: unknown[]) => { diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx new file mode 100644 index 000000000000..8412fb3d8327 --- /dev/null +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -0,0 +1,277 @@ +import {act, render} from '@testing-library/react-native'; + +import type {SearchQueryJSON} from '@components/Search/types'; + +import CONST from '@src/CONST'; +import type {SearchAdvancedFiltersForm} from '@src/types/form'; + +import React, {useRef} from 'react'; +import {View} from 'react-native'; + +// jest.mock factories can't reference imported bindings, but `mock`-prefixed locals are allowed. +const MockView = View; +const mockUseRef = useRef; + +const FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; + +/** Called once per content instance, so a remount shows up as a second call for the same key. */ +const mockOnContentCreated = jest.fn(); + +/** What each mounted content was last told about deriving itself. */ +let mockReadyByFilter: Record = {}; + +/** How many times each content has rendered, so a render of a hidden one shows up here. */ +let mockRenderCountByFilter: Record = {}; + +/** The filter values each mounted content was last rendered with. */ +let mockValuesByFilter: Record | undefined> = {}; + +// Captured from what the popup hands the filter list, so tests can drive the cursor and read what is highlighted. +let mockOnHoverIn: ((filterKey: string) => void) | undefined; +let mockOnFocus: ((filterKey: string) => void) | undefined; +let mockOnPointerMove: ((event: {clientX: number; clientY: number}) => void) | undefined; +let mockOnPointerLeave: ((event: {clientX: number}) => void) | undefined; +let mockSelectedFilter: string | undefined; + +/** The form served by the useOnyx mock. Reassigned by tests to change filter values. */ +let mockFiltersForm: Partial | undefined; + +// Stand-in for the filter list: it renders no rows and only hands the tests what the popup gave it. +jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () => ({ + __esModule: true, + default: (props: { + onHoverIn: (filterKey: string) => void; + onFocus: (filterKey: string) => void; + onPointerMove: (event: {clientX: number; clientY: number}) => void; + onPointerLeave: (event: {clientX: number}) => void; + selectedFilter: string; + }) => { + mockOnHoverIn = props.onHoverIn; + mockOnFocus = props.onFocus; + mockOnPointerMove = props.onPointerMove; + mockOnPointerLeave = props.onPointerLeave; + mockSelectedFilter = props.selectedFilter; + + return null; + }, +})); + +// Stand-in for the filter content, the expensive part being mounted or kept alive. +jest.mock('@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent', () => ({ + __esModule: true, + default: ({baseFilterKey, ready, values}: {baseFilterKey: string; ready?: boolean; values?: Partial}) => { + const isCreated = mockUseRef(false); + if (!isCreated.current) { + isCreated.current = true; + mockOnContentCreated(baseFilterKey); + } + mockRenderCountByFilter[baseFilterKey] = (mockRenderCountByFilter[baseFilterKey] ?? 0) + 1; + mockReadyByFilter[baseFilterKey] = !!ready; + mockValuesByFilter[baseFilterKey] = values; + + return ; + }, +})); + +// One callback for the life of the test, so props of an unvisited content stay identical. +const mockUpdateFilterQueryParams = jest.fn(); +jest.mock('@components/Search/hooks/useUpdateFilterQuery', () => ({ + __esModule: true, + default: () => ({updateFilterQueryParams: mockUpdateFilterQueryParams}), +})); + +jest.mock('@hooks/useOnyx', () => ({ + __esModule: true, + default: () => [mockFiltersForm, {status: 'loaded'}], +})); + +// The popover exists on web only, and jest-expo's resolver prefers the native variant, which renders nothing. +const SearchAdvancedFiltersPopup = require<{ + default: React.ComponentType<{queryJSON: SearchQueryJSON | undefined}>; +}>('../../../src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx').default; + +/** Renders the popup again, which carries a reassigned form into it while the shown filter stays put. */ +let rerenderPopup: () => void; + +// Only forwarded to the mocked query hook, so it is never read. +const queryJSON = undefined; + +/** Moves the cursor onto a filter row without waiting for the hover intent delay. */ +function hover(filterKey: string) { + act(() => { + mockOnHoverIn?.(filterKey); + }); +} + +/** Moves the cursor onto a filter row and leaves it there long enough to release what it withheld. */ +function hoverAndRest(filterKey: string) { + hover(filterKey); + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); +} + +/** Travels the cursor to a point over the filter list. */ +function movePointer(clientX: number, clientY: number) { + act(() => { + mockOnPointerMove?.({clientX, clientY}); + }); +} + +/** Takes the cursor off the filter list at a point, which is to the right of the rows unless a test says otherwise. */ +function leaveList(clientX = Number.MAX_SAFE_INTEGER) { + act(() => { + mockOnPointerLeave?.({clientX}); + }); +} + +/** Moves the keyboard focus onto a filter row. */ +function focus(filterKey: string) { + act(() => { + mockOnFocus?.(filterKey); + }); +} + +beforeEach(() => { + jest.clearAllMocks(); + jest.useFakeTimers(); + mockFiltersForm = undefined; + mockReadyByFilter = {}; + mockRenderCountByFilter = {}; + mockValuesByFilter = {}; + const view = render(); + rerenderPopup = () => view.rerender(); +}); + +afterEach(() => { + jest.useRealTimers(); +}); + +describe('SearchAdvancedFiltersPopup', () => { + it('shows every row the cursor passes over and withholds the contact list from all but the one it stops on', () => { + const peopleFilters = [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE, FILTER_KEYS.ASSIGNEE]; + for (const filterKey of peopleFilters) { + hover(filterKey); + act(() => { + jest.advanceTimersByTime(12); + }); + } + + // The pane kept up with the cursor, and not one of the rows it crossed built a contact list. + expect(mockSelectedFilter).toBe(FILTER_KEYS.ASSIGNEE); + for (const filterKey of peopleFilters) { + expect(mockReadyByFilter[filterKey]).toBe(false); + } + + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); + + expect(mockReadyByFilter[FILTER_KEYS.ASSIGNEE]).toBe(true); + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(false); + }); + + it('marks a filter outside the contact-list group ready the moment it is pointed at', () => { + hover(FILTER_KEYS.STATUS); + + // No timer is advanced: nothing about this filter is worth waiting for. + expect(mockReadyByFilter[FILTER_KEYS.STATUS]).toBe(true); + }); + + it('treats a cursor that only shakes on the spot as at rest', () => { + hover(FILTER_KEYS.FROM); + movePointer(100, 100); + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY - 10); + }); + // Within HOVER_INTENT_REST_RADIUS_PX of where it settled, so it does not restart the wait. + movePointer(104, 103); + act(() => { + jest.advanceTimersByTime(15); + }); + + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); + }); + + it('releases the row the cursor left from when it leaves the list toward the content', () => { + hover(FILTER_KEYS.FROM); + movePointer(100, 100); + leaveList(140); + + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); + }); + + it('releases the row the cursor swept out of away from the content once its wait elapses', () => { + hover(FILTER_KEYS.FROM); + movePointer(100, 100); + leaveList(60); + + // The sweep itself paid for nothing, and the wait left running releases the row that stayed on show. + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(false); + + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); + + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); + }); + + it('hands the shown content the live form and a hidden one the values it was last shown with', () => { + mockFiltersForm = {from: ['9']}; + // The useOnyx mock cannot re-render on its own, so a visit to another row carries the new form into the popup. + hoverAndRest(FILTER_KEYS.STATUS); + hoverAndRest(FILTER_KEYS.FROM); + + // The form changes while this filter is the shown one, so it follows rather than holding its snapshot. + mockFiltersForm = {from: ['9'], to: ['1']}; + rerenderPopup(); + expect(mockValuesByFilter[FILTER_KEYS.FROM]).toEqual({from: ['9'], to: ['1']}); + + // Hidden, it keeps those values rather than following the form on. + mockFiltersForm = {from: ['9'], to: ['1'], category: ['food']}; + hoverAndRest(FILTER_KEYS.STATUS); + expect(mockValuesByFilter[FILTER_KEYS.FROM]).toEqual({from: ['9'], to: ['1']}); + }); + + it('makes a remounted content wait for the cursor again before it derives itself', () => { + hoverAndRest(FILTER_KEYS.FROM); + + // Someone was picked in this very filter, so its content has to decide its selection pinning again. + mockFiltersForm = {from: ['1']}; + rerenderPopup(); + const rendersBeforeLeaving = mockRenderCountByFilter[FILTER_KEYS.FROM]; + + hoverAndRest(FILTER_KEYS.TO); + // Hiding it hands back what it was already rendering, so the rebuild is the only cost. + expect(mockRenderCountByFilter[FILTER_KEYS.FROM]).toBe(rendersBeforeLeaving); + + hover(FILTER_KEYS.FROM); + expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(2); + // The rebuilt instance is as expensive as a new one, so being shown is not enough for it to derive. + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(false); + + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); + }); + + it('keeps a mounted content when only a filter it does not read changed', () => { + hoverAndRest(FILTER_KEYS.FROM); + + // Someone was picked in another filter, which the content of this one neither reads nor renders. + mockFiltersForm = {to: ['1']}; + hoverAndRest(FILTER_KEYS.TO); + + // The content is revealed as it was left, so state it holds itself survives. + hoverAndRest(FILTER_KEYS.FROM); + expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); + }); + + it('withholds nothing from a row focused with the keyboard', () => { + focus(FILTER_KEYS.FROM); + + // No timer is advanced: moving focus is deliberate and never passes over rows on the way. + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); + }); +}); diff --git a/tests/unit/Search/SearchUIUtilsTest.ts b/tests/unit/Search/SearchUIUtilsTest.ts index 6d84e6913aa6..0b1d476331db 100644 --- a/tests/unit/Search/SearchUIUtilsTest.ts +++ b/tests/unit/Search/SearchUIUtilsTest.ts @@ -13549,3 +13549,97 @@ describe('getSavedSearchIconName', () => { spy.mockRestore(); }); }); + +describe('hasFilterContentValuesChanged', () => { + const SYNTAX_FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; + type FilterKey = Parameters[0]; + type FilterValues = Parameters[1]; + type ContentValuesCase = { + /** The kind of content the filter is given, which decides what it reads. */ + kind: string; + + /** The filter whose content is being judged. */ + filterKey: FilterKey; + + /** Two forms differing only in something that content reads. */ + read: [FilterValues, FilterValues]; + + /** Two forms differing only in something it does not, where there is such a thing. */ + ignored?: [FilterValues, FilterValues]; + }; + + // One case per kind of content, because each is handed a different slice of the form. + const contentValuesCases: ContentValuesCase[] = [ + { + kind: 'list', + filterKey: SYNTAX_FILTER_KEYS.FROM, + read: [{[SYNTAX_FILTER_KEYS.FROM]: ['1']}, {[SYNTAX_FILTER_KEYS.FROM]: ['2']}], + ignored: [{[SYNTAX_FILTER_KEYS.FROM]: ['1']}, {[SYNTAX_FILTER_KEYS.FROM]: ['1'], [SYNTAX_FILTER_KEYS.TO]: ['2']}], + }, + { + kind: 'list, negated', + filterKey: SYNTAX_FILTER_KEYS.FROM, + // Built the way the content builds it, so the negated key cannot drift. + read: [SearchQueryUtils.getFilterFormValues(SYNTAX_FILTER_KEYS.FROM, ['1'], false), SearchQueryUtils.getFilterFormValues(SYNTAX_FILTER_KEYS.FROM, ['1'], true)], + }, + { + kind: 'list, reading the search type it offers options for', + filterKey: SYNTAX_FILTER_KEYS.CATEGORY, + read: [{type: CONST.SEARCH.DATA_TYPES.EXPENSE}, {type: CONST.SEARCH.DATA_TYPES.INVOICE}], + }, + { + kind: 'list, reading the workspace that narrows its options', + filterKey: SYNTAX_FILTER_KEYS.CATEGORY, + read: [{[SYNTAX_FILTER_KEYS.POLICY_ID]: ['1']}, {[SYNTAX_FILTER_KEYS.POLICY_ID]: ['2']}], + }, + { + kind: 'text', + filterKey: SYNTAX_FILTER_KEYS.MERCHANT, + read: [{[SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, {[SYNTAX_FILTER_KEYS.MERCHANT]: 'b'}], + // A text content offers no options, so the search type is nothing to it. + ignored: [{[SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, {[SYNTAX_FILTER_KEYS.MERCHANT]: 'a', type: CONST.SEARCH.DATA_TYPES.INVOICE}], + }, + { + kind: 'amount', + filterKey: SYNTAX_FILTER_KEYS.AMOUNT, + read: [ + {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10'}, + {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '20'}, + ], + ignored: [ + {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10'}, + {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10', type: CONST.SEARCH.DATA_TYPES.INVOICE}, + ], + }, + { + kind: 'date', + filterKey: SYNTAX_FILTER_KEYS.DATE, + read: [{[`${SYNTAX_FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01'}, {[`${SYNTAX_FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-02-01'}], + ignored: [ + {[`${SYNTAX_FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01'}, + {[`${SYNTAX_FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01', type: CONST.SEARCH.DATA_TYPES.INVOICE}, + ], + }, + { + // The date content offers card periods only when a feed is picked, so it reads whether one is. + kind: 'date, reading whether a feed is picked', + filterKey: SYNTAX_FILTER_KEYS.DATE, + read: [{}, {[SYNTAX_FILTER_KEYS.FEED]: ['1']}], + ignored: [{[SYNTAX_FILTER_KEYS.FEED]: ['1']}, {[SYNTAX_FILTER_KEYS.FEED]: ['2']}], + }, + { + // The report field content is handed the whole form, so nothing in it is outside what it reads. + kind: 'report field', + filterKey: SYNTAX_FILTER_KEYS.REPORT_FIELD, + read: [{[SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, {[SYNTAX_FILTER_KEYS.MERCHANT]: 'b'}], + }, + ]; + + it.each(contentValuesCases)('$kind: reports a change to what it reads and none to what it does not', ({filterKey, read, ignored}) => { + expect(SearchUIUtils.hasFilterContentValuesChanged(filterKey, read.at(0), read.at(1))).toBe(true); + + if (ignored) { + expect(SearchUIUtils.hasFilterContentValuesChanged(filterKey, ignored.at(0), ignored.at(1))).toBe(false); + } + }); +}); diff --git a/tests/unit/useReleaseOptionListCachesTest.ts b/tests/unit/useReleaseOptionListCachesTest.ts new file mode 100644 index 000000000000..ab91e9226f50 --- /dev/null +++ b/tests/unit/useReleaseOptionListCachesTest.ts @@ -0,0 +1,88 @@ +import {renderHook} from '@testing-library/react-native'; + +import useReleaseOptionListCaches from '@hooks/useReleaseOptionListCaches'; + +/** Called when the built option lists are released. */ +const mockReleaseOptions = jest.fn(); + +/** Called when the filtered and selected option lists are released. */ +const mockReleaseSearchSelector = jest.fn(); + +/** Whether Search is the tab currently on top, read by the hook on every navigation state change. */ +let mockIsSearchTopmostRoute = true; + +/** The listener the hook subscribes to the root navigation with. */ +let mockNavigationListener: (() => void) | undefined; +const mockUnsubscribe = jest.fn(); + +jest.mock('@hooks/usePersonalDetailOptions', () => ({ + __esModule: true, + clearPersonalDetailOptionsCache: () => { + mockReleaseOptions(); + }, +})); + +jest.mock('@hooks/usePersonalDetailSearchSelector/base', () => ({ + __esModule: true, + clearPersonalDetailSearchSelectorCaches: () => { + mockReleaseSearchSelector(); + }, +})); + +jest.mock('@libs/Navigation/helpers/isSearchTopmostFullScreenRoute', () => ({ + __esModule: true, + default: () => mockIsSearchTopmostRoute, +})); + +jest.mock('@libs/Navigation/helpers/subscribeToRootNavigation', () => ({ + __esModule: true, + default: (listener: () => void) => { + mockNavigationListener = listener; + return mockUnsubscribe; + }, +})); + +/** Moves to another tab and reports the navigation state change the hook listens for. */ +function leaveSearch() { + mockIsSearchTopmostRoute = false; + mockNavigationListener?.(); +} + +/** Reports a navigation state change that leaves Search on top, e.g. a right hand pane opening over it. */ +function navigateWithinSearch() { + mockNavigationListener?.(); +} + +function renderReleaseHook() { + return renderHook(() => useReleaseOptionListCaches()); +} + +beforeEach(() => { + jest.clearAllMocks(); + mockIsSearchTopmostRoute = true; + mockNavigationListener = undefined; +}); + +describe('useReleaseOptionListCaches', () => { + it('releases the cached lists when another tab takes over from Search', () => { + const {unmount} = renderReleaseHook(); + + leaveSearch(); + + // Both caches, because releasing only one of them leaves the other holding the lists it was built from. + expect(mockReleaseOptions).toHaveBeenCalled(); + expect(mockReleaseSearchSelector).toHaveBeenCalled(); + + unmount(); + expect(mockUnsubscribe).toHaveBeenCalled(); + }); + + it('keeps the cached lists while Search is still the tab on top', () => { + renderReleaseHook(); + + navigateWithinSearch(); + + expect(mockReleaseOptions).not.toHaveBeenCalled(); + expect(mockReleaseSearchSelector).not.toHaveBeenCalled(); + }); +});