Skip to content

refactor: remove unsafe assertions from SelectionList section flattening - #102964

Merged
blimpich merged 2 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt/restore-98854-selection-20261003
Oct 19, 2026
Merged

blimpich merged 2 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt/restore-98854-selection-20261003

Conversation

@KJ21-ENG

@KJ21-ENG KJ21-ENG commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Keep specialized item types through SelectionList section flattening, narrow rows before checking selection, and remove the unwritten flatIndex type field. The same section, disabled-item, selection, and focus calculations now use React Compiler memoization instead of useMemo.

Fixed Issues

$ #94739
PROPOSAL: #94739 (comment)

Tests

Relevant upstream TypeScript, Jest, and React Compiler checks passed. tests/unit/hooks/useFlattenedSections.test.ts covers headers, custom headers, empty sections, specialized fields, disabled rows, repeated keys, focus lookup and result reuse/recomputation.

Sections and selection

Setup: Use populated Recents and Contacts, an existing chat and your self-DM.

  1. Open Start chat. Verify section headers and representative rows appear.
  2. Use Add to group to select a contact. Verify its checkmark and Next availability.
  3. With the contact selected, try selecting your self-DM. Verify it is disabled.
  4. Deselect the contact. Verify its checkmark and Next availability update.

Keyboard navigation

  1. Use physical Tab and arrow keys across a section boundary. Verify focus follows enabled rows and skips headers and disabled rows.
  2. Clear any group selection.
  3. Press Enter on an enabled existing chat. Verify that chat opens.
  4. Leave without creating a group.
  5. Check for new console errors. Compare any errors with the same flow on base before attributing them to this PR.

Offline tests

Not applicable: section flattening and focus/selection calculations use loaded data; this refactor changes no network, storage, or reconnect behavior.

QA Steps

Same as tests.

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 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 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)
  • 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)
  • 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 the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • 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

Recordings (1)

Windows desktop Chrome: section rows, contact selection/deselection, disabled self-DM and keyboard navigation were observed. Console errors were observed without confirmed attribution to this PR. Native Android/iOS, mobile-web and macOS Chrome/Safari results are unverified.

pr102964-sections-selection-keyboard-desktop.mp4

Seatbelt-Operation: restore98854-selection-sign-e13e42ee-d56d-42f9-bd7e-e667fb74c316
@KJ21-ENG
KJ21-ENG marked this pull request as ready for review October 16, 2026 21:22
@KJ21-ENG
KJ21-ENG requested review from a team as code owners October 16, 2026 21:22
@melvin-bot
melvin-bot Bot requested review from ikevin127 and removed request for a team October 16, 2026 21:22
@melvin-bot

melvin-bot Bot commented Oct 16, 2026

Copy link
Copy Markdown

@ikevin127 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 October 16, 2026 21:22
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-16T22:23:04.665291Z 985e9ad Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.


const useFlattenedSections: UseFlattenedSections = (sections, initiallyFocusedItemKey) => {
'use memo';
type Item = TupleToUnion<typeof sections>['data'][number];

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.

❌ CONSISTENCY-18 (docs)

The type Item = TupleToUnion<typeof sections>['data'][number] derivation combined with the 'use memo' directive is non-obvious: a maintainer can't tell from the code why the generic TItem can't be referenced directly inside the hook body or why this type indirection is required. The previous implementation documented this exact constraint ("OXC bails on type params inside hooks"), but that comment was removed in this refactor, so the reasoning is now lost.

Add a short comment explaining why the item type is recovered via TupleToUnion<typeof sections> and why 'use memo' is used, e.g.:

const useFlattenedSections: UseFlattenedSections = (sections, initiallyFocusedItemKey) => {
    'use memo';
    // Recover the item type from the runtime `sections` param instead of a type param, because OXC's React
    // Compiler can't memoize a hook that declares its own generic ("Unsupported declaration type for hoisting").
    type Item = TupleToUnion<typeof sections>['data'][number];

Reviewed at: 985e9ad | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

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.

Removed the TupleToUnion workaround and restored a plain generic hook. Added a short explanation for 'use memo'. Babel and OXC both compile and memoize the hook.

@ikevin127

ikevin127 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

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
  • 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 proper code patterns were followed (see Reviewing the code)
    • 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 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)
  • 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)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • 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
    • 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 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 the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • 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

Screen.Recording.2026-10-17.at.18.39.14.mov

Comment on lines +21 to +25
type UseFlattenedSections = <TItem extends ListItem>(sections: Array<Section<TItem>>, initiallyFocusedItemKey?: string | null) => UseFlattenedSectionsResultGeneric<TItem>;

const useFlattenedSections: UseFlattenedSections = (sections, initiallyFocusedItemKey) => {
'use memo';
type Item = TupleToUnion<typeof sections>['data'][number];

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.

src/components/SelectionList/hooks/useFlattenedSections.ts L21-25

🟡 We don't need the UseFlattenedSections function type, the TupleToUnion<typeof sections>['data'][number] trick or the type-fest import. I ran both compilers through config/reactCompiler/checkBoth.mjs against a plain generic function declaration.

Babel and OXC both report compiled + memoized, and isDivergent is false. So the old "OXC bails on type params" limitation is gone once useMemo is gone:

/**
 * Hook that flattens sections with headers and items into a single array for FlashList.
 * Also computes disabled indexes, selected items, and initial focus index.
 */
function useFlattenedSections<TItem extends ListItem>(sections: Array<Section<TItem>>, initiallyFocusedItemKey?: string | null): UseFlattenedSectionsResult<TItem> {
    // The body calls no hooks, so React Compiler's infer mode would skip it without this directive
    'use memo';

    const data: Array<FlattenedItem<TItem>> = [];
    const selectedOptions: TItem[] = [];
    // ...
            const itemData: SectionListItem<TItem> = {

This also brings back the JSDoc the PR deleted, and it answers the bot's L25 comment by explaining the one thing that's actually non-obvious here (why 'use memo' is needed).

Since the non-generic result type is gone, can we rename UseFlattenedSectionsResultGeneric to UseFlattenedSectionsResult ?

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.

Changed the hook to a normal generic function, removed the function-type alias and type-fest import, restored its JSDoc, and renamed the result type to UseFlattenedSectionsResult. Kept 'use memo' with a short explanation. Both compilers report compiled and memoized.


import {createElement} from 'react';

type SpecialItem = ListItem & {specialID: number};

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.

tests/unit/hooks/useFlattenedSections.test.ts L9

🟡 Instead of adding a new test-only type, can we use the existing production CalendarPickerListItem from @components/DatePicker/CalendarPicker/types ? It's ListItem & {value: number}, which is exactly the shape we need to prove that a specialized field survives flattening:

import type CalendarPickerListItem from '@components/DatePicker/CalendarPicker/types';
// ...
const sections: Array<Section<CalendarPickerListItem>> = [

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.

Replaced the test-only item type with the production CalendarPickerListItem. The test now checks that its value field survives flattening.

type SpecialItem = ListItem & {specialID: number};

describe('useFlattenedSections', () => {
it('preserves headers, rows, selection, disability, focus, and specialized fields', () => {

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.

tests/unit/hooks/useFlattenedSections.test.ts L12

🟡 This single it contains two Given/When/Then flows: the flattening output and the memoization reuse/recompute. If it fails, the test name doesn't tell us which behavior broke.

Can we split it into it('flattens headers and rows while keeping selection, disabled state and focus') and it('reuses the result for unchanged inputs and recomputes when they change'), with shared sections in a beforeEach or a helper ?

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.

Split flattening behavior and memoization behavior into separate tests, with shared fixtures. Both tests pass.

expect(result.current.flattenedData.at(4)).toMatchObject({specialID: 3, isDisabled: true});
expect(result.current.selectedItems.map((item) => item.specialID)).toEqual([1, 3]);
expect(result.current.disabledIndexes).toEqual([0, 2, 3, 4]);
expect([result.current.itemsCount, result.current.initialFocusedIndex, result.current.firstFocusableIndex]).toEqual([3, 1, 1]);

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.

tests/unit/hooks/useFlattenedSections.test.ts L37

🟢 Packing three values into one array makes a failure read like [3, -1, 1] vs [3, 1, 1], and you have to work out which field changed.

Can we use one expect per field, or toMatchObject({itemsCount: 3, initialFocusedIndex: 1, firstFocusableIndex: 1}) ?

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.

Replaced the packed array assertion with separate named-field assertions so a failure identifies the affected field.

{keyForList: 'off', specialID: 2, isDisabled: true},
],
},
{sectionIndex: 1, customHeader: createElement('div'), isDisabled: true, data: [{keyForList: 'same', specialID: 3, isSelected: 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.

tests/unit/hooks/useFlattenedSections.test.ts L23

🟢 NAB: this is a React Native test suite, so createElement(View) (or Text) is closer to what real customHeader consumers pass than a DOM 'div'.

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.

Replaced the HTML custom-header fixture with a React Native View.

@ikevin127

Copy link
Copy Markdown
Contributor

@KJ21-ENG The PR needs one simplification and some test cleanup - there are no blockers or behavior changes.

  • flatIndex: nothing in src or tests reads the flatIndex field being removed
  • The in check: the new 'isSelected' in item check in shouldTreatItemAsDisabled behaves the same as before
  • Memoization: the PR head memoizes under both Babel and OXC.
  • Compiler test: I ran both compilers on variants of the hook. Without 'use memo', neither compiler compiles it at all (no-components), because the body calls no hooks. So the directive has to stay.
  • Bot comment: github-actions already asked for a comment on the type Item line (L25), so I didn't repeat that. The first code-comment I posted above removes the need for that workaround.

Please tag me once the comments are addressed.

Seatbelt-Operation: reviewer-fix-102964-aedae95f-766a-4315-bf05-3525ca3b63a0
@KJ21-ENG

Copy link
Copy Markdown
Contributor Author

@ikevin127 Could you please check this once you get a chance, Thanks!

@joekaufmanexpensify

Copy link
Copy Markdown
Contributor

No product review needed.

@joekaufmanexpensify
joekaufmanexpensify removed their request for review October 19, 2026 19:53

@ikevin127 ikevin127 left a comment

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.

🟢 LGTM - The author pushed one commit (4ff63f9, with no main merge in between), and it fixes all 5 of my previous comments plus the bot's. Thank you!

Didn't add anything new to flag ✅

@melvin-bot
melvin-bot Bot requested a review from blimpich October 19, 2026 22:25
@blimpich
blimpich merged commit 23d70b1 into Expensify:main Oct 19, 2026
41 of 45 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

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

@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.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/blimpich in version: 9.5.15-1 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site update is needed. This PR is an internal type-safety and memoization refactor of SelectionList section flattening, with no change to user-facing features, labels, or workflows.


view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/grgia in version: 9.5.15-3 🚀

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

Bundle Size Analysis (Sentry):

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