Skip to content

[all components] Fix stale focused field state - #5345

Merged
atomiks merged 5 commits into
mui:masterfrom
atomiks:claude/field-lifecycle-audit-fixes-73dada
Sep 25, 2026
Merged

atomiks merged 5 commits into
mui:masterfrom
atomiks:claude/field-lifecycle-audit-fixes-73dada

Conversation

@atomiks

@atomiks atomiks commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #3987

Disabling or unmounting a focused control can move focus away without firing blur, leaving data-focused stuck on Field.Root, its label, and the control. This is reproducible in Chromium for both native inputs and buttons.

useSetFieldFocused records which focus target owns the field state and releases it when that target becomes disabled or unmounts. Ownership prevents cleanup from an old target from clearing focus that has moved to another target, which is required for components with multiple inherent focus targets such as Slider, Radio Group, and OTP Field.

The cleanup is attached to every field-aware focus target: Field.Control, Switch.Root, Checkbox.Root, NumberField.Input, Radio.Root, OTPField.Input, Slider.Thumb, Select.Trigger, and both Combobox.Input and Combobox.Trigger.

The PR intentionally stays focused on this lifecycle bug. Filled-state remount handling is already covered on master, and uncommon compositions with multiple independent controls under one Field.Root are left unsupported rather than adding runtime coordination.

@atomiks atomiks added component: field Changes related to the field component. type: bug It doesn't behave as expected. labels Jul 27, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jul 27, 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@5345
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@5345
    

commit: 8daa13c

@code-infra-dashboard

code-infra-dashboard Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+304B(+0.07%) 🔺+184B(+0.12%)

Details of bundle changes

Performance

Total duration: 1,292.28 ms +66.83 ms(+5.5%) | Renders: 76 (+0) | Paint: 2,139.90 ms +108.21 ms(+5.3%)

Test Duration Renders
Dialog mount (300 instances) 35.68 ms 🔺+10.95 ms(+44.3%) 1 (+0)

14 tests within noise — details

Metric alarms

Test Metric Change
Dialog mount (300 instances) bench:paint 🔺 +19.50 ms

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

@netlify

netlify Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit 8daa13c
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6ab6151eaa1f840008c95424
😎 Deploy Preview https://deploy-preview-5345--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

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

@atomiks
atomiks force-pushed the claude/field-lifecycle-audit-fixes-73dada branch 2 times, most recently from 4354b0e to 69c0549 Compare July 27, 2026 05:35
@atomiks atomiks changed the title [field] Fix stale label association and lifecycle state on control replacement [field] Fix stale filled and focused state on control replacement Jul 27, 2026
@atomiks
atomiks force-pushed the claude/field-lifecycle-audit-fixes-73dada branch from 69c0549 to c9cc2a5 Compare August 11, 2026 07:09
@atomiks atomiks changed the title [field] Fix stale filled and focused state on control replacement [all components] Fix stale filled and focused field state Aug 11, 2026
@atomiks
atomiks force-pushed the claude/field-lifecycle-audit-fixes-73dada branch 2 times, most recently from dfecc6b to 024457e Compare August 11, 2026 07:33
@atomiks

atomiks commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@github-actions

github-actions Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

review:

PR review

Nothing here is merge-blocking: the two mechanisms (last-attach-wins filled ownership, field-level focus ownership) are sound and well tested for the cases the description names. The concrete risk is that both fixes are incomplete in ways the new tests happen to mask — filled still latches when the owning control unmounts while a sibling survives, and focused still latches when a focused inner element (a Radio.Root, an OTPField.Input) goes away while its group stays mounted. Verification was static only; the PR head is treated as data, so I did not run the new tests.

Bugs (4)

1. 🟠 filled still goes stale when the owning control unmounts and a sibling survives

Location: packages/react/src/field/control/FieldControl.tsx:79

// `filled` belongs to the last control to attach; a null ref means the owner unmounted.
useIsoLayoutEffect(() => {
  if (validation.inputRef.current !== null && validation.inputRef.current !== inputRef.current) {
    return;
  }

  validation.inputRef.current = inputRef.current;
  setFilled(valueProp != null ? valueProp !== '' : Boolean(inputRef.current?.value));
}, [validation.inputRef, setFilled, valueProp]);

Reclaiming a released ref only happens when this effect re-runs, and its only reactive dep is valueProp. So a survivor reclaims ownership and republishes filled only if its value prop later changes — never for an uncontrolled control, and not at the moment the owner disappears. The state published by the now-dead owner stays on Field.Root until something else calls setFilled.

Two related notes on the same lines:

  • The comment is inaccurate and hides the gap: validation.inputRef is attached as an element ref on every Field.Control (line 118), so React nulls it when any control detaches, not only the owner. A null ref means "some control unmounted", which is why the guard alone can't tell "I should take over" from "I already had nothing".
  • While the ref sits at null, useFieldValidation.commit falls back to element = inputRef.current (useFieldValidation.ts:162-165) and Field.Control never populates registeredInputs, so it validates against null and reports an all-valid native state — required/pattern stop being enforced for the field. That fallback is pre-existing, but the new "survivor reclaims" story is what would have closed it and doesn't.

Failure scenario:

<Field.Root>
  <Field.Control value="" onValueChange={setValue} />   {/* empty */}
  {showExtra && <Field.Control defaultValue="x" />}     {/* filled, publishes filled=true */}
</Field.Root>

After showExtra flips to false, the only remaining control is empty but Field.Root still renders data-filled, so a floating label stays raised over an empty input. If the survivor is uncontrolled instead, it never recovers ownership at all.

Fix: Give the filled path the same shape as the focused path instead of overloading validation.inputRef as the ownership token — e.g. a field-level filledOwnerRef plus a cleanup that releases it, and a version counter on Field.Root bumped on release and included in this effect's deps so surviving controls re-run and republish. At minimum, add a cleanup that clears filled when the owner unmounts, so the stale value can't outlive its control.

2. 🟠 data-focused still latches when a focused inner element of a composite control unmounts or is disabled

Location: packages/react/src/radio-group/RadioGroup.tsx:72

const setFocused = useSetFieldFocused(disabled);

useSetFieldFocused is registered per control, but for RadioGroup and OTPField.Root the focusable elements are children. RadioGroup's onBlur sits on the group and is skipped when relatedTarget is inside it (RadioGroup.tsx:241); OTPField's handleInputBlur bails the same way (OTPFieldRoot.tsx:297). Since the group itself is neither disabled nor unmounted, neither the disabled branch nor the cleanup in useSetFieldFocused fires, and the new OTPFieldRoot.tsx:148 effect keys off the root's disabled only. Radio.Root and OTPField.Input have no focus handling of their own (no setFocused call sites in either file).

Failure scenario: <Field.Root><RadioGroup><Radio.Root value="a" disabled={hideA} /><Radio.Root value="b" /></RadioGroup></Field.Root> — focus radio a, then set hideA to true. The input becomes disabled, focus drops to <body>, no blur fires, and data-focused stays on Field.Root, Field.Label, and the group. Same outcome when a focused Radio.Root is unmounted from a dynamic option list, or when a focused OTPField.Input unmounts (which the new length-shrink-style pattern in OTPFieldRoot.test.tsx:716 shows is a real usage shape) — there both the field's focused and OTP's local focused stay latched.

Fix: Register the clear at the element that actually holds focus: call useSetFieldFocused (or a small shared "release focus on disable/unmount" hook) from Radio.Root and OTPField.Input, with ownership still recorded on the field so a sibling gaining focus wins. Delegating from the group via context, as AGENTS.md prescribes for shared handlers, keeps the group as the single owner of the logic.

3. 🟡 focusOwnerRef is never released, and its default is a module-level singleton

Location: packages/react/src/internals/field-root-context/useSetFieldFocused.ts:24

function clearWhenOwned() {
  if (focusOwnerRef.current === setFieldFocused) {
    setFocused(false);
  }
}

focusOwnerRef.current is only ever written on focus; nothing clears it on blur, on disable, or on unmount. After the owner unmounts, the field keeps a strong reference to that control's stable-callback object (which closes over the field context) for the lifetime of the Field.Root. Worse for the default path: DEFAULT_FIELD_ROOT_CONTEXT.focusOwnerRef (FieldRootContext.ts:53) is a single module-level object shared by every control rendered outside a Field.Root (and by ComboboxInput.tsx:456, which provides it downstream), so the last-focused standalone control's callback is retained globally for the app's lifetime.

Failure scenario: No behavioral bug — setFocused is NOOP on the default context and a fresh control always overwrites the owner on focus — but a long-lived page that mounts and unmounts many focused controls keeps one dead closure per Field.Root plus one global, and identity-by-liveness is easy to reason about wrongly in future edits.

Fix: Set focusOwnerRef.current = undefined inside clearWhenOwned after clearing (and when the owner reports focused === false), so ownership is released rather than merely superseded.

4. ℹ️ Two setFocused(false) call sites bypass the new ownership guard

Location: packages/react/src/select/root/SelectRoot.tsx:265

setTouched(true);
setFocused(false);

SelectRoot.tsx:265 and AriaCombobox.tsx:689 still take setFocused straight from useFieldRootContext() and clear it unconditionally on the focusOut/outsidePress close paths. Every other writer now goes through useSetFieldFocused, so these are the only places where one control can clear another control's focused state. I could not construct a failing ordering from the code — the focusout handling that triggers these runs before the receiving control's focus event in the paths I traced — so this is a consistency/maintenance note rather than a demonstrated bug.

Failure scenario: If either close path is ever deferred (microtask/timeout) past the next control's focus event, a Field.Root holding two Selects would drop data-focused right after focus legitimately moved to the second trigger.

Fix: Route both through useSetFieldFocused so the ownership check applies uniformly, or add a comment stating why the unguarded setter is intentional here.

Tests (1)

1. 🟠 No test pins data-filled at the moment the owning control unmounts

Location: packages/react/src/field/control/FieldControl.test.tsx:184

fireEvent.click(screen.getByRole('button', { name: 'Unmount second' }));
fireEvent.click(screen.getByRole('button', { name: 'Clear first' }));

expect(screen.getByTestId('root')).not.toHaveAttribute('data-filled');

Both controls in this fixture are filled (value="a" and defaultValue="filled"), and the only assertion comes after the survivor's value changes — which is exactly the one event that makes the reclaim path in FieldControl.tsx:80 run. The test therefore passes whether or not ownership transfers at unmount time, and it cannot fail for the gap in Bug 1.

Failure scenario: The untested case is an empty survivor plus a filled owner: assert not.toHaveAttribute('data-filled') immediately after Unmount second, before any value change. That assertion fails today. A second uncovered case is an uncontrolled survivor, where the reclaim never runs at all.

Fix: Split into two tests — one asserting data-filled is released as soon as the owner unmounts (empty survivor, no intervening interaction), and one with an uncontrolled survivor.

Simplifications (1)

1. 🟡 The if (disabled) branch in useSetFieldFocused is unreachable work

Location: packages/react/src/internals/field-root-context/useSetFieldFocused.ts:30

if (disabled) {
  clearWhenOwned();
}

return clearWhenOwned;

disabled is the only reactive dep (setFieldFocused, setFocused, and focusOwnerRef are all stable), so on a false -> true transition React runs the previous run's cleanup — clearWhenOwned() — before this setup body. The disable case is already handled there. The only time the branch runs without a preceding cleanup is the initial mount with disabled already true, where focusOwnerRef.current cannot yet equal this hook's freshly created callback. So the branch never clears anything the cleanup wouldn't.

Failure scenario: Three extra lines plus a duplicated call in every field-aware control's bundle, and a reader is led to believe the disable path is driven by the setup body when it is actually driven by the cleanup — which is where a future edit would need to go.

Fix: Drop the branch and keep only return clearWhenOwned;, with a comment noting that disabled is in the dep list precisely so the cleanup fires on the disable transition. (If the explicitness is preferred, keep the branch but say so in the comment, since the mechanism is genuinely non-obvious.)

Verdict

Approve after nits - no regression against master, but both fixes leave a same-class stale-state hole (filled on owner unmount, focused on inner-element unmount/disable) that the current tests cannot catch.


🤖 Review generated with Claude Code · Opus 5 (High) · medium review depth · 29 turns · 10m9s · $2.53 · run

@atomiks
atomiks force-pushed the claude/field-lifecycle-audit-fixes-73dada branch 3 times, most recently from 0f7cd42 to 127d36b Compare August 11, 2026 08:53
@github-actions github-actions Bot added PR: out-of-date The pull request has merge conflicts and can't be merged. and removed PR: out-of-date The pull request has merge conflicts and can't be merged. labels Aug 13, 2026
@atomiks
atomiks marked this pull request as ready for review August 19, 2026 09:25
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Aug 24, 2026
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Aug 26, 2026
@atomiks atomiks changed the title [all components] Fix stale filled and focused field state [all components] Fix stale focused field state Aug 26, 2026
@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Aug 27, 2026
@jjenzz

jjenzz commented Aug 27, 2026

Copy link
Copy Markdown
Member

DX review

The focus-ownership fix is sound overall, but disabled radios can still reacquire the field’s focused state.

Findings (1)

1. 🟠 Disabled radios can reacquire data-focused

Source: RadioRoot.tsx:155, RadioGroup.tsx:236

Problem:

Radio.Root records field focus before checking disabled, while RadioGroup also records every bubbled focus unconditionally. Because the default radio renders a non-native element, consumers can focus a disabled radio through its public ref. That focus reacquires data-focused after the cleanup has run, and no further disabled change clears it.

User scenario:

A design-system wrapper restores focus to the selected radio after an options update. If that option became disabled, the radio, field, and label receive data-focused alongside data-disabled, recreating the styling bug this PR fixes.

Suggested change:

Could we prevent disabled radios from acquiring field focus in both the standalone and grouped paths? Checkbox.Root and Switch.Root already check !disabled before calling their field focus setter: CheckboxRoot.tsx:306, SwitchRoot.tsx:127.

Please apply the same behavior to Radio.Root without preventing read-only radios from receiving focus. The grouped path also needs to avoid reacquiring focus from an individually disabled radio because its focus event bubbles to RadioGroup. A public-contract test should cover programmatic focus of a disabled standalone radio and an individually disabled grouped radio, including disability inherited from Field.Item.

What is already sound

  • The stable callback provides a suitable per-target ownership token without adding public API.
  • Cleanup releases ownership only when the disabled or unmounted target still owns focus.
  • The tests cover focused-target removal, disabling, re-enabling, and sibling ownership handoffs across the affected controls.

Verdict

Approve after nits — The remaining issue is localized to disabled Radio focus acquisition.


🤖 Review generated with Codex

@atomiks
atomiks force-pushed the claude/field-lifecycle-audit-fixes-73dada branch from 3a258aa to 1fccf43 Compare September 1, 2026 08:28
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Sep 1, 2026
@atomiks atomiks added scope: all components Widespread work has an impact on almost all components. and removed component: field Changes related to the field component. labels Sep 25, 2026
@atomiks
atomiks merged commit 5cc9fbd into mui:master Sep 25, 2026
26 checks passed
@atomiks
atomiks deleted the claude/field-lifecycle-audit-fixes-73dada branch September 25, 2026 06:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

scope: all components Widespread work has an impact on almost all components. type: bug It doesn't behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[field] data-focused attribute persists when data-disabled

2 participants