Skip to content

[number field] Deduplicate steppers and simplify internals - #5045

Merged
atomiks merged 1 commit into
mui:masterfrom
atomiks:number-field/cleanup
Jun 15, 2026
Merged

atomiks merged 1 commit into
mui:masterfrom
atomiks:number-field/cleanup

Conversation

@atomiks

@atomiks atomiks commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Headless refactor of the Number Field internals.

Changes

  • Deduplicate steppers: the near-identical NumberFieldIncrement/NumberFieldDecrement now share a useNumberFieldStepperButton hook.
  • Internals tidy:
    • getStepAmount typed () => number; dead DEFAULT_STEP fallbacks and the constant removed.
    • Remove dead UseNumberFieldButton* exports and unused NumberFieldScrubAreaContext fields.
    • Extract isNumeralChar and dedupe the plus/minus keydown handling; type getAllowedNonNumericKeys as Set<string>; derive the numeral-detection regexes from their arrays.
    • Rename getViewportRect's misleading width/height to right/bottom (they're absolute edge coords).
    • Hoist static button/scrub/cursor style objects; drop a per-stepper useMemo.
    • Use the shared stateAttributesMapping directly; Decrement type-only import.
  • Validation coverage: Added coverage for pre-round clamping with fractional bounds.
  • Comment/doc corrections: onValueChange keyboard reason, step="any" modifier stepping, teleportDistance, aria-roledescription, smallStep/largeStep snapping.

@atomiks atomiks added the component: number field Changes related to the number field component. label Jun 15, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

commit: bf15988

@code-infra-dashboard

code-infra-dashboard Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react ▼-1.13KB(-0.24%) ▼-287B(-0.19%)

Details of bundle changes

Performance

Total duration: 1,483.60 ms 🔺+257.00 ms(+21.0%) | Renders: 50 (+0) | Paint: 2,218.79 ms 🔺+370.98 ms(+20.1%)

Test Duration Renders
Slider mount (300 instances) 195.93 ms 🔺+34.50 ms(+21.4%) 3 (+0)
Menu mount (300 instances) 164.04 ms 🔺+31.31 ms(+23.6%) 2 (+0)
Scroll Area mount (300 instances) 112.71 ms 🔺+30.67 ms(+37.4%) 3 (+0)
Mixed surface mount (app-like density) 109.79 ms 🔺+21.48 ms(+24.3%) 5 (+0)
Checkbox mount (500 instances) 84.78 ms 🔺+17.69 ms(+26.4%) 1 (+0)

…and 2 more (+5 within noise) — details


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

@netlify

netlify Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit bf15988
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6a2fb0f740811400086cb211
😎 Deploy Preview https://deploy-preview-5045--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 requested a review from Copilot June 15, 2026 06:47
@atomiks
atomiks marked this pull request as ready for review June 15, 2026 06:47
@atomiks atomiks changed the title [number-field] Deduplicate steppers and simplify internals [number field] Deduplicate steppers and simplify internals Jun 15, 2026

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

Headless refactor of the Number Field internals to reduce duplication between increment/decrement steppers, simplify validation/parsing helpers, and clarify scrub-area coordinate handling while keeping behavior consistent (with a few targeted fixes covered by new tests/docs).

Changes:

  • Deduplicates increment/decrement stepper implementation via a shared useNumberFieldStepperButton hook and removes now-dead button-related exports/usages.
  • Simplifies/clarifies parsing and input handling (shared numeral detection, consolidated +/- sign handling, safer Infinity detection, tighter typing for getAllowedNonNumericKeys / getStepAmount).
  • Clarifies scrub-area viewport rect semantics (left/top/right/bottom) and hoists static style objects; adds tests/docs for edge-case behaviors (clamp-before-rounding, format prop updates, snapOnStep interactions).

Reviewed changes

Copilot reviewed 21 out of 21 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
packages/react/src/number-field/utils/validate.ts Documents clamp-before-rounding rationale for non-integer bounds.
packages/react/src/number-field/utils/validate.test.ts Adds coverage for clamping-before-rounding with integer formatting.
packages/react/src/number-field/utils/parse.ts Derives numeral detect regexes from arrays; adds isNumeralChar; simplifies parsing replacements and Infinity detection.
packages/react/src/number-field/utils/getViewportRect.ts Renames rect fields to left/top/right/bottom to reflect edge coordinates.
packages/react/src/number-field/utils/constants.ts Removes DEFAULT_STEP constant.
packages/react/src/number-field/scrub-area/NumberFieldScrubAreaContext.ts Removes unused scrub-area context fields.
packages/react/src/number-field/scrub-area/NumberFieldScrubArea.tsx Adopts new viewport-rect shape, removes DEFAULT_STEP fallback, hoists styles, and trims context payload.
packages/react/src/number-field/scrub-area-cursor/NumberFieldScrubAreaCursor.tsx Hoists cursor style object.
packages/react/src/number-field/scrub-area-cursor/NumberFieldScrubAreaCursor.test.tsx Updates test context shape to match removed context fields.
packages/react/src/number-field/root/useNumberFieldStepperButton.ts Introduces shared stepper button hook for increment/decrement.
packages/react/src/number-field/root/useNumberFieldButton.ts Removes DEFAULT_STEP fallback; improves dirty-text commit behavior before stepping; reuses shared touch-like detection.
packages/react/src/number-field/root/NumberFieldRootContext.ts Tightens typing of getStepAmount and getAllowedNonNumericKeys.
packages/react/src/number-field/root/NumberFieldRoot.tsx Refactors clamp/out-of-range logic readability; updates wheel listener comment; tightens step handling (step="any" base = 1).
packages/react/src/number-field/root/NumberFieldRoot.test.tsx Updates snap tests to use explicit snapOnStep; adds test for reformatting on format prop changes.
packages/react/src/number-field/input/NumberFieldInput.tsx Uses shared isNumeralChar and shared stateAttributesMapping; dedupes +/- handling.
packages/react/src/number-field/input/NumberFieldInput.test.tsx Renames tests for Home/End to reflect “set to min/max” behavior.
packages/react/src/number-field/increment/NumberFieldIncrement.tsx Replaces component logic with shared useNumberFieldStepperButton.
packages/react/src/number-field/increment/NumberFieldIncrement.test.tsx Adds regression test for avoiding snapped intermediate value before increment.
packages/react/src/number-field/decrement/NumberFieldDecrement.tsx Replaces component logic with shared useNumberFieldStepperButton.
packages/react/src/internals/usePressAndHold.ts Exports isTouchLikePointerType for reuse.
docs/src/app/(docs)/react/components/number-field/types.md Updates docs to match reason semantics, step="any" behavior, aria-roledescription clarifications, and button tag typo fixes.

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

@github-actions github-actions Bot added the PR: out-of-date The pull request has merge conflicts and can't be merged. label Jun 15, 2026
@atomiks
atomiks force-pushed the number-field/cleanup branch from 3d41e2a to 1c45826 Compare June 15, 2026 07:42
@github-actions github-actions Bot removed the PR: out-of-date The pull request has merge conflicts and can't be merged. label Jun 15, 2026

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

Verdict: ✅ Clean. Approve.

No critical or important issues. This is a careful, behavior-preserving refactor with a few intentional, well-tested fixes. TypeScript checks clean.

Critical Issues

None.

Important Issues

None.

Suggestions (all optional)

  1. step="any" interactive stepping is untested — and this PR now leans on it. (tests, criticality 6) Removing ?? DEFAULT_STEP makes the step = stepProp === 'any' ? 1 : stepProp resolution (NumberFieldRoot.tsx:95) load-bearing, but the only step="any" test covers form validation, not stepping. A regression in that resolution would fail no test. Suggest: <NumberField defaultValue={5} step="any" /> → click Increase expects '6' (and Alt→5.1, Shift→15, which the new JSDoc now explicitly promises).

  2. Scrub-area pointer-lock flushSync removal is untested. (tests, criticality 4) The removed nested flushSync relies on onScrubbingChange already flushing — verified correct by reading, but no test exercises the post-pointer-lock cursor path (Chromium-only, low value).

  3. Cosmetic: unused catch (error) binding at NumberFieldScrubArea.tsx:311 (pre-existing, not from this PR). Could be catch { to match line 163's style.

  4. Minor asymmetry now visible side-by-side in the shared hook: onStop commits unconditionally while onClick commits only when committed !== prev (useNumberFieldButton.ts:84 vs :118). Pre-existing and preserved — noting only because dedup put them adjacent.

What was verified sound (the load-bearing changes)

  • Dropped useMemo for buttonState in the new shared useNumberFieldStepperButton — safe; useRenderElement never uses state identity, and a fresh object per render is the established pattern.
  • commitValue no-direction + !details.isCanceled guard — the intended fix; avoids a spurious directionally-snapped intermediate and correctly steps from the applied (not rejected) base. New test at NumberFieldIncrement.test.tsx:397 was confirmed to fail when the fix is reverted.
  • getStepAmount: () => number and all ?? DEFAULT_STEP removals — every path returns a finite number (including step="any"→1); the guards were already dead code.
  • validate.ts two-pass clamp — both clamps genuinely needed for non-integer bounds; new test at validate.test.ts:547 uniquely covers the before-rounding pass (fails only when that clamp is removed).
  • parse.ts — { regex: groupRegex } is equivalent (groupRegex is null when group is falsy), input.includes('∞') ≡ the old regex, DETECT_REs derived from arrays have no TDZ issue.
  • getViewportRect width/height→right/bottom rename — all branches and the sole consumer updated consistently.
  • ScrubArea context field removals and [minWithDefault, formatStyle]→[minWithDefault] dep change — no remaining consumers / no stale closure.
  • All 10 modified comments/JSDoc audited accurate — no comment rot introduced.

Strengths

  • Genuine duplication elimination (two near-identical steppers → one shared hook), directly advancing the "avoid duplicating logic" guideline.
  • The risky behavior fixes each ship with a dedicated regression test that the analyzer empirically confirmed fails without the fix.
  • High-quality "why over what" comments paired with locking tests; docs (types.md) and JSDoc updated together.

Recommended action

Mergeable as-is. If you want to harden it, add the step="any" stepping test (suggestion #1) — that's the one real coverage hole and it's now load-bearing.

Deduplicate the near-identical Increment/Decrement components into a shared
useNumberFieldStepperButton hook, and tidy internals without changing behavior:

- getStepAmount typed () => number; drop the dead DEFAULT_STEP fallbacks/constant.
- Remove dead UseNumberFieldButton exports and unused ScrubAreaContext fields.
- Extract isNumeralChar and dedupe the plus/minus keydown handling; type
  getAllowedNonNumericKeys as Set<string>; derive numeral-detection regexes from
  their arrays.
- Rename getViewportRect's misleading width/height to right/bottom edge coords.
- Hoist static button/scrub/cursor style objects; drop a per-stepper useMemo.
- Use the shared stateAttributesMapping directly; Decrement type-only import.
- Comment/doc corrections (onValueChange keyboard reason, step=any modifier
  stepping, teleportDistance, aria-roledescription, smallStep/largeStep snapping).
@atomiks
atomiks force-pushed the number-field/cleanup branch from 1c45826 to bf15988 Compare June 15, 2026 07:59
@atomiks atomiks added the internal Behind-the-scenes enhancement. Formerly called “core”. label Jun 15, 2026
@atomiks
atomiks merged commit 9945e7f into mui:master Jun 15, 2026
7 checks passed
@atomiks
atomiks deleted the number-field/cleanup branch June 15, 2026 08:35
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. internal Behind-the-scenes enhancement. Formerly called “core”.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants