From b745fb87a4714da50ff528506a22ee58c5de1550 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 7 Aug 2026 12:27:44 +0200 Subject: [PATCH 01/30] perf: avoid rebuilding Search filter contents on hover Hovering a filter row in the Search filters popover remounted its whole content and rebuilt the option lists from scratch, which blocked the main thread for over a second per row on accounts with large personal details. - Switch the content pane to a debounced rested filter, so sweeping the cursor across rows moves only the highlight. - Keep the last three rested filter contents mounted inside , so returning to one toggles visibility instead of remounting. - Memoize the three full passes over the personal details list (createOptionList, getValidOptions, the UserSelector list copy) with a comparator that walks one level into rebuilt record arguments, since the snapshot-aware useOnyx rebuilds collection identities on Search pages every render. - Keep the option list Onyx subscriptions warm for the popover lifetime. --- src/CONST/index.ts | 4 + .../PersonalDetailOptionsKeepWarm.tsx | 13 ++ .../Search/FilterComponents/UserSelector.tsx | 27 +++- .../SearchAdvancedFiltersPopup/index.tsx | 48 ++++-- src/hooks/usePersonalDetailOptions.ts | 13 +- .../usePersonalDetailSearchSelector/base.ts | 28 +++- src/libs/memoize/index.ts | 30 ++++ .../Search/SearchAdvancedFiltersPopupTest.tsx | 145 ++++++++++++++++++ 8 files changed, 282 insertions(+), 26 deletions(-) create mode 100644 src/components/Search/FilterComponents/PersonalDetailOptionsKeepWarm.tsx create mode 100644 tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 9c55d2c4ca07..912966016725 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2106,6 +2106,8 @@ const CONST = { SEARCH_OPTION_LIST_DEBOUNCE_TIME: 300, ACCESSIBILITY_ANNOUNCEMENT_DEBOUNCE_TIME: 1000, SUGGESTION_DEBOUNCE_TIME: 100, + /** How long the cursor has to stay on an advanced filter row before its content is rendered */ + SEARCH_FILTER_HOVER_INTENT_DELAY: 80, RESIZE_DEBOUNCE_TIME: 100, UNREAD_UPDATE_DEBOUNCE_TIME: 300, USE_DEBOUNCED_STATE_DELAY: 300, @@ -6690,6 +6692,8 @@ const CONST = { RESULTS_PAGE_SIZE: 50, EXITING_ANIMATION_DURATION: 200, ME: 'me', + /** How many advanced filter contents the filters popover keeps mounted */ + MAX_MOUNTED_FILTER_CONTENTS: 3, DATA_TYPES: { EXPENSE: 'expense', EXPENSE_REPORT: 'expense-report', diff --git a/src/components/Search/FilterComponents/PersonalDetailOptionsKeepWarm.tsx b/src/components/Search/FilterComponents/PersonalDetailOptionsKeepWarm.tsx new file mode 100644 index 000000000000..7edde424f0ac --- /dev/null +++ b/src/components/Search/FilterComponents/PersonalDetailOptionsKeepWarm.tsx @@ -0,0 +1,13 @@ +import usePersonalDetailOptions from '@hooks/usePersonalDetailOptions'; + +/** + * Holds the Onyx subscriptions behind the personal detail option list for as long as it stays mounted, so the memoized + * list survives filter content remounts (Onyx drops a key's cached snapshot with its last subscriber). Renders nothing. + */ +function PersonalDetailOptionsKeepWarm() { + usePersonalDetailOptions({enabled: false}); + + return null; +} + +export default PersonalDetailOptionsKeepWarm; diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index 905bada8dc61..21cb912901b8 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -11,6 +11,7 @@ import usePersonalDetailSearchSelector from '@hooks/usePersonalDetailSearchSelec import useThemeStyles from '@hooks/useThemeStyles'; import canFocusInputOnScreenFocus from '@libs/canFocusInputOnScreenFocus'; +import memoize, {equivalentArgsComparator} from '@libs/memoize'; import type {OptionData} from '@libs/PersonalDetailOptionsListUtils'; import {getExpensifyTeamExclusions} from '@libs/PolicyUtils'; import moveInitialSelectionToTop from '@libs/SelectionListOrderUtils'; @@ -24,6 +25,22 @@ import ListFilterWrapper from './ListFilterViewWrapper'; type UserSelectorProps = SearchFilterCommonProps; +/** + * `moveInitialSelectionToTop` keys on `value`, so each option's accountID (`keyForList`) is mapped onto it. Copying every + * option is the last full pass over the list per render, so the result is reused while the inputs are unchanged. + */ +const buildListData = (options: OptionData[], initialSelectedValues: string[]) => + moveInitialSelectionToTop( + options.map((option) => ({...option, value: option.keyForList})), + initialSelectedValues, + ); + +const memoizedBuildListData = memoize(buildListData, { + maxSize: 2, + equality: equivalentArgsComparator, + monitoringName: 'UserSelector.buildListData', +}); + function UserSelector({value = [], isNegatable, selectionListTextInputStyle, selectionListStyle, autoFocus, ready = true, footer, onChange}: UserSelectorProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); @@ -61,14 +78,10 @@ function UserSelector({value = [], isNegatable, selectionListTextInputStyle, sel // top on first render without repinning rows that are toggled afterwards (see https://github.com/Expensify/App/issues/61414). const initialSelectedValues = useInitialValue(() => value); - // The current user is excluded from personalDetails, so include it (when present) in the list. moveInitialSelectionToTop - // keys on `value`, so map each option's accountID (keyForList) onto it. Pre-selected rows are moved to the top, - // leaving the current user just below them in its natural sorted position. + // The current user is excluded from personalDetails, so include it (when present) in the list. Pre-selected rows are moved to the + // top, leaving the current user just below them in its natural sorted position. const baseListData = availableOptions.currentUserOption ? [availableOptions.currentUserOption, ...availableOptions.personalDetails] : availableOptions.personalDetails; - const listData = moveInitialSelectionToTop( - baseListData.map((option) => ({...option, value: option.keyForList})), - initialSelectedValues, - ); + const listData = memoizedBuildListData(baseListData, initialSelectedValues); const headerMessage = listData.length === 0 ? translate('common.noResultsFound') : undefined; diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index eadcc3d4e5c9..2b880260a632 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -1,9 +1,11 @@ import SafeTriangle from '@components/SafeTriangle'; import FilterList from '@components/Search/FilterComponents/AdvancedFilters/FilterList'; import SearchAdvancedFiltersContent from '@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent'; +import PersonalDetailOptionsKeepWarm from '@components/Search/FilterComponents/PersonalDetailOptionsKeepWarm'; import useUpdateFilterQuery from '@components/Search/hooks/useUpdateFilterQuery'; import type {SearchQueryJSON} from '@components/Search/types'; +import useDebouncedState from '@hooks/useDebouncedState'; import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -15,7 +17,7 @@ import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import React, {useRef, useState} from 'react'; +import React, {Activity, useRef, useState} from 'react'; import {View} from 'react-native'; import AmountFilterContentPopupWrapper from './AmountFilterContentPopupWrapper'; @@ -28,11 +30,27 @@ type SearchAdvancedFiltersPopupProps = { queryJSON: SearchQueryJSON; }; +const filterComponents = { + List: ListFilterContentPopupWrapper, + Text: TextInputFilterContentPopupWrapper, + Amount: AmountFilterContentPopupWrapper, + Date: DateFilterContentPopupWrapper, + ReportField: ReportFieldFilterContentPopupWrapper, +} as const; + function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps) { const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const {windowHeight} = useWindowDimensions(); - const [selectedFilter, setSelectedFilter] = useState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE); + // The list highlights `selectedFilter` immediately; the content pane follows `restedFilter` once the cursor has stayed + // on a row for SEARCH_FILTER_HOVER_INTENT_DELAY, so sweeping across rows doesn't render a content pane per row. + const [selectedFilter, restedFilter, setSelectedFilter] = useDebouncedState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + // The last MAX_MOUNTED_FILTER_CONTENTS rested filters stay mounted (hidden by Activity), so returning to one of them + // toggles visibility instead of remounting. Adjusted during render so the new pane shows in the same frame. + const [mountedFilters, setMountedFilters] = useState>([CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE]); + if (!mountedFilters.includes(restedFilter)) { + setMountedFilters([...mountedFilters, restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS)); + } const filterContentRef = useRef(null); const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); @@ -40,6 +58,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps return ( + - + {mountedFilters.map((filterKey) => ( + + + + ))} diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 5bb18a2caa56..293310cfa757 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -1,5 +1,6 @@ import {usePersonalDetails} from '@components/OnyxListItemProvider'; +import memoize, {equivalentArgsComparator} from '@libs/memoize'; import {createOptionList} from '@libs/PersonalDetailOptionsListUtils'; import type {OptionData, PrivateIsArchivedMap} from '@libs/PersonalDetailOptionsListUtils/types'; import {isOneOnOneChat, isSelfDM} from '@libs/ReportUtils'; @@ -104,6 +105,16 @@ const filterReportAttributes = (reportAttributes: OnyxEntry ({ + // With nothing selected the options already carry the right state, so the list is passed through without copying, + // keeping its reference stable for the memoized filtering below. + const transformedOptions: OptionData[] = (() => { + if (!optionsWithContacts) { + return []; + } + if (selectedAccountIDs.size === 0) { + return optionsWithContacts; + } + return optionsWithContacts.map((option) => ({ ...option, isSelected: selectedAccountIDs.has(option.accountID.toString()), - })) ?? []; + })); + })(); const selectedOptions = (() => { const options: OptionData[] = []; @@ -214,7 +234,7 @@ function usePersonalDetailSearchSelectorBase({ const optionsList = !areOptionsInitialized ? defaultListOptions - : getValidOptions(transformedOptions, currentUserEmail, formatPhoneNumber, countryCode, loginList, { + : memoizedGetValidOptions(transformedOptions, currentUserEmail, formatPhoneNumber, countryCode, loginList, { excludeLogins, excludeFromSuggestionsOnly, includeSelectedOptions: shouldKeepSelectedInAvailableOptions, diff --git a/src/libs/memoize/index.ts b/src/libs/memoize/index.ts index c29e4cc4bf8d..99abff0f72cc 100644 --- a/src/libs/memoize/index.ts +++ b/src/libs/memoize/index.ts @@ -1,6 +1,8 @@ import type NonPartial from '@src/types/utils/NonPartial'; import type TakeFirst from '@src/types/utils/TupleOperations'; +import {shallowEqual} from 'fast-equals'; + import type {Callable, ClientOptions, Constructable, IsomorphicFn, IsomorphicParameters, IsomorphicReturnType, MemoizedFn, Stats} from './types'; import ArrayCache from './cache/ArrayCache'; @@ -112,4 +114,32 @@ function memoize => typeof value === 'object' && value !== null && !Array.isArray(value); + +/** + * Two arguments are equivalent when they are shallowly equal, or are records with the same keys 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 (!isRecord(previousArgument) || !isRecord(nextArgument)) { + return false; + } + const previousKeys = Object.keys(previousArgument); + if (previousKeys.length !== Object.keys(nextArgument).length) { + return false; + } + return previousKeys.every((key) => 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.every((argument, index) => areArgumentsEquivalent(argument, nextArgs.at(index))); + export default memoize; +export {equivalentArgsComparator}; diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx new file mode 100644 index 000000000000..6fbaf4d0b90c --- /dev/null +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -0,0 +1,145 @@ +import {act, fireEvent, render, screen} from '@testing-library/react-native'; + +import {PressableWithoutFeedback} from '@components/Pressable'; +import type {SearchQueryJSON} from '@components/Search/types'; + +import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; + +import CONST from '@src/CONST'; + +import React, {useEffect, 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 MockPressable = PressableWithoutFeedback; +const mockUseRef = useRef; +const mockUseEffect = useEffect; + +const FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; +const mockHoverableFilterKeys: string[] = [FILTER_KEYS.TYPE, FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]; + +/** Called once per mounted filter content instance, so a remount shows up as a second call for the same key. */ +const mockOnContentCreated = jest.fn(); +/** Effects only run for a visible `Activity`, so this tracks which content the popover is actually showing. */ +const mockOnContentShown = jest.fn(); + +jest.mock('@components/SafeTriangle', () => ({ + __esModule: true, + default: ({children}: {children: React.ReactNode}) => {children}, +})); + +// Only holds Onyx subscriptions (which need providers not present here) and renders nothing. +jest.mock('@components/Search/FilterComponents/PersonalDetailOptionsKeepWarm', () => ({ + __esModule: true, + default: () => null, +})); + +// Stand-in for the filter list: one pressable per filter that reports a hover on the row. +jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () => ({ + __esModule: true, + default: ({onHoverIn}: {onHoverIn: (filterKey: string) => void}) => ( + + {mockHoverableFilterKeys.map((filterKey) => ( + onHoverIn(filterKey)} + /> + ))} + + ), +})); + +// Stand-in for the filter content, which is the expensive part being mounted or kept alive. +jest.mock('@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent', () => ({ + __esModule: true, + default: ({baseFilterKey}: {baseFilterKey: string}) => { + const isCreated = mockUseRef(false); + if (!isCreated.current) { + isCreated.current = true; + mockOnContentCreated(baseFilterKey); + } + + mockUseEffect(() => { + mockOnContentShown(baseFilterKey); + }, [baseFilterKey]); + + return ; + }, +})); + +jest.mock('@components/Search/hooks/useUpdateFilterQuery', () => ({ + __esModule: true, + default: () => ({setFilterQueryParams: jest.fn(), updateFilterQueryParams: jest.fn()}), +})); + +jest.mock('@hooks/useOnyx', () => ({ + __esModule: true, + default: () => [undefined, {status: 'loaded'}], +})); + +// The popover exists on web only (index.native.tsx renders nothing), and jest-expo's RN resolver prefers the native variant. +const SearchAdvancedFiltersPopup = require<{ + default: React.ComponentType<{queryJSON: SearchQueryJSON | undefined}>; +}>('../../../src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx').default; + +// Only forwarded to the mocked query hook, so the parsed query itself does not matter here. +const queryJSON = buildSearchQueryJSON(`type:${CONST.SEARCH.DATA_TYPES.EXPENSE}`); + +/** Moves the cursor onto a filter row without waiting for the hover intent delay to pass. */ +function hover(filterKey: string) { + fireEvent.press(screen.getByTestId(`hover-${filterKey}`)); +} + +/** Moves the cursor onto a filter row and leaves it there long enough for the content to follow. */ +function hoverAndRest(filterKey: string) { + hover(filterKey); + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); +} + +beforeEach(() => { + jest.clearAllMocks(); + jest.useFakeTimers(); +}); + +afterEach(() => { + jest.useRealTimers(); +}); + +describe('SearchAdvancedFiltersPopup', () => { + it('does not mount the content of filters the cursor only passes over', () => { + render(); + + // A fast sweep: every row is left again before the hover intent delay elapses. + for (const filterKey of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]) { + hover(filterKey); + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY - 1); + }); + } + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); + + // Only the row the cursor came to rest on was mounted, the two it swept over were not. + expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.ATTENDEE); + expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.FROM); + expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); + }); + + it('reuses the content of a filter that was already visited instead of remounting it', () => { + render(); + + hoverAndRest(FILTER_KEYS.FROM); + hoverAndRest(FILTER_KEYS.TO); + hoverAndRest(FILTER_KEYS.FROM); + + expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); + expect(mockOnContentShown).toHaveBeenLastCalledWith(FILTER_KEYS.FROM); + }); +}); From fa50d805aacc64f16e61da88a67bbd120fbb7622 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 7 Aug 2026 13:22:43 +0200 Subject: [PATCH 02/30] final code cleanup --- .../SearchAdvancedFiltersPopup/index.tsx | 10 ++-- src/hooks/usePersonalDetailOptions.ts | 46 ++++++++++--------- .../usePersonalDetailSearchSelector/base.ts | 41 ++++++++++++----- src/libs/memoize/index.ts | 20 ++++++-- 4 files changed, 74 insertions(+), 43 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 2b880260a632..2a961d62a315 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -45,11 +45,13 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps // The list highlights `selectedFilter` immediately; the content pane follows `restedFilter` once the cursor has stayed // on a row for SEARCH_FILTER_HOVER_INTENT_DELAY, so sweeping across rows doesn't render a content pane per row. const [selectedFilter, restedFilter, setSelectedFilter] = useDebouncedState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - // The last MAX_MOUNTED_FILTER_CONTENTS rested filters stay mounted (hidden by Activity), so returning to one of them - // toggles visibility instead of remounting. Adjusted during render so the new pane shows in the same frame. + // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filters stay mounted (hidden by Activity), so returning to + // one of them toggles visibility instead of remounting. Kept in least-recently-rested order (revisits move a filter + // back to the end, without remounting since the keys are stable) and adjusted during render so the new pane shows + // in the same frame. const [mountedFilters, setMountedFilters] = useState>([CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE]); - if (!mountedFilters.includes(restedFilter)) { - setMountedFilters([...mountedFilters, restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS)); + if (mountedFilters.at(-1) !== restedFilter) { + setMountedFilters([...mountedFilters.filter((filterKey) => filterKey !== restedFilter), restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS)); } const filterContentRef = useRef(null); const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 293310cfa757..7f16f0670cd2 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -140,35 +140,37 @@ function usePersonalDetailOptions(config: UseFilteredOptionsConfig = {}): UseFil const {accountID} = useCurrentUserPersonalDetails(); const {formatPhoneNumber, translate} = useLocalize(); const [reports, reportsMetadata] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: reportsSelector}); - const reportIDsSet = (() => { - if (!reports) { - return new Set(); - } - const validReportIDs = new Set(); - for (const report of Object.values(reports)) { - if (report) { - validReportIDs.add(report.reportID); - } - } - return validReportIDs; - })(); - const [reportAttributes, reportAttributesMetadata] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES); const [reportNameValuePairs, reportNameValuePairsMetadata] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); const personalDetails = usePersonalDetails(); const isLoading = !enabled || isLoadingOnyxValue(reportsMetadata, reportAttributesMetadata, reportNameValuePairsMetadata); - const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); - const privateIsArchivedMap = filterRNVPs(reportNameValuePairs, reportIDsSet); - const filteredReportAttributes = filterReportAttributes(reportAttributes, reportIDsSet); + // The whole derivation chain is skipped while loading (or disabled), so a consumer that only holds the Onyx + // subscriptions (e.g. PersonalDetailOptionsKeepWarm) doesn't rebuild these maps on every collection update. + const optionsData = (() => { + if (isLoading) { + return undefined; + } - const optionsData = !isLoading - ? memoizedCreateOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, filteredReportAttributes, privateIsArchivedMap, formatPhoneNumber, translate, { - shouldStoreReportErrors, - shouldShowBrickRoadIndicator, - }) - : undefined; + const reportIDsSet = new Set(); + if (reports) { + for (const report of Object.values(reports)) { + if (report) { + reportIDsSet.add(report.reportID); + } + } + } + + const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); + const privateIsArchivedMap = filterRNVPs(reportNameValuePairs, reportIDsSet); + const filteredReportAttributes = filterReportAttributes(reportAttributes, reportIDsSet); + + return memoizedCreateOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, filteredReportAttributes, privateIsArchivedMap, formatPhoneNumber, translate, { + shouldStoreReportErrors, + shouldShowBrickRoadIndicator, + }); + })(); return { options: optionsData?.options, diff --git a/src/hooks/usePersonalDetailSearchSelector/base.ts b/src/hooks/usePersonalDetailSearchSelector/base.ts index 531e2ffdd33a..33a926b4f8bc 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -150,14 +150,28 @@ const defaultListOptions = { /** * Filtering the whole option list is a pure derivation of its inputs, so remounting consumers reuse the previous result. - * A few entries are kept so that lists rendered next to each other don't evict each other. + * The cache is sized to the number of filter contents kept mounted at once, so lists rendered next to each other + * (e.g. the From/To/Attendee filters under the advanced filters popover) don't evict each other. */ const memoizedGetValidOptions = memoize(getValidOptions, { - maxSize: 3, + maxSize: CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS, 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: CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS, + equality: equivalentArgsComparator, + monitoringName: 'usePersonalDetailSearchSelector.buildSelectedOptions', +}); + /** * Base hook that provides search functionality with selection logic for option lists. * This contains the core logic without platform-specific dependencies. @@ -211,10 +225,7 @@ function usePersonalDetailSearchSelectorBase({ if (selectedAccountIDs.size === 0) { return optionsWithContacts; } - return optionsWithContacts.map((option) => ({ - ...option, - isSelected: selectedAccountIDs.has(option.accountID.toString()), - })); + return memoizedBuildSelectedOptions(optionsWithContacts, selectedAccountIDs); })(); const selectedOptions = (() => { @@ -253,13 +264,19 @@ function usePersonalDetailSearchSelectorBase({ const currentUserSearchTerms = [translate('common.you'), translate('common.me')]; const filteredCurrentUserOption = (() => { const newOption = filterOption(currentOption, debouncedSearchTerm, currentUserSearchTerms); - if (newOption) { - return { - ...newOption, - isSelected: selectedAccountIDs.has(newOption.accountID.toString()), - }; + if (!newOption) { + return newOption; + } + const isSelected = selectedAccountIDs.has(newOption.accountID.toString()); + // The original reference is kept when the selection state already matches, so consumers building memoized + // lists on top of this option keep hitting their caches across remounts. + if ((newOption.isSelected ?? false) === isSelected) { + return newOption; } - return newOption; + return { + ...newOption, + isSelected, + }; })(); const existingAccountIDs = new Set(optionsWithContacts?.map((option) => option.accountID.toString())); diff --git a/src/libs/memoize/index.ts b/src/libs/memoize/index.ts index 99abff0f72cc..fe8e2d018d10 100644 --- a/src/libs/memoize/index.ts +++ b/src/libs/memoize/index.ts @@ -114,24 +114,34 @@ function memoize => typeof value === 'object' && value !== null && !Array.isArray(value); +/** + * The two-level fallback below reads arguments through `Object.keys`, which only describes plain objects - for other + * types (Set, Map, Date, class instances) it returns an empty list and any two instances would look identical. + */ +const isPlainObject = (value: unknown): value is Record => { + if (typeof value !== 'object' || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value) as unknown; + return prototype === Object.prototype || prototype === null; +}; /** - * Two arguments are equivalent when they are shallowly equal, or are records with the same keys whose values are + * Two arguments are equivalent when they are shallowly equal, or are plain objects with the same keys 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 (!isRecord(previousArgument) || !isRecord(nextArgument)) { + 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) => shallowEqual(previousArgument[key], nextArgument[key])); + return previousKeys.every((key) => key in nextArgument && shallowEqual(previousArgument[key], nextArgument[key])); }; /** @@ -139,7 +149,7 @@ const areArgumentsEquivalent = (previousArgument: unknown, nextArgument: unknown * call from unchanged sources, where `'shallow'` always misses and `'deep'` would walk the whole payload. */ const equivalentArgsComparator = (previousArgs: Key, nextArgs: Key) => - previousArgs.every((argument, index) => areArgumentsEquivalent(argument, nextArgs.at(index))); + previousArgs.length === nextArgs.length && previousArgs.every((argument, index) => areArgumentsEquivalent(argument, nextArgs.at(index))); export default memoize; export {equivalentArgsComparator}; From 42db692221f294292df662a4045560b37d0493b9 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 7 Aug 2026 14:54:28 +0200 Subject: [PATCH 03/30] fix selected item order --- .../SearchAdvancedFiltersContent.tsx | 5 +- .../FilterComponents/ListFilterContent.tsx | 4 ++ .../Search/FilterComponents/UserSelector.tsx | 24 +++++++--- .../ListFilterContentPopupWrapper.tsx | 3 +- .../SearchAdvancedFiltersPopup/index.tsx | 24 ++++++---- .../Search/SearchAdvancedFiltersPopupTest.tsx | 47 +++++++++++++++---- 6 files changed, 80 insertions(+), 27 deletions(-) diff --git a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx index 586835b5a9e8..9dd7772109a5 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx @@ -26,6 +26,8 @@ type SearchAdvancedFiltersContentProps = { baseFilterKey: SearchFilter['key']; values: Partial | undefined; ready?: boolean; + /** Whether this filter is the one the advanced filters popover currently shows (false for contents kept mounted in the background) */ + isActive?: boolean; components: { Text: React.ComponentType; Amount: React.ComponentType; @@ -36,7 +38,7 @@ type SearchAdvancedFiltersContentProps = { onChange: (values: Partial) => void; }; -function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, onChange}: SearchAdvancedFiltersContentProps) { +function SearchAdvancedFiltersContent({baseFilterKey, values, ready, isActive, components, onChange}: SearchAdvancedFiltersContentProps) { if (isAmountFilterKey(baseFilterKey)) { const AmountFilter = components.Amount; return ( @@ -117,6 +119,7 @@ function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, type={values?.type} policyID={getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, values)} ready={ready} + isActive={isActive} isNegated={isNegated} onChange={(newValue, negated) => onChange(getFilterFormValues(baseFilterKey, newValue, negated))} /> diff --git a/src/components/Search/FilterComponents/ListFilterContent.tsx b/src/components/Search/FilterComponents/ListFilterContent.tsx index 65e66731d823..d0ff7074551b 100644 --- a/src/components/Search/FilterComponents/ListFilterContent.tsx +++ b/src/components/Search/FilterComponents/ListFilterContent.tsx @@ -38,6 +38,8 @@ type ListFilterContentProps = SearchFilterCommonProps; + /** Whether this filter is the one the advanced filters popover currently shows (false for contents kept mounted in the background) */ + isActive?: boolean; onNegationChange: (isNegated: boolean) => void; }; @@ -105,6 +107,7 @@ function ListFilterContent({ selectionListStyle, autoFocus, ready, + isActive, footer, onChange, onNegationChange, @@ -228,6 +231,7 @@ function ListFilterContent({ selectionListStyle={selectionListStyle} autoFocus={autoFocus} ready={ready} + isActive={isActive} footer={footer} onChange={onChange} /> diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index 21cb912901b8..9ee5b8309c7f 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -4,7 +4,6 @@ import SelectionList from '@components/SelectionList'; import UserSelectionListItem from '@components/SelectionList/ListItem/UserSelectionListItem'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; -import useInitialValue from '@hooks/useInitialValue'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import usePersonalDetailSearchSelector from '@hooks/usePersonalDetailSearchSelector'; @@ -19,11 +18,14 @@ import moveInitialSelectionToTop from '@libs/SelectionListOrderUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import React from 'react'; +import React, {useState} from 'react'; import ListFilterWrapper from './ListFilterViewWrapper'; -type UserSelectorProps = SearchFilterCommonProps; +type UserSelectorProps = SearchFilterCommonProps & { + /** Whether this filter is the one the advanced filters popover currently shows. Defaults to true for standalone usages. */ + isActive?: boolean; +}; /** * `moveInitialSelectionToTop` keys on `value`, so each option's accountID (`keyForList`) is mapped onto it. Copying every @@ -41,7 +43,7 @@ const memoizedBuildListData = memoize(buildListData, { monitoringName: 'UserSelector.buildListData', }); -function UserSelector({value = [], isNegatable, selectionListTextInputStyle, selectionListStyle, autoFocus, ready = true, footer, onChange}: UserSelectorProps) { +function UserSelector({value = [], isNegatable, selectionListTextInputStyle, selectionListStyle, autoFocus, ready = true, isActive = true, footer, onChange}: UserSelectorProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const personalDetails = usePersonalDetails(); @@ -74,9 +76,17 @@ function UserSelector({value = [], isNegatable, selectionListTextInputStyle, sel shouldKeepSelectedInAvailableOptions: true, }); - // 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 (see https://github.com/Expensify/App/issues/61414). - const initialSelectedValues = useInitialValue(() => value); + // Snapshot the pre-selected accountIDs from when the filter was last entered so they can be floated to the top + // without repinning rows that are toggled while it stays open (see https://github.com/Expensify/App/issues/61414). + // The filter content stays mounted between visits in the advanced filters popover, so the snapshot is also refreshed + // whenever `isActive` flips: on the way out the list is still shown for the hover intent delay and reorders itself + // while the cursor leaves, so coming back finds the fresh order already laid out in the first visible frame. + const [initialSelectedValues, setInitialSelectedValues] = useState(() => value); + const [wasActive, setWasActive] = useState(isActive); + if (wasActive !== isActive) { + setWasActive(isActive); + setInitialSelectedValues(value); + } // The current user is excluded from personalDetails, so include it (when present) in the list. Pre-selected rows are moved to the // top, leaving the current user just below them in its natural sorted position. diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx index bb02513672fa..74ab476d65e0 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx @@ -7,7 +7,7 @@ import {isFilterNegatable} from '@libs/SearchQueryUtils'; import React, {useState} from 'react'; -function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initialIsNegated, type, policyID, onChange}: ListFilterContentWrapperProps) { +function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initialIsNegated, type, policyID, isActive, onChange}: ListFilterContentWrapperProps) { const styles = useThemeStyles(); const [isNegated, setIsNegated] = useState(initialIsNegated); const isFilterKeyNegatable = isFilterNegatable(baseFilterKey); @@ -19,6 +19,7 @@ function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initial isNegated={isNegated} type={type} policyID={policyID} + isActive={isActive} style={[styles.mt6, styles.flex1]} selectionListTextInputStyle={[!isFilterKeyNegatable && [styles.pt5, styles.pb1]]} selectionListStyle={{contentContainerStyle: [isFilterKeyNegatable ? styles.pb2 : styles.pv2]}} diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 2a961d62a315..2c8aa0851668 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -17,7 +17,7 @@ import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import React, {Activity, useRef, useState} from 'react'; +import React, {useRef, useState} from 'react'; import {View} from 'react-native'; import AmountFilterContentPopupWrapper from './AmountFilterContentPopupWrapper'; @@ -45,10 +45,10 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps // The list highlights `selectedFilter` immediately; the content pane follows `restedFilter` once the cursor has stayed // on a row for SEARCH_FILTER_HOVER_INTENT_DELAY, so sweeping across rows doesn't render a content pane per row. const [selectedFilter, restedFilter, setSelectedFilter] = useDebouncedState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filters stay mounted (hidden by Activity), so returning to - // one of them toggles visibility instead of remounting. Kept in least-recently-rested order (revisits move a filter - // back to the end, without remounting since the keys are stable) and adjusted during render so the new pane shows - // in the same frame. + // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filters stay mounted (hidden with display:none), so returning + // to one of them toggles visibility instead of remounting. Kept in least-recently-rested order (revisits move a + // filter back to the end, without remounting since the keys are stable) and adjusted during render so the new pane + // shows in the same frame. const [mountedFilters, setMountedFilters] = useState>([CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE]); if (mountedFilters.at(-1) !== restedFilter) { setMountedFilters([...mountedFilters.filter((filterKey) => filterKey !== restedFilter), restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS)); @@ -75,17 +75,25 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps style={[styles.filterContentContainer]} > {mountedFilters.map((filterKey) => ( - + ))} diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 6fbaf4d0b90c..5f83d018b8fb 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -7,22 +7,21 @@ import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; import CONST from '@src/CONST'; -import React, {useEffect, useRef} from 'react'; -import {View} from 'react-native'; +import type {StyleProp, ViewStyle} from 'react-native'; + +import React, {useRef} from 'react'; +import {StyleSheet, View} from 'react-native'; // jest.mock factories can't reference imported bindings, but `mock`-prefixed locals are allowed. const MockView = View; const MockPressable = PressableWithoutFeedback; const mockUseRef = useRef; -const mockUseEffect = useEffect; const FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; const mockHoverableFilterKeys: string[] = [FILTER_KEYS.TYPE, FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]; /** Called once per mounted filter content instance, so a remount shows up as a second call for the same key. */ const mockOnContentCreated = jest.fn(); -/** Effects only run for a visible `Activity`, so this tracks which content the popover is actually showing. */ -const mockOnContentShown = jest.fn(); jest.mock('@components/SafeTriangle', () => ({ __esModule: true, @@ -63,10 +62,6 @@ jest.mock('@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFil mockOnContentCreated(baseFilterKey); } - mockUseEffect(() => { - mockOnContentShown(baseFilterKey); - }, [baseFilterKey]); - return ; }, })); @@ -94,6 +89,20 @@ function hover(filterKey: string) { fireEvent.press(screen.getByTestId(`hover-${filterKey}`)); } +/** + * Resolves whether a mounted filter content is the shown one or is kept in the background. Backgrounded contents are + * taken out of the layout flow by their wrapper (the visibility part of the style is web-only, so it is empty here). + */ +function isContentShown(filterKey: string) { + let wrapper = screen.getByTestId(`filter-content-${filterKey}`).parent; + while (wrapper && wrapper.props.style === undefined) { + wrapper = wrapper.parent; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion -- ReactTestInstance props are typed as `any` + const style = StyleSheet.flatten(wrapper?.props.style as StyleProp); + return style?.position !== 'absolute'; +} + /** Moves the cursor onto a filter row and leaves it there long enough for the content to follow. */ function hoverAndRest(filterKey: string) { hover(filterKey); @@ -140,6 +149,24 @@ describe('SearchAdvancedFiltersPopup', () => { hoverAndRest(FILTER_KEYS.FROM); expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); - expect(mockOnContentShown).toHaveBeenLastCalledWith(FILTER_KEYS.FROM); + // The revisited content is the shown one again, while the one left behind stays mounted but hidden. + expect(isContentShown(FILTER_KEYS.FROM)).toBe(true); + expect(isContentShown(FILTER_KEYS.TO)).toBe(false); + }); + + it('keeps only the most recently used contents mounted', () => { + render(); + + // Visiting one filter more than MAX_MOUNTED_FILTER_CONTENTS keeps mounted evicts the least recently used one. + hoverAndRest(FILTER_KEYS.FROM); + hoverAndRest(FILTER_KEYS.TO); + hoverAndRest(FILTER_KEYS.ATTENDEE); + + expect(screen.queryByTestId(`filter-content-${FILTER_KEYS.TYPE}`, {includeHiddenElements: true})).toBeNull(); + expect(isContentShown(FILTER_KEYS.ATTENDEE)).toBe(true); + + // Returning to an evicted filter mounts a fresh content instance for it. + hoverAndRest(FILTER_KEYS.TYPE); + expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.TYPE)).toHaveLength(2); }); }); From 544b133617355f26767df23daa3a0da36a4b8d1e Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 7 Aug 2026 15:05:57 +0200 Subject: [PATCH 04/30] polish comments and tests --- .../SearchAdvancedFiltersContent.tsx | 2 +- .../FilterComponents/ListFilterContent.tsx | 2 +- .../Search/FilterComponents/UserSelector.tsx | 14 +++------- .../SearchAdvancedFiltersPopup/index.tsx | 17 +++++------- .../usePersonalDetailSearchSelector/base.ts | 3 +-- .../Search/SearchAdvancedFiltersPopupTest.tsx | 27 +++---------------- 6 files changed, 16 insertions(+), 49 deletions(-) diff --git a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx index 9dd7772109a5..85842fedaa4d 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx @@ -26,7 +26,7 @@ type SearchAdvancedFiltersContentProps = { baseFilterKey: SearchFilter['key']; values: Partial | undefined; ready?: boolean; - /** Whether this filter is the one the advanced filters popover currently shows (false for contents kept mounted in the background) */ + /** Whether this filter is the one the advanced filters popover currently shows */ isActive?: boolean; components: { Text: React.ComponentType; diff --git a/src/components/Search/FilterComponents/ListFilterContent.tsx b/src/components/Search/FilterComponents/ListFilterContent.tsx index d0ff7074551b..0acb0cd4e44e 100644 --- a/src/components/Search/FilterComponents/ListFilterContent.tsx +++ b/src/components/Search/FilterComponents/ListFilterContent.tsx @@ -38,7 +38,7 @@ type ListFilterContentProps = SearchFilterCommonProps; - /** Whether this filter is the one the advanced filters popover currently shows (false for contents kept mounted in the background) */ + /** Whether this filter is the one the advanced filters popover currently shows */ isActive?: boolean; onNegationChange: (isNegated: boolean) => void; }; diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index 9ee5b8309c7f..ac19b4a1287e 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -23,14 +23,11 @@ import React, {useState} from 'react'; import ListFilterWrapper from './ListFilterViewWrapper'; type UserSelectorProps = SearchFilterCommonProps & { - /** Whether this filter is the one the advanced filters popover currently shows. Defaults to true for standalone usages. */ + /** Whether this filter is the one the advanced filters popover currently shows */ isActive?: boolean; }; -/** - * `moveInitialSelectionToTop` keys on `value`, so each option's accountID (`keyForList`) is mapped onto it. Copying every - * option is the last full pass over the list per render, so the result is reused while the inputs are unchanged. - */ +/** Maps each option's accountID onto `value` (what `moveInitialSelectionToTop` keys on) and pins the pre-selected rows to the top. */ const buildListData = (options: OptionData[], initialSelectedValues: string[]) => moveInitialSelectionToTop( options.map((option) => ({...option, value: option.keyForList})), @@ -76,11 +73,8 @@ function UserSelector({value = [], isNegatable, selectionListTextInputStyle, sel shouldKeepSelectedInAvailableOptions: true, }); - // Snapshot the pre-selected accountIDs from when the filter was last entered so they can be floated to the top - // without repinning rows that are toggled while it stays open (see https://github.com/Expensify/App/issues/61414). - // The filter content stays mounted between visits in the advanced filters popover, so the snapshot is also refreshed - // whenever `isActive` flips: on the way out the list is still shown for the hover intent delay and reorders itself - // while the cursor leaves, so coming back finds the fresh order already laid out in the first visible frame. + // Snapshot of the pre-selected accountIDs, refreshed whenever `isActive` flips so each popover visit pins the current + // selection to the top without repinning rows toggled while it stays open (see https://github.com/Expensify/App/issues/61414). const [initialSelectedValues, setInitialSelectedValues] = useState(() => value); const [wasActive, setWasActive] = useState(isActive); if (wasActive !== isActive) { diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 2c8aa0851668..9f29407e19af 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -45,10 +45,8 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps // The list highlights `selectedFilter` immediately; the content pane follows `restedFilter` once the cursor has stayed // on a row for SEARCH_FILTER_HOVER_INTENT_DELAY, so sweeping across rows doesn't render a content pane per row. const [selectedFilter, restedFilter, setSelectedFilter] = useDebouncedState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filters stay mounted (hidden with display:none), so returning - // to one of them toggles visibility instead of remounting. Kept in least-recently-rested order (revisits move a - // filter back to the end, without remounting since the keys are stable) and adjusted during render so the new pane - // shows in the same frame. + // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filter contents stay mounted, so revisits toggle visibility + // instead of remounting. Kept in least-recently-rested order and adjusted during render so the new pane shows in the same frame. const [mountedFilters, setMountedFilters] = useState>([CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE]); if (mountedFilters.at(-1) !== restedFilter) { setMountedFilters([...mountedFilters.filter((filterKey) => filterKey !== restedFilter), restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS)); @@ -75,17 +73,14 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps style={[styles.filterContentContainer]} > {mountedFilters.map((filterKey) => ( - // Backgrounded contents are hidden with visibility:hidden (not Activity or display:none, which - // both freeze the hidden content - the list inside doesn't lay out updates made while hidden, - // so returning to the filter briefly showed stale content). Keeping the layout alive lets a - // hidden list reorder itself in the background and the reveal is then just a style flip. + // Backgrounded contents keep their layout (hidden with web-only visibility:hidden), so their lists + // keep laying out updates made in the background and showing one again is just a style flip. - {/* `isActive` follows the immediate `selectedFilter` so a content learns the cursor left it - while it is still shown (the hover intent delay hasn't hidden it yet) and can reorder - itself on that edge - its list is still laid out, whereas a hidden one repaints late. */} + {/* `isActive` follows the non-debounced `selectedFilter`, so a content refreshes itself while + still laid out, before the hover intent delay swaps it out. */} ); - return style?.position !== 'absolute'; -} - /** Moves the cursor onto a filter row and leaves it there long enough for the content to follow. */ function hoverAndRest(filterKey: string) { hover(filterKey); @@ -149,21 +133,16 @@ describe('SearchAdvancedFiltersPopup', () => { hoverAndRest(FILTER_KEYS.FROM); expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); - // The revisited content is the shown one again, while the one left behind stays mounted but hidden. - expect(isContentShown(FILTER_KEYS.FROM)).toBe(true); - expect(isContentShown(FILTER_KEYS.TO)).toBe(false); }); it('keeps only the most recently used contents mounted', () => { render(); - // Visiting one filter more than MAX_MOUNTED_FILTER_CONTENTS keeps mounted evicts the least recently used one. + // Visiting more filters than MAX_MOUNTED_FILTER_CONTENTS evicts the least recently used one. hoverAndRest(FILTER_KEYS.FROM); hoverAndRest(FILTER_KEYS.TO); hoverAndRest(FILTER_KEYS.ATTENDEE); - - expect(screen.queryByTestId(`filter-content-${FILTER_KEYS.TYPE}`, {includeHiddenElements: true})).toBeNull(); - expect(isContentShown(FILTER_KEYS.ATTENDEE)).toBe(true); + expect(screen.queryByTestId(`filter-content-${FILTER_KEYS.TYPE}`)).toBeNull(); // Returning to an evicted filter mounts a fresh content instance for it. hoverAndRest(FILTER_KEYS.TYPE); From b4621413aaed92361374b76ebc8d0594df6d91c8 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 10 Aug 2026 09:09:05 +0200 Subject: [PATCH 05/30] perf: keep filter contents mounted without Onyx or memoize changes Drop the keep-warm Onyx subscription, the module-level memoization of the personal detail derivations and the equivalentArgsComparator they needed. Freezing the form values of backgrounded contents and comparing props on them keeps the same panes from re-rendering, so the caches are unnecessary. Explain why React.memo is still needed next to React Compiler: the compiler caches the whole mountedFilters.map() result in a single slot, so it cannot bail out on an individual element. --- .../SearchAdvancedFiltersContent.tsx | 5 +- .../FilterComponents/ListFilterContent.tsx | 4 -- .../PersonalDetailOptionsKeepWarm.tsx | 13 ---- .../Search/FilterComponents/UserSelector.tsx | 47 +++++---------- .../ListFilterContentPopupWrapper.tsx | 3 +- .../SearchAdvancedFiltersPopup/index.tsx | 40 +++++++++---- src/hooks/usePersonalDetailOptions.ts | 57 +++++++----------- .../usePersonalDetailSearchSelector/base.ts | 60 ++++--------------- src/libs/memoize/index.ts | 40 ------------- .../Search/SearchAdvancedFiltersPopupTest.tsx | 29 ++++++--- 10 files changed, 99 insertions(+), 199 deletions(-) delete mode 100644 src/components/Search/FilterComponents/PersonalDetailOptionsKeepWarm.tsx diff --git a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx index 85842fedaa4d..586835b5a9e8 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx @@ -26,8 +26,6 @@ type SearchAdvancedFiltersContentProps = { baseFilterKey: SearchFilter['key']; values: Partial | undefined; ready?: boolean; - /** Whether this filter is the one the advanced filters popover currently shows */ - isActive?: boolean; components: { Text: React.ComponentType; Amount: React.ComponentType; @@ -38,7 +36,7 @@ type SearchAdvancedFiltersContentProps = { onChange: (values: Partial) => void; }; -function SearchAdvancedFiltersContent({baseFilterKey, values, ready, isActive, components, onChange}: SearchAdvancedFiltersContentProps) { +function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, onChange}: SearchAdvancedFiltersContentProps) { if (isAmountFilterKey(baseFilterKey)) { const AmountFilter = components.Amount; return ( @@ -119,7 +117,6 @@ function SearchAdvancedFiltersContent({baseFilterKey, values, ready, isActive, c type={values?.type} policyID={getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, values)} ready={ready} - isActive={isActive} isNegated={isNegated} onChange={(newValue, negated) => onChange(getFilterFormValues(baseFilterKey, newValue, negated))} /> diff --git a/src/components/Search/FilterComponents/ListFilterContent.tsx b/src/components/Search/FilterComponents/ListFilterContent.tsx index 0acb0cd4e44e..65e66731d823 100644 --- a/src/components/Search/FilterComponents/ListFilterContent.tsx +++ b/src/components/Search/FilterComponents/ListFilterContent.tsx @@ -38,8 +38,6 @@ type ListFilterContentProps = SearchFilterCommonProps; - /** Whether this filter is the one the advanced filters popover currently shows */ - isActive?: boolean; onNegationChange: (isNegated: boolean) => void; }; @@ -107,7 +105,6 @@ function ListFilterContent({ selectionListStyle, autoFocus, ready, - isActive, footer, onChange, onNegationChange, @@ -231,7 +228,6 @@ function ListFilterContent({ selectionListStyle={selectionListStyle} autoFocus={autoFocus} ready={ready} - isActive={isActive} footer={footer} onChange={onChange} /> diff --git a/src/components/Search/FilterComponents/PersonalDetailOptionsKeepWarm.tsx b/src/components/Search/FilterComponents/PersonalDetailOptionsKeepWarm.tsx deleted file mode 100644 index 7edde424f0ac..000000000000 --- a/src/components/Search/FilterComponents/PersonalDetailOptionsKeepWarm.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import usePersonalDetailOptions from '@hooks/usePersonalDetailOptions'; - -/** - * Holds the Onyx subscriptions behind the personal detail option list for as long as it stays mounted, so the memoized - * list survives filter content remounts (Onyx drops a key's cached snapshot with its last subscriber). Renders nothing. - */ -function PersonalDetailOptionsKeepWarm() { - usePersonalDetailOptions({enabled: false}); - - return null; -} - -export default PersonalDetailOptionsKeepWarm; diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index ac19b4a1287e..905bada8dc61 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -4,13 +4,13 @@ import SelectionList from '@components/SelectionList'; import UserSelectionListItem from '@components/SelectionList/ListItem/UserSelectionListItem'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; +import useInitialValue from '@hooks/useInitialValue'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; import usePersonalDetailSearchSelector from '@hooks/usePersonalDetailSearchSelector'; import useThemeStyles from '@hooks/useThemeStyles'; import canFocusInputOnScreenFocus from '@libs/canFocusInputOnScreenFocus'; -import memoize, {equivalentArgsComparator} from '@libs/memoize'; import type {OptionData} from '@libs/PersonalDetailOptionsListUtils'; import {getExpensifyTeamExclusions} from '@libs/PolicyUtils'; import moveInitialSelectionToTop from '@libs/SelectionListOrderUtils'; @@ -18,29 +18,13 @@ import moveInitialSelectionToTop from '@libs/SelectionListOrderUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import React, {useState} from 'react'; +import React from 'react'; import ListFilterWrapper from './ListFilterViewWrapper'; -type UserSelectorProps = SearchFilterCommonProps & { - /** Whether this filter is the one the advanced filters popover currently shows */ - isActive?: boolean; -}; +type UserSelectorProps = SearchFilterCommonProps; -/** Maps each option's accountID onto `value` (what `moveInitialSelectionToTop` keys on) and pins the pre-selected rows to the top. */ -const buildListData = (options: OptionData[], initialSelectedValues: string[]) => - moveInitialSelectionToTop( - options.map((option) => ({...option, value: option.keyForList})), - initialSelectedValues, - ); - -const memoizedBuildListData = memoize(buildListData, { - maxSize: 2, - equality: equivalentArgsComparator, - monitoringName: 'UserSelector.buildListData', -}); - -function UserSelector({value = [], isNegatable, selectionListTextInputStyle, selectionListStyle, autoFocus, ready = true, isActive = true, footer, onChange}: UserSelectorProps) { +function UserSelector({value = [], isNegatable, selectionListTextInputStyle, selectionListStyle, autoFocus, ready = true, footer, onChange}: UserSelectorProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const personalDetails = usePersonalDetails(); @@ -73,19 +57,18 @@ function UserSelector({value = [], isNegatable, selectionListTextInputStyle, sel shouldKeepSelectedInAvailableOptions: true, }); - // Snapshot of the pre-selected accountIDs, refreshed whenever `isActive` flips so each popover visit pins the current - // selection to the top without repinning rows toggled while it stays open (see https://github.com/Expensify/App/issues/61414). - const [initialSelectedValues, setInitialSelectedValues] = useState(() => value); - const [wasActive, setWasActive] = useState(isActive); - if (wasActive !== isActive) { - setWasActive(isActive); - setInitialSelectedValues(value); - } - - // The current user is excluded from personalDetails, so include it (when present) in the list. Pre-selected rows are moved to the - // top, leaving the current user just below them in its natural sorted position. + // 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 (see https://github.com/Expensify/App/issues/61414). + const initialSelectedValues = useInitialValue(() => value); + + // The current user is excluded from personalDetails, so include it (when present) in the list. moveInitialSelectionToTop + // keys on `value`, so map each option's accountID (keyForList) onto it. Pre-selected rows are moved to the top, + // leaving the current user just below them in its natural sorted position. const baseListData = availableOptions.currentUserOption ? [availableOptions.currentUserOption, ...availableOptions.personalDetails] : availableOptions.personalDetails; - const listData = memoizedBuildListData(baseListData, initialSelectedValues); + const listData = moveInitialSelectionToTop( + baseListData.map((option) => ({...option, value: option.keyForList})), + initialSelectedValues, + ); const headerMessage = listData.length === 0 ? translate('common.noResultsFound') : undefined; diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx index 74ab476d65e0..bb02513672fa 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx @@ -7,7 +7,7 @@ import {isFilterNegatable} from '@libs/SearchQueryUtils'; import React, {useState} from 'react'; -function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initialIsNegated, type, policyID, isActive, onChange}: ListFilterContentWrapperProps) { +function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initialIsNegated, type, policyID, onChange}: ListFilterContentWrapperProps) { const styles = useThemeStyles(); const [isNegated, setIsNegated] = useState(initialIsNegated); const isFilterKeyNegatable = isFilterNegatable(baseFilterKey); @@ -19,7 +19,6 @@ function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initial isNegated={isNegated} type={type} policyID={policyID} - isActive={isActive} style={[styles.mt6, styles.flex1]} selectionListTextInputStyle={[!isFilterKeyNegatable && [styles.pt5, styles.pb1]]} selectionListStyle={{contentContainerStyle: [isFilterKeyNegatable ? styles.pb2 : styles.pv2]}} diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 9f29407e19af..94ace870ff04 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -1,7 +1,6 @@ import SafeTriangle from '@components/SafeTriangle'; import FilterList from '@components/Search/FilterComponents/AdvancedFilters/FilterList'; import SearchAdvancedFiltersContent from '@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent'; -import PersonalDetailOptionsKeepWarm from '@components/Search/FilterComponents/PersonalDetailOptionsKeepWarm'; import useUpdateFilterQuery from '@components/Search/hooks/useUpdateFilterQuery'; import type {SearchQueryJSON} from '@components/Search/types'; @@ -16,6 +15,7 @@ import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import type {SearchAdvancedFiltersForm} from '@src/types/form'; import React, {useRef, useState} from 'react'; import {View} from 'react-native'; @@ -38,27 +38,43 @@ const filterComponents = { ReportField: ReportFieldFilterContentPopupWrapper, } as const; +// React Compiler caches the whole `mountedFilters.map()` result in a single slot, so changing the shown filter rebuilds +// every element of it - there is no per-element cache it could bail out on. Comparing props here is what keeps the +// kept-mounted contents, whose own props are unchanged, from re-rendering along with the one being shown. +const MemoizedFilterContent = React.memo(SearchAdvancedFiltersContent); + function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps) { const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const {windowHeight} = useWindowDimensions(); + const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); // The list highlights `selectedFilter` immediately; the content pane follows `restedFilter` once the cursor has stayed // on a row for SEARCH_FILTER_HOVER_INTENT_DELAY, so sweeping across rows doesn't render a content pane per row. const [selectedFilter, restedFilter, setSelectedFilter] = useDebouncedState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filter contents stay mounted, so revisits toggle visibility - // instead of remounting. Kept in least-recently-rested order and adjusted during render so the new pane shows in the same frame. + // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filter contents stay mounted (hidden below), so revisits + // toggle visibility instead of remounting. Kept in least-recently-rested order and adjusted during render so the new + // pane shows in the same frame. const [mountedFilters, setMountedFilters] = useState>([CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE]); + // A kept-mounted content shows the filter values from when it was last rested on (its hidden updates are deferred and + // its selection pinning is decided on mount), so returning to a filter after the form changed remounts it instead. + // Both maps are adjusted during render on the rested-filter edge, so the decision applies to the revealing frame. + const [formAtLastRest, setFormAtLastRest] = useState | undefined>>>({ + [CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE]: searchAdvancedFiltersForm, + }); + const [contentVersions, setContentVersions] = useState>>({}); if (mountedFilters.at(-1) !== restedFilter) { + if (mountedFilters.includes(restedFilter) && formAtLastRest[restedFilter] !== searchAdvancedFiltersForm) { + setContentVersions({...contentVersions, [restedFilter]: (contentVersions[restedFilter] ?? 0) + 1}); + } + setFormAtLastRest({...formAtLastRest, [restedFilter]: searchAdvancedFiltersForm}); setMountedFilters([...mountedFilters.filter((filterKey) => filterKey !== restedFilter), restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS)); } const filterContentRef = useRef(null); - const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); const {updateFilterQueryParams} = useUpdateFilterQuery(queryJSON); return ( - {mountedFilters.map((filterKey) => ( - // Backgrounded contents keep their layout (hidden with web-only visibility:hidden), so their lists - // keep laying out updates made in the background and showing one again is just a style flip. + // Backgrounded contents keep their layout (hidden with web-only visibility:hidden) and get the + // form values frozen at their last visit, so moving between filters doesn't re-render them and + // showing one again is just a style flip. A content whose values went stale is remounted (above). - {/* `isActive` follows the non-debounced `selectedFilter`, so a content refreshes itself while - still laid out, before the hover intent delay swaps it out. */} - diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 7f16f0670cd2..5bb18a2caa56 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -1,6 +1,5 @@ import {usePersonalDetails} from '@components/OnyxListItemProvider'; -import memoize, {equivalentArgsComparator} from '@libs/memoize'; import {createOptionList} from '@libs/PersonalDetailOptionsListUtils'; import type {OptionData, PrivateIsArchivedMap} from '@libs/PersonalDetailOptionsListUtils/types'; import {isOneOnOneChat, isSelfDM} from '@libs/ReportUtils'; @@ -105,16 +104,6 @@ const filterReportAttributes = (reportAttributes: OnyxEntry { + if (!reports) { + return new Set(); + } + const validReportIDs = new Set(); + for (const report of Object.values(reports)) { + if (report) { + validReportIDs.add(report.reportID); + } + } + return validReportIDs; + })(); + const [reportAttributes, reportAttributesMetadata] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES); const [reportNameValuePairs, reportNameValuePairsMetadata] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); const personalDetails = usePersonalDetails(); const isLoading = !enabled || isLoadingOnyxValue(reportsMetadata, reportAttributesMetadata, reportNameValuePairsMetadata); - // The whole derivation chain is skipped while loading (or disabled), so a consumer that only holds the Onyx - // subscriptions (e.g. PersonalDetailOptionsKeepWarm) doesn't rebuild these maps on every collection update. - const optionsData = (() => { - if (isLoading) { - return undefined; - } + const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); + const privateIsArchivedMap = filterRNVPs(reportNameValuePairs, reportIDsSet); + const filteredReportAttributes = filterReportAttributes(reportAttributes, reportIDsSet); - const reportIDsSet = new Set(); - if (reports) { - for (const report of Object.values(reports)) { - if (report) { - reportIDsSet.add(report.reportID); - } - } - } - - const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); - const privateIsArchivedMap = filterRNVPs(reportNameValuePairs, reportIDsSet); - const filteredReportAttributes = filterReportAttributes(reportAttributes, reportIDsSet); - - return memoizedCreateOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, filteredReportAttributes, privateIsArchivedMap, formatPhoneNumber, translate, { - shouldStoreReportErrors, - shouldShowBrickRoadIndicator, - }); - })(); + const optionsData = !isLoading + ? createOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, filteredReportAttributes, privateIsArchivedMap, formatPhoneNumber, translate, { + shouldStoreReportErrors, + shouldShowBrickRoadIndicator, + }) + : undefined; return { options: optionsData?.options, diff --git a/src/hooks/usePersonalDetailSearchSelector/base.ts b/src/hooks/usePersonalDetailSearchSelector/base.ts index c3581c17d562..13a1b6be3c62 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -4,7 +4,6 @@ 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 {expensifyLoginsSelector} from '@libs/UserUtils'; @@ -148,29 +147,6 @@ const defaultListOptions = { selectedOptions: [], }; -/** - * Filtering the whole option list is a pure derivation of its inputs, so remounting consumers reuse the previous result. - * The cache is sized to the number of mounted filter contents so lists rendered next to each other don't evict each other. - */ -const memoizedGetValidOptions = memoize(getValidOptions, { - maxSize: CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS, - 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: CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS, - equality: equivalentArgsComparator, - monitoringName: 'usePersonalDetailSearchSelector.buildSelectedOptions', -}); - /** * Base hook that provides search functionality with selection logic for option lists. * This contains the core logic without platform-specific dependencies. @@ -215,17 +191,11 @@ function usePersonalDetailSearchSelectorBase({ const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const currentUserEmail = currentUserPersonalDetails.email ?? ''; - // With nothing selected the options already carry the right state, so the list is passed through without copying, - // keeping its reference stable for the memoized filtering below. - const transformedOptions: OptionData[] = (() => { - if (!optionsWithContacts) { - return []; - } - if (selectedAccountIDs.size === 0) { - return optionsWithContacts; - } - return memoizedBuildSelectedOptions(optionsWithContacts, selectedAccountIDs); - })(); + const transformedOptions: OptionData[] = + optionsWithContacts?.map((option) => ({ + ...option, + isSelected: selectedAccountIDs.has(option.accountID.toString()), + })) ?? []; const selectedOptions = (() => { const options: OptionData[] = []; @@ -244,7 +214,7 @@ function usePersonalDetailSearchSelectorBase({ const optionsList = !areOptionsInitialized ? defaultListOptions - : memoizedGetValidOptions(transformedOptions, currentUserEmail, formatPhoneNumber, countryCode, loginList, { + : getValidOptions(transformedOptions, currentUserEmail, formatPhoneNumber, countryCode, loginList, { excludeLogins, excludeFromSuggestionsOnly, includeSelectedOptions: shouldKeepSelectedInAvailableOptions, @@ -263,19 +233,13 @@ function usePersonalDetailSearchSelectorBase({ const currentUserSearchTerms = [translate('common.you'), translate('common.me')]; const filteredCurrentUserOption = (() => { const newOption = filterOption(currentOption, debouncedSearchTerm, currentUserSearchTerms); - if (!newOption) { - return newOption; - } - const isSelected = selectedAccountIDs.has(newOption.accountID.toString()); - // The original reference is kept when the selection state already matches, so consumers building memoized - // lists on top of this option keep hitting their caches across remounts. - if ((newOption.isSelected ?? false) === isSelected) { - return newOption; + if (newOption) { + return { + ...newOption, + isSelected: selectedAccountIDs.has(newOption.accountID.toString()), + }; } - return { - ...newOption, - isSelected, - }; + return newOption; })(); const existingAccountIDs = new Set(optionsWithContacts?.map((option) => option.accountID.toString())); diff --git a/src/libs/memoize/index.ts b/src/libs/memoize/index.ts index fe8e2d018d10..c29e4cc4bf8d 100644 --- a/src/libs/memoize/index.ts +++ b/src/libs/memoize/index.ts @@ -1,8 +1,6 @@ import type NonPartial from '@src/types/utils/NonPartial'; import type TakeFirst from '@src/types/utils/TupleOperations'; -import {shallowEqual} from 'fast-equals'; - import type {Callable, ClientOptions, Constructable, IsomorphicFn, IsomorphicParameters, IsomorphicReturnType, MemoizedFn, Stats} from './types'; import ArrayCache from './cache/ArrayCache'; @@ -114,42 +112,4 @@ function memoize => { - if (typeof value !== 'object' || value === null) { - return false; - } - const prototype = Object.getPrototypeOf(value) as unknown; - return prototype === Object.prototype || prototype === null; -}; - -/** - * Two arguments are equivalent when they are shallowly equal, or are plain objects with the same keys 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.at(index))); - export default memoize; -export {equivalentArgsComparator}; diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 12c5381d7c45..fc70b3684831 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -6,6 +6,7 @@ import type {SearchQueryJSON} from '@components/Search/types'; import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; import CONST from '@src/CONST'; +import type {SearchAdvancedFiltersForm} from '@src/types/form'; import React, {useRef} from 'react'; import {View} from 'react-native'; @@ -21,17 +22,14 @@ const mockHoverableFilterKeys: string[] = [FILTER_KEYS.TYPE, FILTER_KEYS.FROM, F /** Called once per mounted filter content instance, so a remount shows up as a second call for the same key. */ const mockOnContentCreated = jest.fn(); +/** The advanced filters form value served by the useOnyx mock. Reassigned by tests simulating filter value changes. */ +let mockFiltersForm: Partial | undefined; + jest.mock('@components/SafeTriangle', () => ({ __esModule: true, default: ({children}: {children: React.ReactNode}) => {children}, })); -// Only holds Onyx subscriptions (which need providers not present here) and renders nothing. -jest.mock('@components/Search/FilterComponents/PersonalDetailOptionsKeepWarm', () => ({ - __esModule: true, - default: () => null, -})); - // Stand-in for the filter list: one pressable per filter that reports a hover on the row. jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () => ({ __esModule: true, @@ -71,7 +69,7 @@ jest.mock('@components/Search/hooks/useUpdateFilterQuery', () => ({ jest.mock('@hooks/useOnyx', () => ({ __esModule: true, - default: () => [undefined, {status: 'loaded'}], + default: () => [mockFiltersForm, {status: 'loaded'}], })); // The popover exists on web only (index.native.tsx renders nothing), and jest-expo's RN resolver prefers the native variant. @@ -98,6 +96,7 @@ function hoverAndRest(filterKey: string) { beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); + mockFiltersForm = undefined; }); afterEach(() => { @@ -135,6 +134,20 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); }); + it('remounts a kept content when the filters form changed while it was away', () => { + render(); + + hoverAndRest(FILTER_KEYS.FROM); + + // The form changes (e.g. a value was picked) and the cursor moves on to another filter. + mockFiltersForm = {type: CONST.SEARCH.DATA_TYPES.EXPENSE}; + hoverAndRest(FILTER_KEYS.TO); + + // Returning to the filter now gets a fresh content instance instead of the one from before the change. + hoverAndRest(FILTER_KEYS.FROM); + expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(2); + }); + it('keeps only the most recently used contents mounted', () => { render(); @@ -142,7 +155,7 @@ describe('SearchAdvancedFiltersPopup', () => { hoverAndRest(FILTER_KEYS.FROM); hoverAndRest(FILTER_KEYS.TO); hoverAndRest(FILTER_KEYS.ATTENDEE); - expect(screen.queryByTestId(`filter-content-${FILTER_KEYS.TYPE}`)).toBeNull(); + expect(screen.queryByTestId(`filter-content-${FILTER_KEYS.TYPE}`, {includeHiddenElements: true})).toBeNull(); // Returning to an evicted filter mounts a fresh content instance for it. hoverAndRest(FILTER_KEYS.TYPE); From 58da9959ea55fe19c51282deaf119d5f2953315f Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 10 Aug 2026 11:09:05 +0200 Subject: [PATCH 06/30] perf: memoize the personal detail derivations behind the people filters Building an option per personal details entry and filtering the whole option list are pure derivations of Onyx data, so a remounted filter content can reuse the previous result instead of walking the collection again. Both are memoized at module level behind a new equivalentArgsComparator in @libs/memoize, which compares memoization keys argument by argument: shallowly first, and one level deeper for plain objects that are rebuilt on every call from unchanged sources. Measured on an account with 100k personal details, sweeping and resting on every filter row: 4.2s of blocked JS down to 1.7s. --- src/hooks/usePersonalDetailOptions.ts | 57 +++++++++++------- .../usePersonalDetailSearchSelector/base.ts | 60 +++++++++++++++---- src/libs/memoize/index.ts | 40 +++++++++++++ 3 files changed, 123 insertions(+), 34 deletions(-) diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 5bb18a2caa56..7f16f0670cd2 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -1,5 +1,6 @@ import {usePersonalDetails} from '@components/OnyxListItemProvider'; +import memoize, {equivalentArgsComparator} from '@libs/memoize'; import {createOptionList} from '@libs/PersonalDetailOptionsListUtils'; import type {OptionData, PrivateIsArchivedMap} from '@libs/PersonalDetailOptionsListUtils/types'; import {isOneOnOneChat, isSelfDM} from '@libs/ReportUtils'; @@ -104,6 +105,16 @@ const filterReportAttributes = (reportAttributes: OnyxEntry { - if (!reports) { - return new Set(); - } - const validReportIDs = new Set(); - for (const report of Object.values(reports)) { - if (report) { - validReportIDs.add(report.reportID); - } - } - return validReportIDs; - })(); - const [reportAttributes, reportAttributesMetadata] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES); const [reportNameValuePairs, reportNameValuePairsMetadata] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS); const personalDetails = usePersonalDetails(); const isLoading = !enabled || isLoadingOnyxValue(reportsMetadata, reportAttributesMetadata, reportNameValuePairsMetadata); - const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); - const privateIsArchivedMap = filterRNVPs(reportNameValuePairs, reportIDsSet); - const filteredReportAttributes = filterReportAttributes(reportAttributes, reportIDsSet); + // The whole derivation chain is skipped while loading (or disabled), so a consumer that only holds the Onyx + // subscriptions (e.g. PersonalDetailOptionsKeepWarm) doesn't rebuild these maps on every collection update. + const optionsData = (() => { + if (isLoading) { + return undefined; + } - const optionsData = !isLoading - ? createOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, filteredReportAttributes, privateIsArchivedMap, formatPhoneNumber, translate, { - shouldStoreReportErrors, - shouldShowBrickRoadIndicator, - }) - : undefined; + const reportIDsSet = new Set(); + if (reports) { + for (const report of Object.values(reports)) { + if (report) { + reportIDsSet.add(report.reportID); + } + } + } + + const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); + const privateIsArchivedMap = filterRNVPs(reportNameValuePairs, reportIDsSet); + const filteredReportAttributes = filterReportAttributes(reportAttributes, reportIDsSet); + + return memoizedCreateOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, filteredReportAttributes, privateIsArchivedMap, formatPhoneNumber, translate, { + shouldStoreReportErrors, + shouldShowBrickRoadIndicator, + }); + })(); return { options: optionsData?.options, diff --git a/src/hooks/usePersonalDetailSearchSelector/base.ts b/src/hooks/usePersonalDetailSearchSelector/base.ts index 13a1b6be3c62..c3581c17d562 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -4,6 +4,7 @@ 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 {expensifyLoginsSelector} from '@libs/UserUtils'; @@ -147,6 +148,29 @@ const defaultListOptions = { selectedOptions: [], }; +/** + * Filtering the whole option list is a pure derivation of its inputs, so remounting consumers reuse the previous result. + * The cache is sized to the number of mounted filter contents so lists rendered next to each other don't evict each other. + */ +const memoizedGetValidOptions = memoize(getValidOptions, { + maxSize: CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS, + 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: CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS, + equality: equivalentArgsComparator, + monitoringName: 'usePersonalDetailSearchSelector.buildSelectedOptions', +}); + /** * Base hook that provides search functionality with selection logic for option lists. * This contains the core logic without platform-specific dependencies. @@ -191,11 +215,17 @@ function usePersonalDetailSearchSelectorBase({ const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const currentUserEmail = currentUserPersonalDetails.email ?? ''; - 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 without copying, + // keeping its reference stable for the memoized filtering below. + const transformedOptions: OptionData[] = (() => { + if (!optionsWithContacts) { + return []; + } + if (selectedAccountIDs.size === 0) { + return optionsWithContacts; + } + return memoizedBuildSelectedOptions(optionsWithContacts, selectedAccountIDs); + })(); const selectedOptions = (() => { const options: OptionData[] = []; @@ -214,7 +244,7 @@ function usePersonalDetailSearchSelectorBase({ const optionsList = !areOptionsInitialized ? defaultListOptions - : getValidOptions(transformedOptions, currentUserEmail, formatPhoneNumber, countryCode, loginList, { + : memoizedGetValidOptions(transformedOptions, currentUserEmail, formatPhoneNumber, countryCode, loginList, { excludeLogins, excludeFromSuggestionsOnly, includeSelectedOptions: shouldKeepSelectedInAvailableOptions, @@ -233,13 +263,19 @@ function usePersonalDetailSearchSelectorBase({ const currentUserSearchTerms = [translate('common.you'), translate('common.me')]; const filteredCurrentUserOption = (() => { const newOption = filterOption(currentOption, debouncedSearchTerm, currentUserSearchTerms); - if (newOption) { - return { - ...newOption, - isSelected: selectedAccountIDs.has(newOption.accountID.toString()), - }; + if (!newOption) { + return newOption; + } + const isSelected = selectedAccountIDs.has(newOption.accountID.toString()); + // The original reference is kept when the selection state already matches, so consumers building memoized + // lists on top of this option keep hitting their caches across remounts. + if ((newOption.isSelected ?? false) === isSelected) { + return newOption; } - return newOption; + return { + ...newOption, + isSelected, + }; })(); const existingAccountIDs = new Set(optionsWithContacts?.map((option) => option.accountID.toString())); diff --git a/src/libs/memoize/index.ts b/src/libs/memoize/index.ts index c29e4cc4bf8d..fe8e2d018d10 100644 --- a/src/libs/memoize/index.ts +++ b/src/libs/memoize/index.ts @@ -1,6 +1,8 @@ import type NonPartial from '@src/types/utils/NonPartial'; import type TakeFirst from '@src/types/utils/TupleOperations'; +import {shallowEqual} from 'fast-equals'; + import type {Callable, ClientOptions, Constructable, IsomorphicFn, IsomorphicParameters, IsomorphicReturnType, MemoizedFn, Stats} from './types'; import ArrayCache from './cache/ArrayCache'; @@ -112,4 +114,42 @@ function memoize => { + if (typeof value !== 'object' || value === null) { + return false; + } + const prototype = Object.getPrototypeOf(value) as unknown; + return prototype === Object.prototype || prototype === null; +}; + +/** + * Two arguments are equivalent when they are shallowly equal, or are plain objects with the same keys 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.at(index))); + export default memoize; +export {equivalentArgsComparator}; From 67ca78b3fb31ae2197c9c2aba1ef268e565ddf35 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 10 Aug 2026 15:19:09 +0200 Subject: [PATCH 07/30] fix: address review findings on the filters popover - Keyboard focus no longer goes through the hover intent delay. Moving focus is deliberate and never sweeps across rows, so its content is shown right away instead of replacing the pane a keyboard user has already moved into. - The memoized personal detail caches are released on sign-out, so option lists built for the previous account do not stay in memory. Needed a clear() on the memoize cache, which it did not expose. - formAtLastRest and contentVersions are pruned to the mounted filters instead of gaining an entry per visited filter. - equivalentArgsComparator uses lodash/isPlainObject instead of a local copy. --- .../SearchAdvancedFiltersPopup/index.tsx | 46 ++++++++++++---- src/hooks/usePersonalDetailOptions.ts | 5 ++ .../usePersonalDetailSearchSelector/base.ts | 8 +++ src/libs/memoize/cache/ArrayCache.ts | 4 ++ src/libs/memoize/cache/types.ts | 2 + src/libs/memoize/index.ts | 9 +--- .../Search/SearchAdvancedFiltersPopupTest.tsx | 54 +++++++++++++++---- 7 files changed, 102 insertions(+), 26 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 94ace870ff04..faa9a844e12a 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -4,7 +4,6 @@ import SearchAdvancedFiltersContent from '@components/Search/FilterComponents/Ad import useUpdateFilterQuery from '@components/Search/hooks/useUpdateFilterQuery'; import type {SearchQueryJSON} from '@components/Search/types'; -import useDebouncedState from '@hooks/useDebouncedState'; import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -17,7 +16,8 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; -import React, {useRef, useState} from 'react'; +import debounce from 'lodash/debounce'; +import React, {useEffect, useRef, useState} from 'react'; import {View} from 'react-native'; import AmountFilterContentPopupWrapper from './AmountFilterContentPopupWrapper'; @@ -48,9 +48,23 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps const StyleUtils = useStyleUtils(); const {windowHeight} = useWindowDimensions(); const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); - // The list highlights `selectedFilter` immediately; the content pane follows `restedFilter` once the cursor has stayed - // on a row for SEARCH_FILTER_HOVER_INTENT_DELAY, so sweeping across rows doesn't render a content pane per row. - const [selectedFilter, restedFilter, setSelectedFilter] = useDebouncedState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + // The list highlights `selectedFilter` immediately; the content pane follows `restedFilter`. + const [selectedFilter, setSelectedFilter] = useState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE); + const [restedFilter, setRestedFilter] = useState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE); + // Hovering only shows a row's content once the cursor has stayed on it for SEARCH_FILTER_HOVER_INTENT_DELAY, so + // sweeping across rows doesn't render a content pane per row. Moving focus is deliberate and never sweeps across + // rows, so it shows the content right away and keyboard users don't read a pane that is about to be replaced. + const [debouncedSetRestedFilter] = useState(() => debounce(setRestedFilter, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY)); + useEffect(() => () => debouncedSetRestedFilter.cancel(), [debouncedSetRestedFilter]); + const hoverFilter = (filterKey: SearchFilter['key']) => { + setSelectedFilter(filterKey); + debouncedSetRestedFilter(filterKey); + }; + const focusFilter = (filterKey: SearchFilter['key']) => { + debouncedSetRestedFilter.cancel(); + setSelectedFilter(filterKey); + setRestedFilter(filterKey); + }; // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filter contents stay mounted (hidden below), so revisits // toggle visibility instead of remounting. Kept in least-recently-rested order and adjusted during render so the new // pane shows in the same frame. @@ -63,11 +77,23 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }); const [contentVersions, setContentVersions] = useState>>({}); if (mountedFilters.at(-1) !== restedFilter) { + const nextMountedFilters = [...mountedFilters.filter((filterKey) => filterKey !== restedFilter), restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS); + const nextFormAtLastRest: Partial | undefined>> = {}; + const nextContentVersions: Partial> = {}; + // Both maps describe the mounted contents only, so a filter evicted from `mountedFilters` is dropped from them too. + for (const filterKey of nextMountedFilters) { + nextFormAtLastRest[filterKey] = filterKey === restedFilter ? searchAdvancedFiltersForm : formAtLastRest[filterKey]; + const version = contentVersions[filterKey]; + if (version !== undefined) { + nextContentVersions[filterKey] = version; + } + } if (mountedFilters.includes(restedFilter) && formAtLastRest[restedFilter] !== searchAdvancedFiltersForm) { - setContentVersions({...contentVersions, [restedFilter]: (contentVersions[restedFilter] ?? 0) + 1}); + nextContentVersions[restedFilter] = (contentVersions[restedFilter] ?? 0) + 1; } - setFormAtLastRest({...formAtLastRest, [restedFilter]: searchAdvancedFiltersForm}); - setMountedFilters([...mountedFilters.filter((filterKey) => filterKey !== restedFilter), restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS)); + setFormAtLastRest(nextFormAtLastRest); + setContentVersions(nextContentVersions); + setMountedFilters(nextMountedFilters); } const filterContentRef = useRef(null); @@ -81,8 +107,8 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps type={searchAdvancedFiltersForm?.type} policyID={getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, searchAdvancedFiltersForm)} selectedFilter={selectedFilter} - onHoverIn={setSelectedFilter} - onFocus={setSelectedFilter} + onHoverIn={hoverFilter} + onFocus={focusFilter} /> memoizedCreateOptionList.cache.clear()); + /** * Hook that provides options list for personal details. * diff --git a/src/hooks/usePersonalDetailSearchSelector/base.ts b/src/hooks/usePersonalDetailSearchSelector/base.ts index c3581c17d562..77f87375c52e 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -7,6 +7,7 @@ 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'; @@ -171,6 +172,13 @@ const memoizedBuildSelectedOptions = memoize(buildSelectedOptions, { monitoringName: 'usePersonalDetailSearchSelector.buildSelectedOptions', }); +// Both caches hold option lists built for the signed-in account, so release them on sign-out +// rather than holding them until later calls evict the entries. +registerSessionCleanupCallback(() => { + memoizedGetValidOptions.cache.clear(); + memoizedBuildSelectedOptions.cache.clear(); +}); + /** * Base hook that provides search functionality with selection logic for option lists. * This contains the core logic without platform-specific dependencies. 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..4b337f41939c 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, so values built for a signed-out user do not stay in memory */ + clear: () => void; snapshot: { keys: () => K[]; values: () => V[]; diff --git a/src/libs/memoize/index.ts b/src/libs/memoize/index.ts index fe8e2d018d10..7110b3586979 100644 --- a/src/libs/memoize/index.ts +++ b/src/libs/memoize/index.ts @@ -2,6 +2,7 @@ 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'; @@ -118,13 +119,7 @@ function memoize => { - if (typeof value !== 'object' || value === null) { - return false; - } - const prototype = Object.getPrototypeOf(value) as unknown; - return prototype === Object.prototype || prototype === null; -}; +const isPlainObject = (value: unknown): value is Record => lodashIsPlainObject(value); /** * Two arguments are equivalent when they are shallowly equal, or are plain objects with the same keys whose values are diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index fc70b3684831..355a7a83759a 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -30,19 +30,26 @@ jest.mock('@components/SafeTriangle', () => ({ default: ({children}: {children: React.ReactNode}) => {children}, })); -// Stand-in for the filter list: one pressable per filter that reports a hover on the row. +// Stand-in for the filter list: per filter, one pressable reporting a hover on the row and one reporting focus on it. jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () => ({ __esModule: true, - default: ({onHoverIn}: {onHoverIn: (filterKey: string) => void}) => ( + default: ({onHoverIn, onFocus}: {onHoverIn: (filterKey: string) => void; onFocus: (filterKey: string) => void}) => ( {mockHoverableFilterKeys.map((filterKey) => ( - onHoverIn(filterKey)} - /> + + onHoverIn(filterKey)} + /> + onFocus(filterKey)} + /> + ))} ), @@ -93,6 +100,11 @@ function hoverAndRest(filterKey: string) { }); } +/** Moves the keyboard focus onto a filter row. */ +function focus(filterKey: string) { + fireEvent.press(screen.getByTestId(`focus-${filterKey}`)); +} + beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); @@ -148,6 +160,30 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(2); }); + it('shows the content of a row focused with the keyboard without waiting for the hover intent delay', () => { + render(); + + focus(FILTER_KEYS.FROM); + + // No timer is advanced: moving focus is deliberate, so its content follows in the same frame. + expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); + expect(screen.getByTestId(`filter-content-${FILTER_KEYS.FROM}`)).toBeTruthy(); + }); + + it('does not let a pending hover replace the content of the row focused after it', () => { + render(); + + // The cursor passes over a row and the keyboard moves focus elsewhere before the delay elapses. + hover(FILTER_KEYS.TO); + focus(FILTER_KEYS.FROM); + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); + + expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); + expect(screen.getByTestId(`filter-content-${FILTER_KEYS.FROM}`)).toBeTruthy(); + }); + it('keeps only the most recently used contents mounted', () => { render(); From 84137982df0e4cf38f3d9e5742bc7c045fb6524d Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Wed, 19 Aug 2026 09:11:29 +0200 Subject: [PATCH 08/30] Shorten the filter hover intent delay to 30ms --- src/CONST/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 912966016725..bd5084f6bc61 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2107,7 +2107,7 @@ const CONST = { ACCESSIBILITY_ANNOUNCEMENT_DEBOUNCE_TIME: 1000, SUGGESTION_DEBOUNCE_TIME: 100, /** How long the cursor has to stay on an advanced filter row before its content is rendered */ - SEARCH_FILTER_HOVER_INTENT_DELAY: 80, + SEARCH_FILTER_HOVER_INTENT_DELAY: 30, RESIZE_DEBOUNCE_TIME: 100, UNREAD_UPDATE_DEBOUNCE_TIME: 300, USE_DEBOUNCED_STATE_DELAY: 300, From 20efc0d8bc748da0860481cd666ea05773f09b1d Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 25 Aug 2026 09:22:47 +0200 Subject: [PATCH 09/30] adjust PR to rorys POC --- .../SearchAdvancedFiltersPopup/index.tsx | 139 +++++++++++------- src/hooks/useDebounceNonReactive.ts | 33 ++--- .../Search/SearchAdvancedFiltersPopupTest.tsx | 4 +- 3 files changed, 100 insertions(+), 76 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index faa9a844e12a..cbd8f15d3fb0 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -4,6 +4,7 @@ import SearchAdvancedFiltersContent from '@components/Search/FilterComponents/Ad import useUpdateFilterQuery from '@components/Search/hooks/useUpdateFilterQuery'; import type {SearchQueryJSON} from '@components/Search/types'; +import useDebounceNonReactive from '@hooks/useDebounceNonReactive'; import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -16,8 +17,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; -import debounce from 'lodash/debounce'; -import React, {useEffect, useRef, useState} from 'react'; +import React, {Activity, useRef, useState} from 'react'; import {View} from 'react-native'; import AmountFilterContentPopupWrapper from './AmountFilterContentPopupWrapper'; @@ -30,6 +30,21 @@ type SearchAdvancedFiltersPopupProps = { queryJSON: SearchQueryJSON; }; +/** Which filter contents are mounted and what each of them was given, held together so one filter change moves all of it. */ +type MountedFilterState = { + /** The filter whose content is shown. Also the most recently used entry of `mountedFilters`. */ + activeFilter: SearchFilter['key']; + + /** The filters whose contents are mounted, in least-recently-used order. */ + mountedFilters: Array; + + /** Per mounted content, the filter values it was given when it last became active. */ + formAtLastRest: Partial | undefined>>; + + /** Per mounted content, how many times it has been remounted. Part of its key, so a bump replaces the instance. */ + contentVersions: Partial>; +}; + const filterComponents = { List: ListFilterContentPopupWrapper, Text: TextInputFilterContentPopupWrapper, @@ -48,53 +63,64 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps const StyleUtils = useStyleUtils(); const {windowHeight} = useWindowDimensions(); const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); - // The list highlights `selectedFilter` immediately; the content pane follows `restedFilter`. - const [selectedFilter, setSelectedFilter] = useState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE); - const [restedFilter, setRestedFilter] = useState(CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE); + const initialFilter = CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE; + // The list highlights `hoveredFilter` immediately; the content pane follows `activeFilter`. + const [hoveredFilter, setHoveredFilter] = useState(initialFilter); + const [mountedFilterState, setMountedFilterState] = useState(() => ({ + activeFilter: initialFilter, + mountedFilters: [initialFilter], + formAtLastRest: {[initialFilter]: searchAdvancedFiltersForm}, + contentVersions: {}, + })); + const {activeFilter, mountedFilters, formAtLastRest, contentVersions} = mountedFilterState; + + // The MAX_MOUNTED_FILTER_CONTENTS most recently active contents stay mounted, so revisiting a filter reveals its + // content instead of building it again. Activating a filter promotes it to most recently used and evicts whatever + // falls past the cap. + const activateFilter = (filterKey: SearchFilter['key']) => { + setMountedFilterState((currentState) => { + if (currentState.activeFilter === filterKey) { + return currentState; + } + + const nextMountedFilters = [...currentState.mountedFilters.filter((mountedFilter) => mountedFilter !== filterKey), filterKey].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS); + const nextFormAtLastRest: MountedFilterState['formAtLastRest'] = {}; + const nextContentVersions: MountedFilterState['contentVersions'] = {}; + // Both maps describe the mounted contents only, so a filter evicted from `mountedFilters` is dropped from them too. + for (const mountedFilter of nextMountedFilters) { + nextFormAtLastRest[mountedFilter] = mountedFilter === filterKey ? searchAdvancedFiltersForm : currentState.formAtLastRest[mountedFilter]; + const version = currentState.contentVersions[mountedFilter]; + if (version !== undefined) { + nextContentVersions[mountedFilter] = version; + } + } + // A kept content keeps the values it was last given and decides its selection pinning on mount, so one whose + // values went stale while it was hidden is remounted instead of revealed. + if (currentState.mountedFilters.includes(filterKey) && currentState.formAtLastRest[filterKey] !== searchAdvancedFiltersForm) { + nextContentVersions[filterKey] = (currentState.contentVersions[filterKey] ?? 0) + 1; + } + + return { + activeFilter: filterKey, + mountedFilters: nextMountedFilters, + formAtLastRest: nextFormAtLastRest, + contentVersions: nextContentVersions, + }; + }); + }; // Hovering only shows a row's content once the cursor has stayed on it for SEARCH_FILTER_HOVER_INTENT_DELAY, so // sweeping across rows doesn't render a content pane per row. Moving focus is deliberate and never sweeps across // rows, so it shows the content right away and keyboard users don't read a pane that is about to be replaced. - const [debouncedSetRestedFilter] = useState(() => debounce(setRestedFilter, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY)); - useEffect(() => () => debouncedSetRestedFilter.cancel(), [debouncedSetRestedFilter]); + const debouncedActivateFilter = useDebounceNonReactive(activateFilter, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); const hoverFilter = (filterKey: SearchFilter['key']) => { - setSelectedFilter(filterKey); - debouncedSetRestedFilter(filterKey); + setHoveredFilter(filterKey); + debouncedActivateFilter(filterKey); }; const focusFilter = (filterKey: SearchFilter['key']) => { - debouncedSetRestedFilter.cancel(); - setSelectedFilter(filterKey); - setRestedFilter(filterKey); + debouncedActivateFilter.cancel(); + setHoveredFilter(filterKey); + activateFilter(filterKey); }; - // The MAX_MOUNTED_FILTER_CONTENTS most recently rested filter contents stay mounted (hidden below), so revisits - // toggle visibility instead of remounting. Kept in least-recently-rested order and adjusted during render so the new - // pane shows in the same frame. - const [mountedFilters, setMountedFilters] = useState>([CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE]); - // A kept-mounted content shows the filter values from when it was last rested on (its hidden updates are deferred and - // its selection pinning is decided on mount), so returning to a filter after the form changed remounts it instead. - // Both maps are adjusted during render on the rested-filter edge, so the decision applies to the revealing frame. - const [formAtLastRest, setFormAtLastRest] = useState | undefined>>>({ - [CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE]: searchAdvancedFiltersForm, - }); - const [contentVersions, setContentVersions] = useState>>({}); - if (mountedFilters.at(-1) !== restedFilter) { - const nextMountedFilters = [...mountedFilters.filter((filterKey) => filterKey !== restedFilter), restedFilter].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS); - const nextFormAtLastRest: Partial | undefined>> = {}; - const nextContentVersions: Partial> = {}; - // Both maps describe the mounted contents only, so a filter evicted from `mountedFilters` is dropped from them too. - for (const filterKey of nextMountedFilters) { - nextFormAtLastRest[filterKey] = filterKey === restedFilter ? searchAdvancedFiltersForm : formAtLastRest[filterKey]; - const version = contentVersions[filterKey]; - if (version !== undefined) { - nextContentVersions[filterKey] = version; - } - } - if (mountedFilters.includes(restedFilter) && formAtLastRest[restedFilter] !== searchAdvancedFiltersForm) { - nextContentVersions[restedFilter] = (contentVersions[restedFilter] ?? 0) + 1; - } - setFormAtLastRest(nextFormAtLastRest); - setContentVersions(nextContentVersions); - setMountedFilters(nextMountedFilters); - } const filterContentRef = useRef(null); const {updateFilterQueryParams} = useUpdateFilterQuery(queryJSON); @@ -106,7 +132,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps style={[styles.typeFiltersPopupContainer]} type={searchAdvancedFiltersForm?.type} policyID={getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, searchAdvancedFiltersForm)} - selectedFilter={selectedFilter} + selectedFilter={hoveredFilter} onHoverIn={hoverFilter} onFocus={focusFilter} /> @@ -115,20 +141,23 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps style={[styles.filterContentContainer]} > {mountedFilters.map((filterKey) => ( - // Backgrounded contents keep their layout (hidden with web-only visibility:hidden) and get the - // form values frozen at their last visit, so moving between filters doesn't re-render them and - // showing one again is just a style flip. A content whose values went stale is remounted (above). - + + + + ))} diff --git a/src/hooks/useDebounceNonReactive.ts b/src/hooks/useDebounceNonReactive.ts index 25ec02d1e9bf..1ae1b16b6e22 100644 --- a/src/hooks/useDebounceNonReactive.ts +++ b/src/hooks/useDebounceNonReactive.ts @@ -2,32 +2,25 @@ import type {DebouncedFunc, DebounceSettings} from 'lodash'; import lodashDebounce from 'lodash/debounce'; -import {useEffect, useRef} from 'react'; +import {useEffect, useEffectEvent, useRef} from 'react'; // eslint-disable-next-line @typescript-eslint/no-explicit-any type GenericFunction = (...args: any[]) => void; +type DebouncedFunction = T & {cancel: () => void}; /** * 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 useDebounceNonReactiveImpl(func: GenericFunction, wait: number, options?: DebounceSettings): GenericFunction { - const funcRef = useRef(func); - const debouncedFnRef = useRef | undefined>(undefined); +function useDebounceNonReactiveImpl(func: GenericFunction, wait: number, options?: DebounceSettings): DebouncedFunction { const {leading, maxWait, trailing = true} = options ?? {}; + // Keeps one identity for the lifetime of the hook while always calling the latest `func`, so the debounced function + // below is only ever recreated when a debounce setting changes. + const callFunction = useEffectEvent((...args: unknown[]) => func(...args)); + const debouncedFnRef = useRef | undefined>(undefined); useEffect(() => { - funcRef.current = func; - }, [func]); - - useEffect(() => { - const debouncedFn = lodashDebounce( - (...args: unknown[]) => { - funcRef.current(...args); - }, - wait, - {leading, maxWait, trailing}, - ); + const debouncedFn = lodashDebounce(callFunction, wait, {leading, maxWait, trailing}); debouncedFnRef.current = debouncedFn; @@ -36,9 +29,11 @@ function useDebounceNonReactiveImpl(func: GenericFunction, wait: number, options }; }, [wait, leading, maxWait, trailing]); - return (...args: unknown[]) => { + const debouncedFunction = (...args: unknown[]) => { debouncedFnRef.current?.(...args); }; + debouncedFunction.cancel = () => debouncedFnRef.current?.cancel(); + return debouncedFunction; } /** @@ -54,8 +49,8 @@ function useDebounceNonReactiveImpl(func: GenericFunction, wait: number, options * @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.trailing Specify invoking on the trailing edge of the timeout. - * @returns Returns a function to call the debounced function. + * @returns Returns a function to call the debounced function, with a `cancel` method dropping a pending call. */ -export default function useDebounceNonReactive(func: T, wait: number, options?: DebounceSettings): T { - return useDebounceNonReactiveImpl(func, wait, options) as T; +export default function useDebounceNonReactive(func: T, wait: number, options?: DebounceSettings): DebouncedFunction { + return useDebounceNonReactiveImpl(func, wait, options) as DebouncedFunction; } diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 355a7a83759a..18534ea6d7ae 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -119,11 +119,11 @@ describe('SearchAdvancedFiltersPopup', () => { it('does not mount the content of filters the cursor only passes over', () => { render(); - // A fast sweep: every row is left again before the hover intent delay elapses. + // A fast sweep: every row is left again well before the hover intent delay elapses. for (const filterKey of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]) { hover(filterKey); act(() => { - jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY - 1); + jest.advanceTimersByTime(1); }); } act(() => { From 8b4421f5c5182969a84c554dabac610e1faf5ca6 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 25 Aug 2026 09:52:01 +0200 Subject: [PATCH 10/30] document the Activity effect lifecycle and the option list cache sizing --- .../FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx | 7 ++++--- src/hooks/usePersonalDetailOptions.ts | 2 ++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index cbd8f15d3fb0..1394159478ab 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -142,9 +142,10 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps > {mountedFilters.map((filterKey) => ( // A backgrounded content stays mounted with the filter values frozen at its last visit, so moving - // between filters neither re-renders it nor loses its state, and revealing it again is free. - // `Activity` also keeps it out of layout while hidden and lets React render it at a lower priority - // than the visible one when something both of them read changes underneath. + // between filters neither re-renders it nor loses its state. `Activity` takes it out of layout and + // unmounts its effects while it is hidden - so it holds no Onyx subscriptions of its own until it is + // shown again - and lets React render it at a lower priority than the visible one when a context + // both of them read changes underneath. Date: Tue, 25 Aug 2026 12:57:03 +0200 Subject: [PATCH 11/30] keep the shared debounce hook untouched and drop stale hover activations instead --- .../SearchAdvancedFiltersPopup/index.tsx | 14 ++++++-- src/hooks/useDebounceNonReactive.ts | 33 +++++++++++-------- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 1394159478ab..dd7dd29ecbf3 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -108,16 +108,24 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }; }); }; + // The debounce below always calls the latest version of this, so a hover whose delay elapsed after the cursor or the + // focus already moved on is dropped instead of replacing the content of the row the user is on now. + const activateHoveredFilter = (filterKey: SearchFilter['key']) => { + if (filterKey !== hoveredFilter) { + return; + } + + activateFilter(filterKey); + }; // Hovering only shows a row's content once the cursor has stayed on it for SEARCH_FILTER_HOVER_INTENT_DELAY, so // sweeping across rows doesn't render a content pane per row. Moving focus is deliberate and never sweeps across // rows, so it shows the content right away and keyboard users don't read a pane that is about to be replaced. - const debouncedActivateFilter = useDebounceNonReactive(activateFilter, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + const debouncedActivateHoveredFilter = useDebounceNonReactive(activateHoveredFilter, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); const hoverFilter = (filterKey: SearchFilter['key']) => { setHoveredFilter(filterKey); - debouncedActivateFilter(filterKey); + debouncedActivateHoveredFilter(filterKey); }; const focusFilter = (filterKey: SearchFilter['key']) => { - debouncedActivateFilter.cancel(); setHoveredFilter(filterKey); activateFilter(filterKey); }; diff --git a/src/hooks/useDebounceNonReactive.ts b/src/hooks/useDebounceNonReactive.ts index 1ae1b16b6e22..25ec02d1e9bf 100644 --- a/src/hooks/useDebounceNonReactive.ts +++ b/src/hooks/useDebounceNonReactive.ts @@ -2,25 +2,32 @@ import type {DebouncedFunc, DebounceSettings} from 'lodash'; import lodashDebounce from 'lodash/debounce'; -import {useEffect, useEffectEvent, useRef} from 'react'; +import {useEffect, useRef} from 'react'; // eslint-disable-next-line @typescript-eslint/no-explicit-any type GenericFunction = (...args: any[]) => void; -type DebouncedFunction = T & {cancel: () => void}; /** * 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 useDebounceNonReactiveImpl(func: GenericFunction, wait: number, options?: DebounceSettings): DebouncedFunction { - const {leading, maxWait, trailing = true} = options ?? {}; - // Keeps one identity for the lifetime of the hook while always calling the latest `func`, so the debounced function - // below is only ever recreated when a debounce setting changes. - const callFunction = useEffectEvent((...args: unknown[]) => func(...args)); +function useDebounceNonReactiveImpl(func: GenericFunction, wait: number, options?: DebounceSettings): GenericFunction { + const funcRef = useRef(func); const debouncedFnRef = useRef | undefined>(undefined); + const {leading, maxWait, trailing = true} = options ?? {}; + + useEffect(() => { + funcRef.current = func; + }, [func]); useEffect(() => { - const debouncedFn = lodashDebounce(callFunction, wait, {leading, maxWait, trailing}); + const debouncedFn = lodashDebounce( + (...args: unknown[]) => { + funcRef.current(...args); + }, + wait, + {leading, maxWait, trailing}, + ); debouncedFnRef.current = debouncedFn; @@ -29,11 +36,9 @@ function useDebounceNonReactiveImpl(func: GenericFunction, wait: number, options }; }, [wait, leading, maxWait, trailing]); - const debouncedFunction = (...args: unknown[]) => { + return (...args: unknown[]) => { debouncedFnRef.current?.(...args); }; - debouncedFunction.cancel = () => debouncedFnRef.current?.cancel(); - return debouncedFunction; } /** @@ -49,8 +54,8 @@ function useDebounceNonReactiveImpl(func: GenericFunction, wait: number, options * @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.trailing Specify invoking on the trailing edge of the timeout. - * @returns Returns a function to call the debounced function, with a `cancel` method dropping a pending call. + * @returns Returns a function to call the debounced function. */ -export default function useDebounceNonReactive(func: T, wait: number, options?: DebounceSettings): DebouncedFunction { - return useDebounceNonReactiveImpl(func, wait, options) as DebouncedFunction; +export default function useDebounceNonReactive(func: T, wait: number, options?: DebounceSettings): T { + return useDebounceNonReactiveImpl(func, wait, options) as T; } From bc3e89eeba270d4903f9520436c711f29df1240a Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Wed, 26 Aug 2026 14:17:10 +0200 Subject: [PATCH 12/30] fix the filter pane bugs from review and bound the option list caches - a list revealed from a hidden Activity scrolls back to the offset it reports, so its window matches the scroll position instead of showing an empty area - a kept pane is remounted only when the values it reads changed, so a change to another filter no longer decides whether its own state survives - each mounted pane renders in its own component, so the compiler memoizes it per pane and React.memo is no longer needed - the option list caches are sized next to the hook that owns them and released when Search moves to another tab --- .../SearchAdvancedFiltersPopup/index.tsx | 52 +++++--- .../SelectionList/BaseSelectionList.tsx | 22 ++++ src/hooks/usePersonalDetailOptions.ts | 12 +- .../usePersonalDetailSearchSelector/base.ts | 29 +++-- src/hooks/useReleaseOptionListCaches.ts | 63 ++++++++++ src/libs/SearchUIUtils.ts | 51 ++++++++ src/pages/Search/SearchPage.tsx | 2 + tests/unit/BaseSelectionListTest.tsx | 42 ++++++- .../Search/SearchAdvancedFiltersPopupTest.tsx | 29 ++++- tests/unit/useReleaseOptionListCachesTest.ts | 114 ++++++++++++++++++ 10 files changed, 386 insertions(+), 30 deletions(-) create mode 100644 src/hooks/useReleaseOptionListCaches.ts create mode 100644 tests/unit/useReleaseOptionListCachesTest.ts diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index dd7dd29ecbf3..6b50931be44a 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -10,7 +10,7 @@ import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; -import {getFilterNegatableValue} from '@libs/SearchUIUtils'; +import {getFilterNegatableValue, hasFilterContentValuesChanged} from '@libs/SearchUIUtils'; import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; @@ -53,10 +53,34 @@ const filterComponents = { ReportField: ReportFieldFilterContentPopupWrapper, } as const; +type MountedFilterContentProps = { + /** The filter whose content this is. */ + filterKey: SearchFilter['key']; + + /** The filter values the content reads. */ + values: Partial | undefined; + + /** Called with the values a change in the content produces. */ + onChange: (values: Partial) => void; +}; + // React Compiler caches the whole `mountedFilters.map()` result in a single slot, so changing the shown filter rebuilds -// every element of it - there is no per-element cache it could bail out on. Comparing props here is what keeps the -// kept-mounted contents, whose own props are unchanged, from re-rendering along with the one being shown. -const MemoizedFilterContent = React.memo(SearchAdvancedFiltersContent); +// every element of it. Each content sits in its own component, so the rebuilt element lands on this component's cache +// and one whose props are unchanged returns the element it returned before, which ends the render there. +function MountedFilterContent({filterKey, values, onChange}: MountedFilterContentProps) { + const styles = useThemeStyles(); + + return ( + + + + ); +} function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps) { const styles = useThemeStyles(); @@ -64,7 +88,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps const {windowHeight} = useWindowDimensions(); const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); const initialFilter = CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE; - // The list highlights `hoveredFilter` immediately; the content pane follows `activeFilter`. + // The list highlights `hoveredFilter` immediately. The content pane follows `activeFilter`. const [hoveredFilter, setHoveredFilter] = useState(initialFilter); const [mountedFilterState, setMountedFilterState] = useState(() => ({ activeFilter: initialFilter, @@ -95,8 +119,9 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps } } // A kept content keeps the values it was last given and decides its selection pinning on mount, so one whose - // values went stale while it was hidden is remounted instead of revealed. - if (currentState.mountedFilters.includes(filterKey) && currentState.formAtLastRest[filterKey] !== searchAdvancedFiltersForm) { + // values went stale while it was hidden is remounted instead of revealed. Only the values that content reads + // count as stale - a change to a filter it doesn't read leaves its own state, like a typed search term, alone. + if (currentState.mountedFilters.includes(filterKey) && hasFilterContentValuesChanged(filterKey, currentState.formAtLastRest[filterKey], searchAdvancedFiltersForm)) { nextContentVersions[filterKey] = (currentState.contentVersions[filterKey] ?? 0) + 1; } @@ -158,14 +183,11 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps key={`${filterKey}-${contentVersions[filterKey] ?? 0}`} mode={filterKey === activeFilter ? 'visible' : 'hidden'} > - - - + ))} diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index 5386cb09849a..fcaab1402cd6 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -332,6 +332,28 @@ function BaseSelectionListImpl({ const scrollTimeoutRef = useRef(null); + // A hidden `` subtree keeps its state but unmounts its effects, so this runs again when the list is + // revealed without it being mounted anew. The list has no layout while it is hidden and its container loses the + // scroll position, which leaves the rendered window describing the offset from before - the visible area is blank + // until something scrolls the list. Scrolling back to the offset the list still reports puts the two in sync again. + const hasMountedRef = useRef(false); + useEffect(() => { + if (!hasMountedRef.current) { + hasMountedRef.current = true; + return; + } + + const animationFrameID = requestAnimationFrame(() => { + const listOffset = listRef.current?.getAbsoluteLastScrollOffset(); + if (listOffset === undefined) { + return; + } + listRef.current?.scrollToOffset({offset: listOffset, animated: false}); + }); + + return () => cancelAnimationFrame(animationFrameID); + }, []); + useEffect(() => { return () => { if (keyboardListenerRef.current) { diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 4180e73dac3f..4093e61c9f05 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -116,9 +116,14 @@ const memoizedCreateOptionList = memoize(createOptionList, { monitoringName: 'usePersonalDetailOptions.createOptionList', }); -// The cached options describe the signed-in account's contacts, so release them on sign-out -// rather than holding them until the next call evicts the entry. -registerSessionCleanupCallback(() => memoizedCreateOptionList.cache.clear()); +/** Releases the cached options. The next consumer builds them again, so callers pay that price for the memory back. */ +function clearPersonalDetailOptionsCache() { + memoizedCreateOptionList.cache.clear(); +} + +// The cached options describe the signed-in account's contacts. Search releases them once it is done with them (see +// `useReleaseOptionListCaches`), and sign-out covers whatever is still held at that point. +registerSessionCleanupCallback(clearPersonalDetailOptionsCache); /** * Hook that provides options list for personal details. @@ -177,3 +182,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 27b8caa0b4ee..51d6f8fc0bb9 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -152,12 +152,23 @@ const defaultListOptions = { selectedOptions: [], }; +/** + * How many option lists the caches below hold. Consumers of this hook mount one selector at a time, except the Search + * filters popover, which keeps the contents of its people filters alive next to each other - three entries cover the + * lists it renders side by side. Entries rotate below that number as well, because what a consumer searches for is part + * of the key, so typing in one selector replaces the entries of the others. + * + * Fewer entries cost more than the memory they save: the result of `buildSelectedOptions` is an argument of + * `getValidOptions` and is compared by identity, so an eviction in the first cache produces a new list and makes the + * second one miss as well. + */ +const MAX_CACHED_OPTION_LISTS = 3; + /** * Filtering the whole option list is a pure derivation of its inputs, so remounting consumers reuse the previous result. - * The cache is sized to the number of mounted filter contents so lists rendered next to each other don't evict each other. */ const memoizedGetValidOptions = memoize(getValidOptions, { - maxSize: CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS, + maxSize: MAX_CACHED_OPTION_LISTS, equality: equivalentArgsComparator, monitoringName: 'usePersonalDetailSearchSelector.getValidOptions', }); @@ -170,17 +181,20 @@ const buildSelectedOptions = (options: OptionData[], selectedAccountIDs: Set { +/** Releases the cached lists. The next consumer derives them again, so callers pay that price for the memory back. */ +function clearPersonalDetailSearchSelectorCaches() { memoizedGetValidOptions.cache.clear(); memoizedBuildSelectedOptions.cache.clear(); -}); +} + +// Both caches hold option lists built for the signed-in account. Search releases them once it is done with them (see +// `useReleaseOptionListCaches`), and sign-out covers whatever is still held at that point. +registerSessionCleanupCallback(clearPersonalDetailSearchSelectorCaches); /** * Base hook that provides search functionality with selection logic for option lists. @@ -380,4 +394,5 @@ function usePersonalDetailSearchSelectorBase({ } export default usePersonalDetailSearchSelectorBase; +export {clearPersonalDetailSearchSelectorCaches}; export type {ContactState, UseSearchSelectorConfig, UseSearchSelectorReturn}; diff --git a/src/hooks/useReleaseOptionListCaches.ts b/src/hooks/useReleaseOptionListCaches.ts new file mode 100644 index 000000000000..3ec82d7595a8 --- /dev/null +++ b/src/hooks/useReleaseOptionListCaches.ts @@ -0,0 +1,63 @@ +import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; +import subscribeToRootNavigation from '@libs/Navigation/helpers/subscribeToRootNavigation'; + +import {useEffect, useRef} from 'react'; + +import {clearPersonalDetailOptionsCache} from './usePersonalDetailOptions'; +import {clearPersonalDetailSearchSelectorCaches} from './usePersonalDetailSearchSelector/base'; + +function releaseOptionListCaches() { + clearPersonalDetailOptionsCache(); + clearPersonalDetailSearchSelectorCaches(); +} + +/** + * Releases the option lists cached for the people selectors once Search is done with them: when another tab takes over + * from Search, and when another of its own tabs is selected. 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. + * + * @param tabKey The selected tab of Search, or `undefined` while the query shown matches none of them. + */ +function useReleaseOptionListCaches(tabKey: string | undefined) { + const previousTabKeyRef = useRef(undefined); + + useEffect(() => { + // A query narrowed with filters belongs to no tab, and narrowing one is not leaving it, so the lists are + // released only when the selection moves between tabs. + if (!tabKey) { + return; + } + + const previousTabKey = previousTabKeyRef.current; + previousTabKeyRef.current = tabKey; + + if (!previousTabKey || previousTabKey === tabKey) { + return; + } + + releaseOptionListCaches(); + }, [tabKey]); + + 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(); + if (isSearchTopmostRoute === wasSearchTopmostRoute) { + return; + } + + wasSearchTopmostRoute = isSearchTopmostRoute; + + if (isSearchTopmostRoute) { + return; + } + + releaseOptionListCaches(); + }); + }, []); +} + +export default useReleaseOptionListCaches; diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index bfe586a8ebbd..4c2809b918be 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -98,6 +98,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'; @@ -5871,6 +5872,55 @@ function getFilterNegatableValue | undefined, + values: Partial | undefined, +): boolean { + if (previousValues === values) { + return false; + } + + // The report field content is handed the whole form, so anything in it counts. + if (baseFilterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.REPORT_FIELD) { + return true; + } + + if (isAmountFilterKey(baseFilterKey)) { + return Object.values(CONST.SEARCH.AMOUNT_MODIFIERS).some((modifier) => previousValues?.[`${baseFilterKey}${modifier}`] !== values?.[`${baseFilterKey}${modifier}`]); + } + + if (isDateFilterKey(baseFilterKey)) { + return ( + previousValues?.feed !== values?.feed || + Object.values(CONST.SEARCH.DATE_MODIFIERS).some((modifier) => previousValues?.[`${baseFilterKey}${modifier}`] !== values?.[`${baseFilterKey}${modifier}`]) + ); + } + + if (isTextFilterKey(baseFilterKey)) { + return hasNegatableValueChanged(getFilterNegatableValue(baseFilterKey, previousValues), getFilterNegatableValue(baseFilterKey, values)); + } + + // A list content also reads the search type and the workspace filter, which decide the options it offers. + return ( + hasNegatableValueChanged(getFilterNegatableValue(baseFilterKey, previousValues), getFilterNegatableValue(baseFilterKey, values)) || + previousValues?.type !== values?.type || + hasNegatableValueChanged( + getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, previousValues), + getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, values), + ) + ); +} + function getLabelValue(key: SearchAdvancedFiltersKey, labelKey: TranslationPaths | undefined, translate: LocalizedTranslate) { if (!labelKey) { return undefined; @@ -7030,6 +7080,7 @@ export { getDateDisplayValue, getDisplayValue, getFilterNegatableValue, + hasFilterContentValuesChanged, shouldShowFilter, mapFiltersFormToLabelValueList, isTextFilterKey, diff --git a/src/pages/Search/SearchPage.tsx b/src/pages/Search/SearchPage.tsx index 77a6575c9e0e..555a48610e82 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(currentSearchKey); // 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/tests/unit/BaseSelectionListTest.tsx b/tests/unit/BaseSelectionListTest.tsx index 49f857d96047..eb755dca8024 100644 --- a/tests/unit/BaseSelectionListTest.tsx +++ b/tests/unit/BaseSelectionListTest.tsx @@ -1,4 +1,4 @@ -import {fireEvent, render, screen} from '@testing-library/react-native'; +import {fireEvent, render, screen, waitFor} from '@testing-library/react-native'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; import BaseSelectionList from '@components/SelectionList/BaseSelectionList'; @@ -13,10 +13,12 @@ import CONST from '@src/CONST'; import type ReactNative from 'react-native'; import * as NativeNavigation from '@react-navigation/native'; -import React, {useState} from 'react'; +import React, {Activity, useState} from 'react'; // Captures scrollToIndex calls so tests can assert on scroll behaviour const mockScrollToIndex = jest.fn(); +const mockScrollToOffset = jest.fn(); +const mockGetAbsoluteLastScrollOffset = jest.fn(() => 0); // Mock FlashList jest.mock('@shopify/flash-list', () => { @@ -24,7 +26,7 @@ jest.mock('@shopify/flash-list', () => { const RN = jest.requireActual('react-native'); const FlashList = ReactLocal.forwardRef< - {scrollToIndex: (params: {index: number}) => void}, + {scrollToIndex: (params: {index: number}) => void; scrollToOffset: (params: {offset: number; animated: boolean}) => void; getAbsoluteLastScrollOffset: () => number}, Omit, 'children'> & { data?: unknown[]; renderItem?: (info: {item: unknown; index: number; target: string}) => React.ReactNode; @@ -56,7 +58,11 @@ jest.mock('@shopify/flash-list', () => { }, ref, ) => { - ReactLocal.useImperativeHandle(ref, () => ({scrollToIndex: mockScrollToIndex})); + ReactLocal.useImperativeHandle(ref, () => ({ + scrollToIndex: mockScrollToIndex, + scrollToOffset: mockScrollToOffset, + getAbsoluteLastScrollOffset: mockGetAbsoluteLastScrollOffset, + })); return ReactLocal.createElement( RN.ScrollView, @@ -130,6 +136,8 @@ describe('BaseSelectionList', () => { beforeEach(() => { onSelectRowMock.mockClear(); mockScrollToIndex.mockClear(); + mockScrollToOffset.mockClear(); + mockGetAbsoluteLastScrollOffset.mockReturnValue(0); mockIsFocusRestoreInProgress.mockReturnValue(false); }); @@ -157,6 +165,32 @@ describe('BaseSelectionList', () => { ); } + function ActivitySelectionListRenderer({mode}: {mode: 'visible' | 'hidden'}) { + return ( + + + + ); + } + + it('scrolls back to the offset it reports when it is revealed from a hidden Activity', async () => { + jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); + mockGetAbsoluteLastScrollOffset.mockReturnValue(1200); + + const {rerender} = render(); + + // A list that was just mounted starts where it starts, so nothing scrolls it. + expect(mockScrollToOffset).not.toHaveBeenCalled(); + + // Hiding the list unmounts its effects and drops its layout, and revealing it runs them again. + rerender(); + rerender(); + + await waitFor(() => { + expect(mockScrollToOffset).toHaveBeenCalledWith({offset: 1200, animated: false}); + }); + }); + it('should not trigger item press if screen is not focused', () => { jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(false); render(); diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 18534ea6d7ae..3ba8e29d055b 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -151,7 +151,7 @@ describe('SearchAdvancedFiltersPopup', () => { hoverAndRest(FILTER_KEYS.FROM); - // The form changes (e.g. a value was picked) and the cursor moves on to another filter. + // The form changes in a way this content reads (the search type decides its options) and the cursor moves on. mockFiltersForm = {type: CONST.SEARCH.DATA_TYPES.EXPENSE}; hoverAndRest(FILTER_KEYS.TO); @@ -160,6 +160,33 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(2); }); + it('remounts a kept content when its own value changed while it was away', () => { + render(); + + hoverAndRest(FILTER_KEYS.FROM); + + // Someone was picked in this very filter, so its content has to decide its selection pinning again. + mockFiltersForm = {from: ['1']}; + hoverAndRest(FILTER_KEYS.TO); + + hoverAndRest(FILTER_KEYS.FROM); + expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(2); + }); + + it('keeps a kept content when only the value of a filter it does not read changed', () => { + render(); + + 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 - a typed search term - survives. + hoverAndRest(FILTER_KEYS.FROM); + expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); + }); + it('shows the content of a row focused with the keyboard without waiting for the hover intent delay', () => { render(); diff --git a/tests/unit/useReleaseOptionListCachesTest.ts b/tests/unit/useReleaseOptionListCachesTest.ts new file mode 100644 index 000000000000..4d3103cb8884 --- /dev/null +++ b/tests/unit/useReleaseOptionListCachesTest.ts @@ -0,0 +1,114 @@ +import {renderHook} from '@testing-library/react-native'; + +import useReleaseOptionListCaches from '@hooks/useReleaseOptionListCaches'; + +/** Called once per release of the cached option lists, whichever cache it belongs to. */ +const mockRelease = 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, + default: jest.fn(), + clearPersonalDetailOptionsCache: () => { + mockRelease(); + }, +})); + +jest.mock('@hooks/usePersonalDetailSearchSelector/base', () => ({ + __esModule: true, + default: jest.fn(), + clearPersonalDetailSearchSelectorCaches: () => { + mockRelease(); + }, +})); + +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(initialTabKey: string | undefined) { + return renderHook((tabKey) => useReleaseOptionListCaches(tabKey), {initialProps: initialTabKey}); +} + +beforeEach(() => { + jest.clearAllMocks(); + mockIsSearchTopmostRoute = true; + mockNavigationListener = undefined; +}); + +describe('useReleaseOptionListCaches', () => { + it('keeps the cached lists while the same tab stays selected', () => { + const {rerender} = renderReleaseHook('expenses'); + + rerender('expenses'); + + expect(mockRelease).not.toHaveBeenCalled(); + }); + + it('releases the cached lists when another tab of Search is selected', () => { + const {rerender} = renderReleaseHook('expenses'); + + rerender('reports'); + + expect(mockRelease).toHaveBeenCalled(); + }); + + it('keeps the cached lists when the query shown stops matching a tab', () => { + const {rerender} = renderReleaseHook('expenses'); + + // A filter was applied, so the query belongs to no tab - the user is still on the one they were on. + rerender(undefined); + + expect(mockRelease).not.toHaveBeenCalled(); + }); + + it('releases the cached lists when another tab takes over from Search', () => { + renderReleaseHook('expenses'); + + leaveSearch(); + + expect(mockRelease).toHaveBeenCalled(); + }); + + it('keeps the cached lists while Search is still the tab on top', () => { + renderReleaseHook('expenses'); + + navigateWithinSearch(); + + expect(mockRelease).not.toHaveBeenCalled(); + }); + + it('stops listening to navigation once it is no longer used', () => { + const {unmount} = renderReleaseHook('expenses'); + + unmount(); + + expect(mockUnsubscribe).toHaveBeenCalled(); + }); +}); From 11c0ee513c88532f713191784cce36b5e2816c51 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Thu, 27 Aug 2026 12:48:02 +0200 Subject: [PATCH 13/30] read the offset of a revealed list before the frame that restores it The scroll a container reports on being revealed reaches the list before the animation frame below it, which left the list reporting the top it had just been reset to and turned the restore into a no-op. Reading the offset in the effect takes it while it still describes where the list was, and a list sitting at the top is left alone, since its window already describes that offset. --- .../SelectionList/BaseSelectionList.tsx | 13 +++++++++---- tests/unit/BaseSelectionListTest.tsx | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index fcaab1402cd6..ee1abcc43df5 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -343,11 +343,16 @@ function BaseSelectionListImpl({ return; } + // The offset is read here rather than in the frame below, because the scroll the container reports on being + // revealed reaches the list first and would leave it reporting the top it was reset to. + const listOffset = listRef.current?.getAbsoluteLastScrollOffset(); + // A list sitting at the top has nothing to restore: its window already describes that offset. Skipping the + // scroll keeps revealing such a list - every list nobody scrolled - as cheap as it was before. + if (!listOffset) { + return; + } + const animationFrameID = requestAnimationFrame(() => { - const listOffset = listRef.current?.getAbsoluteLastScrollOffset(); - if (listOffset === undefined) { - return; - } listRef.current?.scrollToOffset({offset: listOffset, animated: false}); }); diff --git a/tests/unit/BaseSelectionListTest.tsx b/tests/unit/BaseSelectionListTest.tsx index eb755dca8024..cbcd3d32d6b4 100644 --- a/tests/unit/BaseSelectionListTest.tsx +++ b/tests/unit/BaseSelectionListTest.tsx @@ -191,6 +191,21 @@ describe('BaseSelectionList', () => { }); }); + it('does not scroll a list revealed at the top, which has no offset to restore', async () => { + jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); + mockGetAbsoluteLastScrollOffset.mockReturnValue(0); + + const {rerender} = render(); + + rerender(); + rerender(); + + await waitFor(() => { + expect(screen.getByText('Item 1')).toBeOnTheScreen(); + }); + expect(mockScrollToOffset).not.toHaveBeenCalled(); + }); + it('should not trigger item press if screen is not focused', () => { jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(false); render(); From 2f9349b085b9644f68cfe151c92bb111ca3ca9a5 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Thu, 27 Aug 2026 12:48:11 +0200 Subject: [PATCH 14/30] tidy the filters popup declarations and the negatable value comparison - the filter the popover opens on is a module constant, so the state initialisers read the same name the rest of the file does - the ref and the query updater sit with the other declarations, and the handlers are separated, so each one reads with the comment that explains it - the pair the two negatable-value helpers pass around has a name instead of being spelled out in the signature - the argument comparator indexes the array directly, which is the whole of its work --- .../SearchAdvancedFiltersPopup/index.tsx | 21 ++++++++++++------- src/libs/SearchUIUtils.ts | 8 ++++++- src/libs/memoize/index.ts | 2 +- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 6b50931be44a..701e030b6780 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -53,6 +53,9 @@ const filterComponents = { ReportField: ReportFieldFilterContentPopupWrapper, } as const; +/** The filter the popover opens on. */ +const INITIAL_FILTER = CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE; + type MountedFilterContentProps = { /** The filter whose content this is. */ filterKey: SearchFilter['key']; @@ -87,16 +90,17 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps const StyleUtils = useStyleUtils(); const {windowHeight} = useWindowDimensions(); const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); - const initialFilter = CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE; + const filterContentRef = useRef(null); // The list highlights `hoveredFilter` immediately. The content pane follows `activeFilter`. - const [hoveredFilter, setHoveredFilter] = useState(initialFilter); + const [hoveredFilter, setHoveredFilter] = useState(INITIAL_FILTER); const [mountedFilterState, setMountedFilterState] = useState(() => ({ - activeFilter: initialFilter, - mountedFilters: [initialFilter], - formAtLastRest: {[initialFilter]: searchAdvancedFiltersForm}, + activeFilter: INITIAL_FILTER, + mountedFilters: [INITIAL_FILTER], + formAtLastRest: {[INITIAL_FILTER]: searchAdvancedFiltersForm}, contentVersions: {}, })); const {activeFilter, mountedFilters, formAtLastRest, contentVersions} = mountedFilterState; + const {updateFilterQueryParams} = useUpdateFilterQuery(queryJSON); // The MAX_MOUNTED_FILTER_CONTENTS most recently active contents stay mounted, so revisiting a filter reveals its // content instead of building it again. Activating a filter promotes it to most recently used and evicts whatever @@ -133,6 +137,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }; }); }; + // The debounce below always calls the latest version of this, so a hover whose delay elapsed after the cursor or the // focus already moved on is dropped instead of replacing the content of the row the user is on now. const activateHoveredFilter = (filterKey: SearchFilter['key']) => { @@ -142,21 +147,21 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps activateFilter(filterKey); }; + // Hovering only shows a row's content once the cursor has stayed on it for SEARCH_FILTER_HOVER_INTENT_DELAY, so // sweeping across rows doesn't render a content pane per row. Moving focus is deliberate and never sweeps across // rows, so it shows the content right away and keyboard users don't read a pane that is about to be replaced. const debouncedActivateHoveredFilter = useDebounceNonReactive(activateHoveredFilter, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + const hoverFilter = (filterKey: SearchFilter['key']) => { setHoveredFilter(filterKey); debouncedActivateHoveredFilter(filterKey); }; + const focusFilter = (filterKey: SearchFilter['key']) => { setHoveredFilter(filterKey); activateFilter(filterKey); }; - const filterContentRef = useRef(null); - - const {updateFilterQueryParams} = useUpdateFilterQuery(queryJSON); return ( diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index 4c2809b918be..4e6a736972fe 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -5860,6 +5860,12 @@ function getDisplayValue( return Array.isArray(formValue) ? formValue.join(', ') : formValue; } +/** A filter value together with whether the form holds it under the negated key. */ +type FilterNegatableValue = { + isNegated: boolean; + value: unknown; +}; + function getFilterNegatableValue( baseFilterKey: K, values: (Partial & Partial>) | undefined, @@ -5873,7 +5879,7 @@ function getFilterNegatableValue(previousArgs: Key, nextArgs: Key) => - previousArgs.length === nextArgs.length && previousArgs.every((argument, index) => areArgumentsEquivalent(argument, nextArgs.at(index))); + previousArgs.length === nextArgs.length && previousArgs.every((argument, index) => areArgumentsEquivalent(argument, nextArgs[index])); export default memoize; export {equivalentArgsComparator}; From 84dd129810d4af53203af44acffac22a60d2d57a Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 28 Aug 2026 12:27:07 +0200 Subject: [PATCH 15/30] show a filter's content once the cursor comes to rest on its row Waiting for the cursor to spend a fixed time on a row cannot tell a deliberate hover from a slow pass over it, so every hover paid the delay while a slow pass still built a pane per row. Waiting for the cursor to stop separates the two: a pass keeps restarting the wait however slowly it moves, and a cursor that arrived at its target stops and lets it through. - distance is measured from where the cursor last counted as moving, so a hand that shakes stays within the rest radius and does not hold the content back - a cursor that never comes to rest is given an allowance instead, counted from entering the row so that moving on to the next one restarts it and a pass across the list never reaches it - `useDebounceNonReactive` cannot express either wait: it always hands lodash a `maxWait` key, and lodash reads the key rather than its value, so every wait it creates is capped and fires mid-movement Measured on a single pass down the list of an account with 100k contacts, two rounds, four speeds: two panes built and no blocked JS at every speed, against five to nine panes and 154-398 ms before. --- src/CONST/index.ts | 13 +- .../AdvancedFilters/FilterList.tsx | 6 +- .../SearchAdvancedFiltersPopup/index.tsx | 69 +++++++-- .../Search/SearchAdvancedFiltersPopupTest.tsx | 140 +++++++++++++++--- 4 files changed, 192 insertions(+), 36 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 2a6e80eec001..985b492dd354 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2137,8 +2137,16 @@ const CONST = { SEARCH_OPTION_LIST_DEBOUNCE_TIME: 300, ACCESSIBILITY_ANNOUNCEMENT_DEBOUNCE_TIME: 1000, SUGGESTION_DEBOUNCE_TIME: 100, - /** How long the cursor has to stay on an advanced filter row before its content is rendered */ + /** How long the cursor has to rest on an advanced filter row before its content is rendered */ SEARCH_FILTER_HOVER_INTENT_DELAY: 30, + + /** + * How long after entering an advanced filter row its content is rendered even if the cursor never came to rest. + * Measured from entering the row, so moving on to the next one restarts it and a pass across the list, however + * slow, never reaches it - the longest a row was held during a measured pass was 257 ms. + */ + SEARCH_FILTER_HOVER_INTENT_MAX_DELAY: 400, + RESIZE_DEBOUNCE_TIME: 100, UNREAD_UPDATE_DEBOUNCE_TIME: 300, USE_DEBOUNCED_STATE_DELAY: 300, @@ -6868,6 +6876,9 @@ const CONST = { ME: 'me', /** How many advanced filter contents the filters popover keeps mounted */ MAX_MOUNTED_FILTER_CONTENTS: 3, + + /** How far the cursor may wander from where it settled 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 ad89d06543a5..0a80b0fc6ae2 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx @@ -38,6 +38,9 @@ type FilterListProps = FilterItemCallbacks & { selectedFilter?: SearchFilter['key']; style?: StyleProp; contentContainerStyle?: StyleProp; + + /** Called as the cursor travels over the list. Web only - it reports the movement between rows that `onHoverIn` cannot. */ + onPointerMove?: (event: {clientX: number; clientY: number}) => void; }; type FilterItemProps = FilterItemCallbacks & { @@ -102,7 +105,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}: FilterListProps) { const styles = useThemeStyles(); const typeFiltersKeys = useAdvancedSearchFilters(type, policyID); @@ -111,6 +114,7 @@ function FilterList({type, policyID, selectedFilter, style, contentContainerStyl style={[style]} contentContainerStyle={[contentContainerStyle]} showsVerticalScrollIndicator={false} + onMouseMove={onPointerMove} > {typeFiltersKeys.map((section, index) => ( diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 701e030b6780..69e1c66a83fc 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -4,7 +4,6 @@ import SearchAdvancedFiltersContent from '@components/Search/FilterComponents/Ad import useUpdateFilterQuery from '@components/Search/hooks/useUpdateFilterQuery'; import type {SearchQueryJSON} from '@components/Search/types'; -import useDebounceNonReactive from '@hooks/useDebounceNonReactive'; import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -17,7 +16,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; -import React, {Activity, useRef, useState} from 'react'; +import React, {Activity, useEffect, useRef, useState} from 'react'; import {View} from 'react-native'; import AmountFilterContentPopupWrapper from './AmountFilterContentPopupWrapper'; @@ -138,27 +137,68 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }); }; - // The debounce below always calls the latest version of this, so a hover whose delay elapsed after the cursor or the - // focus already moved on is dropped instead of replacing the content of the row the user is on now. - const activateHoveredFilter = (filterKey: SearchFilter['key']) => { - if (filterKey !== hoveredFilter) { - return; - } + // Shows the content of whichever row the cursor is on once it comes to rest. Time spent on a row cannot tell a + // deliberate hover from a slow pass over it, but coming to rest can: a cursor traveling down the list keeps + // restarting the wait however slowly it moves, while one that arrived at its target stops and lets it through. + const activateRestingFilter = () => { + activateFilter(hoveredFilter); + }; + // Held in a ref so a wait started by an earlier render still activates the row the cursor is on now. + // `useDebounceNonReactive` cannot express either of the waits below: it always hands lodash a `maxWait` key, and + // lodash reads the key rather than its value, so every wait it creates is capped and fires mid-movement. + const activateRestingFilterRef = useRef(activateRestingFilter); + useEffect(() => { + activateRestingFilterRef.current = activateRestingFilter; + }); + + const restTimeoutRef = useRef | undefined>(undefined); + const rowAllowanceTimeoutRef = useRef | undefined>(undefined); + const cancelPendingActivation = () => { + clearTimeout(restTimeoutRef.current); + clearTimeout(rowAllowanceTimeoutRef.current); + }; + useEffect(() => cancelPendingActivation, []); - activateFilter(filterKey); + /** Restarted by every movement of the cursor, so it only elapses once the cursor has come to rest. */ + const waitForCursorToRest = () => { + clearTimeout(restTimeoutRef.current); + restTimeoutRef.current = setTimeout(() => activateRestingFilterRef.current(), CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); }; - // Hovering only shows a row's content once the cursor has stayed on it for SEARCH_FILTER_HOVER_INTENT_DELAY, so - // sweeping across rows doesn't render a content pane per row. Moving focus is deliberate and never sweeps across - // rows, so it shows the content right away and keyboard users don't read a pane that is about to be replaced. - const debouncedActivateHoveredFilter = useDebounceNonReactive(activateHoveredFilter, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + /** + * What a cursor that never comes to rest is given instead. Movement does not restart it, so wandering around inside + * one row still ends in its content being shown, while moving on to the next row does - which is why a pass across + * the list never reaches it. + */ + const waitForRowAllowance = () => { + clearTimeout(rowAllowanceTimeoutRef.current); + rowAllowanceTimeoutRef.current = setTimeout(() => activateRestingFilterRef.current(), CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY); + }; const hoverFilter = (filterKey: SearchFilter['key']) => { setHoveredFilter(filterKey); - debouncedActivateHoveredFilter(filterKey); + waitForCursorToRest(); + waitForRowAllowance(); + }; + + // Where the cursor was when it last counted as moving. Distance is measured from there rather than from the previous + // event, because a hand that shakes stays within HOVER_INTENT_REST_RADIUS_PX of one point however many events it + // emits, while a cursor crossing the list leaves that point behind even when it creeps a pixel at a time. + const restAnchorRef = useRef<{x: number; y: number} | null>(null); + const trackPointerMovement = (event: {clientX: number; clientY: number}) => { + const anchor = restAnchorRef.current; + if (anchor && Math.hypot(event.clientX - anchor.x, event.clientY - anchor.y) < CONST.SEARCH.HOVER_INTENT_REST_RADIUS_PX) { + return; + } + + restAnchorRef.current = {x: event.clientX, y: event.clientY}; + waitForCursorToRest(); }; + // Moving the focus is deliberate and never passes over rows on the way, so it shows the content right away and + // drops whatever the cursor had pending. const focusFilter = (filterKey: SearchFilter['key']) => { + cancelPendingActivation(); setHoveredFilter(filterKey); activateFilter(filterKey); }; @@ -172,6 +212,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps policyID={getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, searchAdvancedFiltersForm)} selectedFilter={hoveredFilter} onHoverIn={hoverFilter} + onPointerMove={trackPointerMovement} onFocus={focusFilter} /> (); +/** The pointer move handler the popup hands to the filter list, captured so tests can drive the cursor. */ +let mockOnPointerMove: ((event: {clientX: number; clientY: number}) => void) | undefined; + /** The advanced filters form value served by the useOnyx mock. Reassigned by tests simulating filter value changes. */ let mockFiltersForm: Partial | undefined; @@ -33,26 +36,38 @@ jest.mock('@components/SafeTriangle', () => ({ // Stand-in for the filter list: per filter, one pressable reporting a hover on the row and one reporting focus on it. jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () => ({ __esModule: true, - default: ({onHoverIn, onFocus}: {onHoverIn: (filterKey: string) => void; onFocus: (filterKey: string) => void}) => ( - - {mockHoverableFilterKeys.map((filterKey) => ( - - onHoverIn(filterKey)} - /> - onFocus(filterKey)} - /> - - ))} - - ), + default: ({ + onHoverIn, + onFocus, + onPointerMove, + }: { + onHoverIn: (filterKey: string) => void; + onFocus: (filterKey: string) => void; + onPointerMove: (event: {clientX: number; clientY: number}) => void; + }) => { + mockOnPointerMove = onPointerMove; + + return ( + + {mockHoverableFilterKeys.map((filterKey) => ( + + onHoverIn(filterKey)} + /> + onFocus(filterKey)} + /> + + ))} + + ); + }, })); // Stand-in for the filter content, which is the expensive part being mounted or kept alive. @@ -100,6 +115,13 @@ function hoverAndRest(filterKey: string) { }); } +/** Travels the cursor to a point over the filter list. */ +function movePointer(clientX: number, clientY: number) { + act(() => { + mockOnPointerMove?.({clientX, clientY}); + }); +} + /** Moves the keyboard focus onto a filter row. */ function focus(filterKey: string) { fireEvent.press(screen.getByTestId(`focus-${filterKey}`)); @@ -109,6 +131,7 @@ beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); mockFiltersForm = undefined; + mockOnPointerMove = undefined; }); afterEach(() => { @@ -116,6 +139,83 @@ afterEach(() => { }); describe('SearchAdvancedFiltersPopup', () => { + it('keeps the content hidden while the cursor is still traveling over a row', () => { + render(); + + hover(FILTER_KEYS.FROM); + // The cursor crosses the row without ever pausing on it for the rest delay, and within the dwell allowance. + for (let step = 1; step <= 2; step++) { + act(() => { + jest.advanceTimersByTime(15); + }); + movePointer(100, 100 + step * 20); + } + + expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.FROM); + + // It comes to rest, and the content follows without waiting for the full dwell allowance. + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); + + expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); + }); + + it('treats a cursor that only shakes on the spot as at rest', () => { + render(); + + 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(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); + }); + + it('shows the content of a row the cursor never comes to rest on', () => { + render(); + + hover(FILTER_KEYS.FROM); + // Wandering around inside the row, always further than the rest radius: every step restarts the rest wait, so + // only the row allowance can end it. + for (let step = 1; step <= 25; step++) { + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY - 10); + }); + movePointer(100 + (step % 2) * 20, 100 + (step % 3) * 12); + } + + expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); + }); + + it('shows nothing while the cursor travels across several rows without stopping', () => { + render(); + + for (const filterKey of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]) { + hover(filterKey); + movePointer(100, 100 + mockHoverableFilterKeys.indexOf(filterKey) * 30); + act(() => { + jest.advanceTimersByTime(12); + }); + } + + expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.FROM); + expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); + + // Only the row it stopped on ends up shown. + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + }); + + expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.ATTENDEE); + }); + it('does not mount the content of filters the cursor only passes over', () => { render(); From 347335f4869785bf9f18c19213fc162f5578fa48 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 28 Aug 2026 12:31:06 +0200 Subject: [PATCH 16/30] drop what a filter row had pending once the cursor leaves the list A cursor on its way to the content pane passes over the rows between, and the last of them was left holding an activation that would replace the content the user was heading for. Leaving the list now drops it, so only a row the cursor actually settled on can take over the pane. --- .../AdvancedFilters/FilterList.tsx | 6 +++- .../SearchAdvancedFiltersPopup/index.tsx | 9 ++++++ .../Search/SearchAdvancedFiltersPopupTest.tsx | 28 +++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx index 0a80b0fc6ae2..2d345b69fb12 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx @@ -41,6 +41,9 @@ type FilterListProps = FilterItemCallbacks & { /** Called as the cursor travels over the list. Web only - it reports the movement between rows that `onHoverIn` cannot. */ onPointerMove?: (event: {clientX: number; clientY: number}) => void; + + /** Called when the cursor leaves the list, for whatever it has pending for the row it was on. Web only. */ + onPointerLeave?: () => void; }; type FilterItemProps = FilterItemCallbacks & { @@ -105,7 +108,7 @@ function FilterItem({filterKey, isSelected, onPress, onHoverIn, onFocus}: Filter ); } -function FilterList({type, policyID, selectedFilter, style, contentContainerStyle, onHoverIn, onFocus, onPress, onPointerMove}: FilterListProps) { +function FilterList({type, policyID, selectedFilter, style, contentContainerStyle, onHoverIn, onFocus, onPress, onPointerMove, onPointerLeave}: FilterListProps) { const styles = useThemeStyles(); const typeFiltersKeys = useAdvancedSearchFilters(type, policyID); @@ -115,6 +118,7 @@ function FilterList({type, policyID, selectedFilter, style, contentContainerStyl contentContainerStyle={[contentContainerStyle]} showsVerticalScrollIndicator={false} onMouseMove={onPointerMove} + onMouseLeave={onPointerLeave} > {typeFiltersKeys.map((section, index) => ( diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 69e1c66a83fc..89faa4f02cb4 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -195,6 +195,14 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps waitForCursorToRest(); }; + // Leaving the list - for the content pane beside it, or for anywhere else - means the row the cursor last passed + // over was not the one it was after, so whatever it had pending for that row is dropped rather than replacing the + // content the user is on their way to. + const stopTrackingPointer = () => { + cancelPendingActivation(); + restAnchorRef.current = null; + }; + // Moving the focus is deliberate and never passes over rows on the way, so it shows the content right away and // drops whatever the cursor had pending. const focusFilter = (filterKey: SearchFilter['key']) => { @@ -213,6 +221,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps selectedFilter={hoveredFilter} onHoverIn={hoverFilter} onPointerMove={trackPointerMovement} + onPointerLeave={stopTrackingPointer} onFocus={focusFilter} /> (); /** The pointer move handler the popup hands to the filter list, captured so tests can drive the cursor. */ let mockOnPointerMove: ((event: {clientX: number; clientY: number}) => void) | undefined; +/** The pointer leave handler the popup hands to the filter list, captured so tests can drive the cursor off it. */ +let mockOnPointerLeave: (() => void) | undefined; + /** The advanced filters form value served by the useOnyx mock. Reassigned by tests simulating filter value changes. */ let mockFiltersForm: Partial | undefined; @@ -40,12 +43,15 @@ jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () = onHoverIn, onFocus, onPointerMove, + onPointerLeave, }: { onHoverIn: (filterKey: string) => void; onFocus: (filterKey: string) => void; onPointerMove: (event: {clientX: number; clientY: number}) => void; + onPointerLeave: () => void; }) => { mockOnPointerMove = onPointerMove; + mockOnPointerLeave = onPointerLeave; return ( @@ -122,6 +128,13 @@ function movePointer(clientX: number, clientY: number) { }); } +/** Takes the cursor off the filter list, towards the content pane beside it. */ +function leaveList() { + act(() => { + mockOnPointerLeave?.(); + }); +} + /** Moves the keyboard focus onto a filter row. */ function focus(filterKey: string) { fireEvent.press(screen.getByTestId(`focus-${filterKey}`)); @@ -132,6 +145,7 @@ beforeEach(() => { jest.useFakeTimers(); mockFiltersForm = undefined; mockOnPointerMove = undefined; + mockOnPointerLeave = undefined; }); afterEach(() => { @@ -161,6 +175,20 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); }); + it('drops what a row had pending once the cursor leaves the list for the content beside it', () => { + render(); + + // The cursor passes over a row on its way to the content pane, without ever stopping on it. + hover(FILTER_KEYS.FROM); + movePointer(100, 100); + leaveList(); + act(() => { + jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY * 2); + }); + + expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.FROM); + }); + it('treats a cursor that only shakes on the spot as at rest', () => { render(); From 3ee04be8f9c4ea99d430f059c295504a35dce52e Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 28 Aug 2026 12:43:00 +0200 Subject: [PATCH 17/30] show the row the cursor ended on when it leaves the filter list The highlight follows the cursor while the content follows where it settles, so a flick across the rows and out of the popover left a row marked whose content was not the one on screen. There is nothing left to wait for once the cursor is gone, so leaving the list shows the row it ended on and the two agree again - the same row main would have shown, only at the end of the movement rather than partway through it. --- .../SearchAdvancedFiltersPopup/index.tsx | 7 +++--- .../Search/SearchAdvancedFiltersPopupTest.tsx | 24 ++++++++++++------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 89faa4f02cb4..da8991854028 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -195,12 +195,13 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps waitForCursorToRest(); }; - // Leaving the list - for the content pane beside it, or for anywhere else - means the row the cursor last passed - // over was not the one it was after, so whatever it had pending for that row is dropped rather than replacing the - // content the user is on their way to. + // The highlight follows the cursor and the content follows where it settles, so a cursor that leaves the list + // without settling would leave a row marked whose content is not the one on screen. There is nothing left to wait + // for once the cursor is gone, so the row it ended on is shown and the two agree again. const stopTrackingPointer = () => { cancelPendingActivation(); restAnchorRef.current = null; + activateFilter(hoveredFilter); }; // Moving the focus is deliberate and never passes over rows on the way, so it shows the content right away and diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 3737728e349c..5fe0273f7ec9 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -28,6 +28,9 @@ let mockOnPointerMove: ((event: {clientX: number; clientY: number}) => void) | u /** The pointer leave handler the popup hands to the filter list, captured so tests can drive the cursor off it. */ let mockOnPointerLeave: (() => void) | undefined; +/** The row the filter list is told to highlight, captured so tests can check it against the content being shown. */ +let mockSelectedFilter: string | undefined; + /** The advanced filters form value served by the useOnyx mock. Reassigned by tests simulating filter value changes. */ let mockFiltersForm: Partial | undefined; @@ -44,14 +47,17 @@ jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () = onFocus, onPointerMove, onPointerLeave, + selectedFilter, }: { onHoverIn: (filterKey: string) => void; onFocus: (filterKey: string) => void; onPointerMove: (event: {clientX: number; clientY: number}) => void; onPointerLeave: () => void; + selectedFilter: string; }) => { mockOnPointerMove = onPointerMove; mockOnPointerLeave = onPointerLeave; + mockSelectedFilter = selectedFilter; return ( @@ -146,6 +152,7 @@ beforeEach(() => { mockFiltersForm = undefined; mockOnPointerMove = undefined; mockOnPointerLeave = undefined; + mockSelectedFilter = undefined; }); afterEach(() => { @@ -175,18 +182,19 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); }); - it('drops what a row had pending once the cursor leaves the list for the content beside it', () => { + it('shows the row the cursor ended on when it leaves the list without settling', () => { render(); - // The cursor passes over a row on its way to the content pane, without ever stopping on it. - hover(FILTER_KEYS.FROM); - movePointer(100, 100); + // A flick across the rows and straight out of the popover, too fast for any of them to be settled on. + for (const filterKey of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]) { + hover(filterKey); + } leaveList(); - act(() => { - jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY * 2); - }); - expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.FROM); + // The marked row and the content on screen are the same one, and it is the row the cursor left from. + expect(mockSelectedFilter).toBe(FILTER_KEYS.ATTENDEE); + expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.ATTENDEE); + expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); }); it('treats a cursor that only shakes on the spot as at rest', () => { From 64f9c63a4eb5c2883b7ba3c71a477ffd74db9d9c Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 31 Aug 2026 16:59:06 +0200 Subject: [PATCH 18/30] keep every visited filter content mounted The cap on how many filter contents stayed mounted evicted by how recently a filter was used, which is unrelated to what a content costs to rebuild: a detour over three cheap rows dropped the expensive one, and returning to it blocked the JS thread for 733 ms where an uncapped run blocked none. Contents are built only for the filters actually visited and live only while the popover is open, which is what bounds them now. Also tidies the work around it. The tests keep one case per property and drive the popup through the callbacks the filter list hands it instead of rendering rows to press. The option lists are released when Search is left rather than also between its own tabs. The mounted bookkeeping is a spread now that nothing is evicted. The option reference nothing compares by identity is gone, the date pane no longer remounts on a feed array rebuilt from the same values, and the comments that carried measurements or overstated what the caches share are either shorter or corrected. --- src/CONST/index.ts | 6 +- .../SearchAdvancedFiltersPopup/index.tsx | 69 +++----- .../SelectionList/BaseSelectionList.tsx | 12 +- src/hooks/usePersonalDetailOptions.ts | 8 +- .../usePersonalDetailSearchSelector/base.ts | 42 ++--- src/hooks/useReleaseOptionListCaches.ts | 46 +---- src/libs/SearchUIUtils.ts | 2 +- src/libs/memoize/index.ts | 9 +- src/pages/Search/SearchPage.tsx | 2 +- .../Search/SearchAdvancedFiltersPopupTest.tsx | 162 +++--------------- tests/unit/useReleaseOptionListCachesTest.ts | 35 +--- 11 files changed, 90 insertions(+), 303 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 985b492dd354..68d8a07dca62 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2142,8 +2142,7 @@ const CONST = { /** * How long after entering an advanced filter row its content is rendered even if the cursor never came to rest. - * Measured from entering the row, so moving on to the next one restarts it and a pass across the list, however - * slow, never reaches it - the longest a row was held during a measured pass was 257 ms. + * Measured from entering the row, so only moving on to the next one restarts it. */ SEARCH_FILTER_HOVER_INTENT_MAX_DELAY: 400, @@ -6874,9 +6873,6 @@ const CONST = { RESULTS_PAGE_SIZE: 50, EXITING_ANIMATION_DURATION: 200, ME: 'me', - /** How many advanced filter contents the filters popover keeps mounted */ - MAX_MOUNTED_FILTER_CONTENTS: 3, - /** How far the cursor may wander from where it settled over the advanced filter list and still count as resting */ HOVER_INTENT_REST_RADIUS_PX: 8, DATA_TYPES: { diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index da8991854028..e0f14fc823a2 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -31,14 +31,14 @@ type SearchAdvancedFiltersPopupProps = { /** Which filter contents are mounted and what each of them was given, held together so one filter change moves all of it. */ type MountedFilterState = { - /** The filter whose content is shown. Also the most recently used entry of `mountedFilters`. */ + /** The filter whose content is shown. */ activeFilter: SearchFilter['key']; - /** The filters whose contents are mounted, in least-recently-used order. */ + /** The filters whose contents are mounted, in the order they were first visited. */ mountedFilters: Array; /** Per mounted content, the filter values it was given when it last became active. */ - formAtLastRest: Partial | undefined>>; + formAtLastVisit: Partial | undefined>>; /** Per mounted content, how many times it has been remounted. Part of its key, so a bump replaces the instance. */ contentVersions: Partial>; @@ -67,8 +67,8 @@ type MountedFilterContentProps = { }; // React Compiler caches the whole `mountedFilters.map()` result in a single slot, so changing the shown filter rebuilds -// every element of it. Each content sits in its own component, so the rebuilt element lands on this component's cache -// and one whose props are unchanged returns the element it returned before, which ends the render there. +// every element of it. Each content sits in its own component, so one whose props are unchanged returns the element it +// returned before and the render ends there. function MountedFilterContent({filterKey, values, onChange}: MountedFilterContentProps) { const styles = useThemeStyles(); @@ -95,57 +95,41 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps const [mountedFilterState, setMountedFilterState] = useState(() => ({ activeFilter: INITIAL_FILTER, mountedFilters: [INITIAL_FILTER], - formAtLastRest: {[INITIAL_FILTER]: searchAdvancedFiltersForm}, + formAtLastVisit: {[INITIAL_FILTER]: searchAdvancedFiltersForm}, contentVersions: {}, })); - const {activeFilter, mountedFilters, formAtLastRest, contentVersions} = mountedFilterState; + const {activeFilter, mountedFilters, formAtLastVisit, contentVersions} = mountedFilterState; const {updateFilterQueryParams} = useUpdateFilterQuery(queryJSON); - // The MAX_MOUNTED_FILTER_CONTENTS most recently active contents stay mounted, so revisiting a filter reveals its - // content instead of building it again. Activating a filter promotes it to most recently used and evicts whatever - // falls past the cap. + // A content stays mounted once visited, so revisiting a filter reveals it instead of building it again. Contents + // are built only for the filters actually visited and live only while the popover is open. const activateFilter = (filterKey: SearchFilter['key']) => { setMountedFilterState((currentState) => { if (currentState.activeFilter === filterKey) { return currentState; } - const nextMountedFilters = [...currentState.mountedFilters.filter((mountedFilter) => mountedFilter !== filterKey), filterKey].slice(-CONST.SEARCH.MAX_MOUNTED_FILTER_CONTENTS); - const nextFormAtLastRest: MountedFilterState['formAtLastRest'] = {}; - const nextContentVersions: MountedFilterState['contentVersions'] = {}; - // Both maps describe the mounted contents only, so a filter evicted from `mountedFilters` is dropped from them too. - for (const mountedFilter of nextMountedFilters) { - nextFormAtLastRest[mountedFilter] = mountedFilter === filterKey ? searchAdvancedFiltersForm : currentState.formAtLastRest[mountedFilter]; - const version = currentState.contentVersions[mountedFilter]; - if (version !== undefined) { - nextContentVersions[mountedFilter] = version; - } - } + const isMounted = currentState.mountedFilters.includes(filterKey); // A kept content keeps the values it was last given and decides its selection pinning on mount, so one whose // values went stale while it was hidden is remounted instead of revealed. Only the values that content reads // count as stale - a change to a filter it doesn't read leaves its own state, like a typed search term, alone. - if (currentState.mountedFilters.includes(filterKey) && hasFilterContentValuesChanged(filterKey, currentState.formAtLastRest[filterKey], searchAdvancedFiltersForm)) { - nextContentVersions[filterKey] = (currentState.contentVersions[filterKey] ?? 0) + 1; - } + const isStale = isMounted && hasFilterContentValuesChanged(filterKey, currentState.formAtLastVisit[filterKey], searchAdvancedFiltersForm); return { activeFilter: filterKey, - mountedFilters: nextMountedFilters, - formAtLastRest: nextFormAtLastRest, - contentVersions: nextContentVersions, + mountedFilters: isMounted ? currentState.mountedFilters : [...currentState.mountedFilters, filterKey], + formAtLastVisit: {...currentState.formAtLastVisit, [filterKey]: searchAdvancedFiltersForm}, + contentVersions: isStale ? {...currentState.contentVersions, [filterKey]: (currentState.contentVersions[filterKey] ?? 0) + 1} : currentState.contentVersions, }; }); }; // Shows the content of whichever row the cursor is on once it comes to rest. Time spent on a row cannot tell a - // deliberate hover from a slow pass over it, but coming to rest can: a cursor traveling down the list keeps - // restarting the wait however slowly it moves, while one that arrived at its target stops and lets it through. + // deliberate hover from a slow pass over it, but coming to rest can. const activateRestingFilter = () => { activateFilter(hoveredFilter); }; // Held in a ref so a wait started by an earlier render still activates the row the cursor is on now. - // `useDebounceNonReactive` cannot express either of the waits below: it always hands lodash a `maxWait` key, and - // lodash reads the key rather than its value, so every wait it creates is capped and fires mid-movement. const activateRestingFilterRef = useRef(activateRestingFilter); useEffect(() => { activateRestingFilterRef.current = activateRestingFilter; @@ -165,11 +149,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps restTimeoutRef.current = setTimeout(() => activateRestingFilterRef.current(), CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); }; - /** - * What a cursor that never comes to rest is given instead. Movement does not restart it, so wandering around inside - * one row still ends in its content being shown, while moving on to the next row does - which is why a pass across - * the list never reaches it. - */ + /** What a cursor that never comes to rest is given instead. Only moving on to the next row restarts it. */ const waitForRowAllowance = () => { clearTimeout(rowAllowanceTimeoutRef.current); rowAllowanceTimeoutRef.current = setTimeout(() => activateRestingFilterRef.current(), CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY); @@ -182,8 +162,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }; // Where the cursor was when it last counted as moving. Distance is measured from there rather than from the previous - // event, because a hand that shakes stays within HOVER_INTENT_REST_RADIUS_PX of one point however many events it - // emits, while a cursor crossing the list leaves that point behind even when it creeps a pixel at a time. + // event, so a shaking hand stays within HOVER_INTENT_REST_RADIUS_PX of one point while a slow crossing does not. const restAnchorRef = useRef<{x: number; y: number} | null>(null); const trackPointerMovement = (event: {clientX: number; clientY: number}) => { const anchor = restAnchorRef.current; @@ -195,17 +174,15 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps waitForCursorToRest(); }; - // The highlight follows the cursor and the content follows where it settles, so a cursor that leaves the list - // without settling would leave a row marked whose content is not the one on screen. There is nothing left to wait - // for once the cursor is gone, so the row it ended on is shown and the two agree again. + // Nothing is left to wait for once the cursor is gone, so the row it ended on is shown and the highlight and the + // content agree again. const stopTrackingPointer = () => { cancelPendingActivation(); restAnchorRef.current = null; activateFilter(hoveredFilter); }; - // Moving the focus is deliberate and never passes over rows on the way, so it shows the content right away and - // drops whatever the cursor had pending. + // Moving the focus is deliberate and never passes over rows on the way, so it shows the content right away. const focusFilter = (filterKey: SearchFilter['key']) => { cancelPendingActivation(); setHoveredFilter(filterKey); @@ -232,16 +209,14 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps {mountedFilters.map((filterKey) => ( // A backgrounded content stays mounted with the filter values frozen at its last visit, so moving // between filters neither re-renders it nor loses its state. `Activity` takes it out of layout and - // unmounts its effects while it is hidden - so it holds no Onyx subscriptions of its own until it is - // shown again - and lets React render it at a lower priority than the visible one when a context - // both of them read changes underneath. + // unmounts its effects while it is hidden, so it holds no Onyx subscriptions until it is shown again. diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index ee1abcc43df5..a7fa9ebfc8e8 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -333,9 +333,8 @@ function BaseSelectionListImpl({ const scrollTimeoutRef = useRef(null); // A hidden `` subtree keeps its state but unmounts its effects, so this runs again when the list is - // revealed without it being mounted anew. The list has no layout while it is hidden and its container loses the - // scroll position, which leaves the rendered window describing the offset from before - the visible area is blank - // until something scrolls the list. Scrolling back to the offset the list still reports puts the two in sync again. + // revealed. Its container loses the scroll position while the rendered window still describes the old offset, which + // leaves the visible area blank until something scrolls it; scrolling back to the reported offset realigns them. const hasMountedRef = useRef(false); useEffect(() => { if (!hasMountedRef.current) { @@ -343,11 +342,10 @@ function BaseSelectionListImpl({ return; } - // The offset is read here rather than in the frame below, because the scroll the container reports on being - // revealed reaches the list first and would leave it reporting the top it was reset to. + // Read here rather than in the frame below: the scroll reported on being revealed reaches the list first and + // would leave it reporting the top it was reset to. const listOffset = listRef.current?.getAbsoluteLastScrollOffset(); - // A list sitting at the top has nothing to restore: its window already describes that offset. Skipping the - // scroll keeps revealing such a list - every list nobody scrolled - as cheap as it was before. + // A list sitting at the top has nothing to restore, and skipping the scroll keeps revealing one as cheap as before. if (!listOffset) { return; } diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 4093e61c9f05..63078c123f1f 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -107,8 +107,8 @@ const createReportAttributesSelector = /** * 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. - * One entry serves every consumer mounted at the same time, because they only pass different arguments when - * `includeLoginsOnly` narrows the contacts down - and then the list built for each of them is a small one. + * A single entry is held because it covers the whole contact list: consumers narrowing it with `includeLoginsOnly` + * take turns in that entry, and each of them builds a small list. */ const memoizedCreateOptionList = memoize(createOptionList, { maxSize: 1, @@ -121,8 +121,8 @@ function clearPersonalDetailOptionsCache() { memoizedCreateOptionList.cache.clear(); } -// The cached options describe the signed-in account's contacts. Search releases them once it is done with them (see -// `useReleaseOptionListCaches`), and sign-out covers whatever is still held at that point. +// The cached options describe the signed-in account's contacts, released when Search is left +// (`useReleaseOptionListCaches`) and on sign-out. registerSessionCleanupCallback(clearPersonalDetailOptionsCache); /** diff --git a/src/hooks/usePersonalDetailSearchSelector/base.ts b/src/hooks/usePersonalDetailSearchSelector/base.ts index 51d6f8fc0bb9..ee03b403124f 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -153,20 +153,14 @@ const defaultListOptions = { }; /** - * How many option lists the caches below hold. Consumers of this hook mount one selector at a time, except the Search - * filters popover, which keeps the contents of its people filters alive next to each other - three entries cover the - * lists it renders side by side. Entries rotate below that number as well, because what a consumer searches for is part - * of the key, so typing in one selector replaces the entries of the others. - * - * Fewer entries cost more than the memory they save: the result of `buildSelectedOptions` is an argument of - * `getValidOptions` and is compared by identity, so an eviction in the first cache produces a new list and makes the - * second one miss as well. + * How many option lists the caches below hold. Consumers mount one selector at a time, except the Search filters + * popover, which keeps its people filters alive next to each other. Fewer entries cost more than the memory they save: + * the result of `buildSelectedOptions` is an argument of `getValidOptions` compared by identity, so an eviction in the + * first cache makes the second one miss as well. */ const MAX_CACHED_OPTION_LISTS = 3; -/** - * Filtering the whole option list is a pure derivation of its inputs, so remounting consumers reuse the previous result. - */ +/** 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, @@ -192,8 +186,8 @@ function clearPersonalDetailSearchSelectorCaches() { memoizedBuildSelectedOptions.cache.clear(); } -// Both caches hold option lists built for the signed-in account. Search releases them once it is done with them (see -// `useReleaseOptionListCaches`), and sign-out covers whatever is still held at that point. +// Both caches hold option lists built for the signed-in account, released when Search is left +// (`useReleaseOptionListCaches`) and on sign-out. registerSessionCleanupCallback(clearPersonalDetailSearchSelectorCaches); /** @@ -244,8 +238,8 @@ function usePersonalDetailSearchSelectorBase({ })(); const areOptionsInitialized = !isPersonalDetailsOptionsLoading; - // With nothing selected the options already carry the right state, so the list is passed through without copying, - // keeping its reference stable for the memoized filtering below. + // 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 []; @@ -292,19 +286,13 @@ function usePersonalDetailSearchSelectorBase({ const currentUserSearchTerms = [translate('common.you'), translate('common.me')]; const filteredCurrentUserOption = (() => { const newOption = filterOption(currentOption, debouncedSearchTerm, currentUserSearchTerms); - if (!newOption) { - return newOption; - } - const isSelected = selectedAccountIDs.has(newOption.accountID.toString()); - // The original reference is kept when the selection state already matches, so consumers building memoized - // lists on top of this option keep hitting their caches across remounts. - if ((newOption.isSelected ?? false) === isSelected) { - return newOption; + if (newOption) { + return { + ...newOption, + isSelected: selectedAccountIDs.has(newOption.accountID.toString()), + }; } - return { - ...newOption, - isSelected, - }; + return newOption; })(); const existingAccountIDs = new Set(optionsWithContacts?.map((option) => option.accountID.toString())); diff --git a/src/hooks/useReleaseOptionListCaches.ts b/src/hooks/useReleaseOptionListCaches.ts index 3ec82d7595a8..7aee9e61372a 100644 --- a/src/hooks/useReleaseOptionListCaches.ts +++ b/src/hooks/useReleaseOptionListCaches.ts @@ -1,43 +1,17 @@ import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; import subscribeToRootNavigation from '@libs/Navigation/helpers/subscribeToRootNavigation'; -import {useEffect, useRef} from 'react'; +import {useEffect} from 'react'; import {clearPersonalDetailOptionsCache} from './usePersonalDetailOptions'; import {clearPersonalDetailSearchSelectorCaches} from './usePersonalDetailSearchSelector/base'; -function releaseOptionListCaches() { - clearPersonalDetailOptionsCache(); - clearPersonalDetailSearchSelectorCaches(); -} - /** - * Releases the option lists cached for the people selectors once Search is done with them: when another tab takes over - * from Search, and when another of its own tabs is selected. 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. - * - * @param tabKey The selected tab of Search, or `undefined` while the query shown matches none of them. + * 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(tabKey: string | undefined) { - const previousTabKeyRef = useRef(undefined); - - useEffect(() => { - // A query narrowed with filters belongs to no tab, and narrowing one is not leaving it, so the lists are - // released only when the selection moves between tabs. - if (!tabKey) { - return; - } - - const previousTabKey = previousTabKeyRef.current; - previousTabKeyRef.current = tabKey; - - if (!previousTabKey || previousTabKey === tabKey) { - return; - } - - releaseOptionListCaches(); - }, [tabKey]); - +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. @@ -45,17 +19,15 @@ function useReleaseOptionListCaches(tabKey: string | undefined) { return subscribeToRootNavigation(() => { const isSearchTopmostRoute = isSearchTopmostFullScreenRoute(); - if (isSearchTopmostRoute === wasSearchTopmostRoute) { - return; - } - + const hasLeftSearch = wasSearchTopmostRoute && !isSearchTopmostRoute; wasSearchTopmostRoute = isSearchTopmostRoute; - if (isSearchTopmostRoute) { + if (!hasLeftSearch) { return; } - releaseOptionListCaches(); + clearPersonalDetailOptionsCache(); + clearPersonalDetailSearchSelectorCaches(); }); }, []); } diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index 4e6a736972fe..677334e63813 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -5907,7 +5907,7 @@ function hasFilterContentValuesChanged( if (isDateFilterKey(baseFilterKey)) { return ( - previousValues?.feed !== values?.feed || + !previousValues?.feed !== !values?.feed || Object.values(CONST.SEARCH.DATE_MODIFIERS).some((modifier) => previousValues?.[`${baseFilterKey}${modifier}`] !== values?.[`${baseFilterKey}${modifier}`]) ); } diff --git a/src/libs/memoize/index.ts b/src/libs/memoize/index.ts index 207f81cc5375..1defdfbf289b 100644 --- a/src/libs/memoize/index.ts +++ b/src/libs/memoize/index.ts @@ -115,15 +115,12 @@ function memoize => lodashIsPlainObject(value); /** - * Two arguments are equivalent when they are shallowly equal, or are plain objects with the same keys whose values are - * shallowly equal - the second level covers arguments rebuilt from unchanged sources (e.g. a mapped Onyx collection). + * 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)) { diff --git a/src/pages/Search/SearchPage.tsx b/src/pages/Search/SearchPage.tsx index 555a48610e82..2e27ea6b4e23 100644 --- a/src/pages/Search/SearchPage.tsx +++ b/src/pages/Search/SearchPage.tsx @@ -53,7 +53,7 @@ function SearchPage({route}: SearchPageProps) { useSearchPageSetup(currentSearchQueryJSON); useSeedMyExpensesSearch(); - useReleaseOptionListCaches(currentSearchKey); + 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/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 5fe0273f7ec9..815cd518ea30 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -1,6 +1,5 @@ -import {act, fireEvent, render, screen} from '@testing-library/react-native'; +import {act, render, screen} from '@testing-library/react-native'; -import {PressableWithoutFeedback} from '@components/Pressable'; import type {SearchQueryJSON} from '@components/Search/types'; import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; @@ -13,25 +12,21 @@ import {View} from 'react-native'; // jest.mock factories can't reference imported bindings, but `mock`-prefixed locals are allowed. const MockView = View; -const MockPressable = PressableWithoutFeedback; const mockUseRef = useRef; const FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; -const mockHoverableFilterKeys: string[] = [FILTER_KEYS.TYPE, FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]; /** Called once per mounted filter content instance, so a remount shows up as a second call for the same key. */ const mockOnContentCreated = jest.fn(); -/** The pointer move handler the popup hands to the filter list, captured so tests can drive the cursor. */ +// Handed to the filter list by the popup and captured here, 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; - -/** The pointer leave handler the popup hands to the filter list, captured so tests can drive the cursor off it. */ let mockOnPointerLeave: (() => void) | undefined; - -/** The row the filter list is told to highlight, captured so tests can check it against the content being shown. */ let mockSelectedFilter: string | undefined; -/** The advanced filters form value served by the useOnyx mock. Reassigned by tests simulating filter value changes. */ +/** The advanced filters form served by the useOnyx mock. Reassigned by tests simulating filter value changes. */ let mockFiltersForm: Partial | undefined; jest.mock('@components/SafeTriangle', () => ({ @@ -39,46 +34,23 @@ jest.mock('@components/SafeTriangle', () => ({ default: ({children}: {children: React.ReactNode}) => {children}, })); -// Stand-in for the filter list: per filter, one pressable reporting a hover on the row and one reporting focus on it. +// 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: ({ - onHoverIn, - onFocus, - onPointerMove, - onPointerLeave, - selectedFilter, - }: { + default: (props: { onHoverIn: (filterKey: string) => void; onFocus: (filterKey: string) => void; onPointerMove: (event: {clientX: number; clientY: number}) => void; onPointerLeave: () => void; selectedFilter: string; }) => { - mockOnPointerMove = onPointerMove; - mockOnPointerLeave = onPointerLeave; - mockSelectedFilter = selectedFilter; - - return ( - - {mockHoverableFilterKeys.map((filterKey) => ( - - onHoverIn(filterKey)} - /> - onFocus(filterKey)} - /> - - ))} - - ); + mockOnHoverIn = props.onHoverIn; + mockOnFocus = props.onFocus; + mockOnPointerMove = props.onPointerMove; + mockOnPointerLeave = props.onPointerLeave; + mockSelectedFilter = props.selectedFilter; + + return null; }, })); @@ -114,9 +86,11 @@ const SearchAdvancedFiltersPopup = require<{ // Only forwarded to the mocked query hook, so the parsed query itself does not matter here. const queryJSON = buildSearchQueryJSON(`type:${CONST.SEARCH.DATA_TYPES.EXPENSE}`); -/** Moves the cursor onto a filter row without waiting for the hover intent delay to pass. */ +/** Moves the cursor onto a filter row without waiting for the hover intent delay. */ function hover(filterKey: string) { - fireEvent.press(screen.getByTestId(`hover-${filterKey}`)); + act(() => { + mockOnHoverIn?.(filterKey); + }); } /** Moves the cursor onto a filter row and leaves it there long enough for the content to follow. */ @@ -143,16 +117,16 @@ function leaveList() { /** Moves the keyboard focus onto a filter row. */ function focus(filterKey: string) { - fireEvent.press(screen.getByTestId(`focus-${filterKey}`)); + act(() => { + mockOnFocus?.(filterKey); + }); } beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); mockFiltersForm = undefined; - mockOnPointerMove = undefined; - mockOnPointerLeave = undefined; - mockSelectedFilter = undefined; + render(); }); afterEach(() => { @@ -160,31 +134,7 @@ afterEach(() => { }); describe('SearchAdvancedFiltersPopup', () => { - it('keeps the content hidden while the cursor is still traveling over a row', () => { - render(); - - hover(FILTER_KEYS.FROM); - // The cursor crosses the row without ever pausing on it for the rest delay, and within the dwell allowance. - for (let step = 1; step <= 2; step++) { - act(() => { - jest.advanceTimersByTime(15); - }); - movePointer(100, 100 + step * 20); - } - - expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.FROM); - - // It comes to rest, and the content follows without waiting for the full dwell allowance. - act(() => { - jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - }); - - expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); - }); - it('shows the row the cursor ended on when it leaves the list without settling', () => { - render(); - // A flick across the rows and straight out of the popover, too fast for any of them to be settled on. for (const filterKey of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]) { hover(filterKey); @@ -198,8 +148,6 @@ describe('SearchAdvancedFiltersPopup', () => { }); it('treats a cursor that only shakes on the spot as at rest', () => { - render(); - hover(FILTER_KEYS.FROM); movePointer(100, 100); act(() => { @@ -215,8 +163,6 @@ describe('SearchAdvancedFiltersPopup', () => { }); it('shows the content of a row the cursor never comes to rest on', () => { - render(); - hover(FILTER_KEYS.FROM); // Wandering around inside the row, always further than the rest radius: every step restarts the rest wait, so // only the row allowance can end it. @@ -231,11 +177,9 @@ describe('SearchAdvancedFiltersPopup', () => { }); it('shows nothing while the cursor travels across several rows without stopping', () => { - render(); - - for (const filterKey of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]) { + for (const [row, filterKey] of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE].entries()) { hover(filterKey); - movePointer(100, 100 + mockHoverableFilterKeys.indexOf(filterKey) * 30); + movePointer(100, 100 + row * 30); act(() => { jest.advanceTimersByTime(12); }); @@ -252,29 +196,7 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.ATTENDEE); }); - it('does not mount the content of filters the cursor only passes over', () => { - render(); - - // A fast sweep: every row is left again well before the hover intent delay elapses. - for (const filterKey of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]) { - hover(filterKey); - act(() => { - jest.advanceTimersByTime(1); - }); - } - act(() => { - jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - }); - - // Only the row the cursor came to rest on was mounted, the two it swept over were not. - expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.ATTENDEE); - expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.FROM); - expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); - }); - it('reuses the content of a filter that was already visited instead of remounting it', () => { - render(); - hoverAndRest(FILTER_KEYS.FROM); hoverAndRest(FILTER_KEYS.TO); hoverAndRest(FILTER_KEYS.FROM); @@ -282,23 +204,7 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); }); - it('remounts a kept content when the filters form changed while it was away', () => { - render(); - - hoverAndRest(FILTER_KEYS.FROM); - - // The form changes in a way this content reads (the search type decides its options) and the cursor moves on. - mockFiltersForm = {type: CONST.SEARCH.DATA_TYPES.EXPENSE}; - hoverAndRest(FILTER_KEYS.TO); - - // Returning to the filter now gets a fresh content instance instead of the one from before the change. - hoverAndRest(FILTER_KEYS.FROM); - expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(2); - }); - it('remounts a kept content when its own value changed while it was away', () => { - render(); - hoverAndRest(FILTER_KEYS.FROM); // Someone was picked in this very filter, so its content has to decide its selection pinning again. @@ -310,8 +216,6 @@ describe('SearchAdvancedFiltersPopup', () => { }); it('keeps a kept content when only the value of a filter it does not read changed', () => { - render(); - hoverAndRest(FILTER_KEYS.FROM); // Someone was picked in another filter, which the content of this one neither reads nor renders. @@ -324,8 +228,6 @@ describe('SearchAdvancedFiltersPopup', () => { }); it('shows the content of a row focused with the keyboard without waiting for the hover intent delay', () => { - render(); - focus(FILTER_KEYS.FROM); // No timer is advanced: moving focus is deliberate, so its content follows in the same frame. @@ -334,8 +236,6 @@ describe('SearchAdvancedFiltersPopup', () => { }); it('does not let a pending hover replace the content of the row focused after it', () => { - render(); - // The cursor passes over a row and the keyboard moves focus elsewhere before the delay elapses. hover(FILTER_KEYS.TO); focus(FILTER_KEYS.FROM); @@ -346,18 +246,4 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); expect(screen.getByTestId(`filter-content-${FILTER_KEYS.FROM}`)).toBeTruthy(); }); - - it('keeps only the most recently used contents mounted', () => { - render(); - - // Visiting more filters than MAX_MOUNTED_FILTER_CONTENTS evicts the least recently used one. - hoverAndRest(FILTER_KEYS.FROM); - hoverAndRest(FILTER_KEYS.TO); - hoverAndRest(FILTER_KEYS.ATTENDEE); - expect(screen.queryByTestId(`filter-content-${FILTER_KEYS.TYPE}`, {includeHiddenElements: true})).toBeNull(); - - // Returning to an evicted filter mounts a fresh content instance for it. - hoverAndRest(FILTER_KEYS.TYPE); - expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.TYPE)).toHaveLength(2); - }); }); diff --git a/tests/unit/useReleaseOptionListCachesTest.ts b/tests/unit/useReleaseOptionListCachesTest.ts index 4d3103cb8884..15c047503367 100644 --- a/tests/unit/useReleaseOptionListCachesTest.ts +++ b/tests/unit/useReleaseOptionListCachesTest.ts @@ -52,8 +52,8 @@ function navigateWithinSearch() { mockNavigationListener?.(); } -function renderReleaseHook(initialTabKey: string | undefined) { - return renderHook((tabKey) => useReleaseOptionListCaches(tabKey), {initialProps: initialTabKey}); +function renderReleaseHook() { + return renderHook(() => useReleaseOptionListCaches()); } beforeEach(() => { @@ -63,33 +63,8 @@ beforeEach(() => { }); describe('useReleaseOptionListCaches', () => { - it('keeps the cached lists while the same tab stays selected', () => { - const {rerender} = renderReleaseHook('expenses'); - - rerender('expenses'); - - expect(mockRelease).not.toHaveBeenCalled(); - }); - - it('releases the cached lists when another tab of Search is selected', () => { - const {rerender} = renderReleaseHook('expenses'); - - rerender('reports'); - - expect(mockRelease).toHaveBeenCalled(); - }); - - it('keeps the cached lists when the query shown stops matching a tab', () => { - const {rerender} = renderReleaseHook('expenses'); - - // A filter was applied, so the query belongs to no tab - the user is still on the one they were on. - rerender(undefined); - - expect(mockRelease).not.toHaveBeenCalled(); - }); - it('releases the cached lists when another tab takes over from Search', () => { - renderReleaseHook('expenses'); + renderReleaseHook(); leaveSearch(); @@ -97,7 +72,7 @@ describe('useReleaseOptionListCaches', () => { }); it('keeps the cached lists while Search is still the tab on top', () => { - renderReleaseHook('expenses'); + renderReleaseHook(); navigateWithinSearch(); @@ -105,7 +80,7 @@ describe('useReleaseOptionListCaches', () => { }); it('stops listening to navigation once it is no longer used', () => { - const {unmount} = renderReleaseHook('expenses'); + const {unmount} = renderReleaseHook(); unmount(); From 957014e5491640139f3708f236e319507fe59581 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 1 Sep 2026 19:05:19 +0200 Subject: [PATCH 19/30] show every filter as the cursor reaches it and withhold only the contact list Pointing at a filter row shows that filter straight away, at any cursor speed. What waits for the cursor to come to rest is no longer the pane but the one derivation heavy enough to be felt: building the contact list, which only the four filters routed to UserSelector read. They mount at once and stand as their own spinner until the cursor rests, and every other filter renders with no wait. `ready` already ran from SearchAdvancedFiltersContent down to the selectors that honour it; the popup wrapper was dropping it, so it now passes it through. getExpensifyTeamExclusions walks every personal detail and is skipped until the selector is allowed to derive. The values each content reads are decided once, in getFilterContentValues, and both the props a content is handed and the check for whether they changed are built from it, so the two cannot drift apart. --- src/CONST/index.ts | 8 +- .../AdvancedFilters/FilterList.tsx | 4 +- .../SearchAdvancedFiltersContent.tsx | 63 +++---- .../Search/FilterComponents/UserSelector.tsx | 37 ++-- .../ListFilterContentPopupWrapper.tsx | 3 +- .../SearchAdvancedFiltersPopup/index.tsx | 110 +++++++----- .../SelectionList/BaseSelectionList.tsx | 8 +- src/hooks/usePersonalDetailOptions.ts | 5 +- .../usePersonalDetailSearchSelector/base.ts | 7 +- src/libs/SearchUIUtils.ts | 91 +++++----- src/libs/memoize/cache/types.ts | 2 +- tests/unit/BaseSelectionListTest.tsx | 23 +-- .../Search/SearchAdvancedFiltersPopupTest.tsx | 164 +++++++++++------- tests/unit/Search/SearchUIUtilsTest.ts | 98 +++++++++++ tests/unit/useReleaseOptionListCachesTest.ts | 28 ++- 15 files changed, 417 insertions(+), 234 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 68d8a07dca62..230dc50cac9e 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2137,12 +2137,12 @@ 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 is rendered */ + /** 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, /** - * How long after entering an advanced filter row its content is rendered even if the cursor never came to rest. - * Measured from entering the row, so only moving on to the next one restarts it. + * How long after entering an advanced filter row its content may derive the contact list even if the cursor + * never came to rest. Measured from entering a row, so only entering one restarts it. */ SEARCH_FILTER_HOVER_INTENT_MAX_DELAY: 400, @@ -6873,7 +6873,7 @@ const CONST = { RESULTS_PAGE_SIZE: 50, EXITING_ANIMATION_DURATION: 200, ME: 'me', - /** How far the cursor may wander from where it settled over the advanced filter list and still count as resting */ + /** 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', diff --git a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx index 2d345b69fb12..4d7fa7a47ad3 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx @@ -39,10 +39,10 @@ type FilterListProps = FilterItemCallbacks & { style?: StyleProp; contentContainerStyle?: StyleProp; - /** Called as the cursor travels over the list. Web only - it reports the movement between rows that `onHoverIn` cannot. */ + /** 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, for whatever it has pending for the row it was on. Web only. */ + /** 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?: () => void; }; diff --git a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx index 586835b5a9e8..aa9699e653c4 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx @@ -1,7 +1,7 @@ import type {ListFilterContentProps} from '@components/Search/FilterComponents/ListFilterContent'; import {getFilterFormValues} from '@libs/SearchQueryUtils'; -import {getFilterNegatableValue, isAmountFilterKey, isDateFilterKey, isTextFilterKey} from '@libs/SearchUIUtils'; +import {getFilterContentValues} from '@libs/SearchUIUtils'; import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; @@ -37,23 +37,21 @@ type SearchAdvancedFiltersContentProps = { }; function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, onChange}: SearchAdvancedFiltersContentProps) { - if (isAmountFilterKey(baseFilterKey)) { + const contentValues = getFilterContentValues(baseFilterKey, values); + + if (contentValues.kind === 'amount') { const AmountFilter = components.Amount; return ( ); } - if (isDateFilterKey(baseFilterKey)) { + if (contentValues.kind === 'date') { const DateFilter = components.Date; const onModifier = CONST.SEARCH.DATE_MODIFIERS.ON; const afterModifier = CONST.SEARCH.DATE_MODIFIERS.AFTER; @@ -62,15 +60,10 @@ function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, return ( onChange({ [`${baseFilterKey}${onModifier}`]: newValues[onModifier], @@ -83,42 +76,40 @@ function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, ); } - if (baseFilterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.REPORT_FIELD) { + if (contentValues.kind === 'reportField') { const ReportFieldFilter = components.ReportField; return ( ); } - if (isTextFilterKey(baseFilterKey)) { - const {isNegated, value} = getFilterNegatableValue(baseFilterKey, values); + if (contentValues.kind === 'text') { const TextFilter = components.Text; return ( onChange(getFilterFormValues(baseFilterKey, newValue, negated))} + key={contentValues.baseFilterKey} + baseFilterKey={contentValues.baseFilterKey} + value={contentValues.negatable.value} + isNegated={contentValues.negatable.isNegated} + onChange={(newValue, negated) => onChange(getFilterFormValues(contentValues.baseFilterKey, newValue, negated))} /> ); } - const {isNegated, value} = getFilterNegatableValue(baseFilterKey, values); const ListFilter = components.List; return ( onChange(getFilterFormValues(baseFilterKey, newValue, negated))} + isNegated={contentValues.negatable.isNegated} + onChange={(newValue, negated) => onChange(getFilterFormValues(contentValues.baseFilterKey, newValue, negated))} /> ); } diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index 73d8f5cf404d..6ceada04488e 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -1,3 +1,4 @@ +import LoadingIndicator from '@components/LoadingIndicator'; import {usePersonalDetails} from '@components/OnyxListItemProvider'; import type {Filter, SearchFilterCommonProps} from '@components/Search/types'; import SelectionList from '@components/SelectionList'; @@ -47,7 +48,9 @@ function UserSelector({value = [], isNegatable, policyID, selectionListTextInput return acc; }, new Set()); - const expensifyTeamExclusions = getExpensifyTeamExclusions(personalDetails, policies, currentUserPersonalDetails.email); + // getExpensifyTeamExclusions walks every personal detail, and it only narrows options that are not being built while + // the selector stands as its own loading state, so it is skipped until then. + 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. @@ -133,19 +136,27 @@ function UserSelector({value = [], isNegatable, policyID, selectionListTextInput itemCount={listData.length} isSearchable={shouldShowSearchInput} isNegatable={isNegatable} + // Held at the height a contact list occupies, so what arrives does not push the panel open under the cursor. + shouldUseFixedPopoverHeight={!ready} > - + {ready ? ( + + ) : ( + // One spinner while the contact list is not being built yet. A skeleton of rows would draw a list that + // is not there and flicker row by row as the cursor moves from filter to filter. + + )} ); } diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx index bb02513672fa..b3f34c3e6abc 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx @@ -7,7 +7,7 @@ import {isFilterNegatable} from '@libs/SearchQueryUtils'; import React, {useState} from 'react'; -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); @@ -19,6 +19,7 @@ function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initial isNegated={isNegated} type={type} policyID={policyID} + ready={ready} style={[styles.mt6, styles.flex1]} selectionListTextInputStyle={[!isFilterKeyNegatable && [styles.pt5, styles.pb1]]} selectionListStyle={{contentContainerStyle: [isFilterKeyNegatable ? styles.pb2 : styles.pv2]}} diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index e0f14fc823a2..d2ab3ace3ae7 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -29,19 +29,22 @@ type SearchAdvancedFiltersPopupProps = { queryJSON: SearchQueryJSON; }; -/** Which filter contents are mounted and what each of them was given, held together so one filter change moves all of it. */ +/** Which filter contents are mounted and what each was given. Kept in one object so a single update moves them together. */ type MountedFilterState = { /** The filter whose content is shown. */ activeFilter: SearchFilter['key']; - /** The filters whose contents are mounted, in the order they were first visited. */ + /** The filters whose contents are mounted, in the order they were first visited. They stay mounted until the popover closes. */ mountedFilters: Array; - /** Per mounted content, the filter values it was given when it last became active. */ + /** Per mounted content, the filter values it was given when it last became the shown one. What a hidden content goes on rendering, and what a revisit is compared against. */ formAtLastVisit: Partial | undefined>>; /** Per mounted content, how many times it has been remounted. Part of its key, so a bump replaces the instance. */ contentVersions: Partial>; + + /** The deferred filters now allowed to derive their contents. A deferred filter left out of this stands as its own loading state. */ + readyFilters: Array; }; const filterComponents = { @@ -55,6 +58,18 @@ const filterComponents = { /** 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, which is the one derivation heavy enough to be + * felt. They are the four routed to `UserSelector`, the only component under Search that reads personal detail options. + * Every other filter renders as fast as the row is pointed at. + */ +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']; @@ -62,14 +77,18 @@ type MountedFilterContentProps = { /** 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()` result in a single slot, so changing the shown filter rebuilds -// every element of it. Each content sits in its own component, so one whose props are unchanged returns the element it -// returned before and the render ends there. -function MountedFilterContent({filterKey, values, onChange}: MountedFilterContentProps) { +// every element of it. Each content sits in its own component, so moving between filters ends the render at the boundary +// of the ones whose props did not change. A change to the form does change `onChange`, and then every mounted content +// re-renders. +function MountedFilterContent({filterKey, values, ready, onChange}: MountedFilterContentProps) { const styles = useThemeStyles(); return ( @@ -78,6 +97,7 @@ function MountedFilterContent({filterKey, values, onChange}: MountedFilterConten values={values} baseFilterKey={filterKey} components={filterComponents} + ready={ready} onChange={onChange} /> @@ -90,20 +110,19 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps const {windowHeight} = useWindowDimensions(); const [searchAdvancedFiltersForm] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); const filterContentRef = useRef(null); - // The list highlights `hoveredFilter` immediately. The content pane follows `activeFilter`. - const [hoveredFilter, setHoveredFilter] = useState(INITIAL_FILTER); const [mountedFilterState, setMountedFilterState] = useState(() => ({ activeFilter: INITIAL_FILTER, mountedFilters: [INITIAL_FILTER], formAtLastVisit: {[INITIAL_FILTER]: searchAdvancedFiltersForm}, contentVersions: {}, + readyFilters: [], })); - const {activeFilter, mountedFilters, formAtLastVisit, contentVersions} = mountedFilterState; + const {activeFilter, mountedFilters, formAtLastVisit, contentVersions, readyFilters} = mountedFilterState; const {updateFilterQueryParams} = useUpdateFilterQuery(queryJSON); - // A content stays mounted once visited, so revisiting a filter reveals it instead of building it again. Contents - // are built only for the filters actually visited and live only while the popover is open. - const activateFilter = (filterKey: SearchFilter['key']) => { + // The pane follows the cursor with no wait of its own, so pointing at a row shows that filter at any speed. A content + // stays mounted once visited, so coming back to one reveals it instead of building it again. + const showFilter = (filterKey: SearchFilter['key']) => { setMountedFilterState((currentState) => { if (currentState.activeFilter === filterKey) { return currentState; @@ -120,49 +139,59 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps mountedFilters: isMounted ? currentState.mountedFilters : [...currentState.mountedFilters, filterKey], formAtLastVisit: {...currentState.formAtLastVisit, [filterKey]: 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, }; }); }; - // Shows the content of whichever row the cursor is on once it comes to rest. Time spent on a row cannot tell a - // deliberate hover from a slow pass over it, but coming to rest can. - const activateRestingFilter = () => { - activateFilter(hoveredFilter); - }; - // Held in a ref so a wait started by an earlier render still activates the row the cursor is on now. - const activateRestingFilterRef = useRef(activateRestingFilter); - useEffect(() => { - activateRestingFilterRef.current = activateRestingFilter; - }); + /** + * Lets the shown filter derive what it withheld. Which filter that is comes from the updater rather than from the + * render that scheduled the wait, so a wait outlives the render it started in. Only a deferred filter withholds + * anything, so marking any other one would be an update that changes nothing on screen. + */ + 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]}; + }); + }; const restTimeoutRef = useRef | undefined>(undefined); const rowAllowanceTimeoutRef = useRef | undefined>(undefined); - const cancelPendingActivation = () => { + const cancelReadyWaits = () => { clearTimeout(restTimeoutRef.current); clearTimeout(rowAllowanceTimeoutRef.current); }; - useEffect(() => cancelPendingActivation, []); + // Drops both waits when the popover closes. + useEffect(() => cancelReadyWaits, []); - /** Restarted by every movement of the cursor, so it only elapses once the cursor has come to rest. */ + /** + * Restarted by every movement of the cursor, so it only elapses once the cursor has come to rest. Time spent on a + * row cannot tell a deliberate hover from a slow pass over it, but coming to rest can. + */ const waitForCursorToRest = () => { clearTimeout(restTimeoutRef.current); - restTimeoutRef.current = setTimeout(() => activateRestingFilterRef.current(), CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + restTimeoutRef.current = setTimeout(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); }; - /** What a cursor that never comes to rest is given instead. Only moving on to the next row restarts it. */ + /** What a cursor that wanders inside one row without ever resting is given instead. Only entering a row restarts it. */ const waitForRowAllowance = () => { clearTimeout(rowAllowanceTimeoutRef.current); - rowAllowanceTimeoutRef.current = setTimeout(() => activateRestingFilterRef.current(), CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY); + rowAllowanceTimeoutRef.current = setTimeout(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY); }; const hoverFilter = (filterKey: SearchFilter['key']) => { - setHoveredFilter(filterKey); + showFilter(filterKey); waitForCursorToRest(); waitForRowAllowance(); }; // Where the cursor was when it last counted as moving. Distance is measured from there rather than from the previous - // event, so a shaking hand stays within HOVER_INTENT_REST_RADIUS_PX of one point while a slow crossing does not. + // event, so a shaking hand stays within HOVER_INTENT_REST_RADIUS_PX of one point while a slow crossing does not. The + // anchor marks where the cursor last moved, not which row it is over, so entering a row does not reset it. const restAnchorRef = useRef<{x: number; y: number} | null>(null); const trackPointerMovement = (event: {clientX: number; clientY: number}) => { const anchor = restAnchorRef.current; @@ -174,21 +203,23 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps waitForCursorToRest(); }; - // Nothing is left to wait for once the cursor is gone, so the row it ended on is shown and the highlight and the - // content agree again. + // Nothing is left to wait for once the cursor is gone, so whatever the row it ended on was withholding is released. const stopTrackingPointer = () => { - cancelPendingActivation(); + cancelReadyWaits(); restAnchorRef.current = null; - activateFilter(hoveredFilter); + markShownFilterReady(); }; - // Moving the focus is deliberate and never passes over rows on the way, so it shows the content right away. + // Moving the focus is deliberate and never passes over rows on the way, so nothing is withheld from it. const focusFilter = (filterKey: SearchFilter['key']) => { - cancelPendingActivation(); - setHoveredFilter(filterKey); - activateFilter(filterKey); + cancelReadyWaits(); + showFilter(filterKey); + markShownFilterReady(); }; + // Only the contact-list filters withhold anything; every other content is ready as soon as it is mounted. + const mayDeriveContent = (filterKey: SearchFilter['key']) => !DEFERRED_CONTENT_FILTERS.has(filterKey) || readyFilters.includes(filterKey); + return ( @@ -196,7 +227,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps style={[styles.typeFiltersPopupContainer]} type={searchAdvancedFiltersForm?.type} policyID={getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, searchAdvancedFiltersForm)} - selectedFilter={hoveredFilter} + selectedFilter={activeFilter} onHoverIn={hoverFilter} onPointerMove={trackPointerMovement} onPointerLeave={stopTrackingPointer} @@ -217,6 +248,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index a7fa9ebfc8e8..0a14b1650c8c 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -335,10 +335,12 @@ function BaseSelectionListImpl({ // A hidden `` subtree keeps its state but unmounts its effects, so this runs again when the list is // revealed. Its container loses the scroll position while the rendered window still describes the old offset, which // leaves the visible area blank until something scrolls it; scrolling back to the reported offset realigns them. - const hasMountedRef = useRef(false); + // The ref rather than the mount: this component stays mounted while it is hidden, which is the whole premise here. + const hasEffectRunRef = useRef(false); useEffect(() => { - if (!hasMountedRef.current) { - hasMountedRef.current = true; + // The first run is the real mount, where the list is already where it belongs. + if (!hasEffectRunRef.current) { + hasEffectRunRef.current = true; return; } diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 63078c123f1f..b8b5243e691b 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -107,8 +107,9 @@ const createReportAttributesSelector = /** * 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 because it covers the whole contact list: consumers narrowing it with `includeLoginsOnly` - * take turns in that entry, and each of them builds a small list. + * A single entry is held because the whole contact list is the expensive case. A consumer narrowing it with + * `includeLoginsOnly` evicts that entry, but both its own build and the next whole-list one are cheap enough to be + * worth the memory saved. */ const memoizedCreateOptionList = memoize(createOptionList, { maxSize: 1, diff --git a/src/hooks/usePersonalDetailSearchSelector/base.ts b/src/hooks/usePersonalDetailSearchSelector/base.ts index ee03b403124f..7ec689727a0c 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -154,9 +154,12 @@ const defaultListOptions = { /** * How many option lists the caches below hold. Consumers mount one selector at a time, except the Search filters - * popover, which keeps its people filters alive next to each other. Fewer entries cost more than the memory they save: + * popover, which keeps its people filters alive next to each other - three of them, which is the most a single search + * type offers at once (from, to and attendee, on expense searches). Fewer entries cost more than the memory they save: * the result of `buildSelectedOptions` is an argument of `getValidOptions` compared by identity, so an eviction in the - * first cache makes the second one miss as well. + * first cache makes the second one miss as well. What the entries cost in memory is bounded by + * `useReleaseOptionListCaches`, which drops both caches once another tab takes over from Search, so this number only + * has to cover how many lists are wanted at once rather than how long any of them lives. */ const MAX_CACHED_OPTION_LISTS = 3; diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index 677334e63813..0fc8179b921d 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -5860,12 +5860,6 @@ function getDisplayValue( return Array.isArray(formValue) ? formValue.join(', ') : formValue; } -/** A filter value together with whether the form holds it under the negated key. */ -type FilterNegatableValue = { - isNegated: boolean; - value: unknown; -}; - function getFilterNegatableValue( baseFilterKey: K, values: (Partial & Partial>) | undefined, @@ -5878,53 +5872,69 @@ function getFilterNegatableValue | undefined, - values: Partial | undefined, -): boolean { - if (previousValues === values) { - return false; +function getFilterContentValues(baseFilterKey: SearchFilter['key'], values: Partial | undefined) { + if (isAmountFilterKey(baseFilterKey)) { + return { + kind: 'amount', + baseFilterKey, + value: { + [CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO]: values?.[`${baseFilterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO}`], + [CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN]: values?.[`${baseFilterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`], + [CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN]: values?.[`${baseFilterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN}`], + }, + } as const; + } + + if (isDateFilterKey(baseFilterKey)) { + return { + kind: 'date', + baseFilterKey, + value: { + [CONST.SEARCH.DATE_MODIFIERS.ON]: values?.[`${baseFilterKey}${CONST.SEARCH.DATE_MODIFIERS.ON}`], + [CONST.SEARCH.DATE_MODIFIERS.AFTER]: values?.[`${baseFilterKey}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`], + [CONST.SEARCH.DATE_MODIFIERS.BEFORE]: values?.[`${baseFilterKey}${CONST.SEARCH.DATE_MODIFIERS.BEFORE}`], + [CONST.SEARCH.DATE_MODIFIERS.RANGE]: values?.[`${baseFilterKey}${CONST.SEARCH.DATE_MODIFIERS.RANGE}`], + }, + hasFeed: !!values?.feed, + } as const; } // The report field content is handed the whole form, so anything in it counts. if (baseFilterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.REPORT_FIELD) { - return true; + return {kind: 'reportField', values} as const; } - if (isAmountFilterKey(baseFilterKey)) { - return Object.values(CONST.SEARCH.AMOUNT_MODIFIERS).some((modifier) => previousValues?.[`${baseFilterKey}${modifier}`] !== values?.[`${baseFilterKey}${modifier}`]); + if (isTextFilterKey(baseFilterKey)) { + return {kind: 'text', baseFilterKey, negatable: getFilterNegatableValue(baseFilterKey, values)} as const; } - if (isDateFilterKey(baseFilterKey)) { - return ( - !previousValues?.feed !== !values?.feed || - Object.values(CONST.SEARCH.DATE_MODIFIERS).some((modifier) => previousValues?.[`${baseFilterKey}${modifier}`] !== values?.[`${baseFilterKey}${modifier}`]) - ); - } + // A list content also reads the search type and the workspace filter, which decide the options it offers. + return { + kind: 'list', + baseFilterKey, + negatable: getFilterNegatableValue(baseFilterKey, values), + type: values?.type, + policyID: getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, values), + } as const; +} - if (isTextFilterKey(baseFilterKey)) { - return hasNegatableValueChanged(getFilterNegatableValue(baseFilterKey, previousValues), getFilterNegatableValue(baseFilterKey, values)); +/** Whether the values the content of `baseFilterKey` reads differ between two versions of the form, so a change to a filter it doesn't read leaves it alone. */ +function hasFilterContentValuesChanged( + baseFilterKey: SearchFilter['key'], + previousValues: Partial | undefined, + values: Partial | undefined, +): boolean { + if (previousValues === values) { + return false; } - // A list content also reads the search type and the workspace filter, which decide the options it offers. - return ( - hasNegatableValueChanged(getFilterNegatableValue(baseFilterKey, previousValues), getFilterNegatableValue(baseFilterKey, values)) || - previousValues?.type !== values?.type || - hasNegatableValueChanged( - getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, previousValues), - getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, values), - ) - ); + return !deepEqual(getFilterContentValues(baseFilterKey, previousValues), getFilterContentValues(baseFilterKey, values)); } function getLabelValue(key: SearchAdvancedFiltersKey, labelKey: TranslationPaths | undefined, translate: LocalizedTranslate) { @@ -7085,6 +7095,7 @@ export { adjustTimeRangeToDateFilters, getDateDisplayValue, getDisplayValue, + getFilterContentValues, getFilterNegatableValue, hasFilterContentValuesChanged, shouldShowFilter, diff --git a/src/libs/memoize/cache/types.ts b/src/libs/memoize/cache/types.ts index 4b337f41939c..b33e430194af 100644 --- a/src/libs/memoize/cache/types.ts +++ b/src/libs/memoize/cache/types.ts @@ -15,7 +15,7 @@ type Cache = { * @returns The value for the key */ getSet: (key: K, valueProducer: () => V) => BoxedValue; - /** Drops every entry, so values built for a signed-out user do not stay in memory */ + /** Drops every entry, so cached values can be released once they are no longer worth holding */ clear: () => void; snapshot: { keys: () => K[]; diff --git a/tests/unit/BaseSelectionListTest.tsx b/tests/unit/BaseSelectionListTest.tsx index cbcd3d32d6b4..d33abd253b8d 100644 --- a/tests/unit/BaseSelectionListTest.tsx +++ b/tests/unit/BaseSelectionListTest.tsx @@ -175,11 +175,15 @@ describe('BaseSelectionList', () => { it('scrolls back to the offset it reports when it is revealed from a hidden Activity', async () => { jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); - mockGetAbsoluteLastScrollOffset.mockReturnValue(1200); + // The offset is read as the list is revealed and reported as zero afterwards, so a read taken a frame later + // would restore the top the list was reset to rather than where it was. + mockGetAbsoluteLastScrollOffset.mockReturnValueOnce(1200).mockReturnValue(0); const {rerender} = render(); - // A list that was just mounted starts where it starts, so nothing scrolls it. + // A list that was just mounted starts where it starts, so nothing scrolls it. The frame has to pass first, + // otherwise this holds whether or not the mount is skipped. Nothing here sets state, so no act is needed. + jest.advanceTimersByTime(32); expect(mockScrollToOffset).not.toHaveBeenCalled(); // Hiding the list unmounts its effects and drops its layout, and revealing it runs them again. @@ -191,21 +195,6 @@ describe('BaseSelectionList', () => { }); }); - it('does not scroll a list revealed at the top, which has no offset to restore', async () => { - jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); - mockGetAbsoluteLastScrollOffset.mockReturnValue(0); - - const {rerender} = render(); - - rerender(); - rerender(); - - await waitFor(() => { - expect(screen.getByText('Item 1')).toBeOnTheScreen(); - }); - expect(mockScrollToOffset).not.toHaveBeenCalled(); - }); - it('should not trigger item press if screen is not focused', () => { jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(false); render(); diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 815cd518ea30..4beb357fc024 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -19,6 +19,12 @@ const FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; /** Called once per mounted filter 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 = {}; + +/** The filter values each mounted content was last rendered with. */ +let mockValuesByFilter: Record | undefined> = {}; + // Handed to the filter list by the popup and captured here, so tests can drive the cursor and read what is highlighted. let mockOnHoverIn: ((filterKey: string) => void) | undefined; let mockOnFocus: ((filterKey: string) => void) | undefined; @@ -57,20 +63,25 @@ jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () = // Stand-in for the filter content, which is the expensive part being mounted or kept alive. jest.mock('@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent', () => ({ __esModule: true, - default: ({baseFilterKey}: {baseFilterKey: string}) => { + default: ({baseFilterKey, ready, values}: {baseFilterKey: string; ready?: boolean; values?: Partial}) => { const isCreated = mockUseRef(false); if (!isCreated.current) { isCreated.current = true; mockOnContentCreated(baseFilterKey); } + mockReadyByFilter[baseFilterKey] = !!ready; + mockValuesByFilter[baseFilterKey] = values; return ; }, })); +// One callback for the life of the test: a fresh one per render would defeat the boundary that keeps mounted contents +// from re-rendering, and hide a regression that removed it. +const mockUpdateFilterQueryParams = jest.fn(); jest.mock('@components/Search/hooks/useUpdateFilterQuery', () => ({ __esModule: true, - default: () => ({setFilterQueryParams: jest.fn(), updateFilterQueryParams: jest.fn()}), + default: () => ({updateFilterQueryParams: mockUpdateFilterQueryParams}), })); jest.mock('@hooks/useOnyx', () => ({ @@ -84,6 +95,9 @@ const SearchAdvancedFiltersPopup = require<{ }>('../../../src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx').default; // Only forwarded to the mocked query hook, so the parsed query itself does not matter here. +/** Renders the popup again, which is what carries a reassigned form into it while the shown filter stays put. */ +let rerenderPopup: () => void; + const queryJSON = buildSearchQueryJSON(`type:${CONST.SEARCH.DATA_TYPES.EXPENSE}`); /** Moves the cursor onto a filter row without waiting for the hover intent delay. */ @@ -93,7 +107,7 @@ function hover(filterKey: string) { }); } -/** Moves the cursor onto a filter row and leaves it there long enough for the content to follow. */ +/** Moves the cursor onto a filter row and leaves it there long enough for what it withheld to be released. */ function hoverAndRest(filterKey: string) { hover(filterKey); act(() => { @@ -126,7 +140,10 @@ beforeEach(() => { jest.clearAllMocks(); jest.useFakeTimers(); mockFiltersForm = undefined; - render(); + mockReadyByFilter = {}; + mockValuesByFilter = {}; + const view = render(); + rerenderPopup = () => view.rerender(); }); afterEach(() => { @@ -134,17 +151,37 @@ afterEach(() => { }); describe('SearchAdvancedFiltersPopup', () => { - it('shows the row the cursor ended on when it leaves the list without settling', () => { - // A flick across the rows and straight out of the popover, too fast for any of them to be settled on. - for (const filterKey of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE]) { + 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 [row, filterKey] of peopleFilters.entries()) { hover(filterKey); + movePointer(100, 100 + row * 30); + act(() => { + jest.advanceTimersByTime(12); + }); } - leaveList(); - // The marked row and the content on screen are the same one, and it is the row the cursor left from. - expect(mockSelectedFilter).toBe(FILTER_KEYS.ATTENDEE); - expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.ATTENDEE); - expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); + // 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(mockOnContentCreated).toHaveBeenCalledWith(filterKey); + 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(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.STATUS); + expect(mockReadyByFilter[FILTER_KEYS.STATUS]).toBe(true); }); it('treats a cursor that only shakes on the spot as at rest', () => { @@ -159,63 +196,86 @@ describe('SearchAdvancedFiltersPopup', () => { jest.advanceTimersByTime(15); }); - expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); - it('shows the content of a row the cursor never comes to rest on', () => { - hover(FILTER_KEYS.FROM); - // Wandering around inside the row, always further than the rest radius: every step restarts the rest wait, so - // only the row allowance can end it. - for (let step = 1; step <= 25; step++) { + it('releases a row the cursor never rests on once its per-row allowance elapses', () => { + const step = CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY - 10; + let elapsed = 0; + let corner = 0; + // Wandering inside the row, always further than the rest radius, so every step restarts the rest wait and only + // the row allowance can end it. + const wander = () => { act(() => { - jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY - 10); + jest.advanceTimersByTime(step); }); - movePointer(100 + (step % 2) * 20, 100 + (step % 3) * 12); + elapsed += step; + corner += 1; + movePointer(100 + (corner % 2) * 30, 100); + }; + + hover(FILTER_KEYS.FROM); + while (elapsed < CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY - step) { + wander(); } + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(false); - expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); + wander(); + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); - it('shows nothing while the cursor travels across several rows without stopping', () => { - for (const [row, filterKey] of [FILTER_KEYS.FROM, FILTER_KEYS.TO, FILTER_KEYS.ATTENDEE].entries()) { - hover(filterKey); - movePointer(100, 100 + row * 30); - act(() => { - jest.advanceTimersByTime(12); - }); - } + it('releases the row the cursor left from when it leaves the list without settling', () => { + hover(FILTER_KEYS.FROM); + leaveList(); - expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.FROM); - expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); + }); - // Only the row it stopped on ends up shown. - act(() => { - jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - }); + it('goes on rendering a hidden content with the values it was last given', () => { + mockFiltersForm = {from: ['9']}; + // The useOnyx mock serves a module variable and cannot re-render on its own, so a visit to another row is what + // carries a new form into the popup. + hoverAndRest(FILTER_KEYS.STATUS); + hoverAndRest(FILTER_KEYS.FROM); - expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.ATTENDEE); + // A filter this content does not read changes, so it stays mounted rather than being rebuilt. + mockFiltersForm = {from: ['9'], to: ['1']}; + hoverAndRest(FILTER_KEYS.STATUS); + + expect(mockValuesByFilter[FILTER_KEYS.FROM]).toEqual({from: ['9']}); }); - it('reuses the content of a filter that was already visited instead of remounting it', () => { - hoverAndRest(FILTER_KEYS.FROM); - hoverAndRest(FILTER_KEYS.TO); + it('hands the shown content the live form rather than the values it was mounted on', () => { + mockFiltersForm = {from: ['9']}; + hoverAndRest(FILTER_KEYS.STATUS); hoverAndRest(FILTER_KEYS.FROM); - expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); + // The form changes while this filter stays the shown one, so it has to follow rather than hold its snapshot. + mockFiltersForm = {from: ['9'], to: ['1']}; + rerenderPopup(); + + expect(mockValuesByFilter[FILTER_KEYS.FROM]).toEqual({from: ['9'], to: ['1']}); }); - it('remounts a kept content when its own value changed while it was away', () => { + 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']}; hoverAndRest(FILTER_KEYS.TO); - hoverAndRest(FILTER_KEYS.FROM); + 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 kept content when only the value of a filter it does not read changed', () => { + 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. @@ -227,23 +287,11 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockOnContentCreated.mock.calls.filter(([filterKey]) => filterKey === FILTER_KEYS.FROM)).toHaveLength(1); }); - it('shows the content of a row focused with the keyboard without waiting for the hover intent delay', () => { + it('withholds nothing from a row focused with the keyboard', () => { focus(FILTER_KEYS.FROM); - // No timer is advanced: moving focus is deliberate, so its content follows in the same frame. - expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.FROM); - expect(screen.getByTestId(`filter-content-${FILTER_KEYS.FROM}`)).toBeTruthy(); - }); - - it('does not let a pending hover replace the content of the row focused after it', () => { - // The cursor passes over a row and the keyboard moves focus elsewhere before the delay elapses. - hover(FILTER_KEYS.TO); - focus(FILTER_KEYS.FROM); - act(() => { - jest.advanceTimersByTime(CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - }); - - expect(mockOnContentCreated).not.toHaveBeenCalledWith(FILTER_KEYS.TO); + // No timer is advanced: moving focus is deliberate and never passes over rows on the way. expect(screen.getByTestId(`filter-content-${FILTER_KEYS.FROM}`)).toBeTruthy(); + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); }); diff --git a/tests/unit/Search/SearchUIUtilsTest.ts b/tests/unit/Search/SearchUIUtilsTest.ts index e384f5957da4..283911c376ef 100644 --- a/tests/unit/Search/SearchUIUtilsTest.ts +++ b/tests/unit/Search/SearchUIUtilsTest.ts @@ -12819,3 +12819,101 @@ describe('getSavedSearchIconName', () => { spy.mockRestore(); }); }); + +describe('hasFilterContentValuesChanged', () => { + const 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. */ + ignored: [FilterValues, FilterValues]; + }; + + it('reports no change when handed the same form twice', () => { + const values = {[FILTER_KEYS.FROM]: ['1']}; + + expect(SearchUIUtils.hasFilterContentValuesChanged(FILTER_KEYS.FROM, values, values)).toBe(false); + }); + + // One case per kind of content, because each is handed a different slice of the form and a filter that reads a + // slice must not be rebuilt for a change outside it. + const contentValuesCases: ContentValuesCase[] = [ + { + kind: 'list', + filterKey: FILTER_KEYS.FROM, + read: [{[FILTER_KEYS.FROM]: ['1']}, {[FILTER_KEYS.FROM]: ['2']}], + ignored: [{[FILTER_KEYS.FROM]: ['1']}, {[FILTER_KEYS.FROM]: ['1'], [FILTER_KEYS.TO]: ['2']}], + }, + { + kind: 'list, negated', + filterKey: FILTER_KEYS.FROM, + // Built the way the content builds it, so the negated key cannot drift from what the comparator reads. + read: [SearchQueryUtils.getFilterFormValues(FILTER_KEYS.FROM, ['1'], false), SearchQueryUtils.getFilterFormValues(FILTER_KEYS.FROM, ['1'], true)], + ignored: [{[FILTER_KEYS.FROM]: ['1']}, {[FILTER_KEYS.FROM]: ['1'], [FILTER_KEYS.CATEGORY]: ['food']}], + }, + { + kind: 'list, reading the search type it offers options for', + filterKey: FILTER_KEYS.CATEGORY, + read: [{type: CONST.SEARCH.DATA_TYPES.EXPENSE}, {type: CONST.SEARCH.DATA_TYPES.INVOICE}], + ignored: [{type: CONST.SEARCH.DATA_TYPES.EXPENSE}, {type: CONST.SEARCH.DATA_TYPES.EXPENSE, [FILTER_KEYS.KEYWORD]: 'a'}], + }, + { + kind: 'list, reading the workspace that narrows its options', + filterKey: FILTER_KEYS.CATEGORY, + read: [{[FILTER_KEYS.POLICY_ID]: ['1']}, {[FILTER_KEYS.POLICY_ID]: ['2']}], + ignored: [{[FILTER_KEYS.POLICY_ID]: ['1']}, {[FILTER_KEYS.POLICY_ID]: ['1'], [FILTER_KEYS.MERCHANT]: 'a'}], + }, + { + kind: 'text', + filterKey: FILTER_KEYS.MERCHANT, + read: [{[FILTER_KEYS.MERCHANT]: 'a'}, {[FILTER_KEYS.MERCHANT]: 'b'}], + ignored: [{[FILTER_KEYS.MERCHANT]: 'a'}, {[FILTER_KEYS.MERCHANT]: 'a', [FILTER_KEYS.DESCRIPTION]: 'b'}], + }, + { + kind: 'amount', + filterKey: FILTER_KEYS.AMOUNT, + read: [{[`${FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10'}, {[`${FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '20'}], + ignored: [ + {[`${FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10'}, + {[`${FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10', [FILTER_KEYS.MERCHANT]: 'a'}, + ], + }, + { + kind: 'date', + filterKey: FILTER_KEYS.DATE, + read: [{[`${FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01'}, {[`${FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-02-01'}], + ignored: [ + {[`${FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01'}, + {[`${FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01', [FILTER_KEYS.MERCHANT]: 'a'}, + ], + }, + { + // 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: FILTER_KEYS.DATE, + read: [{}, {[FILTER_KEYS.FEED]: ['1']}], + ignored: [{[FILTER_KEYS.FEED]: ['1']}, {[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: FILTER_KEYS.REPORT_FIELD, + read: [{[FILTER_KEYS.MERCHANT]: 'a'}, {[FILTER_KEYS.MERCHANT]: 'b'}], + ignored: [{[FILTER_KEYS.MERCHANT]: 'a'}, {[FILTER_KEYS.MERCHANT]: 'a'}], + }, + ]; + + 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); + expect(SearchUIUtils.hasFilterContentValuesChanged(filterKey, ignored.at(0), ignored.at(1))).toBe(false); + }); +}); diff --git a/tests/unit/useReleaseOptionListCachesTest.ts b/tests/unit/useReleaseOptionListCachesTest.ts index 15c047503367..f6b658d88e97 100644 --- a/tests/unit/useReleaseOptionListCachesTest.ts +++ b/tests/unit/useReleaseOptionListCachesTest.ts @@ -2,8 +2,11 @@ import {renderHook} from '@testing-library/react-native'; import useReleaseOptionListCaches from '@hooks/useReleaseOptionListCaches'; -/** Called once per release of the cached option lists, whichever cache it belongs to. */ -const mockRelease = jest.fn(); +/** 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; @@ -14,17 +17,15 @@ const mockUnsubscribe = jest.fn(); jest.mock('@hooks/usePersonalDetailOptions', () => ({ __esModule: true, - default: jest.fn(), clearPersonalDetailOptionsCache: () => { - mockRelease(); + mockReleaseOptions(); }, })); jest.mock('@hooks/usePersonalDetailSearchSelector/base', () => ({ __esModule: true, - default: jest.fn(), clearPersonalDetailSearchSelectorCaches: () => { - mockRelease(); + mockReleaseSearchSelector(); }, })); @@ -68,7 +69,9 @@ describe('useReleaseOptionListCaches', () => { leaveSearch(); - expect(mockRelease).toHaveBeenCalled(); + // Both caches, because releasing only one of them leaves the other holding the lists it was built from. + expect(mockReleaseOptions).toHaveBeenCalled(); + expect(mockReleaseSearchSelector).toHaveBeenCalled(); }); it('keeps the cached lists while Search is still the tab on top', () => { @@ -76,14 +79,7 @@ describe('useReleaseOptionListCaches', () => { navigateWithinSearch(); - expect(mockRelease).not.toHaveBeenCalled(); - }); - - it('stops listening to navigation once it is no longer used', () => { - const {unmount} = renderReleaseHook(); - - unmount(); - - expect(mockUnsubscribe).toHaveBeenCalled(); + expect(mockReleaseOptions).not.toHaveBeenCalled(); + expect(mockReleaseSearchSelector).not.toHaveBeenCalled(); }); }); From b389daa6ce3aea14d0f246c7ebef9cab402be192 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Wed, 2 Sep 2026 11:46:26 +0200 Subject: [PATCH 20/30] code cleaned up after design review --- .../Search/FilterComponents/UserSelector.tsx | 6 +- .../SearchAdvancedFiltersPopup/index.tsx | 73 ++++++++---------- .../SelectionList/BaseSelectionList.tsx | 5 +- src/hooks/usePersonalDetailOptions.ts | 9 +-- .../usePersonalDetailSearchSelector/base.ts | 14 ++-- src/libs/SearchUIUtils.ts | 9 +-- src/libs/memoize/cache/types.ts | 2 +- .../Search/SearchAdvancedFiltersPopupTest.tsx | 76 ++++++++---------- tests/unit/Search/SearchUIUtilsTest.ts | 77 +++++++++---------- tests/unit/useReleaseOptionListCachesTest.ts | 5 +- 10 files changed, 120 insertions(+), 156 deletions(-) diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index 6ceada04488e..18c098c3c5c9 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -48,8 +48,7 @@ function UserSelector({value = [], isNegatable, policyID, selectionListTextInput return acc; }, new Set()); - // getExpensifyTeamExclusions walks every personal detail, and it only narrows options that are not being built while - // the selector stands as its own loading state, so it is skipped until then. + // 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 @@ -153,8 +152,7 @@ function UserSelector({value = [], isNegatable, policyID, selectionListTextInput footerContent={footer} /> ) : ( - // One spinner while the contact list is not being built yet. A skeleton of rows would draw a list that - // is not there and flicker row by row as the cursor moves from filter to filter. + // One spinner while the contact list is not being built yet. )} diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index d2ab3ace3ae7..896760efb066 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -29,21 +29,24 @@ type SearchAdvancedFiltersPopupProps = { queryJSON: SearchQueryJSON; }; -/** Which filter contents are mounted and what each was given. Kept in one object so a single update moves them together. */ +/** Which filter contents are mounted and what each was given. */ type MountedFilterState = { /** The filter whose content is shown. */ activeFilter: SearchFilter['key']; - /** The filters whose contents are mounted, in the order they were first visited. They stay mounted until the popover closes. */ + /** The mounted contents, in visit order. They stay mounted until the popover closes. */ mountedFilters: Array; - /** Per mounted content, the filter values it was given when it last became the shown one. What a hidden content goes on rendering, and what a revisit is compared against. */ - formAtLastVisit: Partial | undefined>>; + /** The filter values each mounted instance was built from. A revisit compares against it. */ + formAtMount: Partial | undefined>>; - /** Per mounted content, how many times it has been remounted. Part of its key, so a bump replaces the instance. */ + /** The filter values each content was last shown with. It goes on rendering with them while hidden. */ + formWhileHidden: Partial | undefined>>; + + /** 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 their contents. A deferred filter left out of this stands as its own loading state. */ + /** The deferred filters now allowed to derive. One left out stands as its own loading state. */ readyFilters: Array; }; @@ -58,11 +61,7 @@ const filterComponents = { /** 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, which is the one derivation heavy enough to be - * felt. They are the four routed to `UserSelector`, the only component under Search that reads personal detail options. - * Every other filter renders as fast as the row is pointed at. - */ +/** 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, @@ -84,10 +83,9 @@ type MountedFilterContentProps = { onChange: (values: Partial) => void; }; -// React Compiler caches the whole `mountedFilters.map()` result in a single slot, so changing the shown filter rebuilds -// every element of it. Each content sits in its own component, so moving between filters ends the render at the boundary -// of the ones whose props did not change. A change to the form does change `onChange`, and then every mounted content -// re-renders. +// 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(); @@ -113,15 +111,15 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps const [mountedFilterState, setMountedFilterState] = useState(() => ({ activeFilter: INITIAL_FILTER, mountedFilters: [INITIAL_FILTER], - formAtLastVisit: {[INITIAL_FILTER]: searchAdvancedFiltersForm}, + formAtMount: {[INITIAL_FILTER]: searchAdvancedFiltersForm}, + formWhileHidden: {}, contentVersions: {}, readyFilters: [], })); - const {activeFilter, mountedFilters, formAtLastVisit, contentVersions, readyFilters} = mountedFilterState; + const {activeFilter, mountedFilters, formWhileHidden, contentVersions, readyFilters} = mountedFilterState; const {updateFilterQueryParams} = useUpdateFilterQuery(queryJSON); - // The pane follows the cursor with no wait of its own, so pointing at a row shows that filter at any speed. A content - // stays mounted once visited, so coming back to one reveals it instead of building it again. + // 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) { @@ -129,15 +127,17 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps } const isMounted = currentState.mountedFilters.includes(filterKey); - // A kept content keeps the values it was last given and decides its selection pinning on mount, so one whose - // values went stale while it was hidden is remounted instead of revealed. Only the values that content reads - // count as stale - a change to a filter it doesn't read leaves its own state, like a typed search term, alone. - const isStale = isMounted && hasFilterContentValuesChanged(filterKey, currentState.formAtLastVisit[filterKey], searchAdvancedFiltersForm); + // 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], - formAtLastVisit: {...currentState.formAtLastVisit, [filterKey]: searchAdvancedFiltersForm}, + 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, @@ -145,11 +145,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }); }; - /** - * Lets the shown filter derive what it withheld. Which filter that is comes from the updater rather than from the - * render that scheduled the wait, so a wait outlives the render it started in. Only a deferred filter withholds - * anything, so marking any other one would be an update that changes nothing on screen. - */ + /** 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)) { @@ -168,16 +164,13 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps // Drops both waits when the popover closes. useEffect(() => cancelReadyWaits, []); - /** - * Restarted by every movement of the cursor, so it only elapses once the cursor has come to rest. Time spent on a - * row cannot tell a deliberate hover from a slow pass over it, but coming to rest can. - */ + /** Restarted by every movement, so it elapses only once the cursor has come to rest. */ const waitForCursorToRest = () => { clearTimeout(restTimeoutRef.current); restTimeoutRef.current = setTimeout(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); }; - /** What a cursor that wanders inside one row without ever resting is given instead. Only entering a row restarts it. */ + /** The cap for a cursor that wanders inside one row without resting. */ const waitForRowAllowance = () => { clearTimeout(rowAllowanceTimeoutRef.current); rowAllowanceTimeoutRef.current = setTimeout(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY); @@ -189,9 +182,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps waitForRowAllowance(); }; - // Where the cursor was when it last counted as moving. Distance is measured from there rather than from the previous - // event, so a shaking hand stays within HOVER_INTENT_REST_RADIUS_PX of one point while a slow crossing does not. The - // anchor marks where the cursor last moved, not which row it is over, so entering a row does not reset it. + // Where the cursor last counted as moving; a hand shaking within the rest radius does not restart the wait. const restAnchorRef = useRef<{x: number; y: number} | null>(null); const trackPointerMovement = (event: {clientX: number; clientY: number}) => { const anchor = restAnchorRef.current; @@ -217,7 +208,6 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps markShownFilterReady(); }; - // Only the contact-list filters withhold anything; every other content is ready as soon as it is mounted. const mayDeriveContent = (filterKey: SearchFilter['key']) => !DEFERRED_CONTENT_FILTERS.has(filterKey) || readyFilters.includes(filterKey); return ( @@ -238,16 +228,15 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps style={[styles.filterContentContainer]} > {mountedFilters.map((filterKey) => ( - // A backgrounded content stays mounted with the filter values frozen at its last visit, so moving - // between filters neither re-renders it nor loses its state. `Activity` takes it out of layout and - // unmounts its effects while it is hidden, so it holds no Onyx subscriptions until it is shown again. + // `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/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index 0a14b1650c8c..89a800f4468d 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -334,8 +334,7 @@ function BaseSelectionListImpl({ // A hidden `` subtree keeps its state but unmounts its effects, so this runs again when the list is // revealed. Its container loses the scroll position while the rendered window still describes the old offset, which - // leaves the visible area blank until something scrolls it; scrolling back to the reported offset realigns them. - // The ref rather than the mount: this component stays mounted while it is hidden, which is the whole premise here. + // leaves the visible area blank until scrolling back to the reported offset realigns them. const hasEffectRunRef = useRef(false); useEffect(() => { // The first run is the real mount, where the list is already where it belongs. @@ -347,7 +346,7 @@ function BaseSelectionListImpl({ // Read here rather than in the frame below: the scroll reported on being revealed reaches the list first and // would leave it reporting the top it was reset to. const listOffset = listRef.current?.getAbsoluteLastScrollOffset(); - // A list sitting at the top has nothing to restore, and skipping the scroll keeps revealing one as cheap as before. + // A list sitting at the top has nothing to restore. if (!listOffset) { return; } diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index b8b5243e691b..9d89537cf282 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -107,9 +107,7 @@ const createReportAttributesSelector = /** * 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 because the whole contact list is the expensive case. A consumer narrowing it with - * `includeLoginsOnly` evicts that entry, but both its own build and the next whole-list one are cheap enough to be - * worth the memory saved. + * A single entry is held, so a consumer narrowing the list with `includeLoginsOnly` evicts the whole-list one. */ const memoizedCreateOptionList = memoize(createOptionList, { maxSize: 1, @@ -117,13 +115,12 @@ const memoizedCreateOptionList = memoize(createOptionList, { monitoringName: 'usePersonalDetailOptions.createOptionList', }); -/** Releases the cached options. The next consumer builds them again, so callers pay that price for the memory back. */ +/** Releases the cached options. */ function clearPersonalDetailOptionsCache() { memoizedCreateOptionList.cache.clear(); } -// The cached options describe the signed-in account's contacts, released when Search is left -// (`useReleaseOptionListCaches`) and on sign-out. +// The cached options describe the signed-in account's contacts. registerSessionCleanupCallback(clearPersonalDetailOptionsCache); /** diff --git a/src/hooks/usePersonalDetailSearchSelector/base.ts b/src/hooks/usePersonalDetailSearchSelector/base.ts index 7ec689727a0c..133e1b4bd01c 100644 --- a/src/hooks/usePersonalDetailSearchSelector/base.ts +++ b/src/hooks/usePersonalDetailSearchSelector/base.ts @@ -154,12 +154,9 @@ const defaultListOptions = { /** * How many option lists the caches below hold. Consumers mount one selector at a time, except the Search filters - * popover, which keeps its people filters alive next to each other - three of them, which is the most a single search - * type offers at once (from, to and attendee, on expense searches). Fewer entries cost more than the memory they save: - * the result of `buildSelectedOptions` is an argument of `getValidOptions` compared by identity, so an eviction in the - * first cache makes the second one miss as well. What the entries cost in memory is bounded by - * `useReleaseOptionListCaches`, which drops both caches once another tab takes over from Search, so this number only - * has to cover how many lists are wanted at once rather than how long any of them lives. + * 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; @@ -183,14 +180,13 @@ const memoizedBuildSelectedOptions = memoize(buildSelectedOptions, { monitoringName: 'usePersonalDetailSearchSelector.buildSelectedOptions', }); -/** Releases the cached lists. The next consumer derives them again, so callers pay that price for the memory back. */ +/** Releases the cached lists. */ function clearPersonalDetailSearchSelectorCaches() { memoizedGetValidOptions.cache.clear(); memoizedBuildSelectedOptions.cache.clear(); } -// Both caches hold option lists built for the signed-in account, released when Search is left -// (`useReleaseOptionListCaches`) and on sign-out. +// Both caches hold option lists built for the signed-in account. registerSessionCleanupCallback(clearPersonalDetailSearchSelectorCaches); /** diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index 0fc8179b921d..5c1741c1561c 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -5873,10 +5873,9 @@ function getFilterNegatableValue | undefined) { if (isAmountFilterKey(baseFilterKey)) { @@ -5924,7 +5923,7 @@ function getFilterContentValues(baseFilterKey: SearchFilter['key'], values: Part } as const; } -/** Whether the values the content of `baseFilterKey` reads differ between two versions of the form, so a change to a filter it doesn't read leaves it alone. */ +/** Whether the values the content of `baseFilterKey` reads differ between two versions of the form. */ function hasFilterContentValuesChanged( baseFilterKey: SearchFilter['key'], previousValues: Partial | undefined, diff --git a/src/libs/memoize/cache/types.ts b/src/libs/memoize/cache/types.ts index b33e430194af..53a2bd83e64c 100644 --- a/src/libs/memoize/cache/types.ts +++ b/src/libs/memoize/cache/types.ts @@ -15,7 +15,7 @@ type Cache = { * @returns The value for the key */ getSet: (key: K, valueProducer: () => V) => BoxedValue; - /** Drops every entry, so cached values can be released once they are no longer worth holding */ + /** Drops every entry */ clear: () => void; snapshot: { keys: () => K[]; diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 4beb357fc024..5ddb08df1fd2 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -1,9 +1,7 @@ -import {act, render, screen} from '@testing-library/react-native'; +import {act, render} from '@testing-library/react-native'; import type {SearchQueryJSON} from '@components/Search/types'; -import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; - import CONST from '@src/CONST'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; @@ -16,30 +14,28 @@ const mockUseRef = useRef; const FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; -/** Called once per mounted filter content instance, so a remount shows up as a second call for the same key. */ +/** 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> = {}; -// Handed to the filter list by the popup and captured here, so tests can drive the cursor and read what is highlighted. +// 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: (() => void) | undefined; let mockSelectedFilter: string | undefined; -/** The advanced filters form served by the useOnyx mock. Reassigned by tests simulating filter value changes. */ +/** The form served by the useOnyx mock. Reassigned by tests to change filter values. */ let mockFiltersForm: Partial | undefined; -jest.mock('@components/SafeTriangle', () => ({ - __esModule: true, - default: ({children}: {children: React.ReactNode}) => {children}, -})); - // 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, @@ -60,7 +56,7 @@ jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () = }, })); -// Stand-in for the filter content, which is the expensive part being mounted or kept alive. +// 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}) => { @@ -69,6 +65,7 @@ jest.mock('@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFil isCreated.current = true; mockOnContentCreated(baseFilterKey); } + mockRenderCountByFilter[baseFilterKey] = (mockRenderCountByFilter[baseFilterKey] ?? 0) + 1; mockReadyByFilter[baseFilterKey] = !!ready; mockValuesByFilter[baseFilterKey] = values; @@ -76,8 +73,7 @@ jest.mock('@components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFil }, })); -// One callback for the life of the test: a fresh one per render would defeat the boundary that keeps mounted contents -// from re-rendering, and hide a regression that removed it. +// 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, @@ -89,16 +85,16 @@ jest.mock('@hooks/useOnyx', () => ({ default: () => [mockFiltersForm, {status: 'loaded'}], })); -// The popover exists on web only (index.native.tsx renders nothing), and jest-expo's RN resolver prefers the native variant. +// 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; -// Only forwarded to the mocked query hook, so the parsed query itself does not matter here. -/** Renders the popup again, which is what carries a reassigned form into it while the shown filter stays put. */ +/** Renders the popup again, which carries a reassigned form into it while the shown filter stays put. */ let rerenderPopup: () => void; -const queryJSON = buildSearchQueryJSON(`type:${CONST.SEARCH.DATA_TYPES.EXPENSE}`); +// 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) { @@ -107,7 +103,7 @@ function hover(filterKey: string) { }); } -/** Moves the cursor onto a filter row and leaves it there long enough for what it withheld to be released. */ +/** 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(() => { @@ -122,7 +118,7 @@ function movePointer(clientX: number, clientY: number) { }); } -/** Takes the cursor off the filter list, towards the content pane beside it. */ +/** Takes the cursor off the filter list. */ function leaveList() { act(() => { mockOnPointerLeave?.(); @@ -141,6 +137,7 @@ beforeEach(() => { jest.useFakeTimers(); mockFiltersForm = undefined; mockReadyByFilter = {}; + mockRenderCountByFilter = {}; mockValuesByFilter = {}; const view = render(); rerenderPopup = () => view.rerender(); @@ -153,9 +150,8 @@ afterEach(() => { 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 [row, filterKey] of peopleFilters.entries()) { + for (const filterKey of peopleFilters) { hover(filterKey); - movePointer(100, 100 + row * 30); act(() => { jest.advanceTimersByTime(12); }); @@ -164,7 +160,6 @@ describe('SearchAdvancedFiltersPopup', () => { // 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(mockOnContentCreated).toHaveBeenCalledWith(filterKey); expect(mockReadyByFilter[filterKey]).toBe(false); } @@ -180,7 +175,6 @@ describe('SearchAdvancedFiltersPopup', () => { hover(FILTER_KEYS.STATUS); // No timer is advanced: nothing about this filter is worth waiting for. - expect(mockOnContentCreated).toHaveBeenCalledWith(FILTER_KEYS.STATUS); expect(mockReadyByFilter[FILTER_KEYS.STATUS]).toBe(true); }); @@ -203,8 +197,7 @@ describe('SearchAdvancedFiltersPopup', () => { const step = CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY - 10; let elapsed = 0; let corner = 0; - // Wandering inside the row, always further than the rest radius, so every step restarts the rest wait and only - // the row allowance can end it. + // Wandering further than the rest radius, so every step restarts the rest wait and only the allowance ends it. const wander = () => { act(() => { jest.advanceTimersByTime(step); @@ -231,29 +224,20 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); - it('goes on rendering a hidden content with the values it was last given', () => { + 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 serves a module variable and cannot re-render on its own, so a visit to another row is what - // carries a new form into the popup. + // 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); - // A filter this content does not read changes, so it stays mounted rather than being rebuilt. - mockFiltersForm = {from: ['9'], to: ['1']}; - hoverAndRest(FILTER_KEYS.STATUS); - - expect(mockValuesByFilter[FILTER_KEYS.FROM]).toEqual({from: ['9']}); - }); - - it('hands the shown content the live form rather than the values it was mounted on', () => { - mockFiltersForm = {from: ['9']}; - hoverAndRest(FILTER_KEYS.STATUS); - hoverAndRest(FILTER_KEYS.FROM); - - // The form changes while this filter stays the shown one, so it has to follow rather than hold its snapshot. + // 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']}); }); @@ -262,7 +246,12 @@ describe('SearchAdvancedFiltersPopup', () => { // 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); @@ -282,7 +271,7 @@ describe('SearchAdvancedFiltersPopup', () => { mockFiltersForm = {to: ['1']}; hoverAndRest(FILTER_KEYS.TO); - // The content is revealed as it was left, so state it holds itself - a typed search term - survives. + // 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); }); @@ -291,7 +280,6 @@ describe('SearchAdvancedFiltersPopup', () => { focus(FILTER_KEYS.FROM); // No timer is advanced: moving focus is deliberate and never passes over rows on the way. - expect(screen.getByTestId(`filter-content-${FILTER_KEYS.FROM}`)).toBeTruthy(); expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); }); diff --git a/tests/unit/Search/SearchUIUtilsTest.ts b/tests/unit/Search/SearchUIUtilsTest.ts index 283911c376ef..111446c9906a 100644 --- a/tests/unit/Search/SearchUIUtilsTest.ts +++ b/tests/unit/Search/SearchUIUtilsTest.ts @@ -12821,7 +12821,7 @@ describe('getSavedSearchIconName', () => { }); describe('hasFilterContentValuesChanged', () => { - const FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; + const SYNTAX_FILTER_KEYS = CONST.SEARCH.SYNTAX_FILTER_KEYS; type FilterKey = Parameters[0]; type FilterValues = Parameters[1]; type ContentValuesCase = { @@ -12834,86 +12834,81 @@ describe('hasFilterContentValuesChanged', () => { /** Two forms differing only in something that content reads. */ read: [FilterValues, FilterValues]; - /** Two forms differing only in something it does not. */ - ignored: [FilterValues, FilterValues]; + /** Two forms differing only in something it does not, where there is such a thing. */ + ignored?: [FilterValues, FilterValues]; }; - it('reports no change when handed the same form twice', () => { - const values = {[FILTER_KEYS.FROM]: ['1']}; - - expect(SearchUIUtils.hasFilterContentValuesChanged(FILTER_KEYS.FROM, values, values)).toBe(false); - }); - - // One case per kind of content, because each is handed a different slice of the form and a filter that reads a - // slice must not be rebuilt for a change outside it. + // One case per kind of content, because each is handed a different slice of the form. const contentValuesCases: ContentValuesCase[] = [ { kind: 'list', - filterKey: FILTER_KEYS.FROM, - read: [{[FILTER_KEYS.FROM]: ['1']}, {[FILTER_KEYS.FROM]: ['2']}], - ignored: [{[FILTER_KEYS.FROM]: ['1']}, {[FILTER_KEYS.FROM]: ['1'], [FILTER_KEYS.TO]: ['2']}], + 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: FILTER_KEYS.FROM, - // Built the way the content builds it, so the negated key cannot drift from what the comparator reads. - read: [SearchQueryUtils.getFilterFormValues(FILTER_KEYS.FROM, ['1'], false), SearchQueryUtils.getFilterFormValues(FILTER_KEYS.FROM, ['1'], true)], - ignored: [{[FILTER_KEYS.FROM]: ['1']}, {[FILTER_KEYS.FROM]: ['1'], [FILTER_KEYS.CATEGORY]: ['food']}], + 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: FILTER_KEYS.CATEGORY, + filterKey: SYNTAX_FILTER_KEYS.CATEGORY, read: [{type: CONST.SEARCH.DATA_TYPES.EXPENSE}, {type: CONST.SEARCH.DATA_TYPES.INVOICE}], - ignored: [{type: CONST.SEARCH.DATA_TYPES.EXPENSE}, {type: CONST.SEARCH.DATA_TYPES.EXPENSE, [FILTER_KEYS.KEYWORD]: 'a'}], }, { kind: 'list, reading the workspace that narrows its options', - filterKey: FILTER_KEYS.CATEGORY, - read: [{[FILTER_KEYS.POLICY_ID]: ['1']}, {[FILTER_KEYS.POLICY_ID]: ['2']}], - ignored: [{[FILTER_KEYS.POLICY_ID]: ['1']}, {[FILTER_KEYS.POLICY_ID]: ['1'], [FILTER_KEYS.MERCHANT]: 'a'}], + filterKey: SYNTAX_FILTER_KEYS.CATEGORY, + read: [{[SYNTAX_FILTER_KEYS.POLICY_ID]: ['1']}, {[SYNTAX_FILTER_KEYS.POLICY_ID]: ['2']}], }, { kind: 'text', - filterKey: FILTER_KEYS.MERCHANT, - read: [{[FILTER_KEYS.MERCHANT]: 'a'}, {[FILTER_KEYS.MERCHANT]: 'b'}], - ignored: [{[FILTER_KEYS.MERCHANT]: 'a'}, {[FILTER_KEYS.MERCHANT]: 'a', [FILTER_KEYS.DESCRIPTION]: 'b'}], + filterKey: SYNTAX_FILTER_KEYS.MERCHANT, + read: [{[SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, {[SYNTAX_FILTER_KEYS.MERCHANT]: 'b'}], + ignored: [{[SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, {[SYNTAX_FILTER_KEYS.MERCHANT]: 'a', [SYNTAX_FILTER_KEYS.DESCRIPTION]: 'b'}], }, { kind: 'amount', - filterKey: FILTER_KEYS.AMOUNT, - read: [{[`${FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10'}, {[`${FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '20'}], + 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: [ - {[`${FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10'}, - {[`${FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10', [FILTER_KEYS.MERCHANT]: 'a'}, + {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10'}, + {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10', [SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, ], }, { kind: 'date', - filterKey: FILTER_KEYS.DATE, - read: [{[`${FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01'}, {[`${FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-02-01'}], + 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: [ - {[`${FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01'}, - {[`${FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01', [FILTER_KEYS.MERCHANT]: 'a'}, + {[`${SYNTAX_FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01'}, + {[`${SYNTAX_FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01', [SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, ], }, { // 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: FILTER_KEYS.DATE, - read: [{}, {[FILTER_KEYS.FEED]: ['1']}], - ignored: [{[FILTER_KEYS.FEED]: ['1']}, {[FILTER_KEYS.FEED]: ['2']}], + 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: FILTER_KEYS.REPORT_FIELD, - read: [{[FILTER_KEYS.MERCHANT]: 'a'}, {[FILTER_KEYS.MERCHANT]: 'b'}], - ignored: [{[FILTER_KEYS.MERCHANT]: 'a'}, {[FILTER_KEYS.MERCHANT]: 'a'}], + 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); - expect(SearchUIUtils.hasFilterContentValuesChanged(filterKey, ignored.at(0), ignored.at(1))).toBe(false); + + 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 index f6b658d88e97..ab91e9226f50 100644 --- a/tests/unit/useReleaseOptionListCachesTest.ts +++ b/tests/unit/useReleaseOptionListCachesTest.ts @@ -65,13 +65,16 @@ beforeEach(() => { describe('useReleaseOptionListCaches', () => { it('releases the cached lists when another tab takes over from Search', () => { - renderReleaseHook(); + 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', () => { From 4acd75e63347372f32d3759ab01e2f15c87dcc8d Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Thu, 3 Sep 2026 10:34:19 +0200 Subject: [PATCH 21/30] reveal a filter list as it was built rather than as it was left Drops the per-row wait cap and compares the form values a pane reads directly. --- src/CONST/index.ts | 6 -- .../SearchAdvancedFiltersContent.tsx | 63 +++++++++------- .../Search/FilterComponents/MultiSelect.tsx | 1 + .../Search/FilterComponents/SingleSelect.tsx | 1 + .../Search/FilterComponents/UserSelector.tsx | 1 + .../SearchAdvancedFiltersPopup/index.tsx | 15 +--- .../SelectionList/BaseSelectionList.tsx | 45 ++++++------ src/components/SelectionList/types.ts | 3 + src/libs/SearchUIUtils.ts | 71 ++++++------------- tests/unit/BaseSelectionListTest.tsx | 70 ++++++++++++++---- .../Search/SearchAdvancedFiltersPopupTest.tsx | 24 ------- 11 files changed, 147 insertions(+), 153 deletions(-) diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 230dc50cac9e..7697ed768789 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2140,12 +2140,6 @@ const CONST = { /** 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, - /** - * How long after entering an advanced filter row its content may derive the contact list even if the cursor - * never came to rest. Measured from entering a row, so only entering one restarts it. - */ - SEARCH_FILTER_HOVER_INTENT_MAX_DELAY: 400, - RESIZE_DEBOUNCE_TIME: 100, UNREAD_UPDATE_DEBOUNCE_TIME: 300, USE_DEBOUNCED_STATE_DELAY: 300, diff --git a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx index aa9699e653c4..586835b5a9e8 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/SearchAdvancedFiltersContent.tsx @@ -1,7 +1,7 @@ import type {ListFilterContentProps} from '@components/Search/FilterComponents/ListFilterContent'; import {getFilterFormValues} from '@libs/SearchQueryUtils'; -import {getFilterContentValues} from '@libs/SearchUIUtils'; +import {getFilterNegatableValue, isAmountFilterKey, isDateFilterKey, isTextFilterKey} from '@libs/SearchUIUtils'; import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; @@ -37,21 +37,23 @@ type SearchAdvancedFiltersContentProps = { }; function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, onChange}: SearchAdvancedFiltersContentProps) { - const contentValues = getFilterContentValues(baseFilterKey, values); - - if (contentValues.kind === 'amount') { + if (isAmountFilterKey(baseFilterKey)) { const AmountFilter = components.Amount; return ( ); } - if (contentValues.kind === 'date') { + if (isDateFilterKey(baseFilterKey)) { const DateFilter = components.Date; const onModifier = CONST.SEARCH.DATE_MODIFIERS.ON; const afterModifier = CONST.SEARCH.DATE_MODIFIERS.AFTER; @@ -60,10 +62,15 @@ function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, return ( onChange({ [`${baseFilterKey}${onModifier}`]: newValues[onModifier], @@ -76,40 +83,42 @@ function SearchAdvancedFiltersContent({baseFilterKey, values, ready, components, ); } - if (contentValues.kind === 'reportField') { + if (baseFilterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.REPORT_FIELD) { const ReportFieldFilter = components.ReportField; return ( ); } - if (contentValues.kind === 'text') { + if (isTextFilterKey(baseFilterKey)) { + const {isNegated, value} = getFilterNegatableValue(baseFilterKey, values); const TextFilter = components.Text; return ( onChange(getFilterFormValues(contentValues.baseFilterKey, newValue, negated))} + key={baseFilterKey} + baseFilterKey={baseFilterKey} + value={value} + isNegated={isNegated} + onChange={(newValue, negated) => onChange(getFilterFormValues(baseFilterKey, newValue, negated))} /> ); } + const {isNegated, value} = getFilterNegatableValue(baseFilterKey, values); const ListFilter = components.List; return ( onChange(getFilterFormValues(contentValues.baseFilterKey, newValue, negated))} + isNegated={isNegated} + onChange={(newValue, negated) => onChange(getFilterFormValues(baseFilterKey, newValue, negated))} /> ); } diff --git a/src/components/Search/FilterComponents/MultiSelect.tsx b/src/components/Search/FilterComponents/MultiSelect.tsx index abec90f3894b..2b957d1aee77 100644 --- a/src/components/Search/FilterComponents/MultiSelect.tsx +++ b/src/components/Search/FilterComponents/MultiSelect.tsx @@ -144,6 +144,7 @@ function MultiSelect({ ListItem={MultiSelectListItem} onSelectRow={updateSelectedItems} textInputOptions={textInputOptions} + shouldClearInputWhenHidden style={{contentContainerStyle: [styles.pb0], ...selectionListStyle}} footerContent={footer} /> diff --git a/src/components/Search/FilterComponents/SingleSelect.tsx b/src/components/Search/FilterComponents/SingleSelect.tsx index 2ceb55945f54..5eb1b4063c5d 100644 --- a/src/components/Search/FilterComponents/SingleSelect.tsx +++ b/src/components/Search/FilterComponents/SingleSelect.tsx @@ -144,6 +144,7 @@ function SingleSelectImpl({ ListItem={SingleSelectListItem} onSelectRow={updateSelectedItem} textInputOptions={textInputOptions} + shouldClearInputWhenHidden style={{ contentContainerStyle: [styles.pb0], ...selectionListStyle, diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index 18c098c3c5c9..f855f2614104 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -142,6 +142,7 @@ function UserSelector({value = [], isNegatable, policyID, selectionListTextInput | undefined>(undefined); - const rowAllowanceTimeoutRef = useRef | undefined>(undefined); - const cancelReadyWaits = () => { - clearTimeout(restTimeoutRef.current); - clearTimeout(rowAllowanceTimeoutRef.current); - }; - // Drops both waits when the popover closes. + const cancelReadyWaits = () => clearTimeout(restTimeoutRef.current); + // Drops the wait when the popover closes. useEffect(() => cancelReadyWaits, []); /** Restarted by every movement, so it elapses only once the cursor has come to rest. */ @@ -170,16 +166,9 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps restTimeoutRef.current = setTimeout(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); }; - /** The cap for a cursor that wanders inside one row without resting. */ - const waitForRowAllowance = () => { - clearTimeout(rowAllowanceTimeoutRef.current); - rowAllowanceTimeoutRef.current = setTimeout(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY); - }; - const hoverFilter = (filterKey: SearchFilter['key']) => { showFilter(filterKey); waitForCursorToRest(); - waitForRowAllowance(); }; // Where the cursor last counted as moving; a hand shaking within the rest radius does not restart the wait. diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index 89a800f4468d..0133e650a185 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -12,7 +12,7 @@ import type {FlashListRef, ListRenderItem, ListRenderItemInfo} from '@shopify/fl import {useIsFocused} from '@react-navigation/native'; import {FlashList} from '@shopify/flash-list'; import {deepEqual} from 'fast-equals'; -import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useEffectEvent, useImperativeHandle, useMemo, useRef, useState} from 'react'; import {Keyboard, View} from 'react-native'; import type {DataDetailsType, ListItem, SelectionListProps} from './types'; @@ -97,6 +97,7 @@ function BaseSelectionListImpl({ shouldPreventDefaultFocusOnSelectRow = false, shouldShowTextInput: shouldShowTextInputProp, shouldClearInputOnSelect = false, + shouldClearInputWhenHidden = false, shouldHighlightSelectedItem, shouldDisableHoverStyle = false, selectionButtonPosition, @@ -118,6 +119,8 @@ function BaseSelectionListImpl({ const keyboardListenerRef = useRef | null>(null); const initialFocusedIndex = useMemo(() => data.findIndex((i) => i.keyForList === initiallyFocusedItemKey), [data, initiallyFocusedItemKey]); + // Part of the list's key, so a bump replaces the recycler. + const [revealedListVersion, setRevealedListVersion] = useState(0); const [itemsToHighlight, setItemsToHighlight] = useState | null>(null); const isItemSelected = useCallback( @@ -332,30 +335,31 @@ function BaseSelectionListImpl({ const scrollTimeoutRef = useRef(null); - // A hidden `` subtree keeps its state but unmounts its effects, so this runs again when the list is - // revealed. Its container loses the scroll position while the rendered window still describes the old offset, which - // leaves the visible area blank until scrolling back to the reported offset realigns them. - const hasEffectRunRef = useRef(false); - useEffect(() => { - // The first run is the real mount, where the list is already where it belongs. - if (!hasEffectRunRef.current) { - hasEffectRunRef.current = true; + /** Reads the current props, so a list hidden long after it was mounted drops what it was filtered by by then. */ + const clearTextInput = useEffectEvent(() => { + if (!shouldClearInputWhenHidden || !textInputOptions?.value) { return; } - // Read here rather than in the frame below: the scroll reported on being revealed reaches the list first and - // would leave it reporting the top it was reset to. - const listOffset = listRef.current?.getAbsoluteLastScrollOffset(); - // A list sitting at the top has nothing to restore. - if (!listOffset) { - return; - } + textInputOptions.onChangeText?.(''); + }); - const animationFrameID = requestAnimationFrame(() => { - listRef.current?.scrollToOffset({offset: listOffset, animated: false}); - }); + // A hidden `` subtree keeps its state but unmounts its effects, so this runs again when the list is + // revealed and its cleanup runs as the list is hidden. + const hasEffectRunRef = useRef(false); + useEffect(() => { + // A revealed list starts at the top. Its container lost the scroll position while hidden while the recycler + // still reports the offset it was left at, which is what leaves the visible area blank. The recycler takes an + // offset only from a scroll event, and scrolling to a top it already sits at produces none, so it is replaced + // rather than scrolled: a new one starts where its container is. The first run is the real mount. + if (hasEffectRunRef.current && listRef.current?.getAbsoluteLastScrollOffset()) { + setRevealedListVersion((version) => version + 1); + } + hasEffectRunRef.current = true; - return () => cancelAnimationFrame(animationFrameID); + // Cleared as the list is hidden rather than as it is revealed: the debounce behind the input elapses while + // nobody is looking, and the list it leaves behind is the one the reveal replaces. + return () => clearTextInput(); }, []); useEffect(() => { @@ -528,6 +532,7 @@ function BaseSelectionListImpl({ <> {!shouldHeaderBeInsideList && header} = { /** Whether to clear the text input when a row is selected */ shouldClearInputOnSelect?: boolean; + /** Whether to clear the text input when an `` hides the list, so it is revealed as it was built */ + shouldClearInputWhenHidden?: boolean; + /** Whether hover style should be disabled */ shouldDisableHoverStyle?: boolean; diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts index 5c1741c1561c..73e49a9f8f4a 100644 --- a/src/libs/SearchUIUtils.ts +++ b/src/libs/SearchUIUtils.ts @@ -5872,68 +5872,44 @@ function getFilterNegatableValue | undefined) { +/** Whether the values the content of `baseFilterKey` reads differ between two versions of the form. */ +function hasFilterContentValuesChanged( + baseFilterKey: SearchFilter['key'], + previousValues: Partial | undefined, + values: Partial | undefined, +): boolean { + if (previousValues === values) { + return false; + } + if (isAmountFilterKey(baseFilterKey)) { - return { - kind: 'amount', - baseFilterKey, - value: { - [CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO]: values?.[`${baseFilterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.EQUAL_TO}`], - [CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN]: values?.[`${baseFilterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`], - [CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN]: values?.[`${baseFilterKey}${CONST.SEARCH.AMOUNT_MODIFIERS.LESS_THAN}`], - }, - } as const; + 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)) { - return { - kind: 'date', - baseFilterKey, - value: { - [CONST.SEARCH.DATE_MODIFIERS.ON]: values?.[`${baseFilterKey}${CONST.SEARCH.DATE_MODIFIERS.ON}`], - [CONST.SEARCH.DATE_MODIFIERS.AFTER]: values?.[`${baseFilterKey}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`], - [CONST.SEARCH.DATE_MODIFIERS.BEFORE]: values?.[`${baseFilterKey}${CONST.SEARCH.DATE_MODIFIERS.BEFORE}`], - [CONST.SEARCH.DATE_MODIFIERS.RANGE]: values?.[`${baseFilterKey}${CONST.SEARCH.DATE_MODIFIERS.RANGE}`], - }, - hasFeed: !!values?.feed, - } as const; + 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 {kind: 'reportField', values} as const; + return !deepEqual(previousValues, values); } - if (isTextFilterKey(baseFilterKey)) { - return {kind: 'text', baseFilterKey, negatable: getFilterNegatableValue(baseFilterKey, values)} as const; + if (!deepEqual(getFilterNegatableValue(baseFilterKey, previousValues), getFilterNegatableValue(baseFilterKey, values))) { + return true; } - // A list content also reads the search type and the workspace filter, which decide the options it offers. - return { - kind: 'list', - baseFilterKey, - negatable: getFilterNegatableValue(baseFilterKey, values), - type: values?.type, - policyID: getFilterNegatableValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID, values), - } as const; -} - -/** Whether the values the content of `baseFilterKey` reads differ between two versions of the form. */ -function hasFilterContentValuesChanged( - baseFilterKey: SearchFilter['key'], - previousValues: Partial | undefined, - values: Partial | undefined, -): boolean { - if (previousValues === values) { + if (isTextFilterKey(baseFilterKey)) { return false; } - return !deepEqual(getFilterContentValues(baseFilterKey, previousValues), getFilterContentValues(baseFilterKey, values)); + // 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) { @@ -7094,7 +7070,6 @@ export { adjustTimeRangeToDateFilters, getDateDisplayValue, getDisplayValue, - getFilterContentValues, getFilterNegatableValue, hasFilterContentValuesChanged, shouldShowFilter, diff --git a/tests/unit/BaseSelectionListTest.tsx b/tests/unit/BaseSelectionListTest.tsx index d33abd253b8d..71cefd29fc7d 100644 --- a/tests/unit/BaseSelectionListTest.tsx +++ b/tests/unit/BaseSelectionListTest.tsx @@ -1,4 +1,4 @@ -import {fireEvent, render, screen, waitFor} from '@testing-library/react-native'; +import {fireEvent, render, screen} from '@testing-library/react-native'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; import BaseSelectionList from '@components/SelectionList/BaseSelectionList'; @@ -19,6 +19,8 @@ import React, {Activity, useState} from 'react'; const mockScrollToIndex = jest.fn(); const mockScrollToOffset = jest.fn(); const mockGetAbsoluteLastScrollOffset = jest.fn(() => 0); +// Called once per mounted list, so a test can tell a revealed list from a replaced one +const mockListMount = jest.fn(); // Mock FlashList jest.mock('@shopify/flash-list', () => { @@ -58,6 +60,10 @@ jest.mock('@shopify/flash-list', () => { }, ref, ) => { + ReactLocal.useState(() => { + mockListMount(); + return null; + }); ReactLocal.useImperativeHandle(ref, () => ({ scrollToIndex: mockScrollToIndex, scrollToOffset: mockScrollToOffset, @@ -137,6 +143,7 @@ describe('BaseSelectionList', () => { onSelectRowMock.mockClear(); mockScrollToIndex.mockClear(); mockScrollToOffset.mockClear(); + mockListMount.mockClear(); mockGetAbsoluteLastScrollOffset.mockReturnValue(0); mockIsFocusRestoreInProgress.mockReturnValue(false); }); @@ -157,6 +164,7 @@ describe('BaseSelectionList', () => { onSelectRow={onSelectRowMock} shouldSingleExecuteRowSelect shouldShowTextInput={!!setSearchText} + shouldClearInputWhenHidden canSelectMultiple={canSelectMultiple} initiallyFocusedItemKey={focusedKey} isDisabled={isDisabled} @@ -165,34 +173,66 @@ describe('BaseSelectionList', () => { ); } - function ActivitySelectionListRenderer({mode}: {mode: 'visible' | 'hidden'}) { + function ActivitySelectionListRenderer({mode, searchText, setSearchText}: {mode: 'visible' | 'hidden'; searchText?: string; setSearchText?: (text: string) => void}) { return ( - + ); } - it('scrolls back to the offset it reports when it is revealed from a hidden Activity', async () => { + it('replaces the list it reveals from a hidden Activity only when it was left scrolled', () => { jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); - // The offset is read as the list is revealed and reported as zero afterwards, so a read taken a frame later - // would restore the top the list was reset to rather than where it was. - mockGetAbsoluteLastScrollOffset.mockReturnValueOnce(1200).mockReturnValue(0); const {rerender} = render(); - - // A list that was just mounted starts where it starts, so nothing scrolls it. The frame has to pass first, - // otherwise this holds whether or not the mount is skipped. Nothing here sets state, so no act is needed. - jest.advanceTimersByTime(32); - expect(mockScrollToOffset).not.toHaveBeenCalled(); + expect(mockListMount).toHaveBeenCalledTimes(1); // Hiding the list unmounts its effects and drops its layout, and revealing it runs them again. rerender(); rerender(); - await waitFor(() => { - expect(mockScrollToOffset).toHaveBeenCalledWith({offset: 1200, animated: false}); - }); + // A list left at the top is revealed as it was, which is what keeps a revisit cheap. + expect(mockListMount).toHaveBeenCalledTimes(1); + + // The offset is read as the list is revealed and reported as zero afterwards, so it is read there. + mockGetAbsoluteLastScrollOffset.mockReturnValueOnce(1200).mockReturnValue(0); + rerender(); + rerender(); + + // A recycler takes an offset only from a scroll event, so the one left at 1200 is replaced rather than scrolled. + expect(mockListMount).toHaveBeenCalledTimes(2); + expect(mockScrollToOffset).not.toHaveBeenCalled(); + }); + + it('drops what the list was filtered by as it is hidden', () => { + jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); + const setSearchText = jest.fn(); + + const {rerender} = render( + , + ); + // A list is mounted with whatever it is given, so nothing is cleared until it is hidden. + expect(setSearchText).not.toHaveBeenCalled(); + + // Cleared here rather than on the way back, so the debounce behind the input elapses while the list is hidden + // and the data it is revealed with is the data it is replaced against. + rerender( + , + ); + + expect(setSearchText).toHaveBeenCalledWith(''); }); it('should not trigger item press if screen is not focused', () => { diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 5ddb08df1fd2..1e514b07621d 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -193,30 +193,6 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); - it('releases a row the cursor never rests on once its per-row allowance elapses', () => { - const step = CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY - 10; - let elapsed = 0; - let corner = 0; - // Wandering further than the rest radius, so every step restarts the rest wait and only the allowance ends it. - const wander = () => { - act(() => { - jest.advanceTimersByTime(step); - }); - elapsed += step; - corner += 1; - movePointer(100 + (corner % 2) * 30, 100); - }; - - hover(FILTER_KEYS.FROM); - while (elapsed < CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_MAX_DELAY - step) { - wander(); - } - expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(false); - - wander(); - expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); - }); - it('releases the row the cursor left from when it leaves the list without settling', () => { hover(FILTER_KEYS.FROM); leaveList(); From cb36f2c48a8395aa7e71a6bff267f50afcfc5060 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Thu, 3 Sep 2026 12:01:25 +0200 Subject: [PATCH 22/30] reset a revealed filter list from one place, so the section lists get it too Drops the prop from a single select that is never searchable in the filters. --- src/CONST/index.ts | 1 - .../FilterComponents/BankAccountSelector.tsx | 1 + .../Search/FilterComponents/CardSelector.tsx | 1 + .../Search/FilterComponents/InSelector.tsx | 1 + .../Search/FilterComponents/SingleSelect.tsx | 1 - .../FilterComponents/WorkspaceSelector.tsx | 1 + .../SearchAdvancedFiltersPopup/index.tsx | 14 +++---- .../SelectionList/BaseSelectionList.tsx | 28 +++----------- .../BaseSelectionListWithSections.tsx | 13 +++++++ .../hooks/useRevealedListReset.ts | 37 +++++++++++++++++++ tests/unit/BaseSelectionListTest.tsx | 24 +++++++----- tests/unit/Search/SearchUIUtilsTest.ts | 7 ++-- 12 files changed, 85 insertions(+), 44 deletions(-) create mode 100644 src/components/SelectionList/hooks/useRevealedListReset.ts diff --git a/src/CONST/index.ts b/src/CONST/index.ts index 7697ed768789..6cfe1c7a4277 100644 --- a/src/CONST/index.ts +++ b/src/CONST/index.ts @@ -2139,7 +2139,6 @@ const CONST = { 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, diff --git a/src/components/Search/FilterComponents/BankAccountSelector.tsx b/src/components/Search/FilterComponents/BankAccountSelector.tsx index 4b26b94c6c4b..b653e7aefac1 100644 --- a/src/components/Search/FilterComponents/BankAccountSelector.tsx +++ b/src/components/Search/FilterComponents/BankAccountSelector.tsx @@ -181,6 +181,7 @@ function BankAccountSelector({value = [], selectionListTextInputStyle, selection shouldPreventDefaultFocusOnSelectRow={false} shouldShowTextInput={shouldShowSearchInput} textInputOptions={textInputOptions} + shouldClearInputWhenHidden shouldStopPropagation canSelectMultiple shouldClearInputOnSelect={false} diff --git a/src/components/Search/FilterComponents/CardSelector.tsx b/src/components/Search/FilterComponents/CardSelector.tsx index f49bff3b9ce3..f05984367f1e 100644 --- a/src/components/Search/FilterComponents/CardSelector.tsx +++ b/src/components/Search/FilterComponents/CardSelector.tsx @@ -160,6 +160,7 @@ function CardSelector({value = [], selectionListTextInputStyle, selectionListSty shouldPreventDefaultFocusOnSelectRow={false} shouldShowTextInput={shouldShowSearchInput} textInputOptions={textInputOptions} + shouldClearInputWhenHidden shouldStopPropagation canSelectMultiple shouldClearInputOnSelect={false} diff --git a/src/components/Search/FilterComponents/InSelector.tsx b/src/components/Search/FilterComponents/InSelector.tsx index acfae321da0d..a91d804d1304 100644 --- a/src/components/Search/FilterComponents/InSelector.tsx +++ b/src/components/Search/FilterComponents/InSelector.tsx @@ -230,6 +230,7 @@ function InSelector({value = [], selectionListTextInputStyle, selectionListStyle shouldPreventAutoScrollOnSelect shouldPreventDefaultFocusOnSelectRow={!canUseTouchScreen()} textInputOptions={textInputOptions} + shouldClearInputWhenHidden isLoadingNewOptions={isLoadingNewOptions} shouldShowLoadingPlaceholder={shouldShowLoadingPlaceholder} shouldShowTextInput diff --git a/src/components/Search/FilterComponents/SingleSelect.tsx b/src/components/Search/FilterComponents/SingleSelect.tsx index 5eb1b4063c5d..2ceb55945f54 100644 --- a/src/components/Search/FilterComponents/SingleSelect.tsx +++ b/src/components/Search/FilterComponents/SingleSelect.tsx @@ -144,7 +144,6 @@ function SingleSelectImpl({ ListItem={SingleSelectListItem} onSelectRow={updateSelectedItem} textInputOptions={textInputOptions} - shouldClearInputWhenHidden style={{ contentContainerStyle: [styles.pb0], ...selectionListStyle, diff --git a/src/components/Search/FilterComponents/WorkspaceSelector.tsx b/src/components/Search/FilterComponents/WorkspaceSelector.tsx index c7ce27e27941..2a9651598ada 100644 --- a/src/components/Search/FilterComponents/WorkspaceSelector.tsx +++ b/src/components/Search/FilterComponents/WorkspaceSelector.tsx @@ -223,6 +223,7 @@ function WorkspaceSelector({value = [], selectionListTextInputStyle, selectionLi shouldShowTextInput={shouldShowWorkspaceSearchInput} shouldShowLoadingPlaceholder={isLoadingOnyxValue(policiesResult) || !ready} textInputOptions={textInputOptions} + shouldClearInputWhenHidden shouldStopPropagation canSelectMultiple shouldSingleExecuteRowSelect diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 0f8f8a17ff92..37111cbc0c00 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -38,10 +38,10 @@ type MountedFilterState = { mountedFilters: Array; /** The filter values each mounted instance was built from. A revisit compares against it. */ - formAtMount: Partial | undefined>>; + formAtMount: Partial>>; /** The filter values each content was last shown with. It goes on rendering with them while hidden. */ - formWhileHidden: Partial | undefined>>; + formWhileHidden: Partial>>; /** How many times each content has been remounted. Part of its key, so a bump replaces the instance. */ contentVersions: Partial>; @@ -156,13 +156,13 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }); }; const restTimeoutRef = useRef | undefined>(undefined); - const cancelReadyWaits = () => clearTimeout(restTimeoutRef.current); + const cancelReadyWait = () => clearTimeout(restTimeoutRef.current); // Drops the wait when the popover closes. - useEffect(() => cancelReadyWaits, []); + useEffect(() => cancelReadyWait, []); /** Restarted by every movement, so it elapses only once the cursor has come to rest. */ const waitForCursorToRest = () => { - clearTimeout(restTimeoutRef.current); + cancelReadyWait(); restTimeoutRef.current = setTimeout(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); }; @@ -185,14 +185,14 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps // Nothing is left to wait for once the cursor is gone, so whatever the row it ended on was withholding is released. const stopTrackingPointer = () => { - cancelReadyWaits(); + cancelReadyWait(); restAnchorRef.current = null; 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']) => { - cancelReadyWaits(); + cancelReadyWait(); showFilter(filterKey); markShownFilterReady(); }; diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index 0133e650a185..15454c90f384 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -12,7 +12,7 @@ import type {FlashListRef, ListRenderItem, ListRenderItemInfo} from '@shopify/fl import {useIsFocused} from '@react-navigation/native'; import {FlashList} from '@shopify/flash-list'; import {deepEqual} from 'fast-equals'; -import React, {useCallback, useEffect, useEffectEvent, useImperativeHandle, useMemo, useRef, useState} from 'react'; +import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react'; import {Keyboard, View} from 'react-native'; import type {DataDetailsType, ListItem, SelectionListProps} from './types'; @@ -21,6 +21,7 @@ import Footer from './components/Footer'; import ListHeader from './components/ListHeader'; import SelectionListEmptyState from './components/SelectionListEmptyState'; import TextInput from './components/TextInput'; +import useRevealedListReset from './hooks/useRevealedListReset'; import useSearchFocusSync from './hooks/useSearchFocusSync'; import useSelectedItemFocusSync from './hooks/useSelectedItemFocusSync'; import useSelectionListKeyboardFocus from './hooks/useSelectionListKeyboardFocus'; @@ -119,8 +120,6 @@ function BaseSelectionListImpl({ const keyboardListenerRef = useRef | null>(null); const initialFocusedIndex = useMemo(() => data.findIndex((i) => i.keyForList === initiallyFocusedItemKey), [data, initiallyFocusedItemKey]); - // Part of the list's key, so a bump replaces the recycler. - const [revealedListVersion, setRevealedListVersion] = useState(0); const [itemsToHighlight, setItemsToHighlight] = useState | null>(null); const isItemSelected = useCallback( @@ -335,8 +334,9 @@ function BaseSelectionListImpl({ const scrollTimeoutRef = useRef(null); - /** Reads the current props, so a list hidden long after it was mounted drops what it was filtered by by then. */ - const clearTextInput = useEffectEvent(() => { + // Cleared as the list is hidden rather than as it is revealed, so the debounce behind the input elapses while + // nobody is looking and the list is revealed with the data it is replaced against. + const revealedListVersion = useRevealedListReset(listRef, () => { if (!shouldClearInputWhenHidden || !textInputOptions?.value) { return; } @@ -344,24 +344,6 @@ function BaseSelectionListImpl({ textInputOptions.onChangeText?.(''); }); - // A hidden `` subtree keeps its state but unmounts its effects, so this runs again when the list is - // revealed and its cleanup runs as the list is hidden. - const hasEffectRunRef = useRef(false); - useEffect(() => { - // A revealed list starts at the top. Its container lost the scroll position while hidden while the recycler - // still reports the offset it was left at, which is what leaves the visible area blank. The recycler takes an - // offset only from a scroll event, and scrolling to a top it already sits at produces none, so it is replaced - // rather than scrolled: a new one starts where its container is. The first run is the real mount. - if (hasEffectRunRef.current && listRef.current?.getAbsoluteLastScrollOffset()) { - setRevealedListVersion((version) => version + 1); - } - hasEffectRunRef.current = true; - - // Cleared as the list is hidden rather than as it is revealed: the debounce behind the input elapses while - // nobody is looking, and the list it leaves behind is the one the reveal replaces. - return () => clearTextInput(); - }, []); - useEffect(() => { return () => { if (keyboardListenerRef.current) { diff --git a/src/components/SelectionList/SelectionListWithSections/BaseSelectionListWithSections.tsx b/src/components/SelectionList/SelectionListWithSections/BaseSelectionListWithSections.tsx index 501e3e25be01..2a0185e25218 100644 --- a/src/components/SelectionList/SelectionListWithSections/BaseSelectionListWithSections.tsx +++ b/src/components/SelectionList/SelectionListWithSections/BaseSelectionListWithSections.tsx @@ -2,6 +2,7 @@ import Footer from '@components/SelectionList/components/Footer'; import SelectionListEmptyState from '@components/SelectionList/components/SelectionListEmptyState'; import TextInput from '@components/SelectionList/components/TextInput'; import useFlattenedSections, {isItemSelected, shouldTreatItemAsDisabled} from '@components/SelectionList/hooks/useFlattenedSections'; +import useRevealedListReset from '@components/SelectionList/hooks/useRevealedListReset'; import useScrollToFocusedInput from '@components/SelectionList/hooks/useScrollToFocusedInput'; import useSearchFocusSync from '@components/SelectionList/hooks/useSearchFocusSync'; import useSelectedItemFocusSync from '@components/SelectionList/hooks/useSelectedItemFocusSync'; @@ -45,6 +46,7 @@ function BaseSelectionListWithSectionsImpl({ ref, ListItem, textInputOptions, + shouldClearInputWhenHidden = false, searchValueForFocusSync, initiallyFocusedItemKey, confirmButtonOptions, @@ -102,6 +104,16 @@ function BaseSelectionListWithSectionsImpl({ const {scrollToIndex, debouncedScrollToIndex} = useSelectionListScroll(listRef, flattenedData); const {containerRef, trackScrollOffset, scrollInputIntoView} = useScrollToFocusedInput(listRef, isKeyboardShown); + // Cleared as the list is hidden rather than as it is revealed, so the debounce behind the input elapses while + // nobody is looking and the list is revealed with the data it is replaced against. + const revealedListVersion = useRevealedListReset(listRef, () => { + if (!shouldClearInputWhenHidden || !textInputOptions?.value) { + return; + } + + textInputOptions.onChangeText?.(''); + }); + const {focusedIndex, setFocusedIndex, isKeyboardNavigating, setHasKeyBeenPressed} = useSelectionListKeyboardFocus({ initialFocusedIndex, maxIndex: flattenedData.length - 1, @@ -327,6 +339,7 @@ function BaseSelectionListWithSectionsImpl({ /> ) : ( number; +}; + +/** + * Keeps a list that can be hidden by an `` looking as it was built. A hidden subtree keeps its state but + * unmounts its effects, so the effect below runs again when the list is revealed and its cleanup runs as it is hidden. + * + * Returns the version to key the list on. A revealed list starts at the top: its container lost the scroll position + * while hidden while the recycler still reports the offset it was left at, which is what leaves the visible area blank. + * The recycler takes an offset only from a scroll event, and scrolling to a top it already sits at produces none, so it + * is replaced rather than scrolled: a new one starts where its container is. + */ +function useRevealedListReset(listRef: RefObject, onHidden: () => void): number { + const [revealedListVersion, setRevealedListVersion] = useState(0); + const runOnHidden = useEffectEvent(onHidden); + const hasEffectRunRef = useRef(false); + + useEffect(() => { + // The first run is the real mount, where the list is where it belongs. + if (hasEffectRunRef.current && listRef.current?.getAbsoluteLastScrollOffset()) { + setRevealedListVersion((version) => version + 1); + } + hasEffectRunRef.current = true; + + return () => runOnHidden(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return revealedListVersion; +} + +export default useRevealedListReset; diff --git a/tests/unit/BaseSelectionListTest.tsx b/tests/unit/BaseSelectionListTest.tsx index 71cefd29fc7d..e4ce21b578af 100644 --- a/tests/unit/BaseSelectionListTest.tsx +++ b/tests/unit/BaseSelectionListTest.tsx @@ -17,7 +17,6 @@ import React, {Activity, useState} from 'react'; // Captures scrollToIndex calls so tests can assert on scroll behaviour const mockScrollToIndex = jest.fn(); -const mockScrollToOffset = jest.fn(); const mockGetAbsoluteLastScrollOffset = jest.fn(() => 0); // Called once per mounted list, so a test can tell a revealed list from a replaced one const mockListMount = jest.fn(); @@ -28,7 +27,7 @@ jest.mock('@shopify/flash-list', () => { const RN = jest.requireActual('react-native'); const FlashList = ReactLocal.forwardRef< - {scrollToIndex: (params: {index: number}) => void; scrollToOffset: (params: {offset: number; animated: boolean}) => void; getAbsoluteLastScrollOffset: () => number}, + {scrollToIndex: (params: {index: number}) => void; getAbsoluteLastScrollOffset: () => number}, Omit, 'children'> & { data?: unknown[]; renderItem?: (info: {item: unknown; index: number; target: string}) => React.ReactNode; @@ -66,7 +65,6 @@ jest.mock('@shopify/flash-list', () => { }); ReactLocal.useImperativeHandle(ref, () => ({ scrollToIndex: mockScrollToIndex, - scrollToOffset: mockScrollToOffset, getAbsoluteLastScrollOffset: mockGetAbsoluteLastScrollOffset, })); @@ -88,6 +86,7 @@ jest.mock('@shopify/flash-list', () => { type BaseSelectionListTestProps = { data: TItem[]; canSelectMultiple?: boolean; + shouldClearInputWhenHidden?: boolean; searchText?: string; setSearchText?: (searchText: string) => void; isDisabled?: boolean; @@ -142,14 +141,13 @@ describe('BaseSelectionList', () => { beforeEach(() => { onSelectRowMock.mockClear(); mockScrollToIndex.mockClear(); - mockScrollToOffset.mockClear(); mockListMount.mockClear(); mockGetAbsoluteLastScrollOffset.mockReturnValue(0); mockIsFocusRestoreInProgress.mockReturnValue(false); }); function SelectionListRenderer(props: BaseSelectionListTestProps) { - const {data, canSelectMultiple, setSearchText, searchText, isDisabled} = props; + const {data, canSelectMultiple, setSearchText, searchText, isDisabled, shouldClearInputWhenHidden} = props; const focusedKey = data.find((item) => item.isSelected)?.keyForList; return ( @@ -164,7 +162,7 @@ describe('BaseSelectionList', () => { onSelectRow={onSelectRowMock} shouldSingleExecuteRowSelect shouldShowTextInput={!!setSearchText} - shouldClearInputWhenHidden + shouldClearInputWhenHidden={shouldClearInputWhenHidden} canSelectMultiple={canSelectMultiple} initiallyFocusedItemKey={focusedKey} isDisabled={isDisabled} @@ -180,6 +178,7 @@ describe('BaseSelectionList', () => { data={mockItems} searchText={searchText} setSearchText={setSearchText} + shouldClearInputWhenHidden /> ); @@ -199,27 +198,34 @@ describe('BaseSelectionList', () => { expect(mockListMount).toHaveBeenCalledTimes(1); // The offset is read as the list is revealed and reported as zero afterwards, so it is read there. - mockGetAbsoluteLastScrollOffset.mockReturnValueOnce(1200).mockReturnValue(0); + mockGetAbsoluteLastScrollOffset.mockReturnValueOnce(1200); rerender(); rerender(); // A recycler takes an offset only from a scroll event, so the one left at 1200 is replaced rather than scrolled. expect(mockListMount).toHaveBeenCalledTimes(2); - expect(mockScrollToOffset).not.toHaveBeenCalled(); }); it('drops what the list was filtered by as it is hidden', () => { jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); const setSearchText = jest.fn(); + // Mounted with an empty input and filtered afterwards, so a hidden list reading the value it was mounted with + // would find nothing to clear. const {rerender} = render( + , + ); + rerender( , ); - // A list is mounted with whatever it is given, so nothing is cleared until it is hidden. expect(setSearchText).not.toHaveBeenCalled(); // Cleared here rather than on the way back, so the debounce behind the input elapses while the list is hidden diff --git a/tests/unit/Search/SearchUIUtilsTest.ts b/tests/unit/Search/SearchUIUtilsTest.ts index 111446c9906a..e41cf0074d8a 100644 --- a/tests/unit/Search/SearchUIUtilsTest.ts +++ b/tests/unit/Search/SearchUIUtilsTest.ts @@ -12866,7 +12866,8 @@ describe('hasFilterContentValuesChanged', () => { kind: 'text', filterKey: SYNTAX_FILTER_KEYS.MERCHANT, read: [{[SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, {[SYNTAX_FILTER_KEYS.MERCHANT]: 'b'}], - ignored: [{[SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, {[SYNTAX_FILTER_KEYS.MERCHANT]: 'a', [SYNTAX_FILTER_KEYS.DESCRIPTION]: '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', @@ -12877,7 +12878,7 @@ describe('hasFilterContentValuesChanged', () => { ], ignored: [ {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10'}, - {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10', [SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, + {[`${SYNTAX_FILTER_KEYS.AMOUNT}${CONST.SEARCH.AMOUNT_MODIFIERS.GREATER_THAN}`]: '10', type: CONST.SEARCH.DATA_TYPES.INVOICE}, ], }, { @@ -12886,7 +12887,7 @@ describe('hasFilterContentValuesChanged', () => { 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', [SYNTAX_FILTER_KEYS.MERCHANT]: 'a'}, + {[`${SYNTAX_FILTER_KEYS.DATE}${CONST.SEARCH.DATE_MODIFIERS.AFTER}`]: '2026-01-01', type: CONST.SEARCH.DATA_TYPES.INVOICE}, ], }, { From 6f18ca9aaea12f72b6055d002c5943efe82c7f38 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Fri, 4 Sep 2026 14:53:57 +0200 Subject: [PATCH 23/30] release a filter row only when the cursor heads for the content, and move the input clearing into the reset hook --- .../AdvancedFilters/FilterList.tsx | 2 +- .../SearchAdvancedFiltersPopup/index.tsx | 13 +++++++++-- .../SelectionList/BaseSelectionList.tsx | 10 +------- .../BaseSelectionListWithSections.tsx | 10 +------- .../hooks/useRevealedListReset.ts | 20 +++++++++++++--- .../Search/SearchAdvancedFiltersPopupTest.tsx | 23 +++++++++++++------ 6 files changed, 47 insertions(+), 31 deletions(-) diff --git a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx index 4d7fa7a47ad3..7bb5576eb503 100644 --- a/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx +++ b/src/components/Search/FilterComponents/AdvancedFilters/FilterList.tsx @@ -43,7 +43,7 @@ type FilterListProps = FilterItemCallbacks & { 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?: () => void; + onPointerLeave?: (event: {clientX: number}) => void; }; type FilterItemProps = FilterItemCallbacks & { diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 37111cbc0c00..937d40a941f5 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -183,10 +183,19 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps waitForCursorToRest(); }; - // Nothing is left to wait for once the cursor is gone, so whatever the row it ended on was withholding is released. - const stopTrackingPointer = () => { + // Nothing is left to wait for once the cursor is gone, so the row it ended on releases what it was withholding, + // but only for a cursor heading toward the content. The direction comes from the last tracked position rather than + // from the exit point alone, because `SafeTriangle` covers that path with an overlay of its own and the cursor + // leaves the list above it as often as through its edge. + const stopTrackingPointer = (event: {clientX: number}) => { cancelReadyWait(); + const anchor = restAnchorRef.current; restAnchorRef.current = null; + + if (anchor && event.clientX <= anchor.x) { + return; + } + markShownFilterReady(); }; diff --git a/src/components/SelectionList/BaseSelectionList.tsx b/src/components/SelectionList/BaseSelectionList.tsx index 15454c90f384..78c385dffd63 100644 --- a/src/components/SelectionList/BaseSelectionList.tsx +++ b/src/components/SelectionList/BaseSelectionList.tsx @@ -334,15 +334,7 @@ function BaseSelectionListImpl({ const scrollTimeoutRef = useRef(null); - // Cleared as the list is hidden rather than as it is revealed, so the debounce behind the input elapses while - // nobody is looking and the list is revealed with the data it is replaced against. - const revealedListVersion = useRevealedListReset(listRef, () => { - if (!shouldClearInputWhenHidden || !textInputOptions?.value) { - return; - } - - textInputOptions.onChangeText?.(''); - }); + const revealedListVersion = useRevealedListReset(listRef, {shouldClearInputWhenHidden, textInputOptions}); useEffect(() => { return () => { diff --git a/src/components/SelectionList/SelectionListWithSections/BaseSelectionListWithSections.tsx b/src/components/SelectionList/SelectionListWithSections/BaseSelectionListWithSections.tsx index 2a0185e25218..c973b23dd639 100644 --- a/src/components/SelectionList/SelectionListWithSections/BaseSelectionListWithSections.tsx +++ b/src/components/SelectionList/SelectionListWithSections/BaseSelectionListWithSections.tsx @@ -104,15 +104,7 @@ function BaseSelectionListWithSectionsImpl({ const {scrollToIndex, debouncedScrollToIndex} = useSelectionListScroll(listRef, flattenedData); const {containerRef, trackScrollOffset, scrollInputIntoView} = useScrollToFocusedInput(listRef, isKeyboardShown); - // Cleared as the list is hidden rather than as it is revealed, so the debounce behind the input elapses while - // nobody is looking and the list is revealed with the data it is replaced against. - const revealedListVersion = useRevealedListReset(listRef, () => { - if (!shouldClearInputWhenHidden || !textInputOptions?.value) { - return; - } - - textInputOptions.onChangeText?.(''); - }); + const revealedListVersion = useRevealedListReset(listRef, {shouldClearInputWhenHidden, textInputOptions}); const {focusedIndex, setFocusedIndex, isKeyboardNavigating, setHasKeyBeenPressed} = useSelectionListKeyboardFocus({ initialFocusedIndex, diff --git a/src/components/SelectionList/hooks/useRevealedListReset.ts b/src/components/SelectionList/hooks/useRevealedListReset.ts index 356494667158..271578425c34 100644 --- a/src/components/SelectionList/hooks/useRevealedListReset.ts +++ b/src/components/SelectionList/hooks/useRevealedListReset.ts @@ -1,3 +1,5 @@ +import type {TextInputOptions} from '@components/SelectionList/types'; + import type {RefObject} from 'react'; import {useEffect, useEffectEvent, useRef, useState} from 'react'; @@ -14,10 +16,22 @@ type RevealableList = { * while hidden while the recycler still reports the offset it was left at, which is what leaves the visible area blank. * The recycler takes an offset only from a scroll event, and scrolling to a top it already sits at produces none, so it * is replaced rather than scrolled: a new one starts where its container is. + * + * The input is cleared as the list is hidden rather than as it is revealed, so the debounce behind it elapses while + * nobody is looking and the list is revealed with the data it is replaced against. */ -function useRevealedListReset(listRef: RefObject, onHidden: () => void): number { +function useRevealedListReset( + listRef: RefObject, + {shouldClearInputWhenHidden, textInputOptions}: {shouldClearInputWhenHidden?: boolean; textInputOptions?: TextInputOptions}, +): number { const [revealedListVersion, setRevealedListVersion] = useState(0); - const runOnHidden = useEffectEvent(onHidden); + const clearInputWhileHidden = useEffectEvent(() => { + if (!shouldClearInputWhenHidden || !textInputOptions?.value) { + return; + } + + textInputOptions.onChangeText?.(''); + }); const hasEffectRunRef = useRef(false); useEffect(() => { @@ -27,7 +41,7 @@ function useRevealedListReset(listRef: RefObject, onHidde } hasEffectRunRef.current = true; - return () => runOnHidden(); + return () => clearInputWhileHidden(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); diff --git a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx index 1e514b07621d..19a50969d134 100644 --- a/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx +++ b/tests/unit/Search/SearchAdvancedFiltersPopupTest.tsx @@ -30,7 +30,7 @@ let mockValuesByFilter: Record | unde let mockOnHoverIn: ((filterKey: string) => void) | undefined; let mockOnFocus: ((filterKey: string) => void) | undefined; let mockOnPointerMove: ((event: {clientX: number; clientY: number}) => void) | undefined; -let mockOnPointerLeave: (() => 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. */ @@ -43,7 +43,7 @@ jest.mock('@components/Search/FilterComponents/AdvancedFilters/FilterList', () = onHoverIn: (filterKey: string) => void; onFocus: (filterKey: string) => void; onPointerMove: (event: {clientX: number; clientY: number}) => void; - onPointerLeave: () => void; + onPointerLeave: (event: {clientX: number}) => void; selectedFilter: string; }) => { mockOnHoverIn = props.onHoverIn; @@ -118,10 +118,10 @@ function movePointer(clientX: number, clientY: number) { }); } -/** Takes the cursor off the filter list. */ -function leaveList() { +/** 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?.(); + mockOnPointerLeave?.({clientX}); }); } @@ -193,13 +193,22 @@ describe('SearchAdvancedFiltersPopup', () => { expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); - it('releases the row the cursor left from when it leaves the list without settling', () => { + it('releases the row the cursor left from when it leaves the list toward the content', () => { hover(FILTER_KEYS.FROM); - leaveList(); + movePointer(100, 100); + leaveList(140); expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); + it('keeps the row withheld when the cursor leaves away from the content', () => { + hover(FILTER_KEYS.FROM); + movePointer(100, 100); + leaveList(60); + + expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(false); + }); + 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. From 4aa3727c48ac47946e361f6772e88b49cb1a73f1 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 7 Sep 2026 11:33:05 +0200 Subject: [PATCH 24/30] wait for the cursor with the shared debounce hook, which now takes controls to drop a pending wait and caps its wait only where a caller asks --- .../SearchAdvancedFiltersPopup/index.tsx | 15 ++--- .../hooks/useSelectionListScroll.ts | 7 ++- src/hooks/useDebounce.ts | 56 +++++++++++++++---- src/hooks/useSearchSelector/base.ts | 27 +++++---- .../inbox/report/useDebouncedSaveDraft.ts | 3 +- 5 files changed, 73 insertions(+), 35 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 937d40a941f5..51e898d83130 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -4,6 +4,7 @@ import SearchAdvancedFiltersContent from '@components/Search/FilterComponents/Ad import useUpdateFilterQuery from '@components/Search/hooks/useUpdateFilterQuery'; import type {SearchQueryJSON} from '@components/Search/types'; +import {useDebounceWithControls} from '@hooks/useDebounce'; import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; @@ -16,7 +17,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; -import React, {Activity, useEffect, useRef, useState} from 'react'; +import React, {Activity, useRef, useState} from 'react'; import {View} from 'react-native'; import AmountFilterContentPopupWrapper from './AmountFilterContentPopupWrapper'; @@ -155,16 +156,10 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps return {...currentState, readyFilters: [...currentState.readyFilters, currentState.activeFilter]}; }); }; - const restTimeoutRef = useRef | undefined>(undefined); - const cancelReadyWait = () => clearTimeout(restTimeoutRef.current); - // Drops the wait when the popover closes. - useEffect(() => cancelReadyWait, []); - /** Restarted by every movement, so it elapses only once the cursor has come to rest. */ - const waitForCursorToRest = () => { - cancelReadyWait(); - restTimeoutRef.current = setTimeout(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); - }; + // Restarted by every movement, so it elapses only once the cursor has come to rest, and dropped when the popover + // closes. + const {invoke: waitForCursorToRest, cancel: cancelReadyWait} = useDebounceWithControls(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); const hoverFilter = (filterKey: SearchFilter['key']) => { showFilter(filterKey); diff --git a/src/components/SelectionList/hooks/useSelectionListScroll.ts b/src/components/SelectionList/hooks/useSelectionListScroll.ts index 5165585e73c5..f7f9feda3d84 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; + + /** Drops a pending invocation. */ + cancel: () => void; +}; + type UseDebounceOptions = DebounceSettings & { /** * When true, any pending trailing invocation is flushed on component unmount instead of cancelled. @@ -19,7 +27,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 +43,9 @@ function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebou }, [shouldExecuteOnUnmount]); useEffect(() => { - const debouncedFn = lodashDebounce(func, wait, {leading, maxWait, trailing}); + // Lodash reads whether `maxWait` was given, not what it holds, so the key is left out when there is no cap to + // apply. With the key present it caps the wait at `wait` even when the value is `undefined`. + const debouncedFn = maxWait === undefined ? lodashDebounce(func, wait, {leading, trailing}) : lodashDebounce(func, wait, {leading, maxWait, trailing}); debouncedFnRef.current = debouncedFn; @@ -44,32 +54,54 @@ function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebou }; }, [func, wait, leading, maxWait, trailing]); - return (...args: unknown[]) => { - const debouncedFn = debouncedFnRef.current; - - if (debouncedFn) { - debouncedFn(...args); - } + // The debounced function is rebuilt whenever func or wait change, so both controls read it from the ref. + return { + invoke: (...args: unknown[]) => { + debouncedFnRef.current?.(...args); + }, + cancel: () => { + debouncedFnRef.current?.cancel(); + }, }; } +/** + * Same as `useDebounce`, with a `cancel` that drops a pending invocation. + * + * The controls come back as an object rather than as properties of the debounced function, because OXC's React Compiler + * fails on a function value carrying methods that read a ref ("Ref type environment did not converge"). + * + * @param func The function to debounce. + * @param wait The number of milliseconds to delay. + * @param options The options object, the same one `useDebounce` takes. + * @returns The debounced function under `invoke`, and `cancel` for the invocation it has pending. + */ +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. * + * Every call pushes the wait back, so func runs once the calls stop for `wait`. Pass `maxWait` to cap how far the wait + * can be pushed: a burst of calls then invokes func every `maxWait` instead of only after it stops. + * * @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. Left out, the wait is uncapped. * @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. + * @returns Returns a function to call the debounced function. Use `useDebounceWithControls` when the wait has to be cancellable. */ 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 type {UseDebounceOptions}; +export {useDebounceWithControls}; + +export type {DebounceControls, UseDebounceOptions}; diff --git a/src/hooks/useSearchSelector/base.ts b/src/hooks/useSearchSelector/base.ts index 4d0bda7c9253..d5b7c90c4848 100644 --- a/src/hooks/useSearchSelector/base.ts +++ b/src/hooks/useSearchSelector/base.ts @@ -424,18 +424,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(); + } + // Capped so pages keep arriving while someone scrolls on, rather than only once the scrolling stops. + }, + CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME, + {maxWait: CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME}, + ); const isOptionSelected = (option: OptionData) => selectedOptions.some((selected) => doOptionsMatch(selected, option)); diff --git a/src/pages/inbox/report/useDebouncedSaveDraft.ts b/src/pages/inbox/report/useDebouncedSaveDraft.ts index 7a70947d1c73..5bf824e6abb5 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}, + // Capped so a draft is still written every `wait` while someone keeps typing, rather than only once they pause. + {shouldExecuteOnUnmount, maxWait: wait}, ); const saveDraft = (...args: unknown[]) => { From 4ec6b1ecbd6555c82c3ea96c9530be680569cb29 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 7 Sep 2026 11:53:00 +0200 Subject: [PATCH 25/30] pull the pointer rest radius out of the filters popover into a hook, so the popover asks for movement rather than measuring it --- .../SearchAdvancedFiltersPopup/index.tsx | 28 ++++------- src/hooks/usePointerMovement.ts | 49 +++++++++++++++++++ 2 files changed, 58 insertions(+), 19 deletions(-) create mode 100644 src/hooks/usePointerMovement.ts diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 51e898d83130..905a0d7c59cd 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -6,6 +6,7 @@ import type {SearchQueryJSON} from '@components/Search/types'; import {useDebounceWithControls} from '@hooks/useDebounce'; import useOnyx from '@hooks/useOnyx'; +import usePointerMovement from '@hooks/usePointerMovement'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; @@ -166,31 +167,20 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps waitForCursorToRest(); }; - // Where the cursor last counted as moving; a hand shaking within the rest radius does not restart the wait. - const restAnchorRef = useRef<{x: number; y: number} | null>(null); - const trackPointerMovement = (event: {clientX: number; clientY: number}) => { - const anchor = restAnchorRef.current; - if (anchor && Math.hypot(event.clientX - anchor.x, event.clientY - anchor.y) < CONST.SEARCH.HOVER_INTENT_REST_RADIUS_PX) { - return; - } + const {trackMovement: trackPointerMovement, stopTracking} = usePointerMovement(CONST.SEARCH.HOVER_INTENT_REST_RADIUS_PX, waitForCursorToRest); - restAnchorRef.current = {x: event.clientX, y: event.clientY}; - waitForCursorToRest(); - }; - - // Nothing is left to wait for once the cursor is gone, so the row it ended on releases what it was withholding, - // but only for a cursor heading toward the content. The direction comes from the last tracked position rather than - // from the exit point alone, because `SafeTriangle` covers that path with an overlay of its own and the cursor - // leaves the list above it as often as through its edge. + // The row the cursor ended on stays on show, so it releases what it was withholding either way: at once for a + // cursor heading toward the content, and once the wait left running elapses for one heading away. The direction + // comes from the last tracked position rather than from the exit point alone, because `SafeTriangle` covers that + // path with an overlay of its own and the cursor leaves the list above it as often as through its edge. const stopTrackingPointer = (event: {clientX: number}) => { - cancelReadyWait(); - const anchor = restAnchorRef.current; - restAnchorRef.current = null; + const lastMovement = stopTracking(); - if (anchor && event.clientX <= anchor.x) { + if (lastMovement && event.clientX <= lastMovement.x) { return; } + cancelReadyWait(); markShownFilterReady(); }; diff --git a/src/hooks/usePointerMovement.ts b/src/hooks/usePointerMovement.ts new file mode 100644 index 000000000000..28553261e9bc --- /dev/null +++ b/src/hooks/usePointerMovement.ts @@ -0,0 +1,49 @@ +import {useRef} from 'react'; + +type PointerPosition = { + /** Horizontal position of the pointer, in viewport pixels. */ + x: number; + + /** Vertical position of the pointer, in viewport pixels. */ + y: number; +}; + +type PointerMovement = { + /** Handles a pointer move. `onMove` runs only for a pointer that traveled past the rest radius. */ + 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 position it kept is what tells a later handler which way the pointer was heading. + * + * @param restRadius How far the pointer has to travel, in pixels, before it counts as moving. + * @param onMove Called for a move past that radius. + */ +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; From 27c3174b7d1a1acd77e3e9e6741ca1ec8c8ad671 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 7 Sep 2026 11:54:40 +0200 Subject: [PATCH 26/30] release a swept-out filter row once its wait elapses, and keep the withheld loading state to the popup --- .../Search/FilterComponents/UserSelector.tsx | 34 +++++++------------ .../ListFilterContentPopupWrapper.tsx | 12 ++++++- .../Search/SearchAdvancedFiltersPopupTest.tsx | 9 ++++- 3 files changed, 32 insertions(+), 23 deletions(-) diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index f855f2614104..8e4fbda2b63b 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -1,4 +1,3 @@ -import LoadingIndicator from '@components/LoadingIndicator'; import {usePersonalDetails} from '@components/OnyxListItemProvider'; import type {Filter, SearchFilterCommonProps} from '@components/Search/types'; import SelectionList from '@components/SelectionList'; @@ -135,27 +134,20 @@ function UserSelector({value = [], isNegatable, policyID, selectionListTextInput itemCount={listData.length} isSearchable={shouldShowSearchInput} isNegatable={isNegatable} - // Held at the height a contact list occupies, so what arrives does not push the panel open under the cursor. - shouldUseFixedPopoverHeight={!ready} > - {ready ? ( - - ) : ( - // One spinner while the contact list is not being built yet. - - )} + ); } diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx index b3f34c3e6abc..7dc0fe662e2d 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, ready, onChange}: ListFilterContentWrapperProps) { const styles = useThemeStyles(); const [isNegated, setIsNegated] = useState(initialIsNegated); const isFilterKeyNegatable = isFilterNegatable(baseFilterKey); + // A withheld filter stands as its own loading state, so none of its controls are drawn behind the spinner. + if (ready === false) { + return ( + + + + ); + } + return ( { expect(mockReadyByFilter[FILTER_KEYS.FROM]).toBe(true); }); - it('keeps the row withheld when the cursor leaves away from the content', () => { + 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', () => { From f94a354f2d347781b34cdb9f4c0ac04ea20f8a84 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 7 Sep 2026 12:31:03 +0200 Subject: [PATCH 27/30] drop the revealed list reset, so a kept filter list comes back as it was left --- .../FilterComponents/BankAccountSelector.tsx | 1 - .../Search/FilterComponents/CardSelector.tsx | 1 - .../Search/FilterComponents/InSelector.tsx | 1 - .../Search/FilterComponents/MultiSelect.tsx | 1 - .../Search/FilterComponents/UserSelector.tsx | 1 - .../FilterComponents/WorkspaceSelector.tsx | 1 - .../SelectionList/BaseSelectionList.tsx | 5 - .../BaseSelectionListWithSections.tsx | 5 - .../hooks/useRevealedListReset.ts | 51 ---------- src/components/SelectionList/types.ts | 3 - tests/unit/BaseSelectionListTest.tsx | 92 +------------------ 11 files changed, 4 insertions(+), 158 deletions(-) delete mode 100644 src/components/SelectionList/hooks/useRevealedListReset.ts diff --git a/src/components/Search/FilterComponents/BankAccountSelector.tsx b/src/components/Search/FilterComponents/BankAccountSelector.tsx index b653e7aefac1..4b26b94c6c4b 100644 --- a/src/components/Search/FilterComponents/BankAccountSelector.tsx +++ b/src/components/Search/FilterComponents/BankAccountSelector.tsx @@ -181,7 +181,6 @@ function BankAccountSelector({value = [], selectionListTextInputStyle, selection shouldPreventDefaultFocusOnSelectRow={false} shouldShowTextInput={shouldShowSearchInput} textInputOptions={textInputOptions} - shouldClearInputWhenHidden shouldStopPropagation canSelectMultiple shouldClearInputOnSelect={false} diff --git a/src/components/Search/FilterComponents/CardSelector.tsx b/src/components/Search/FilterComponents/CardSelector.tsx index f05984367f1e..f49bff3b9ce3 100644 --- a/src/components/Search/FilterComponents/CardSelector.tsx +++ b/src/components/Search/FilterComponents/CardSelector.tsx @@ -160,7 +160,6 @@ function CardSelector({value = [], selectionListTextInputStyle, selectionListSty shouldPreventDefaultFocusOnSelectRow={false} shouldShowTextInput={shouldShowSearchInput} textInputOptions={textInputOptions} - shouldClearInputWhenHidden shouldStopPropagation canSelectMultiple shouldClearInputOnSelect={false} diff --git a/src/components/Search/FilterComponents/InSelector.tsx b/src/components/Search/FilterComponents/InSelector.tsx index a91d804d1304..acfae321da0d 100644 --- a/src/components/Search/FilterComponents/InSelector.tsx +++ b/src/components/Search/FilterComponents/InSelector.tsx @@ -230,7 +230,6 @@ function InSelector({value = [], selectionListTextInputStyle, selectionListStyle shouldPreventAutoScrollOnSelect shouldPreventDefaultFocusOnSelectRow={!canUseTouchScreen()} textInputOptions={textInputOptions} - shouldClearInputWhenHidden isLoadingNewOptions={isLoadingNewOptions} shouldShowLoadingPlaceholder={shouldShowLoadingPlaceholder} shouldShowTextInput diff --git a/src/components/Search/FilterComponents/MultiSelect.tsx b/src/components/Search/FilterComponents/MultiSelect.tsx index 2b957d1aee77..abec90f3894b 100644 --- a/src/components/Search/FilterComponents/MultiSelect.tsx +++ b/src/components/Search/FilterComponents/MultiSelect.tsx @@ -144,7 +144,6 @@ function MultiSelect({ ListItem={MultiSelectListItem} onSelectRow={updateSelectedItems} textInputOptions={textInputOptions} - shouldClearInputWhenHidden style={{contentContainerStyle: [styles.pb0], ...selectionListStyle}} footerContent={footer} /> diff --git a/src/components/Search/FilterComponents/UserSelector.tsx b/src/components/Search/FilterComponents/UserSelector.tsx index 8e4fbda2b63b..b6e516f665dd 100644 --- a/src/components/Search/FilterComponents/UserSelector.tsx +++ b/src/components/Search/FilterComponents/UserSelector.tsx @@ -138,7 +138,6 @@ function UserSelector({value = [], isNegatable, policyID, selectionListTextInput (null); - const revealedListVersion = useRevealedListReset(listRef, {shouldClearInputWhenHidden, textInputOptions}); - useEffect(() => { return () => { if (keyboardListenerRef.current) { @@ -506,7 +502,6 @@ function BaseSelectionListImpl({ <> {!shouldHeaderBeInsideList && header} ) : ( number; -}; - -/** - * Keeps a list that can be hidden by an `` looking as it was built. A hidden subtree keeps its state but - * unmounts its effects, so the effect below runs again when the list is revealed and its cleanup runs as it is hidden. - * - * Returns the version to key the list on. A revealed list starts at the top: its container lost the scroll position - * while hidden while the recycler still reports the offset it was left at, which is what leaves the visible area blank. - * The recycler takes an offset only from a scroll event, and scrolling to a top it already sits at produces none, so it - * is replaced rather than scrolled: a new one starts where its container is. - * - * The input is cleared as the list is hidden rather than as it is revealed, so the debounce behind it elapses while - * nobody is looking and the list is revealed with the data it is replaced against. - */ -function useRevealedListReset( - listRef: RefObject, - {shouldClearInputWhenHidden, textInputOptions}: {shouldClearInputWhenHidden?: boolean; textInputOptions?: TextInputOptions}, -): number { - const [revealedListVersion, setRevealedListVersion] = useState(0); - const clearInputWhileHidden = useEffectEvent(() => { - if (!shouldClearInputWhenHidden || !textInputOptions?.value) { - return; - } - - textInputOptions.onChangeText?.(''); - }); - const hasEffectRunRef = useRef(false); - - useEffect(() => { - // The first run is the real mount, where the list is where it belongs. - if (hasEffectRunRef.current && listRef.current?.getAbsoluteLastScrollOffset()) { - setRevealedListVersion((version) => version + 1); - } - hasEffectRunRef.current = true; - - return () => clearInputWhileHidden(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - return revealedListVersion; -} - -export default useRevealedListReset; diff --git a/src/components/SelectionList/types.ts b/src/components/SelectionList/types.ts index 5610f34d1c9b..475c9ae4eb15 100644 --- a/src/components/SelectionList/types.ts +++ b/src/components/SelectionList/types.ts @@ -124,9 +124,6 @@ type BaseSelectionListProps = { /** Whether to clear the text input when a row is selected */ shouldClearInputOnSelect?: boolean; - /** Whether to clear the text input when an `` hides the list, so it is revealed as it was built */ - shouldClearInputWhenHidden?: boolean; - /** Whether hover style should be disabled */ shouldDisableHoverStyle?: boolean; diff --git a/tests/unit/BaseSelectionListTest.tsx b/tests/unit/BaseSelectionListTest.tsx index e4ce21b578af..49f857d96047 100644 --- a/tests/unit/BaseSelectionListTest.tsx +++ b/tests/unit/BaseSelectionListTest.tsx @@ -13,13 +13,10 @@ import CONST from '@src/CONST'; import type ReactNative from 'react-native'; import * as NativeNavigation from '@react-navigation/native'; -import React, {Activity, useState} from 'react'; +import React, {useState} from 'react'; // Captures scrollToIndex calls so tests can assert on scroll behaviour const mockScrollToIndex = jest.fn(); -const mockGetAbsoluteLastScrollOffset = jest.fn(() => 0); -// Called once per mounted list, so a test can tell a revealed list from a replaced one -const mockListMount = jest.fn(); // Mock FlashList jest.mock('@shopify/flash-list', () => { @@ -27,7 +24,7 @@ jest.mock('@shopify/flash-list', () => { const RN = jest.requireActual('react-native'); const FlashList = ReactLocal.forwardRef< - {scrollToIndex: (params: {index: number}) => void; getAbsoluteLastScrollOffset: () => number}, + {scrollToIndex: (params: {index: number}) => void}, Omit, 'children'> & { data?: unknown[]; renderItem?: (info: {item: unknown; index: number; target: string}) => React.ReactNode; @@ -59,14 +56,7 @@ jest.mock('@shopify/flash-list', () => { }, ref, ) => { - ReactLocal.useState(() => { - mockListMount(); - return null; - }); - ReactLocal.useImperativeHandle(ref, () => ({ - scrollToIndex: mockScrollToIndex, - getAbsoluteLastScrollOffset: mockGetAbsoluteLastScrollOffset, - })); + ReactLocal.useImperativeHandle(ref, () => ({scrollToIndex: mockScrollToIndex})); return ReactLocal.createElement( RN.ScrollView, @@ -86,7 +76,6 @@ jest.mock('@shopify/flash-list', () => { type BaseSelectionListTestProps = { data: TItem[]; canSelectMultiple?: boolean; - shouldClearInputWhenHidden?: boolean; searchText?: string; setSearchText?: (searchText: string) => void; isDisabled?: boolean; @@ -141,13 +130,11 @@ describe('BaseSelectionList', () => { beforeEach(() => { onSelectRowMock.mockClear(); mockScrollToIndex.mockClear(); - mockListMount.mockClear(); - mockGetAbsoluteLastScrollOffset.mockReturnValue(0); mockIsFocusRestoreInProgress.mockReturnValue(false); }); function SelectionListRenderer(props: BaseSelectionListTestProps) { - const {data, canSelectMultiple, setSearchText, searchText, isDisabled, shouldClearInputWhenHidden} = props; + const {data, canSelectMultiple, setSearchText, searchText, isDisabled} = props; const focusedKey = data.find((item) => item.isSelected)?.keyForList; return ( @@ -162,7 +149,6 @@ describe('BaseSelectionList', () => { onSelectRow={onSelectRowMock} shouldSingleExecuteRowSelect shouldShowTextInput={!!setSearchText} - shouldClearInputWhenHidden={shouldClearInputWhenHidden} canSelectMultiple={canSelectMultiple} initiallyFocusedItemKey={focusedKey} isDisabled={isDisabled} @@ -171,76 +157,6 @@ describe('BaseSelectionList', () => { ); } - function ActivitySelectionListRenderer({mode, searchText, setSearchText}: {mode: 'visible' | 'hidden'; searchText?: string; setSearchText?: (text: string) => void}) { - return ( - - - - ); - } - - it('replaces the list it reveals from a hidden Activity only when it was left scrolled', () => { - jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); - - const {rerender} = render(); - expect(mockListMount).toHaveBeenCalledTimes(1); - - // Hiding the list unmounts its effects and drops its layout, and revealing it runs them again. - rerender(); - rerender(); - - // A list left at the top is revealed as it was, which is what keeps a revisit cheap. - expect(mockListMount).toHaveBeenCalledTimes(1); - - // The offset is read as the list is revealed and reported as zero afterwards, so it is read there. - mockGetAbsoluteLastScrollOffset.mockReturnValueOnce(1200); - rerender(); - rerender(); - - // A recycler takes an offset only from a scroll event, so the one left at 1200 is replaced rather than scrolled. - expect(mockListMount).toHaveBeenCalledTimes(2); - }); - - it('drops what the list was filtered by as it is hidden', () => { - jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(true); - const setSearchText = jest.fn(); - - // Mounted with an empty input and filtered afterwards, so a hidden list reading the value it was mounted with - // would find nothing to clear. - const {rerender} = render( - , - ); - rerender( - , - ); - expect(setSearchText).not.toHaveBeenCalled(); - - // Cleared here rather than on the way back, so the debounce behind the input elapses while the list is hidden - // and the data it is revealed with is the data it is replaced against. - rerender( - , - ); - - expect(setSearchText).toHaveBeenCalledWith(''); - }); - it('should not trigger item press if screen is not focused', () => { jest.mocked(NativeNavigation.useIsFocused).mockReturnValue(false); render(); From 7a28f616ce9f08e1319d1c376913c009ec1ab3cd Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Mon, 7 Sep 2026 15:35:32 +0200 Subject: [PATCH 28/30] pin every debounce caller cap so only the filters wait is uncapped, and trim the comments the review flagged --- .../ListFilterContentPopupWrapper.tsx | 2 +- .../SearchAdvancedFiltersPopup/index.tsx | 9 +++---- .../Search/SearchAutocompleteList.tsx | 16 +++++++----- .../hooks/useSelectionListScroll.ts | 2 +- src/hooks/useDebounce.ts | 25 ++++++------------- src/hooks/useIsScrollLikelyLayoutTriggered.ts | 1 + src/hooks/usePointerMovement.ts | 10 +++----- src/hooks/useSearchSelector/base.ts | 2 +- .../ReportActionCompose/SuggestionEmoji.tsx | 2 ++ .../ReportActionCompose/SuggestionMention.tsx | 3 +++ .../inbox/report/useDebouncedSaveDraft.ts | 2 +- 11 files changed, 34 insertions(+), 40 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx index 7dc0fe662e2d..f850c4e346ed 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/ListFilterContentPopupWrapper.tsx @@ -14,7 +14,7 @@ function ListFilterContentPopupWrapper({baseFilterKey, value, isNegated: initial const [isNegated, setIsNegated] = useState(initialIsNegated); const isFilterKeyNegatable = isFilterNegatable(baseFilterKey); - // A withheld filter stands as its own loading state, so none of its controls are drawn behind the spinner. + // The filter is its own loading state, so its controls do not render behind the spinner. if (ready === false) { return ( diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 905a0d7c59cd..335aa67fb9a5 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -158,8 +158,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }); }; - // Restarted by every movement, so it elapses only once the cursor has come to rest, and dropped when the popover - // closes. + // Elapses once the cursor comes to rest on a row. const {invoke: waitForCursorToRest, cancel: cancelReadyWait} = useDebounceWithControls(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); const hoverFilter = (filterKey: SearchFilter['key']) => { @@ -169,10 +168,8 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps const {trackMovement: trackPointerMovement, stopTracking} = usePointerMovement(CONST.SEARCH.HOVER_INTENT_REST_RADIUS_PX, waitForCursorToRest); - // The row the cursor ended on stays on show, so it releases what it was withholding either way: at once for a - // cursor heading toward the content, and once the wait left running elapses for one heading away. The direction - // comes from the last tracked position rather than from the exit point alone, because `SafeTriangle` covers that - // path with an overlay of its own and the cursor leaves the list above it as often as through its edge. + // 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(); diff --git a/src/components/Search/SearchAutocompleteList.tsx b/src/components/Search/SearchAutocompleteList.tsx index 6e0186669458..e67aaf4044d8 100644 --- a/src/components/Search/SearchAutocompleteList.tsx +++ b/src/components/Search/SearchAutocompleteList.tsx @@ -461,13 +461,17 @@ function SearchAutocompleteList({ setFrozenLocalRank(buildRankMap(recentReportsOptions)); } - 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(() => { debounceHandleSearch(); diff --git a/src/components/SelectionList/hooks/useSelectionListScroll.ts b/src/components/SelectionList/hooks/useSelectionListScroll.ts index f7f9feda3d84..612b3a234274 100644 --- a/src/components/SelectionList/hooks/useSelectionListScroll.ts +++ b/src/components/SelectionList/hooks/useSelectionListScroll.ts @@ -32,7 +32,7 @@ function useSelectionListScroll(listRef: RefObject = { /** Calls the debounced function, restarting the wait. */ invoke: T; - /** Drops a pending invocation. */ cancel: () => void; }; @@ -43,8 +42,7 @@ function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebou }, [shouldExecuteOnUnmount]); useEffect(() => { - // Lodash reads whether `maxWait` was given, not what it holds, so the key is left out when there is no cap to - // apply. With the key present it caps the wait at `wait` even when the value is `undefined`. + // 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; @@ -54,7 +52,6 @@ function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebou }; }, [func, wait, leading, maxWait, trailing]); - // The debounced function is rebuilt whenever func or wait change, so both controls read it from the ref. return { invoke: (...args: unknown[]) => { debouncedFnRef.current?.(...args); @@ -66,15 +63,10 @@ function useDebounceImpl(func: GenericFunction, wait: number, options?: UseDebou } /** - * Same as `useDebounce`, with a `cancel` that drops a pending invocation. + * Same as `useDebounce`, with a `cancel` that drops a pending invocation. See `useDebounce` for the parameters. * - * The controls come back as an object rather than as properties of the debounced function, because OXC's React Compiler - * fails on a function value carrying methods that read a ref ("Ref type environment did not converge"). - * - * @param func The function to debounce. - * @param wait The number of milliseconds to delay. - * @param options The options object, the same one `useDebounce` takes. - * @returns The debounced function under `invoke`, and `cancel` for the invocation it has pending. + * 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; @@ -86,17 +78,16 @@ function useDebounceWithControls(func: T, wait: numbe * 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. * - * Every call pushes the wait back, so func runs once the calls stop for `wait`. Pass `maxWait` to cap how far the wait - * can be pushed: a burst of calls then invokes func every `maxWait` instead of only after it stops. + * 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. Left out, the wait is uncapped. + * @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. Use `useDebounceWithControls` when the wait has to be cancellable. + * @returns Returns a function to call the debounced function. */ export default function useDebounce(func: T, wait: number, options?: UseDebounceOptions): T { return useDebounceWithControls(func, wait, options).invoke; @@ -104,4 +95,4 @@ export default function useDebounce(func: T, wait: nu export {useDebounceWithControls}; -export type {DebounceControls, UseDebounceOptions}; +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/usePointerMovement.ts b/src/hooks/usePointerMovement.ts index 28553261e9bc..ef0e5f8bef14 100644 --- a/src/hooks/usePointerMovement.ts +++ b/src/hooks/usePointerMovement.ts @@ -1,15 +1,11 @@ import {useRef} from 'react'; type PointerPosition = { - /** Horizontal position of the pointer, in viewport pixels. */ x: number; - - /** Vertical position of the pointer, in viewport pixels. */ y: number; }; type PointerMovement = { - /** Handles a pointer move. `onMove` runs only for a pointer that traveled past the rest radius. */ trackMovement: (event: {clientX: number; clientY: number}) => void; /** Forgets the tracked position and hands back the one the pointer was last seen moving at. */ @@ -18,10 +14,10 @@ type PointerMovement = { /** * Tracks where a pointer moves, ignoring travel shorter than `restRadius`, so a hand shaking on the spot counts as - * still. The position it kept is what tells a later handler which way the pointer was heading. + * still. The first move after mount and after `stopTracking` has nothing to measure against, so it always counts. * - * @param restRadius How far the pointer has to travel, in pixels, before it counts as moving. - * @param onMove Called for a move past that radius. + * `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); diff --git a/src/hooks/useSearchSelector/base.ts b/src/hooks/useSearchSelector/base.ts index d5b7c90c4848..804102668599 100644 --- a/src/hooks/useSearchSelector/base.ts +++ b/src/hooks/useSearchSelector/base.ts @@ -436,9 +436,9 @@ function useSearchSelectorBase({ if (hasMoreReports) { loadMoreReports(); } - // Capped so pages keep arriving while someone scrolls on, rather than only once the scrolling stops. }, CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME, + // maxWait keeps pages arriving while the scrolling continues. {maxWait: CONST.TIMING.SEARCH_OPTION_LIST_DEBOUNCE_TIME}, ); 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 2ccd83a9568c..b589c3c6f75a 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 5bf824e6abb5..73127f082966 100644 --- a/src/pages/inbox/report/useDebouncedSaveDraft.ts +++ b/src/pages/inbox/report/useDebouncedSaveDraft.ts @@ -28,7 +28,7 @@ function useDebouncedSaveDraftImpl(saveDraftFn: (...args: unknown[]) => void, wa isSavePending.current = false; }, wait, - // Capped so a draft is still written every `wait` while someone keeps typing, rather than only once they pause. + // maxWait writes a draft every `wait` while typing continues. {shouldExecuteOnUnmount, maxWait: wait}, ); From b49f964886bce5be7833ecf36f95eb5d62b3b1b3 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 8 Sep 2026 10:16:28 +0200 Subject: [PATCH 29/30] name the debounced filters wait after the function it invokes --- .../FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 335aa67fb9a5..62cce1c24439 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -159,14 +159,14 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps }; // Elapses once the cursor comes to rest on a row. - const {invoke: waitForCursorToRest, cancel: cancelReadyWait} = useDebounceWithControls(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); + const {invoke: debouncedMarkShownFilterReady, cancel: cancelReadyWait} = useDebounceWithControls(markShownFilterReady, CONST.TIMING.SEARCH_FILTER_HOVER_INTENT_DELAY); const hoverFilter = (filterKey: SearchFilter['key']) => { showFilter(filterKey); - waitForCursorToRest(); + debouncedMarkShownFilterReady(); }; - const {trackMovement: trackPointerMovement, stopTracking} = usePointerMovement(CONST.SEARCH.HOVER_INTENT_REST_RADIUS_PX, waitForCursorToRest); + 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. From c6a5547f46e59593793d9d52adb8715d6bbccec9 Mon Sep 17 00:00:00 2001 From: sumo_slonik Date: Tue, 8 Sep 2026 10:16:28 +0200 Subject: [PATCH 30/30] lift the personal detail options derivation out of an IIFE into a named function --- src/hooks/usePersonalDetailOptions.ts | 65 +++++++++++++++++++++------ 1 file changed, 51 insertions(+), 14 deletions(-) diff --git a/src/hooks/usePersonalDetailOptions.ts b/src/hooks/usePersonalDetailOptions.ts index 9d89537cf282..aefd8f4c04bb 100644 --- a/src/hooks/usePersonalDetailOptions.ts +++ b/src/hooks/usePersonalDetailOptions.ts @@ -1,3 +1,4 @@ +import type {LocaleContextProps} from '@components/LocaleContextProvider'; import {usePersonalDetails} from '@components/OnyxListItemProvider'; import memoize, {equivalentArgsComparator} from '@libs/memoize'; @@ -7,7 +8,7 @@ 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'; @@ -123,6 +124,41 @@ function clearPersonalDetailOptionsCache() { // 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. * @@ -158,19 +194,20 @@ function usePersonalDetailOptions(config: UseFilteredOptionsConfig = {}): UseFil // 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 = (() => { - if (isLoading) { - return undefined; - } - - const personalDetails = includeLoginsOnly ? filterPersonalDetailsByLogins(allPersonalDetails, includeLoginsOnly) : allPersonalDetails; - const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID); - - return memoizedCreateOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, reportAttributes, reportNameValuePairs ?? {}, formatPhoneNumber, translate, { - shouldStoreReportErrors, - shouldShowBrickRoadIndicator, - }); - })(); + const optionsData = isLoading + ? undefined + : buildOptionsData({ + accountID, + allPersonalDetails, + includeLoginsOnly, + reports, + reportAttributes, + reportNameValuePairs, + formatPhoneNumber, + translate, + shouldStoreReportErrors, + shouldShowBrickRoadIndicator, + }); return { options: optionsData?.options,