Skip to content

[select] Clear stale item text ref - #4683

Merged
atomiks merged 5 commits into
mui:masterfrom
atomiks:codex/select-stale-item-text-ref-pr
Apr 28, 2026
Merged

atomiks merged 5 commits into
mui:masterfrom
atomiks:codex/select-stale-item-text-ref-pr

Conversation

@atomiks

@atomiks atomiks commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1922 (comment)

When a controlled Select resets its value to null while replacing its options, React can reuse an old item text node if the rendered items are keyed by index. That leaves selectedItemTextRef connected but stale, so alignItemWithTrigger measures the wrong item and reopens the popup scrolled to the old selected position.

Changes

  • Clear the selected item text ref whenever the closed Select resolves to no selected index.
  • Add a Chromium regression test for replacing options while resetting the controlled value to null.

@atomiks atomiks added component: select Changes related to the select component. type: bug It doesn't behave as expected. labels Apr 26, 2026 — with ChatGPT Codex Connector
@pkg-pr-new

pkg-pr-new Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
  • base-ui-tanstack-start

  • vite-css-base-ui-example

    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/react@4683
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@4683
    

commit: 73a50f4

@code-infra-dashboard

code-infra-dashboard Bot commented Apr 26, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react ▼-11B(0.00%) 🔺+24B(+0.02%)

Details of bundle changes

Performance

Total duration: 1,223.58 ms -12.81 ms(-1.0%) | Renders: 53 (+0) | Paint: 1,900.30 ms -31.14 ms(-1.6%)

Test Duration Renders
Dialog mount (300 instances) 78.73 ms 🔺+6.66 ms(+9.2%) 2 (+0)
Menu open (500 items) 72.35 ms 🔺+5.63 ms(+8.4%) 12 (+0)
Menu mount (300 instances) 147.60 ms 🔺+4.86 ms(+3.4%) 2 (+0)
Mixed surface mount (app-like density) 87.26 ms 🔺+4.13 ms(+5.0%) 5 (+0)
Scroll Area mount (300 instances) 82.13 ms 🔺+3.28 ms(+4.2%) 3 (+0)

...and 7 more. View full report

Details of benchmark changes


Check out the code infra dashboard for more information about this PR.

@atomiks
atomiks force-pushed the codex/select-stale-item-text-ref-pr branch from 0bce4d4 to 8cc55c4 Compare April 26, 2026 22:33
@netlify

netlify Bot commented Apr 26, 2026

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit 0bce4d4
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/69ee91cbcc24940008cfba75
😎 Deploy Preview https://deploy-preview-4683--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify

netlify Bot commented Apr 26, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit 73a50f4
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/69f0336a84c5a50008b73956
😎 Deploy Preview https://deploy-preview-4683--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@atomiks
atomiks marked this pull request as ready for review April 27, 2026 01:49

@flaviendelangle flaviendelangle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

PR #4683 Review — [select] Clear stale item text ref

URL: #4683
Author: atomiks
Base: master ← codex/select-stale-item-text-ref-pr
Files changed: 2 (+160 / −11)

  • packages/react/src/select/root/SelectRoot.tsx (+30 / −11)
  • packages/react/src/select/root/SelectRoot.test.tsx (+130 / −0)

Summary

Targeted bug fix in SelectRoot.tsx that nulls selectedItemTextRef when the resolved selection becomes empty, plus two Chromium regression tests in SelectRoot.test.tsx. The change addresses issue #1922: when items are keyed by index and the controlled value resets to null while options are replaced, the previously-set ref keeps pointing to a recycled DOM node. alignItemWithTrigger then misaligns the popup on next open.


Why the existing clearance paths miss it

Tracing the three places that touch selectedItemTextRef:

  • SelectItemText.tsx:29-33 — only reassigns when selectedItemTextRef.current === null || !isConnected. With key-by-index reuse the node remains connected, so this guard does nothing.
  • SelectItem.tsx:102-112 — only writes the ref when an item value matches the selected value; with value=null no item matches, so nothing overwrites or clears.
  • SelectPositioner.tsx:186-209 — clears via onMapChange, but that path is gated on map.size changing. Index-keyed reuse keeps the size identical, so onMapChange skips the clearance.

The PR plugs the gap inside syncSelectedIndex, which is already triggered on the relevant transitions.


Critical issues

None.


Important issues

None. The fix is minimal, scoped to the documented scenario, and behavior-preserves all existing branches. I walked each old/new code path:

Case Old behavior New behavior
multiple + value [] set selectedIndex=null clear ref, set selectedIndex=null
multiple + last value found set selectedIndex=lastIndex set selectedIndex=lastIndex
multiple + last value not in list set selectedIndex=null clear ref, set selectedIndex=null
single + value found set selectedIndex=index set selectedIndex=index
single + value not found set selectedIndex=null clear ref, set selectedIndex=null
open transition + value=null (no-op, early return) clear ref (new), early return

Every existing case reaches an equivalent selectedIndex; the only added behavior is the ref-clearance, which is the intended fix.


Suggestions

1. Open-branch only clears on !hasSelectedValue

The closed branch clears whenever nextIndex === null (covers both value=null and value=stale-not-in-list). The open branch at the new if (open) { if (!hasSelectedValue) { ... } return; } only clears when !hasSelectedValue.

If a consumer batches setItems(newItems-without-stale-x) + setOpen(true) while leaving value="x" set, hasSelectedValue stays true and the stale ref isn't cleared. Probably out of scope here (the issue is specifically about resetting to null), but worth either:

  • mentioning the limitation in the PR description, or
  • mirroring the closed-branch logic in the open branch (resolve the index and clear when -1).

2. Optional one-line comment

Inside syncSelectedIndex, a short note on why the ref is cleared (e.g. // Drop a possibly-recycled DOM node from index-keyed item replacement before alignment reads it.) would help future readers. The two existing clearances in SelectPositioner.tsx are also uncommented, so this is consistency-neutral — pick one.

3. Dependency-array (no action needed)

Adding selectedItemTextRef to the deps is redundant (refs are stable) but matches the project's existing pattern of including refs (see valuesRef in the same array). Fine as-is.


Strengths

  • Surgical fix; no API or public-types churn.
  • Refactor extracting hasSelectedValue removes a duplicate expression between the setFilled effect and the new check.
  • The nextIndex rewrite unifies the previously branching multiple / single early-returns into one assignment + one store.set, making the ref-clearing site obvious.
  • Behavior parity verified for all five branches (table above).

Tests

Both tests meet AGENTS.md guidelines:

  • ✅ it.skipIf(isJSDOM) — correct, both rely on real layout (getBoundingClientRect, scrollTop).
  • ✅ No await flushMicrotasks() after render.
  • ✅ Vitest-only APIs (expect, waitFor).
  • ✅ key={index} in fixtures is the precise reproducer; selecting a-35 (deep in a 40-item list) makes the misalignment unambiguous.
  • ✅ Three assertions cover open state, scroll reset, and the first option being below the positioner top — together they pin down the bug.

Test coverage:

  • Test 1 — Unbatched path (closed-branch clear via separate render → click trigger).
  • Test 2 — Batched path (setGroup + setValue(null) + setOpen(true) in one handler, exercising the open-branch clear).

Both are necessary; Test 2 specifically justifies the open-branch addition.

Possible enhancement (non-blocking): if you later want to harden the batched scenario, a third variant where value is set to a new-but-stale-against-old-options value (instead of null) would exercise the gap mentioned in suggestion (1).


Compliance check (AGENTS.md)

  • ✅ useIsoLayoutEffect, useStableCallback patterns intact
  • ✅ Shadow-DOM-safe utilities — not relevant here, no new DOM traversal
  • ✅ No new comments where they aren't needed
  • ✅ No duplicated logic (deduped via hasSelectedValue)
  • ✅ Commit messages follow [scope] format ([select] Clear stale item text ref, etc.)
  • ✅ No public API change → pnpm docs:api not required
  • ✅ No new error messages → pnpm extract-error-codes not required

Recommendation

Approve / merge after the author confirms whether suggestion (1) — the open-branch stale-non-null-value case — is worth covering now or deferring. Everything else is approval-level.

@atomiks
atomiks merged commit b4511b7 into mui:master Apr 28, 2026
7 checks passed
@atomiks
atomiks deleted the codex/select-stale-item-text-ref-pr branch April 28, 2026 04:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: select Changes related to the select component. type: bug It doesn't behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[select] with dynamic items fails to show popup upon update

2 participants