Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(NumberInput): commit an out-of-range entry at the nearest bound (#5152)

Cindy Zhang60cea48a97ad
diff --git a/.changeset/numberinput-clamp-to-bound.md b/.changeset/numberinput-clamp-to-bound.md
new file mode 100644
index 0000000000..397436f720
--- /dev/null
+++ b/.changeset/numberinput-clamp-to-bound.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] NumberInput: an entry past `min`/`max` now commits at the nearest bound on blur or Enter instead of falling back to the last in-range prefix — typing 100 into a 1–2 field lands on 2, not 1. Pagination inherits this.
+
+@cixzhang
diff --git a/packages/core/src/NumberInput/NumberInput.doc.mjs b/packages/core/src/NumberInput/NumberInput.doc.mjs
index bcfc134a90..a816367f3e 100644
--- a/packages/core/src/NumberInput/NumberInput.doc.mjs
+++ b/packages/core/src/NumberInput/NumberInput.doc.mjs
@@ -128,12 +128,14 @@ export const docs = {
{
name: 'min',
type: 'number | null',
- description: 'Minimum value allowed.',
+ description:
+ 'Minimum value allowed. A smaller entry commits at this value on blur or Enter.',
},
{
name: 'max',
type: 'number | null',
- description: 'Maximum value allowed.',
+ description:
+ 'Maximum value allowed. A larger entry commits at this value on blur or Enter.',
},
{
name: 'step',
@@ -410,12 +412,12 @@ export const docsZh = {
{
name: 'min',
type: 'number | null',
- description: '允许的最小值。',
+ description: '允许的最小值。更小的输入会在失焦或按 Enter 时提交为该值。',
},
{
name: 'max',
type: 'number | null',
- description: '允许的最大值。',
+ description: '允许的最大值。更大的输入会在失焦或按 Enter 时提交为该值。',
},
{
name: 'step',
diff --git a/packages/core/src/NumberInput/NumberInput.test.tsx b/packages/core/src/NumberInput/NumberInput.test.tsx
index 164b29a8f6..eb9ea1c2a9 100644
--- a/packages/core/src/NumberInput/NumberInput.test.tsx
+++ b/packages/core/src/NumberInput/NumberInput.test.tsx
@@ -10,6 +10,7 @@
*/
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {useState} from 'react';
import {render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {TestIcon} from '../__tests__/TestIcon';
@@ -540,6 +541,233 @@ describe('NumberInput', () => {
});
});
+ describe('range clamping on commit', () => {
+ it('commits an over-max entry at max on blur', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Page"
+ value={null}
+ onChange={handleChange}
+ min={1}
+ max={2}
+ isIntegerOnly
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '100');
+ handleChange.mockClear();
+ await user.tab();
+
+ expect(handleChange).toHaveBeenCalledWith(2);
+ });
+
+ it('commits an over-max entry at max on Enter', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Rating"
+ value={null}
+ onChange={handleChange}
+ max={5}
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '10');
+ handleChange.mockClear();
+ await user.keyboard('{Enter}');
+
+ expect(handleChange).toHaveBeenCalledWith(5);
+ });
+
+ it('commits a below-min entry at min', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Age"
+ value={null}
+ onChange={handleChange}
+ min={0}
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '-5');
+ await user.tab();
+
+ expect(handleChange).toHaveBeenCalledWith(0);
+ });
+
+ it('does not clamp while typing', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Rating"
+ value={null}
+ onChange={handleChange}
+ max={5}
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '10');
+
+ // The entry stays exactly as typed until it is committed.
+ expect(input).toHaveValue('10');
+ expect(handleChange).not.toHaveBeenCalledWith(5);
+ });
+
+ it('displays the clamped value after commit', async () => {
+ const user = userEvent.setup();
+ function ControlledNumberInput() {
+ const [value, setValue] = useState<number>(1);
+ return (
+ <NumberInput
+ label="Page"
+ value={value}
+ onChange={setValue}
+ min={1}
+ max={2}
+ isIntegerOnly
+ />
+ );
+ }
+ render(<ControlledNumberInput />);
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.clear(input);
+ await user.type(input, '100');
+ await user.tab();
+
+ expect(input).toHaveValue('2');
+ });
+
+ it('shows the clamped value in the field after Enter', async () => {
+ const user = userEvent.setup();
+ function ControlledNumberInput() {
+ const [value, setValue] = useState<number | null>(null);
+ return (
+ <NumberInput
+ label="Rating"
+ value={value}
+ onChange={setValue}
+ min={1}
+ max={5}
+ />
+ );
+ }
+ render(<ControlledNumberInput />);
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '10{Enter}');
+
+ // Still focused: the field must not keep showing the rejected entry.
+ expect(input).toHaveValue('5');
+ });
+
+ it('reverts an entry that is not a usable number', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Count"
+ value={null}
+ onChange={handleChange}
+ max={10}
+ isIntegerOnly
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '12.5');
+ handleChange.mockClear();
+ await user.tab();
+
+ expect(handleChange).not.toHaveBeenCalled();
+ expect(input).toHaveValue('');
+ });
+
+ it('rounds a fractional max inwards for an integer-only field', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Count"
+ value={null}
+ onChange={handleChange}
+ max={9.5}
+ isIntegerOnly
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '20');
+ handleChange.mockClear();
+ await user.tab();
+
+ expect(handleChange).toHaveBeenCalledWith(9);
+ });
+
+ it('rounds a fractional min inwards for an integer-only field', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Count"
+ value={null}
+ onChange={handleChange}
+ min={0.5}
+ isIntegerOnly
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '0');
+ handleChange.mockClear();
+ await user.tab();
+
+ expect(handleChange).toHaveBeenCalledWith(1);
+ });
+
+ it('does not clamp when no value can satisfy both bounds', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Count"
+ value={null}
+ onChange={handleChange}
+ min={5}
+ max={2}
+ />,
+ );
+
+ const input = screen.getByRole('spinbutton');
+ await user.click(input);
+ await user.type(input, '10');
+ handleChange.mockClear();
+ await user.tab();
+
+ expect(handleChange).not.toHaveBeenCalled();
+ expect(input).toHaveValue('');
+ });
+ });
+
describe('status prop', () => {
it('renders with error status icon', () => {
const {container} = render(
diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsx
index d10bcc8f0f..9eb883965c 100644
--- a/packages/core/src/NumberInput/NumberInput.tsx
+++ b/packages/core/src/NumberInput/NumberInput.tsx
@@ -351,10 +351,12 @@ interface NumberInputPropsBase extends Omit<
autoComplete?: string;
/**
* The minimum value allowed.
+ * A smaller entry commits at this value on blur or Enter.
*/
min?: number | null;
/**
* The maximum value allowed.
+ * A larger entry commits at this value on blur or Enter.
*/
max?: number | null;
/**
@@ -429,15 +431,12 @@ export type NumberInputProps =
NumberInputPropsNonClearable | NumberInputPropsClearable;
/**
- * Read the typed or pasted text as a number, then apply the field's
- * constraints.
- * Returns null if the input is not a valid number or fails validation.
+ * Read the typed or pasted text as a number, applying the shape rules (finite,
+ * and integral when `isIntegerOnly`) but not the min/max range.
*/
-function parseNumberInput(
+function parseNumericInput(
input: string,
options: {
- min?: number | null;
- max?: number | null;
isIntegerOnly?: boolean;
locale?: Locale;
},
@@ -452,11 +451,31 @@ function parseNumberInput(
return null;
}
- // Check integer constraint
if (options.isIntegerOnly && !Number.isInteger(num)) {
return null;
}
+ return num;
+}
+
+/**
+ * Parse and validate a string input as a number.
+ * Returns null if the input is not a valid number or fails validation.
+ */
+function parseNumberInput(
+ input: string,
+ options: {
+ min?: number | null;
+ max?: number | null;
+ isIntegerOnly?: boolean;
+ locale?: Locale;
+ },
+): number | null {
+ const num = parseNumericInput(input, options);
+ if (num === null) {
+ return null;
+ }
+
// Check min constraint
if (options.min != null && num < options.min) {
return null;
@@ -470,6 +489,65 @@ function parseNumberInput(
return num;
}
+/**
+ * Parse a string input for commit (blur/Enter), clamping an out-of-range
+ * number to the nearest bound.
+ *
+ * Rejecting an out-of-range entry outright leaves the last in-range prefix
+ * committed, so typing 100 into a [1, 2] field lands on 1; the nearest bound
+ * is what the entry actually asked for.
+ */
+function parseNumberInputForCommit(
+ input: string,
+ options: {
+ min?: number | null;
+ max?: number | null;
+ isIntegerOnly?: boolean;
+ locale?: Locale;
+ },
+): number | null {
+ const num = parseNumericInput(input, options);
+ if (num === null) {
+ return null;
+ }
+
+ // The bound itself has to satisfy the field's own shape rule, or an
+ // integer-only field commits the fractional `max` it was handed. Round
+ // inwards, the same way stepping from empty does.
+ const {min, max} = getCommittableBounds(options);
+ // No number satisfies both, so there is nothing to clamp to.
+ if (min != null && max != null && min > max) {
+ return null;
+ }
+
+ if (min != null && num < min) {
+ return min;
+ }
+ if (max != null && num > max) {
+ return max;
+ }
+
+ return num;
+}
+
+function getCommittableBounds({
+ min,
+ max,
+ isIntegerOnly,
+}: {
+ min?: number | null;
+ max?: number | null;
+ isIntegerOnly?: boolean;
+}): {min: number | null; max: number | null} {
+ if (!isIntegerOnly) {
+ return {min: min ?? null, max: max ?? null};
+ }
+ return {
+ min: min == null ? null : Math.ceil(min),
+ max: max == null ? null : Math.floor(max),
+ };
+}
+
type StepDirection = -1 | 1;
function getDecimalPlaces(value: number): number {
@@ -664,6 +742,17 @@ export function NumberInput({
[isIntegerOnly, locale, max, min],
);
+ const parseInputForCommit = useCallback(
+ (text: string) =>
+ parseNumberInputForCommit(text, {min, max, isIntegerOnly, locale}),
+ [isIntegerOnly, locale, max, min],
+ );
+
+ const parseNumeric = useCallback(
+ (text: string) => parseNumericInput(text, {isIntegerOnly, locale}),
+ [isIntegerOnly, locale],
+ );
+
const formattedValue = useMemo(() => {
if (value == null) {
return '';
@@ -732,7 +821,7 @@ export function NumberInput({
onChange(null);
}
} else {
- const parsed = parseInput(pendingInput);
+ const parsed = parseInputForCommit(pendingInput);
if (parsed !== null && parsed !== value) {
onChange(parsed);
}
@@ -744,7 +833,7 @@ export function NumberInput({
setIsFocused(false);
onBlur?.(e);
},
- [pendingInput, value, onChange, parseInput, onBlur, hasClear],
+ [pendingInput, value, onChange, parseInputForCommit, onBlur, hasClear],
);
const valueForStepping = useMemo(() => {
@@ -820,9 +909,16 @@ export function NumberInput({
onChange(null);
}
} else {
- const parsed = parseInput(pendingInput);
- if (parsed !== null && parsed !== value) {
- onChange(parsed);
+ const parsed = parseInputForCommit(pendingInput);
+ if (parsed !== null) {
+ // Enter otherwise keeps the pending text, which would leave a
+ // clamped entry showing the number that was not committed.
+ if (parsed !== parseNumeric(pendingInput)) {
+ setPendingInput(null);
+ }
+ if (parsed !== value) {
+ onChange(parsed);
+ }
}
}
}
@@ -834,7 +930,8 @@ export function NumberInput({
pendingInput,
value,
onChange,
- parseInput,
+ parseInputForCommit,
+ parseNumeric,
onEnter,
onKeyDown,
hasClear,
diff --git a/packages/core/src/Pagination/Pagination.test.tsx b/packages/core/src/Pagination/Pagination.test.tsx
index e4427b3cef..e8b027d352 100644
--- a/packages/core/src/Pagination/Pagination.test.tsx
+++ b/packages/core/src/Pagination/Pagination.test.tsx
@@ -613,7 +613,7 @@ describe('Pagination', () => {
expect(box).toHaveAttribute('aria-valuemax', '10');
});
- it('commits a typed page on Enter and rejects an over-range entry', async () => {
+ it('commits a typed page on Enter and clamps an over-range entry', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
@@ -633,9 +633,10 @@ describe('Pagination', () => {
onChange.mockClear();
await user.clear(box);
// The box is a NumberInput bounded to [1, totalPages]: an over-max entry
- // is rejected and never navigates past the last page.
+ // lands on the last page rather than navigating past it.
await user.type(box, '99{Enter}');
expect(onChange).not.toHaveBeenCalledWith(99);
+ expect(onChange).toHaveBeenCalledWith(10);
});
it('commits on blur', async () => {