Skip to content

Stop scroll jump when selecting items in category filter#89392

Merged
francoisl merged 14 commits intomainfrom
claude-fixCategoryFilterScrollJump
May 4, 2026
Merged

Stop scroll jump when selecting items in category filter#89392
francoisl merged 14 commits intomainfrom
claude-fixCategoryFilterScrollJump

Conversation

@MelvinBot
Copy link
Copy Markdown
Contributor

@MelvinBot MelvinBot commented May 1, 2026

Explanation of Change

When selecting a category in the Spend > Filters > Category picker, the selected item jumps to the top of the list and the view scrolls up, disorienting the user.

This happened because SearchMultipleSelectionPicker split items into two sections (selected vs remaining). When an item was newly selected, BaseSelectionListWithSections.selectRow detected sections.length > 1 and called scrollToIndex(0), scrolling back to the top.

This PR merges all items into a single sorted section so selecting an item no longer triggers re-ordering or scroll jumps. It also sets initiallyFocusedItemKey to the first selected item so the list scrolls to the right position on initial render.

Fixed Issues

$ #61414

Tests

  1. Go to the Search page (Spend tab)
  2. Tap on the Filters icon
  3. Tap on Category
  4. Select a category from the list
  5. Verify the selected item stays in place and the list does NOT scroll/jump to the top
  6. Select additional categories — verify no scroll jumping occurs
  7. Deselect a category — verify no scroll jumping occurs
  8. Close and reopen the Category filter — verify the list scrolls to the first selected category on open
  9. Verify that no errors appear in the JS console

Offline tests

  1. Go offline
  2. Open Search > Filters > Category
  3. Select/deselect categories
  4. Verify no scroll jumping and no console errors

QA Steps

  1. Go to the Search page (Spend tab)
  2. Tap on the Filters icon
  3. Tap on Category
  4. Select several categories from the list and verify:
    • The list does NOT scroll or jump when selecting/deselecting items
    • Items remain in alphabetical order (they do not move to a separate "selected" section at the top)
  5. Close and reopen the Category filter picker
  6. Verify the list scrolls to the first selected category on reopen
  7. Use the search field to filter categories, select one, clear the search — verify no scroll jump
  8. Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

Merge selected and remaining items into a single sorted section instead
of splitting them across two sections. This prevents the scroll-to-top
triggered by BaseSelectionListWithSections when sections.length > 1.

Also set initiallyFocusedItemKey to the first selected item so the list
scrolls to the right position on initial render.

Co-authored-by: mkhutornyi <mkhutornyi@users.noreply.github.com>
@codecov
Copy link
Copy Markdown

codecov Bot commented May 1, 2026

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/components/SelectionList/BaseSelectionList.tsx 65.45% <100.00%> (ø)
...ListWithSections/BaseSelectionListWithSections.tsx 86.46% <100.00%> (+0.10%) ⬆️
...mponents/SelectionList/hooks/useSearchFocusSync.ts 100.00% <ø> (ø)
...omponents/Search/SearchMultipleSelectionPicker.tsx 0.00% <0.00%> (ø)
... and 80 files with indirect coverage changes

<SelectionListWithSections
sections={sections}
ListItem={MultiSelectListItem}
initiallyFocusedItemKey={firstSelectedKey}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot do we also need to set shouldUpdateFocusedIndex true?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Also, we need to set shouldClearInputOnSelect false

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No — these two props are independent and serve different purposes:

  • initiallyFocusedItemKey — one-time setup: scrolls to the first selected item when the list mounts.
  • shouldUpdateFocusedIndex — ongoing: updates the focused index every time the user clicks/selects a row (via BaseSelectionListWithSections.tsx:171-173).

In a multi-select picker where users are toggling items on and off, enabling shouldUpdateFocusedIndex would cause setFocusedIndex to fire on each click, which could trigger scroll repositioning — potentially reintroducing the scroll-jump behavior this PR is fixing.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done — moved shouldClearInputOnSelect from SelectionListProps to BaseSelectionListProps so it's available to SelectionListWithSections, then set it to false in SearchMultipleSelectionPicker. The default remains true to preserve existing behavior for other callers.

Move shouldClearInputOnSelect from SelectionListProps to BaseSelectionListProps
so it can be used by SelectionListWithSections. Set it to false in
SearchMultipleSelectionPicker to preserve the search filter text when
selecting/deselecting items.

Co-authored-by: mkhutornyi <mkhutornyi@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

The test (job 7) failure is unrelated to this PR — it's a GitHub Actions infrastructure flake.

The runner failed to download the actions/github-script action after 3 retries due to network errors (Error while copying content to a stream). No test code actually ran.

Fix: Re-run the failed job. This should resolve on its own.

@MelvinBot
Copy link
Copy Markdown
Contributor Author

The test (job 7) failure is unrelated to this PR — it's a GitHub Actions infrastructure issue. The runner failed to download action archives (actions/github-script, 1password/load-secrets-action) due to network errors during job setup, before any tests ran.

Evidence: The error is Error while copying content to a stream during Set up job, not a test assertion failure. All other test jobs (1–6, 8) passed.

The two checklist failures are the PR Author/Reviewer checklists, which are expected.

You can re-run the failed job to resolve this.

@mkhutornyi
Copy link
Copy Markdown
Contributor

@MelvinBot The selected item should not be auto scrolled to the top of the viewport on first selection after opening page first time

Screen.Recording.2026-05-03.at.10.55.50.pm.mov

Co-authored-by: mkhutornyi <mkhutornyi@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Removed initiallyFocusedItemKey so the list no longer auto-scrolls to the selected item on mount. Pushed in edc56c3.

@mkhutornyi
Copy link
Copy Markdown
Contributor

Removed initiallyFocusedItemKey so the list no longer auto-scrolls to the selected item on mount. Pushed in edc56c3.

@MelvinBot we still need this to auto scroll to the preselected item when opening page.
Just prevent auto scroll when select item, not on page mount.

Re-adds initiallyFocusedItemKey so the list scrolls to the first
preselected item when opening the page. This does not cause scroll
jumps on item selection because FlashList's initialScrollIndex only
applies on mount and useArrowKeyFocusManager ignores prop changes
after its initial useState call.

Co-authored-by: mkhutornyi <mkhutornyi@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Restored initiallyFocusedItemKey in 1632f76. The list will auto-scroll to the first preselected item on mount, but selecting/deselecting items won't cause scroll jumps — FlashList's initialScrollIndex only applies on mount and useArrowKeyFocusManager ignores prop changes after its initial useState call.

@mkhutornyi
Copy link
Copy Markdown
Contributor

@MelvinBot check off all items in author checklist with this screen recording:

demo.mov

@MelvinBot
Copy link
Copy Markdown
Contributor Author

I'm unable to process video content, so I can't verify the screen recording to check off the author checklist items. Could you check off the applicable items directly in the PR description? You can edit the PR body and toggle the checkboxes yourself.

@mkhutornyi
Copy link
Copy Markdown
Contributor

@MelvinBot C+ doesn't have permission to edit author checklist. Check off all items as I already verified myself.

@MelvinBot
Copy link
Copy Markdown
Contributor Author

Done — all PR Author Checklist items have been checked off.

@mkhutornyi
Copy link
Copy Markdown
Contributor

@MelvinBot add Tests, QA Steps

@MelvinBot
Copy link
Copy Markdown
Contributor Author

Added Tests, Offline tests, and QA Steps to the PR description.

@mkhutornyi
Copy link
Copy Markdown
Contributor

@Expensify/design please check if this behavior is fine.

Selected item is auto scrolled to the top of the viewport first time.

first.selection.mov

Similar to scrolling to the preselected first item when open page.

first.open.mov

From 2nd selection, auto scroll never happens. Auto scrolled only when search input changes.

2nd.selection.mov

@dubielzyk-expensify
Copy link
Copy Markdown
Contributor

Selected item is auto scrolled to the top of the viewport first time.

I don't think we want this cause it's quite jarring :/

Similar to scrolling to the preselected first item when open page.

On one hand I like this, but it feels overly clever to me given that it's not super obvious there's more items above.

I just think we don't want any scrolling or have I missed something here. Curious what @Expensify/design thinks too

@mkhutornyi
Copy link
Copy Markdown
Contributor

ok after disabling scroll in both cases:

disable.mov

@dubielzyk-expensify
Copy link
Copy Markdown
Contributor

Curious what @Expensify/design thinks as well, but that feels a bit better to me. I understand the reasoning for wanting the selected options at the top when you go back into the flow though so I can see that still being enabled, but I still don't think we should have any auto-scrolling

@shawnborton
Copy link
Copy Markdown
Contributor

Why aren't we solving this everywhere instead of just the filters list? Remember, we have this issue that we were planning to use to fix this behavior across the whole app: #61414

I think the idea is quite simple:

  • when you view a selection list, never jump the position of items as you select/unselect
  • when you view a selection list, if any items have already been selected, they float to the top. Selecting/unselecting them should NOT jump their position (see point above)

@mkhutornyi
Copy link
Copy Markdown
Contributor

We'll solve this everywhere eventually.
In this PR, we'll fix multi selection pickers on search - currency, category, expense type, exported to, tag, tax rate
I am going to handle this per basic component level, similar to this plan

<SelectionListWithSections
sections={sections}
ListItem={MultiSelectListItem}
initiallyFocusedItemKey={firstSelectedKey}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

            initiallyFocusedItemKey={firstSelectedKey}

@MelvinBot while keeping this, we should not update initialScrollIndex of FlashList to prevent auto scroll whenever item is selected. But still update when page is first rendered.

(Scroll happens when this prop value of FlashList is changed from -1)

initialScrollIndex={initialScrollIndex ?? initialFocusedIndex}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — initiallyFocusedItemKey is now computed once on mount via a useState lazy initializer (from initiallySelectedItems and the sorted items), so it stays stable across re-renders. This prevents initialFocusedIndexinitialScrollIndex from changing when the user toggles selections.

Copy link
Copy Markdown
Contributor

@mkhutornyi mkhutornyi May 4, 2026

Choose a reason for hiding this comment

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

@MelvinBot "scrolling to the inital focused item on clear search" issue still happens because of native feature in FlashList.
FlashList internally auto-scrolls whenever data changes and updates initiallyFocusedItemKey existence (from "not found" to "found") in data
The ideal solution is to clear initiallyFocusedKey after first render.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done — initiallyFocusedItemKey is now cleared after the first render using a ref to track post-mount state. On the initial render the key is passed so FlashList scrolls to the selected item, and on all subsequent renders it's undefined so data changes (like clearing a search) won't trigger auto-scrolling.

Compute the initial focused key once on mount using useState lazy
initializer, so it doesn't change when the user toggles selections.
This prevents FlashList's initialScrollIndex from updating and
triggering auto-scroll on each item click.

Co-authored-by: mkhutornyi <mkhutornyi@users.noreply.github.com>
@MelvinBot
Copy link
Copy Markdown
Contributor Author

⚠️ MelvinBot CI Fix Loop Detected

MelvinBot has made 5 consecutive commits trying to fix CI failures. Automatic CI fix dispatches are now paused for this PR.

Next steps: A human should review the recent commits and resolve the conflicting CI errors manually.

@melvin-bot melvin-bot Bot requested a review from mkhutornyi May 4, 2026 12:00
@MelvinBot
Copy link
Copy Markdown
Contributor Author

🤖 PR has been marked as ready for review.

@melvin-bot melvin-bot Bot removed the request for review from a team May 4, 2026 12:00
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented May 4, 2026

@mkhutornyi Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot melvin-bot Bot requested review from flaviadefaria and removed request for a team May 4, 2026 12:00
@mkhutornyi
Copy link
Copy Markdown
Contributor

Author Checklist failing should be fixed by re-trigger.

@mkhutornyi
Copy link
Copy Markdown
Contributor

mkhutornyi commented May 4, 2026

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
Android: mWeb Chrome
mchrome.mov
iOS: HybridApp
ios.mov
iOS: mWeb Safari
msafari.mov
MacOS: Chrome / Safari
web.mov

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 47fdb69e85

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

const [selectedItemIDs, setSelectedItemIDs] = useState(() => new Set((initiallySelectedItems ?? []).map((item) => item.value.toString())));
const [initialSelectedIDs] = useState(() => new Set((initiallySelectedItems ?? []).map((item) => item.value.toString())));
const [selectedItemIDs, setSelectedItemIDs] = useState(() => initialSelectedIDs);
const [initiallyFocusedKeyComputed] = useState(() => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Recompute initial focus key when options load after mount

initiallyFocusedKeyComputed is captured in a useState initializer, so it is only derived from the very first items snapshot. In flows where picker options arrive asynchronously (for example SearchFiltersCategoryPage builds items from Onyx collections that can populate after first render), the selected option may not exist yet when this runs; the next frame then clears the key, and the picker never scrolls to the first selected item on reopen. This makes the new “scroll to selected item on open” behavior unreliable whenever data loads after mount.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

{!isLoadingOnyxValue(searchAdvancedFiltersFormResult) && (
<SearchMultipleSelectionPicker
items={categoryItems}
initiallySelectedItems={selectedCategoriesItems}
onSaveSelection={onSaveSelection}
shouldShowTextInput={categoryItems.length >= CONST.STANDARD_LIST_ITEM_LIMIT}
/>

There's guard so it's fine

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — inlined the computation directly into the initiallyFocusedKey useState initializer, removing the extra state slot.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — inlined the computation directly into the initiallyFocusedKey useState initializer, removing the extra state slot.

@mkhutornyi
Copy link
Copy Markdown
Contributor

@MelvinBot this is not caused by our PR but I noticed that above line is called 3 times when type anything on search while scrolled down the list.

The below line is unnecessarily called so scroll is still animating, which doesn't fix this completely.

(shouldDebounceScrolling ? debouncedScrollToIndex : scrollToIndex)(index);

@MelvinBot
Copy link
Copy Markdown
Contributor Author

Good catch — this is a pre-existing issue in BaseSelectionListWithSections. Here's why scrollToIndex fires 3 times per keystroke:

Call 1: useSearchFocusSync.ts:93 directly calls scrollToIndex(0, false) when search text changes.

Call 2: Immediately after, useSearchFocusSync.ts:94 calls setFocusedIndex(firstFocusableIndex), which triggers useArrowKeyFocusManager.ts:80-86onFocusedIndexChangeBaseSelectionListWithSections.tsx:141 with animated=true. This is the call causing the visible scroll animation.

Call 3: On the next render cycle, when filtered data arrives or usePrevious refs update (they're in the dependency array), useSearchFocusSync re-fires.

Root cause of the animated scroll: The suppressNextFocusScrollRef mechanism exists to prevent exactly this — but useSearchFocusSync calls raw setFocusedIndex instead of updateAndScrollToFocusedIndex, so the suppress flag is never set during search.

Fix direction: useSearchFocusSync should either (a) set suppressNextFocusScrollRef.current = true before calling setFocusedIndex, or (b) use updateAndScrollToFocusedIndex(index, false) instead of separate scrollToIndex + setFocusedIndex calls. This would eliminate Call 2 and the unwanted animation. Since this is a pre-existing issue beyond this PR's scope, it could be addressed in a follow-up.

@mkhutornyi
Copy link
Copy Markdown
Contributor

mkhutornyi commented May 4, 2026

@MelvinBot implement this in a new PR as not caused by our PR.

@MelvinBot
Copy link
Copy Markdown
Contributor Author

🤖 Created follow-up draft PR: #89498

This implements the fix described in this analysis — suppresses the redundant animated scroll triggered by onFocusedIndexChange when useSearchFocusSync already called scrollToIndex directly.

Please mark it as "Ready for review" when it is ready for review.

@mkhutornyi
Copy link
Copy Markdown
Contributor

@MelvinBot review

@MelvinBot
Copy link
Copy Markdown
Contributor Author

Code Review

The approach is sound — merging into a single section eliminates the scroll jump, and the requestAnimationFrame trick to clear initiallyFocusedItemKey after mount is a reasonable workaround for FlashList's auto-scroll behavior.

Two things to flag:

1. animated=false in useSearchFocusSync is a global change

useSearchFocusSync.ts:74 and useSearchFocusSync.ts:93 now hardcode animated=false. This hook is shared by all selection lists in the app (member pickers, tag pickers, etc.), so every search-clear scroll will now be an instant jump instead of animated. If this is intentional — fine. If not, consider accepting animated as a parameter to the hook so each caller can choose.

2. Nit: initiallyFocusedKeyComputed is an unnecessary intermediate state

SearchMultipleSelectionPicker.tsx:44-55 uses two useState calls where one would suffice — initiallyFocusedKeyComputed is never updated and only read to initialize initiallyFocusedKey. The computation could be inlined into the second useState initializer to save a state slot.

Everything else looks good
  • requestAnimationFrame cleanup is correct — rAF is cancelled on unmount, empty deps ensure single execution
  • initiallyFocusedKeyComputed correctly finds the minimum selected item using the same sortOptionsWithEmptyValue comparator used for list sorting
  • shouldClearInputOnSelect gating at BaseSelectionListWithSections.tsx:168 is correct and backward-compatible (defaults to true)
  • Type move of shouldClearInputOnSelect to BaseSelectionListProps is clean — no duplication, both component types inherit it

@mkhutornyi
Copy link
Copy Markdown
Contributor

2. Nit: initiallyFocusedKeyComputed is an unnecessary intermediate state

SearchMultipleSelectionPicker.tsx:44-55 uses two useState calls where one would suffice — initiallyFocusedKeyComputed is never updated and only read to initialize initiallyFocusedKey. The computation could be inlined into the second useState initializer to save a state slot.

@MelvinBot fix this

…initializer

Co-authored-by: mkhutornyi <mkhutornyi@users.noreply.github.com>
@MelvinBot MelvinBot requested a review from a team as a code owner May 4, 2026 15:43
@melvin-bot melvin-bot Bot requested review from francoisl and removed request for a team May 4, 2026 15:43
@MelvinBot
Copy link
Copy Markdown
Contributor Author

Fixed the nit — inlined initiallyFocusedKeyComputed directly into the initiallyFocusedKey useState initializer, removing the extra state slot (7c662c0).

@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented May 4, 2026

@francoisl Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

Copy link
Copy Markdown
Contributor

@francoisl francoisl left a comment

Choose a reason for hiding this comment

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

👍

@francoisl francoisl merged commit bdce78b into main May 4, 2026
50 checks passed
@francoisl francoisl deleted the claude-fixCategoryFilterScrollJump branch May 4, 2026 16:10
@OSBotify
Copy link
Copy Markdown
Contributor

OSBotify commented May 4, 2026

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 4, 2026

🚧 @francoisl has triggered a test Expensify/App build. You can view the workflow run here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants