Repository navigation
[number field] Deduplicate steppers and simplify internals - #5045
Conversation
commit: |
Bundle size
PerformanceTotal duration: 1,483.60 ms 🔺+257.00 ms(+21.0%) | Renders: 50 (+0) | Paint: 2,218.79 ms 🔺+370.98 ms(+20.1%)
…and 2 more (+5 within noise) — details Check out the code infra dashboard for more information about this PR. |
✅ Deploy Preview for base-ui ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
There was a problem hiding this comment.
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
useNumberFieldStepperButtonhook 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.
3d41e2a to
1c45826
Compare
There was a problem hiding this comment.
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)
-
step="any"interactive stepping is untested — and this PR now leans on it. (tests, criticality 6) Removing?? DEFAULT_STEPmakes thestep = stepProp === 'any' ? 1 : stepPropresolution (NumberFieldRoot.tsx:95) load-bearing, but the onlystep="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). -
Scrub-area pointer-lock
flushSyncremoval is untested. (tests, criticality 4) The removed nestedflushSyncrelies ononScrubbingChangealready flushing — verified correct by reading, but no test exercises the post-pointer-lock cursor path (Chromium-only, low value). -
Cosmetic: unused
catch (error)binding atNumberFieldScrubArea.tsx:311(pre-existing, not from this PR). Could becatch {to match line 163's style. -
Minor asymmetry now visible side-by-side in the shared hook:
onStopcommits unconditionally whileonClickcommits only whencommitted !== prev(useNumberFieldButton.ts:84vs:118). Pre-existing and preserved — noting only because dedup put them adjacent.
What was verified sound (the load-bearing changes)
- Dropped
useMemoforbuttonStatein the new shareduseNumberFieldStepperButton— safe;useRenderElementnever usesstateidentity, and a fresh object per render is the established pattern. commitValueno-direction +!details.isCanceledguard — the intended fix; avoids a spurious directionally-snapped intermediate and correctly steps from the applied (not rejected) base. New test atNumberFieldIncrement.test.tsx:397was confirmed to fail when the fix is reverted.getStepAmount: () => numberand all?? DEFAULT_STEPremovals — every path returns a finite number (includingstep="any"→1); the guards were already dead code.validate.tstwo-pass clamp — both clamps genuinely needed for non-integer bounds; new test atvalidate.test.ts:547uniquely 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.getViewportRectwidth/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).
1c45826 to
bf15988
Compare
Headless refactor of the Number Field internals.
Changes
NumberFieldIncrement/NumberFieldDecrementnow share auseNumberFieldStepperButtonhook.getStepAmounttyped() => number; deadDEFAULT_STEPfallbacks and the constant removed.UseNumberFieldButton*exports and unusedNumberFieldScrubAreaContextfields.isNumeralCharand dedupe the plus/minus keydown handling; typegetAllowedNonNumericKeysasSet<string>; derive the numeral-detection regexes from their arrays.getViewportRect's misleadingwidth/heighttoright/bottom(they're absolute edge coords).useMemo.stateAttributesMappingdirectly;Decrementtype-only import.onValueChangekeyboard reason,step="any"modifier stepping,teleportDistance,aria-roledescription,smallStep/largeStepsnapping.