Skip to content

Search selection: move write-side off <Search> onto provider/controller - #92809

Merged
mountiny merged 25 commits into
Expensify:mainfrom
callstack-internal:perf/search-selection-writeside
Jun 17, 2026
Merged

mountiny merged 25 commits into
Expensify:mainfrom
callstack-internal:perf/search-selection-writeside

Conversation

@adhorodyski

@adhorodyski adhorodyski commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

<Search> previously owned the entire selection write-path inline: toggling individual rows, toggling groups, toggling all, reconciling stale keys when the result set changed, wiring selectedTransactions into FlashList's extraData, and driving mobile selection mode. All of that lived inside one ~800-line component that also handled data-fetching, routing, and rendering — so every checkbox press re-rendered the whole screen subtree (SearchPage → <Search> → the list).

This PR moves the write-side out of <Search> entirely and splits selection into single-responsibility units, each on its own context so a checkbox press only re-renders what genuinely depends on the new selection.

New / changed units

  • selectionBuilders.ts (new) — pure, side-effect-free functions that take the current selection map and return the next one: mapTransactionItemToSelectedEntry, mapEmptyReportToSelectedEntry, prepareTransactionsList, and deriveSelectedReports. Easy to unit-test in isolation.

  • SearchSelectionProvider (now state-only) — owns selection state and the pure setters. Adds applySelection: a functional read-modify-write commit ((prev) => next) so callers mutate the selection without subscribing to it (and therefore without re-rendering on every change). Passing data derives selectedReports in the same commit; passing totalSelectableItemsCount keeps "select all matching" in lock-step.

  • SearchWriteActionsProvider (new) — the screen-level owner of the write path. Exposes toggle/toggleAll on a dedicated SearchRowSelectionActionsContext, committing exclusively through applySelection so dispatching an action re-renders neither the provider's stable children nor the rows. It also co-locates the effects that respond to data: the reconcile-on-data-change effect (rebuilds the selection when an Onyx push adds/removes rows, with the deep-equal bail-out that prevents the [Due for payment 2026-05-26] [$250] Spend - The app crashes after selecting a group on the search page. #89588 infinite-update loop) and the mobile-selection-mode sync effects.

  • SearchSelectionFooter (new) — a self-subscribing footer leaf. It owns the selectedTransactions read and the footer-totals computation that used to live in SearchPage, so toggling a checkbox re-renders only this footer rather than the page and the list it contains.

Wiring / read-side isolation

  • SearchList no longer receives onCheckboxPress, onAllCheckboxPress, or selectedTransactions as props — it pulls toggle/toggleAll from useSearchRowSelectionActions() and selectedTransactions from context directly.
  • SearchPage drops its useSearchSelectionContext() read and the footerData/shouldShowFooter derivation (moved into SearchSelectionFooter), so a selection change no longer re-renders the page.
  • Context plumbing (SearchContext, SearchContextDefinitions, types.ts): adds SearchRowSelectionActionsContext + the useSearchRowSelectionActions hook, the applySelection action, and the SearchData / SearchRowSelectionActionsValue types.

extraData cleanup

  • selectedTransactions is removed from FlashList's extraData (and from BaseSearchList's props). Rows already re-render off item-reference identity — Onyx delivers a new object for a row on selection change — so the extra full-list double-render that extraData forced on every toggle is gone.

Net effect

<Search> drops its entire selection machinery (~600 lines net) and becomes a thin router/shell that mounts SearchWriteActionsProvider around the list. The selection logic is testable, isolated, and a checkbox press now re-renders only the affected row(s) and the footer — not the page, not the full list. No user-facing behavior changes.

Fixed Issues

$ #93677
PROPOSAL:

Tests

  1. Open Search (Reports / Expenses).
  2. Tap a single expense row's checkbox — verify it selects, the bulk-action footer appears with the correct count/total, and only that row + footer update (no full-list flicker).
  3. Tap a report/group checkbox — verify all of its transactions select together.
  4. Tap "Select all" — verify every selectable row selects and the footer reflects the matching-items total; untoggle one row and verify "select all" turns off.
  5. With a selection active, trigger a data change (e.g. let an Onyx update add/remove a row) — verify the selection reconciles and stale keys are dropped, with no console "Maximum update depth" errors.
  6. On narrow/mobile layout: long-press a row to enter selection mode, select/deselect down to zero — verify selection mode turns off automatically.
  7. Verify bulk actions (hold/unhold, approve, pay, change report, etc.) still operate on the selected set.
  • Verify that no errors appear in the JS console

Offline tests

N/A

QA Steps

Same as tests

  • 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
    • 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

adhorodyski and others added 6 commits June 5, 2026 19:13
…ers.ts

Move mapTransactionItemToSelectedEntry, mapEmptyReportToSelectedEntry and
prepareTransactionsList out of Search/index.tsx and deriveSelectedReports out
of SearchSelectionProvider.tsx into a shared selectionBuilders.ts, deduping
deriveSelectedReports. Pure relocation, no behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Add a dedicated SearchRowSelectionActionsContext carrying stable-identity
toggle/toggleAll/clearAll/reconcileSelection plus a screenContextRef populated
by the upcoming SearchSelectionController. The write actions read screen-derived
inputs from the ref and the latest committed selection from selectedTransactionsRef
at call time, so they keep a stable identity and never close over high-churn
selection state. Coordination state (isRefreshingSelection, the select-all check)
lives here too.

Kept on its own context rather than the shared SearchSelectionActionsValue to
avoid leaking an internal ref into action payload types and churning test
fixtures; the stability/separation intent is preserved.

Inert until wired: <Search> still uses its own handlers. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Introduce SearchSelectionController, a renderless child of <Search> that owns
the selection-only Onyx subscriptions (OUTSTANDING_REPORTS_BY_POLICY_ID, selfDM,
env, focus) and composes named hooks — useReconcileSelectionWithData,
useTurnOffSelectionModeWhenEmpty, useSyncMobileSelectionModeWithScreenSize and
useSyncSelectedReports — plus publishes the screen-derived inputs the provider's
write actions read at call time. Returns null.

Mounted in the main list branch, where selectable rows exist; selection state
lives in the root provider and survives mount/unmount, and the reconcile effect
re-syncs on remount. <Search> still runs its own copies of these effects in this
commit (idempotent: reconcile is deepEqual-guarded, mobile-mode sync is a no-op
when already settled); the next commit removes them. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…roller

<Search> no longer reads selectedTransactions or owns the selection write
logic. Deleted from it: the selectedTransactions/areAllMatchingItemsSelected
context read, the ~190-line refresh-selection effect, both mobile-selection-mode
effects, the isRefreshingSelection ref + reset, updateSelectAllMatchingItemsState,
toggleTransaction, toggleAllTransactions, the useSyncSelectedReports call, and the
now-orphaned outstandingReportsByPolicyID/selfDMReport/isProduction subscriptions.
onSelectRowInMobileSelectionMode now calls the stable toggle from
useRowSelectionActions().

SearchList sources toggle/toggleAll from useRowSelectionActions() (passing toggle
to rows via the existing onSelectionButtonPress) and reads selectedTransactions
from context for its visible select-all count, so onCheckboxPress/onAllCheckboxPress/
selectedTransactions props are dropped from its public API. Updated the render-count
test accordingly.

This is the change that moves the metric: a checkbox press no longer re-renders
<Search> or recreates its handlers.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Rows self-hydrate their selected state via useRowSelection(keyForList) (read
side, already shipped), so the row re-renders on its own context subscription
when selection changes. The selectedTransactions entry in BaseSearchList's
FlashList extraData is therefore redundant and only forced extra row diffing —
remove it, along with the now-unused prop on BaseSearchList and the prop pass
from SearchList. SearchList keeps reading selectedTransactions from context for
its visible select-all count.

Isolated commit: it is the one piece with an independent row re-render surface,
so it reverts cleanly if a platform regresses.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@codecov

codecov Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
src/components/Search/SearchContext.tsx 100.00% <100.00%> (ø)
src/libs/SearchUIUtils.ts 64.47% <ø> (+0.49%) ⬆️
src/pages/Search/SearchPage.tsx 85.71% <ø> (+14.69%) ⬆️
src/pages/Search/SearchPageNarrow/index.tsx 73.33% <100.00%> (ø)
...ponents/Search/SearchList/BaseSearchList/index.tsx 0.00% <0.00%> (ø)
src/components/Search/SearchContextDefinitions.ts 51.85% <40.00%> (-2.70%) ⬇️
src/components/Search/SearchList/index.tsx 51.42% <44.44%> (-0.05%) ⬇️
src/pages/Search/SearchPageWide.tsx 0.00% <0.00%> (ø)
src/components/Search/SearchSelectionProvider.tsx 49.38% <15.38%> (-5.07%) ⬇️
src/components/Search/SearchSelectionFooter.tsx 41.66% <41.66%> (ø)
... and 3 more
... and 128 files with indirect coverage changes

- Extract the repeated TransactionListItemType[] | ... row-data union into
  a single exported SearchData type in types.ts; reuse it across the
  controller, provider, and selectionBuilders.
- Drop the unused SearchRowSelectionActionsContext re-export from
  SearchContext.tsx (knip).
- Reword the SearchSelectionController doc comment to drop "Renderless"
  (cspell).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@adhorodyski

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

ℹ️ 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".

…riteside

# Conflicts:
#	src/components/Search/index.tsx
@adhorodyski
adhorodyski marked this pull request as ready for review June 9, 2026 10:15
@adhorodyski
adhorodyski requested review from a team as code owners June 9, 2026 10:15
@melvin-bot
melvin-bot Bot requested review from a team, mananjadhav and trjExpensify and removed request for a team June 9, 2026 10:15
@melvin-bot

melvin-bot Bot commented Jun 9, 2026

Copy link
Copy Markdown

@mananjadhav 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 joekaufmanexpensify and removed request for a team June 9, 2026 10:15

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

Copy link
Copy Markdown

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: 4af4f444b1

ℹ️ 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".

@trjExpensify

Copy link
Copy Markdown
Contributor

PR doesn’t need product input as a performance PR. Unassigning and unsubscribing myself.

@trjExpensify
trjExpensify removed their request for review June 9, 2026 15:02
adhorodyski and others added 2 commits June 10, 2026 18:49
…read

Replace the screenContextRef mutable channel with a functional applySelection
setter and a screen-level SearchWriteActionsProvider; fold in the renderless
SearchSelectionController and de-dup the reconcile build onto selectionBuilders.

Isolate SearchPage's selectedTransactions read into a self-subscribing
SearchSelectionFooter leaf so a checkbox press no longer cascades through
SearchPage -> SearchPageNarrow/Wide into <Search>. Profiler: <Search> now
renders in 0 press commits (was every press).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…riteside

Resolve conflicts in src/components/Search/index.tsx: the write-side
selection functions removed by this branch conflicted with upstream's
flatten-params + archivedReportsIDSet changes. Kept our deletions and
ported upstream's archivedReportsIDSet (threaded into canChangeReport)
plus the object-param signature into the extracted selectionBuilders.ts
and SearchWriteActionsProvider.tsx.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@joekaufmanexpensify

Copy link
Copy Markdown
Contributor

No product review needed

@BartekObudzinski

Copy link
Copy Markdown
Contributor

Should be good now @ZhenjaHorbach
image

@BartekObudzinski

Copy link
Copy Markdown
Contributor

resolving conflicts 👀

…on-writeside

# Conflicts:
#	src/components/Search/SearchList/BaseSearchList/index.tsx
#	src/components/Search/SearchList/BaseSearchList/types.ts
#	src/components/Search/SearchList/index.tsx
#	src/components/Search/index.tsx
@BartekObudzinski

Copy link
Copy Markdown
Contributor

@ZhenjaHorbach

@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

@ZhenjaHorbach

I'm checking 😅
I just don't want to rush approval, as the changes are quite complex

@BartekObudzinski

Copy link
Copy Markdown
Contributor

Yeah sure, just kindly bumping ❤️

@ZhenjaHorbach

Copy link
Copy Markdown
Contributor

LGTM

@melvin-bot
melvin-bot Bot requested a review from mountiny June 17, 2026 09:14
@mountiny
mountiny merged commit b8e920a into Expensify:main Jun 17, 2026
32 checks passed
@OSBotify

Copy link
Copy Markdown
Contributor

✋ 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

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

@OSBotify OSBotify mentioned this pull request Jun 17, 2026
67 tasks done
@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 9.4.10-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

@MelvinBot

Copy link
Copy Markdown
Contributor

Help site review — no changes required

I reviewed the changes in this PR against the help site docs under App/docs/articles, and no help site updates are required.

Why: This PR is a purely internal refactor of the Search selection write-path. It moves selection logic off the <Search> component onto dedicated providers/controllers (SearchWriteActionsProvider, SearchSelectionProvider, SearchSelectionFooter, selectionBuilders.ts) to reduce re-renders on checkbox presses. There are:

  • No changes to src/languages/* (no copy/text changes)
  • No new or renamed user-facing features, tabs, settings, or buttons
  • No behavioral changes — the PR description explicitly states "No user-facing behavior changes."

Since help site articles document user-facing behavior, and this PR changes only the internal component architecture (the same selection, footer totals, "select all", and bulk actions behave identically), there is nothing to document or update.

Because no changes are required, I did not create a draft docs PR.


@adhorodyski, please confirm whether you agree no help site changes are needed. If you believe a user-facing behavior did change and warrants documentation, reply with @MelvinBot and the specifics, and I'll draft the docs PR.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 9.4.12-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 I reviewed this PR against the help site articles in docs/articles and no documentation changes are required.

This is a pure internal refactor of the Search component's selection write-path — it moves selection state/actions off <Search> onto dedicated providers and contexts (SearchSelectionProvider, SearchWriteActionsProvider, SearchSelectionFooter, selectionBuilders.ts) to reduce unnecessary re-renders. As the PR description states, there are no user-facing behavior changes:

  • No new or renamed features, tabs, settings, or buttons
  • No changes to pricing, billing, workspaces, integrations, or workflows
  • All changed files are React components/contexts/providers and their tests

Since the help site documents user-facing behavior and product features — none of which change here — there is nothing to update under docs/articles, so no draft help site PR was created.

@adhorodyski, please confirm this assessment. If you believe any user-facing behavior did change and warrants a help site update, reply with the details and I'll create the draft PR.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 9.4.14-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

@mitarachim

Copy link
Copy Markdown

@adhorodyski This PR is failing in step 6 because of a regression issue #93911

Screenshot 2026-06-18 at 12 35 40 PM

The issue is reproducible in: Android

Bug7184107_1781737576612.1.mp4

@ZhenjaHorbach

ZhenjaHorbach commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

[$250] Spends - Selection mode does not automatically exit when selection count drops to zero #93911

Oh
Sorry
I think this is an incorrect test step in the description
Since this PR is a refactoring,
The behaviour shouldn't have changed
And we currently have the same behavior in prod

2026-06-18.08.04.19.mov

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/puneetlath in version: 9.4.14-1 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

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.

10 participants