Skip to content

[form] Focus the first invalid field in document order - #5287

Merged
atomiks merged 6 commits into
mui:masterfrom
atomiks:claude/base-ui-5284-version-76a953
Jul 21, 2026
Merged

atomiks merged 6 commits into
mui:masterfrom
atomiks:claude/base-ui-5284-version-76a953

Conversation

@atomiks

@atomiks atomiks commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Closes #5284

After an invalid submit, Form focuses the first invalid field by iterating the internal fields Map in insertion order. That order drifts: a control re-registers whenever its value changes, and the deregister/re-register cycle deletes and re-adds the Map entry, moving the field to the end. Toggling a required checkbox and submitting again then focuses a later field instead of the first invalid one in the DOM, which degrades the experience for keyboard and screen reader users relying on focus landing on the first error.

Two changes:

  • Value changes no longer deregister and re-register the field control; re-registration updates the existing Map entry in place, keeping the registry stable. Deregistration now happens only on unmount or when registration is disabled. This alone fixes the reported sequence.
  • focusFirstInvalid selects the invalid control by document position rather than registration order, since registration order can also diverge from DOM order without any re-registration (keyed fields reordered without remounting, portals). The comparison applies only when the controls are in the same tree; for disconnected controls (e.g. separate shadow roots), where compareDocumentPosition is implementation-specific, the now-stable registration order is kept.

The existing contract is preserved: submission stays blocked when a field is invalid without a focusable control. The keyed-reorder regression test renders without Strict Mode, which re-runs effects when a keyed subtree moves and would re-register the fields in DOM order, masking the divergence the test pins.

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

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

commit: 01ae34b

@code-infra-dashboard

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

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+222B(+0.05%) 🔺+104B(+0.07%)

Details of bundle changes

Performance

Total duration: 1,238.56 ms -74.05 ms(-5.6%) | Renders: 78 (+0) | Paint: 1,940.45 ms -97.04 ms(-4.8%)

No significant changes — details


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

@netlify

netlify Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit 01ae34b
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6a5f2dad92475900084bbf5d
😎 Deploy Preview https://deploy-preview-5287--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 marked this pull request as ready for review July 21, 2026 05:26

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

This PR fixes invalid-field focus drifting away from the first DOM error by (1) making field re-registration update the fields Map entry in place instead of delete+re-add, and (2) selecting the invalid control by document position rather than registration order. The logic is correct, the DOM-position comparison uses the right compareDocumentPosition argument order, and the disconnected-tree fallback is genuinely exercised by the shadow-root test. Nothing merge-blocking; I found only two minor observations.

Bugs (0)

No findings.

The two behavioral changes hold up under scrutiny:

  • comesBeforeInSameTree(control, firstControl) returns true exactly when control precedes firstControl in the same tree (element.compareDocumentPosition(reference) & FOLLOWING means reference follows element), so the loop keeps the DOM-earliest control. The DOCUMENT_POSITION_DISCONNECTED guard correctly falls back to registration order for separate roots — verified by the shadow-root test, which would focus b instead of a if the disconnected branch were mishandled.
  • Splitting useRegisterFieldControl into a register/re-register effect plus an unmount-only cleanup effect preserves every prior invariant: disable still deregisters (registerFieldControl(source, undefined)), unmount still deregisters (stable sourceRef/registerFieldControl deps), and id changes still delete the previous entry inside register. The removed per-render cleanup only elided a transient deregister that was immediately overwritten.

Tests (0)

No findings.

Coverage is strong: value-change stability, keyed-reorder DOM ordering (correctly rendered with strict: false, since Strict Mode's effect re-runs would re-register in DOM order and mask the divergence), and the disconnected-tree fallback each pin a distinct branch.

Simplifications (0)

No findings.

comesBeforeInSameTree overlaps with sortByDocumentPosition in CompositeList.tsx, but the added DOCUMENT_POSITION_DISCONNECTED guard is a real semantic difference, so keeping it local is reasonable rather than duplication worth consolidating.

Docs (0)

No findings.

Verdict

Approve — correct, well-tested fix with no blocking or non-blocking issues; the only NumberField test failure is a pre-existing ICU/locale issue on master, unrelated to this diff.

Two optional notes for the maintainer:

  • ℹ️ Form.test.tsx — the two new render(<App />, ...) / render(<Form>...) calls (value-change and keyed-reorder tests) omit await, while the rest of the file (including the line changed at ~47) uses await render(...). Harmless since render returns a synchronously-usable result, but inconsistent.
  • ℹ️ Form.tsx:63-64 — if a still-registered field's controlRef ever pointed at a node detached from the document while later invalid controls were connected, the disconnected guard would keep the detached control and .focus() would silently no-op. Not reachable through normal mount/unmount (unmount deregisters), so no action needed — just the one edge the compareDocumentPosition fallback doesn't rank.

🤖 Review generated with Claude Code

@atomiks
atomiks merged commit 293a0f1 into mui:master Jul 21, 2026
6 checks passed
@atomiks
atomiks deleted the claude/base-ui-5284-version-76a953 branch July 21, 2026 08:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[form] Focus can land on the wrong invalid field on submit

2 participants