Skip to content

[field] Fix data-dirty tracking for null-valued controls - #5290

Merged
sai6855 merged 15 commits into
mui:masterfrom
sai6855:number-field-null
Jul 23, 2026
Merged

sai6855 merged 15 commits into
mui:masterfrom
sai6855:number-field-null

Conversation

@sai6855

@sai6855 sai6855 commented Jul 21, 2026 •

Copy link
Copy Markdown
Member

RCA and reproduction steps: #5290 (comment)

@sai6855
sai6855 requested a review from Copilot July 21, 2026 06:23
@sai6855 sai6855 added component: number field Changes related to the number field component. type: bug It doesn't behave as expected. labels Jul 21, 2026
@pkg-pr-new

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

commit: 5eb12e0

@netlify

netlify Bot commented Jul 21, 2026

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit a7195c3
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6a5f0ff41dc78a0008fb9508
😎 Deploy Preview https://deploy-preview-5290--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.

@code-infra-dashboard

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

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+13B(0.00%) 🔺+9B(+0.01%)

Details of bundle changes

Performance

Total duration: 1,394.62 ms +112.84 ms(+8.8%) | Renders: 78 (+0) | Paint: 2,158.96 ms +140.58 ms(+7.0%)

Test Duration Renders
Tabs mount (200 instances) 224.13 ms 🔺+41.92 ms(+23.0%) 3 (+0)
Checkbox mount (500 instances) 86.35 ms 🔺+19.47 ms(+29.1%) 1 (+0)
Dialog mount (300 instances) 72.72 ms 🔺+12.94 ms(+21.6%) 1 (+0)

12 tests within noise — details

Metric alarms

Test Metric Change
Tabs mount (200 instances) bench:paint 🔺 +58.80 ms
Checkbox mount (500 instances) bench:paint 🔺 +24.74 ms
Dialog mount (300 instances) bench:paint 🔺 +19.39 ms

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

Copilot AI 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.

Pull request overview

This PR fixes how data-dirty is computed for fields whose “empty” value is null (notably NumberField), ensuring the field is no longer considered dirty after the user returns to the original empty value.

Changes:

  • Prevent useFieldControlRegistration from re-syncing the field’s “initial value” after the first registration, avoiding accidental capture of a later user-edited value as the initial value.
  • Add a regression test verifying data-dirty is cleared when a NumberField goes from empty → non-empty → empty.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
packages/react/src/internals/field-register-control/useFieldControlRegistration.ts Sync initial field value only once to avoid mis-tracking dirty state for null-empty controls.
packages/react/src/field/root/FieldRoot.test.tsx Adds coverage for data-dirty clearing when a null-empty NumberField returns to its empty initial value.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@netlify

netlify Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit 5eb12e0
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6a616240ac99cc000829d7c8
😎 Deploy Preview https://deploy-preview-5290--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.

@@ -82,6 +83,12 @@ export function useFieldControlRegistration(params: UseFieldControlRegistrationP
}

function syncInitialValue() {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Root cause

syncInitialValue is intended to run only once when a field mounts. However, it currently runs on every value change. As a result, the field's initial value is overwritten with the latest value, which causes the data-dirty state to be calculated incorrectly.

Running syncInitialValue only once on mount fixes the issue.

Reproduction

  1. Open https://base-ui.com/react/handbook/forms.
  2. Enter 5 in both the Server name and Number of instances fields.
  3. Verify that data-dirty is applied to both fields. ✅
  4. Clear both fields.
  5. Notice that data-dirty is removed from Server name, but remains on Number of instances. ❌

Why this happens

For components such as NumberField and Select, the initial value is null rather than "".

Because syncInitialValue runs on every value change, validityData.initialValue is overwritten with the first value entered by the user instead of preserving the original null value. Consequently, when the field is cleared back to null, the current value no longer matches the stored initial value, so data-dirty incorrectly remains applied.

Making syncInitialValue run only once during mount preserves the correct initial value and fixes the issue.

@sai6855
sai6855 marked this pull request as ready for review July 21, 2026 06:36
@atomiks

atomiks commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

PR review

Root cause analysis is correct and the fix works — I reproduced the bug on master with Select (stuck data-dirty after clearing to null) and RadioGroup (inverse: data-dirty wrongly clears when returning to the first-picked value), and both heal with this change. The affected surface is every null-initial control (NumberField, Select single, Combobox/Autocomplete single, RadioGroup with no defaultValue), so the scope is wider than the title suggests. Nothing merge-blocking; the main gap is test coverage for the other affected components.

Bugs (2)

1. 🟡 ranOnce never resets when the control unregisters

Location: packages/react/src/internals/field-register-control/useFieldControlRegistration.ts:33

const ranOnce = React.useRef(false);

The flag lives on the Field root and is never cleared, including in the register(source, undefined) unregister path. If a null-initial control (e.g. NumberField) mounts first and is later swapped for a different control with a defaultValue under the same Field.Root, the second control's initial value is never captured, so its dirty state is computed against the first control's null baseline.

Failure scenario: Field conditionally renders NumberField, then swaps to a text input with defaultValue="x" — the input shows data-dirty immediately without user interaction.

Fix: Reset ranOnce.current = false in the unregister branch of register (where registrationRef.current = null is set).

2. ℹ️ Behavior change for late-arriving controlled values

Location: packages/react/src/internals/field-register-control/useFieldControlRegistration.ts:86

Previously, a controlled null-initial control whose value arrives asynchronously (e.g. Select value set after a fetch) had that first non-null value recorded as the baseline, so it was not dirty. With this fix the baseline stays null, so the field becomes data-dirty with no user interaction. Arguably the new behavior is the correct reading of "changed since mount", but it is an observable change worth deciding intentionally rather than by accident.

Tests (1)

1. 🟠 Only NumberField is pinned; the other affected controls have no regression test

Location: packages/react/src/field/root/FieldRoot.test.tsx:1470

The fix is in a shared util, and the two failure modes are distinct: stuck-dirty (NumberField, Select single, Combobox single) and dirty-wrongly-cleared (RadioGroup: pick A, pick B, return to A — must stay dirty since the true initial was null). The new test pins only the first mode via NumberField. Existing [data-dirty] tests for Select single, Combobox, and Autocomplete are one-way (assert dirty appears, never return to initial), and RadioGroup has no positive dirty test at all, so a future regression in either mode would ship silently for those components.

Fix: Add one test per failure mode — a Select (or Combobox) clear-to-null round-trip, and the RadioGroup return-to-first-pick case.

Simplifications (1)

1. 🟡 Ref naming convention

Location: packages/react/src/internals/field-register-control/useFieldControlRegistration.ts:33

Refs in this file follow the xxxRef suffix (registrationRef, markedDirtyRef, activeFieldControlSourceRef). Rename ranOnce to something like syncedInitialValueRef — also self-documents what ran once.

Docs (1)

1. ℹ️ Title/commit scope undersells the fix

The change fixes Select, Combobox/Autocomplete, and RadioGroup dirty tracking too, not just NumberField. Suggest retitling to [field] Fix data-dirty tracking for null-valued controls so the changelog reaches affected users.

Verdict

Approve after nits — fix is verified correct across all affected components; missing regression tests for Select/RadioGroup are the main gap.


🤖 Review generated with Claude Code

@sai6855 sai6855 changed the title [number field] Fix applying data-dirty correctly [field] Fix applying data-dirty correctly Jul 21, 2026
@sai6855 sai6855 added component: select Changes related to the select component. component: radio group Changes related to the radio group component. labels Jul 21, 2026
@sai6855
sai6855 force-pushed the number-field-null branch 2 times, most recently from 632ea1a to 90730e0 Compare July 21, 2026 11:51
@sai6855 sai6855 changed the title [field] Fix applying data-dirty correctly [field] Fix data-dirty tracking for null-valued controls Jul 21, 2026
@sai6855

sai6855 commented Jul 21, 2026

Copy link
Copy Markdown
Member Author
  1. 🟡 ranOnce never resets when the control unregisters

Fixed this bug but in different way than suggested. Suggested way reintroduced initial bug which this PR intended to fix

  1. ℹ️ Behavior change for late-arriving controlled values

I think new behaviour is correct, dirty means the value differs from the initial value captured at mount, so a value that arrives later (async fetch / setValue) is a change → dirty. If a fetched value should be the baseline, set it as the field's initial value (render it from the start or reset the form).

Only NumberField is pinned; the other affected controls have no regression test

Fixed

Ref naming convention

Fixed

Title/commit scope undersells the fix

Fixed

@atomiks

atomiks commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

PR review (follow-up)

No merge-blocking issues found, but control swapping still has one narrow dirty-state bug. Existing FieldRoot suites pass in jsdom and Chromium; an added non-null baseline regression test fails on the current head.

Bugs (1)

1. 🟠 Recapture non-null baselines when swapping controls

Location: packages/react/src/internals/field-register-control/useFieldControlRegistration.ts:100

if (validityData.initialValue === null && initialValue !== null) {
  setValidityData((prev) => ({ ...prev, initialValue }));
}

The new source guard permits synchronization for each swapped-in control, but this condition only replaces a null baseline. When the previous control had a non-null initial value, the replacement control continues comparing against that stale value.

Failure scenario: Swap a control with defaultValue="a" for one with defaultValue="x", change the replacement to y, then return it to x. The field incorrectly retains data-dirty.

Fix: Update the baseline whenever the control source changes, while returning the previous state object when the value is unchanged to avoid an unnecessary render:

diff --git a/packages/react/src/internals/field-register-control/useFieldControlRegistration.ts b/packages/react/src/internals/field-register-control/useFieldControlRegistration.ts
@@
     const initialValue = getRegistrationValue(registration);

-    if (validityData.initialValue === null && initialValue !== null) {
-      setValidityData((prev) => ({ ...prev, initialValue }));
-    }
+    setValidityData((prev) => {
+      if (Object.is(prev.initialValue, initialValue)) {
+        return prev;
+      }
+
+      return { ...prev, initialValue };
+    });

The source guard prevents subsequent value changes from overwriting the baseline. Please also add a non-null-to-non-null control-swap regression test.

Tests (0)

No findings.

Simplifications (0)

No findings.

Docs (0)

No findings.

Verdict

Approve after nits - the null-initial-value fix works, but swapped controls can retain a stale non-null baseline.


🤖 Review generated with Codex

@sai6855
sai6855 force-pushed the number-field-null branch from 90730e0 to 426a5a3 Compare July 21, 2026 12:54
@sai6855

sai6855 commented Jul 21, 2026

Copy link
Copy Markdown
Member Author

done

@atomiks

atomiks commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

New agent review, keep finding fresh issues - this one is narrow, though

PR review

The fix direction is sound: capturing the baseline once per control source (including null) fixes data-dirty never clearing for null-valued controls, and the new tests pin it well. One confirmed behavior change worth an explicit decision before merge.

Bugs (1)

1. 🟠 Remounting the same control resets the dirty baseline to the current value

Location: packages/react/src/internals/field-register-control/useFieldControlRegistration.ts:86

useRegisterFieldControl creates a fresh Symbol() per component instance, so an unmount/remount of the same control is indistinguishable from a control swap: the new symbol passes the gate and initialValue is recaptured as whatever the value is at remount time. Before this PR, a non-null baseline was never overwritten, so it survived remounts.

Failure scenario: Controlled Select inside a persistent Field.Root, initial value 'a'. User picks 'b' (dirty), the control is conditionally hidden and reshown (e.g. collapsible section) while Field.Root stays mounted, then the user picks 'a' again. The field now stays data-dirty ('a' !== 'b') and would read as clean at 'b'. Verified locally: this exact test passes on master and fails with the PR applied. (StrictMode is fine — the symbol persists across effect re-runs; only a real remount triggers it.)

Fix: If recapture-on-swap is the intended semantic this may be acceptable, but it should be pinned with a test. A heuristic that fixes the remount case while keeping the swap tests green — skip recapture when the field is already dirty:

   function syncInitialValue() {
     const source = activeFieldControlSourceRef.current;
     if (syncedInitialValueSourceRef.current === source) {
       return;
     }

     syncedInitialValueSourceRef.current = source;

+    // A new control source normally recaptures the baseline (control swap), but if the
+    // user has already dirtied the field, treat the remounting control as the same
+    // logical field and keep the original baseline.
+    if (markedDirtyRef.current) {
+      return;
+    }
+
     const registration = registrationRef.current;
     if (!registration) {
       return;
     }

The trade-off: a swap after interaction now keeps the old baseline instead of recapturing — ambiguous either way; this picks "preserve".

Docs (1)

2. ℹ️ New per-source gate deserves a one-line comment

syncInitialValue now encodes a non-obvious contract: capture the baseline exactly once per control source (even null), recapture only when a different control registers. A short comment would stop a future "simplification" from reintroducing the original bug (covered by the suggestion above if taken).

Verdict

Approve after nits — the confirmed remount baseline reset is narrow and possibly acceptable, but should be an explicit decision with a pinning test.


🤖 Review generated with Claude Code

@sai6855

sai6855 commented Jul 22, 2026

Copy link
Copy Markdown
Member Author

New agent review, keep finding fresh issues - this one is narrow, though

Fixed, hopefully everything is resolved now :)

@atomiks

atomiks commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

They kept finding new issues :-)

A remount and a control swap look identical to the registration hook (both are unregister -> register with all-new identity), and each fix guessed with a different proxy, so each one fixed one case and broke another.

The new guard (I pushed above) uses the only signal that actually separates them: a new instance registering with the previous instance's last known value is a remount (keep baseline), anything else is a swap (recapture). This is independent of dirty history, so validate()/user edits can't poison a later swap.

Will re-review with both 5.6 + Fable now

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Jul 22, 2026
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Jul 22, 2026
@atomiks

atomiks commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

It turns out the first review's bug was something that should have been ignored.

The original review assumed swapping controls inside the same <Field.Root> should reset its baseline. Trying to preserve remounts while supporting that behavior led to unreliable source/value heuristics and several follow-up fixes. I ultimately realized that the baseline belongs to <Field.Root>, so the original capture-once approach was correct

The first reported bug was a non-issue because swapping a control does not create a new field: the baseline belongs to the Field root. The reported immediate data-dirty issue also does not occur, since registration does not recompute dirty state on mount. A new baseline requires remounting or keying the Field root.

@sai6855
sai6855 merged commit d060189 into mui:master Jul 23, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: number field Changes related to the number field component. component: radio group Changes related to the radio group component. 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.

3 participants