Skip to content

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

TypeScript

feat(NumberInput): add formatted display, wheel control, and steppers (#4896)

Andrey Goder7f247bc58244
diff --git a/.changeset/number-input-formatted-wheel-steppers.md b/.changeset/number-input-formatted-wheel-steppers.md
new file mode 100644
index 0000000000..bee7d910ac
--- /dev/null
+++ b/.changeset/number-input-formatted-wheel-steppers.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] NumberInput: render a text-backed spinbutton that supports formatted display values, explicit wheel and keyboard stepping, and opt-in trailing increment/decrement buttons. Existing wheel stepping remains enabled by default and can now be disabled with `isWheelEnabled={false}`.
+
+@czarandy
diff --git a/apps/storybook/stories/NumberInput.stories.tsx b/apps/storybook/stories/NumberInput.stories.tsx
index 1354265b5e..9b7c50c2a2 100644
--- a/apps/storybook/stories/NumberInput.stories.tsx
+++ b/apps/storybook/stories/NumberInput.stories.tsx
@@ -82,6 +82,19 @@ const meta: Meta<typeof NumberInput> = {
control: 'number',
description: 'Step increment for the input',
},
+ formatValue: {
+ control: false,
+ description: 'Formats the committed value while the input is not focused',
+ },
+ isWheelEnabled: {
+ control: 'boolean',
+ description:
+ 'Whether a wheel gesture over the focused input steps the value',
+ },
+ hasNumberSteppers: {
+ control: 'boolean',
+ description: 'Shows increment and decrement buttons',
+ },
units: {
control: 'text',
description:
@@ -152,6 +165,74 @@ export const WithStep: Story = {
},
};
+export const FormattedDisplay: Story = {
+ render: args => {
+ const [value, setValue] = useState<number | null>(args.value ?? 1234.56);
+ return <NumberInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Monthly revenue',
+ value: 1234.56,
+ min: 0,
+ step: 0.01,
+ description: 'Focus the input to edit the raw numeric value',
+ formatValue: value =>
+ new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ }).format(value),
+ },
+};
+
+export const WithNumberSteppers: Story = {
+ render: args => {
+ const [value, setValue] = useState<number | null>(args.value ?? 2);
+ return <NumberInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Quantity',
+ value: 2,
+ min: 0,
+ max: 10,
+ hasNumberSteppers: true,
+ },
+};
+
+export const WheelBehavior: Story = {
+ render: () => {
+ const [enabledValue, setEnabledValue] = useState<number | null>(2);
+ const [disabledValue, setDisabledValue] = useState<number | null>(2);
+ return (
+ <div
+ style={{
+ width: 360,
+ height: 260,
+ overflowY: 'auto',
+ padding: 16,
+ border: '1px solid #ccd3db',
+ }}>
+ <div style={{height: 140}}>Scroll down to the focused examples.</div>
+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
+ <NumberInput
+ label="Wheel stepping enabled (default)"
+ description="Focus, then use the wheel to change the value"
+ value={enabledValue}
+ onChange={setEnabledValue}
+ />
+ <NumberInput
+ label="Wheel stepping disabled"
+ description="Focused wheel gestures continue scrolling"
+ value={disabledValue}
+ onChange={setDisabledValue}
+ isWheelEnabled={false}
+ />
+ </div>
+ <div style={{height: 180}} />
+ </div>
+ );
+ },
+};
+
export const WithUnits: Story = {
render: args => {
const [value, setValue] = useState<number | null>(args.value ?? 50);
diff --git a/packages/cli/assets/templates/blocks/components/NumberInput/NumberInputShowcase.tsx b/packages/cli/assets/templates/blocks/components/NumberInput/NumberInputShowcase.tsx
index ad04c7a9da..3646b3cdbb 100644
--- a/packages/cli/assets/templates/blocks/components/NumberInput/NumberInputShowcase.tsx
+++ b/packages/cli/assets/templates/blocks/components/NumberInput/NumberInputShowcase.tsx
@@ -14,6 +14,8 @@ export default function NumberInputShowcase() {
placeholder="Enter quantity"
value={value}
onChange={setValue}
+ formatValue={number => `${number} items`}
+ hasNumberSteppers
/>
</div>
);
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index ac23e64b41..7679fed823 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -867,6 +867,14 @@
"defaultMessage": "Clear {label}",
"description": "Screen-reader-only label on the X that clears the value from a NumberInput. Example: `Clear Age`, `Clear Quantity`."
},
+ "@astryx.numberInput.decrementLabel": {
+ "defaultMessage": "Decrement {label}",
+ "description": "Accessible label for the NumberInput button that decreases the value by one configured step. Example: `Decrement Quantity`."
+ },
+ "@astryx.numberInput.incrementLabel": {
+ "defaultMessage": "Increment {label}",
+ "description": "Accessible label for the NumberInput button that increases the value by one configured step. Example: `Increment Quantity`."
+ },
"@astryx.selector.clearLabel": {
"defaultMessage": "Clear {label}",
"description": "Screen-reader-only label on the X that clears the selected value from a Selector. `{label}` is the selector's visible label — example: `Clear Country`."
diff --git a/packages/core/src/NumberInput/NumberInput.doc.mjs b/packages/core/src/NumberInput/NumberInput.doc.mjs
index 325beebf9b..69f73e528f 100644
--- a/packages/core/src/NumberInput/NumberInput.doc.mjs
+++ b/packages/core/src/NumberInput/NumberInput.doc.mjs
@@ -6,7 +6,17 @@ export const docs = {
name: 'NumberInput',
displayName: 'Number Input',
category: 'Data Input',
- keywords: ["numberinput","numberfield","stepper","spinner","counter","increment","decrement","quantity","numberpicker"],
+ keywords: [
+ 'numberinput',
+ 'numberfield',
+ 'stepper',
+ 'spinner',
+ 'counter',
+ 'increment',
+ 'decrement',
+ 'quantity',
+ 'numberpicker',
+ ],
props: [
{
name: 'label',
@@ -66,7 +76,7 @@ export const docs = {
name: 'isReadOnly',
type: 'boolean',
description:
- 'Makes the input read-only: the value is shown at full opacity and still submits with the form, but cannot be edited. Unlike isDisabled, a read-only input is not dimmed and stays in the tab order. isDisabled takes precedence when both are set.',
+ 'Makes the input read-only: the value is shown at full opacity and still submits with the form, but cannot be edited. Unlike isDisabled, a read-only input is not dimmed and stays in the tab order. Stepping is off in every form while read-only: arrow keys, the wheel, and the number steppers. isDisabled takes precedence when both are set.',
default: 'false',
},
{
@@ -89,12 +99,14 @@ export const docs = {
{
name: 'startIcon',
type: 'IconType',
- description: 'Icon to display at the start of the input. See `astryx docs icons` for valid semantic names.',
+ description:
+ 'Icon to display at the start of the input. See `astryx docs icons` for valid semantic names.',
},
{
name: 'labelIcon',
type: 'IconType',
- description: 'Icon to display before the label text. See `astryx docs icons` for valid semantic names.',
+ description:
+ 'Icon to display before the label text. See `astryx docs icons` for valid semantic names.',
},
{
name: 'status',
@@ -124,6 +136,26 @@ export const docs = {
description: 'Step increment for the input.',
default: '1',
},
+ {
+ name: 'formatValue',
+ type: '(value: number) => string',
+ description:
+ 'Formats the committed value while the input is not focused. The raw numeric value is shown on focus for editing and the formatted value is exposed through aria-valuetext.',
+ },
+ {
+ name: 'isWheelEnabled',
+ type: 'boolean',
+ description:
+ 'Whether scrolling the wheel over the focused input steps the value. Disable this when page scrolling should always take priority.',
+ default: 'true',
+ },
+ {
+ name: 'hasNumberSteppers',
+ type: 'boolean',
+ description:
+ 'Shows increment and decrement buttons at the end of the input.',
+ default: 'false',
+ },
{
name: 'units',
type: 'string | null',
@@ -181,24 +213,74 @@ export const docs = {
],
theming: {
targets: [
- {className: 'astryx-number-input', visualProps: ['size', 'status'], states: ['disabled', 'readonly']},
+ {
+ className: 'astryx-number-input',
+ visualProps: ['size', 'status'],
+ states: ['disabled', 'readonly'],
+ },
],
},
usage: {
description:
'A form input for numeric values with built-in validation, min/max constraints, and step controls. Use NumberInput for quantities, measurements, percentages, and similar inputs.',
bestPractices: [
- { guidance: true, description: 'Set min, max, and step to guide users toward valid values.' },
- { guidance: true, description: 'Show units (e.g. "%" or "GB") so users know what the number represents.' },
- { guidance: false, description: 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.' },
- { guidance: false, description: 'Set both isOptional and isRequired on the same field.' },
- { guidance: false, description: "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead." },
+ {
+ guidance: true,
+ description:
+ 'Set min, max, and step to guide users toward valid values.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Show units (e.g. "%" or "GB") so users know what the number represents.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set isWheelEnabled={false} when the input appears in a scrolling surface where wheel gestures should always scroll the page.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.',
+ },
+ {
+ guidance: false,
+ description: 'Set both isOptional and isRequired on the same field.',
+ },
+ {
+ guidance: false,
+ description:
+ "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead.",
+ },
],
anatomy: [
- {name: 'Label', required: true, description: 'The label for the number input.'},
- {name: 'Description', required: false, description: 'Additional description text below the label.'},
- {name: 'Icon', required: false, description: 'An optional icon within the input.'},
- {name: 'Placeholder', required: false, description: 'Placeholder text shown when the input is empty.'},
+ {
+ name: 'Label',
+ required: true,
+ description: 'The label for the number input.',
+ },
+ {
+ name: 'Description',
+ required: false,
+ description: 'Additional description text below the label.',
+ },
+ {
+ name: 'Icon',
+ required: false,
+ description: 'An optional icon within the input.',
+ },
+ {
+ name: 'Placeholder',
+ required: false,
+ description: 'Placeholder text shown when the input is empty.',
+ },
+ {
+ name: 'Number steppers',
+ required: false,
+ description:
+ 'Optional buttons that increment or decrement by the configured step.',
+ },
],
},
};
@@ -211,8 +293,7 @@ export const docsZh = {
{
name: 'label',
type: 'string',
- description:
- '输入框的标签文本(始终渲染以确保无障碍访问)。',
+ description: '输入框的标签文本(始终渲染以确保无障碍访问)。',
required: true,
},
{
@@ -224,8 +305,7 @@ export const docsZh = {
{
name: 'onChange',
type: '(value: number) => void',
- description:
- '输入值变化时触发的回调(仅在输入有效时触发)。',
+ description: '输入值变化时触发的回调(仅在输入有效时触发)。',
required: true,
},
{
@@ -237,8 +317,7 @@ export const docsZh = {
{
name: 'isLabelHidden',
type: 'boolean',
- description:
- '视觉隐藏标签(屏幕阅读器仍可访问)。',
+ description: '视觉隐藏标签(屏幕阅读器仍可访问)。',
},
{
name: 'description',
@@ -248,14 +327,12 @@ export const docsZh = {
{
name: 'isOptional',
type: 'boolean',
- description:
- '字段是否可选(与 isRequired 互斥)。',
+ description: '字段是否可选(与 isRequired 互斥)。',
},
{
name: 'isRequired',
type: 'boolean',
- description:
- '字段是否必填(与 isOptional 互斥)。',
+ description: '字段是否必填(与 isOptional 互斥)。',
},
{
name: 'isDisabled',
@@ -266,7 +343,7 @@ export const docsZh = {
name: 'isReadOnly',
type: 'boolean',
description:
- '将输入框设为只读:值以完整不透明度显示并仍随表单提交,但无法编辑。与 isDisabled 不同,只读输入框不会变暗,并保留在 Tab 顺序中。同时设置时 isDisabled 优先。',
+ '将输入框设为只读:值以完整不透明度显示并仍随表单提交,但无法编辑。与 isDisabled 不同,只读输入框不会变暗,并保留在 Tab 顺序中。只读时所有步进方式均被禁用:方向键、滚轮和步进按钮。同时设置时 isDisabled 优先。',
default: 'false',
},
{
@@ -283,8 +360,7 @@ export const docsZh = {
{
name: 'labelTooltip',
type: 'string',
- description:
- '在标签末尾的信息图标中显示的工具提示文本。',
+ description: '在标签末尾的信息图标中显示的工具提示文本。',
},
{
name: 'startIcon',
@@ -324,11 +400,29 @@ export const docsZh = {
description: '输入框的步进增量。',
default: '1',
},
+ {
+ name: 'formatValue',
+ type: '(value: number) => string',
+ description:
+ '输入框未聚焦时格式化已提交的值。聚焦编辑时显示原始数值,并通过 aria-valuetext 提供格式化值。',
+ },
+ {
+ name: 'isWheelEnabled',
+ type: 'boolean',
+ description:
+ '是否允许在已聚焦的输入框上滚动滚轮来步进数值。当页面滚动应始终优先时请禁用。',
+ default: 'true',
+ },
+ {
+ name: 'hasNumberSteppers',
+ type: 'boolean',
+ description: '是否在输入框末尾显示递增和递减按钮。',
+ default: 'false',
+ },
{
name: 'units',
type: 'string | null',
- description:
- '在输入框末尾显示的单位文本(例如"%"或"GB")。',
+ description: '在输入框末尾显示的单位文本(例如"%"或"GB")。',
},
{
name: 'isIntegerOnly',
@@ -338,7 +432,8 @@ export const docsZh = {
{
name: 'hasClear',
type: 'boolean',
- description: '输入有值时显示清除 (×) 按鈕。启用后, onChange 回调还接受 null 表示用户已清空输入。',
+ description:
+ '输入有值时显示清除 (×) 按鈕。启用后, onChange 回调还接受 null 表示用户已清空输入。',
default: 'false',
},
{
@@ -374,46 +469,143 @@ export const docsZh = {
],
theming: {
targets: [
- {className: 'astryx-number-input', visualProps: ['size', 'status'], states: ['disabled', 'readonly']},
+ {
+ className: 'astryx-number-input',
+ visualProps: ['size', 'status'],
+ states: ['disabled', 'readonly'],
+ },
],
},
usage: {
description:
'A form input for numeric values with built-in validation, min/max constraints, and step controls. Use NumberInput for quantities, measurements, percentages, and similar inputs.',
bestPractices: [
- { guidance: true, description: 'Set min, max, and step to guide users toward valid values.' },
- { guidance: true, description: 'Show units (e.g. "%" or "GB") so users know what the number represents.' },
- { guidance: false, description: 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.' },
- { guidance: false, description: 'Set both isOptional and isRequired on the same field.' },
- { guidance: false, description: "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead." },
+ {
+ guidance: true,
+ description:
+ 'Set min, max, and step to guide users toward valid values.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Show units (e.g. "%" or "GB") so users know what the number represents.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set isWheelEnabled={false} when the input appears in a scrolling surface where wheel gestures should always scroll the page.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.',
+ },
+ {
+ guidance: false,
+ description: 'Set both isOptional and isRequired on the same field.',
+ },
+ {
+ guidance: false,
+ description:
+ "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead.",
+ },
],
anatomy: [
- {name: 'Label', required: true, description: 'The label for the number input.'},
- {name: 'Description', required: false, description: 'Additional description text below the label.'},
- {name: 'Icon', required: false, description: 'An optional icon within the input.'},
- {name: 'Placeholder', required: false, description: 'Placeholder text shown when the input is empty.'},
+ {
+ name: 'Label',
+ required: true,
+ description: 'The label for the number input.',
+ },
+ {
+ name: 'Description',
+ required: false,
+ description: 'Additional description text below the label.',
+ },
+ {
+ name: 'Icon',
+ required: false,
+ description: 'An optional icon within the input.',
+ },
+ {
+ name: 'Placeholder',
+ required: false,
+ description: 'Placeholder text shown when the input is empty.',
+ },
+ {
+ name: 'Number steppers',
+ required: false,
+ description:
+ 'Optional buttons that increment or decrement by the configured step.',
+ },
],
},
};
/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */
export const docsDense = {
- description: 'Number input component for collecting numeric user input w/ validation.',
+ description:
+ 'Number input component for collecting numeric user input w/ validation.',
usage: {
description:
'A form input for numeric values with built-in validation, min/max constraints, and step controls. Use NumberInput for quantities, measurements, percentages, and similar inputs.',
bestPractices: [
- { guidance: true, description: 'Set min, max, and step to guide users toward valid values.' },
- { guidance: true, description: 'Show units (e.g. "%" or "GB") so users know what the number represents.' },
- { guidance: false, description: 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.' },
- { guidance: false, description: 'Set both isOptional and isRequired on the same field.' },
- { guidance: false, description: "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead." },
+ {
+ guidance: true,
+ description:
+ 'Set min, max, and step to guide users toward valid values.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Show units (e.g. "%" or "GB") so users know what the number represents.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set isWheelEnabled={false} when the input appears in a scrolling surface where wheel gestures should always scroll the page.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use NumberInput for free-form text that happens to contain numbers; use TextInput instead.',
+ },
+ {
+ guidance: false,
+ description: 'Set both isOptional and isRequired on the same field.',
+ },
+ {
+ guidance: false,
+ description:
+ "Wrap a disabled NumberInput in Tooltip to explain why it's disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead.",
+ },
],
anatomy: [
- {name: 'Label', required: true, description: 'The label for the number input.'},
- {name: 'Description', required: false, description: 'Additional description text below the label.'},
- {name: 'Icon', required: false, description: 'An optional icon within the input.'},
- {name: 'Placeholder', required: false, description: 'Placeholder text shown when the input is empty.'},
+ {
+ name: 'Label',
+ required: true,
+ description: 'The label for the number input.',
+ },
+ {
+ name: 'Description',
+ required: false,
+ description: 'Additional description text below the label.',
+ },
+ {
+ name: 'Icon',
+ required: false,
+ description: 'An optional icon within the input.',
+ },
+ {
+ name: 'Placeholder',
+ required: false,
+ description: 'Placeholder text shown when the input is empty.',
+ },
+ {
+ name: 'Number steppers',
+ required: false,
+ description:
+ 'Optional buttons that increment or decrement by the configured step.',
+ },
],
},
propDescriptions: {
@@ -435,13 +627,20 @@ export const docsDense = {
startIcon: 'Icon at input start.',
labelIcon: 'Icon before label text.',
status: 'Validation status w/ optional message.',
- statusVariant: 'How status message is placed: attached overlaps below input; detached floats below w/ spacing; tooltip hides the box and shows it on the status icon.',
+ statusVariant:
+ 'How status message is placed: attached overlaps below input; detached floats below w/ spacing; tooltip hides the box and shows it on the status icon.',
min: 'Minimum value allowed.',
max: 'Maximum value allowed.',
step: 'Step increment.',
+ formatValue:
+ 'Formats committed value at rest; raw number is shown while editing.',
+ isWheelEnabled:
+ 'Allow focused wheel gestures to step value. Defaults to true.',
+ hasNumberSteppers: 'Show increment + decrement buttons. Defaults to false.',
units: 'Units suffix (e.g. "%" or "GB").',
isIntegerOnly: 'Only allow integer values.',
- hasClear: 'Shows clear button when input has value. onChange also accepts null on clear.',
+ hasClear:
+ 'Shows clear button when input has value. onChange also accepts null on clear.',
htmlName: 'HTML name for form submissions.',
autoComplete: 'HTML autocomplete attribute.',
hasAutoFocus: 'Focus input on mount.',
diff --git a/packages/core/src/NumberInput/NumberInput.test.tsx b/packages/core/src/NumberInput/NumberInput.test.tsx
index 91a8f83e35..7c9a9ab538 100644
--- a/packages/core/src/NumberInput/NumberInput.test.tsx
+++ b/packages/core/src/NumberInput/NumberInput.test.tsx
@@ -73,21 +73,21 @@ describe('NumberInput', () => {
expect(screen.getByPlaceholderText('Enter number')).toBeInTheDocument();
});
- it('displays controlled value as number', () => {
+ it('displays the controlled value as editable text', () => {
render(<NumberInput label="Quantity" value={456} onChange={() => {}} />);
- expect(screen.getByRole('spinbutton')).toHaveValue(456);
+ expect(screen.getByRole('spinbutton')).toHaveValue('456');
});
- it('displays null for null value', () => {
+ it('displays an empty string for a null value', () => {
render(<NumberInput label="Quantity" value={null} onChange={() => {}} />);
- expect(screen.getByRole('spinbutton')).toHaveValue(null);
+ expect(screen.getByRole('spinbutton')).toHaveValue('');
});
- it('displays null for undefined value', () => {
+ it('displays an empty string for an undefined value', () => {
render(
<NumberInput label="Quantity" value={undefined} onChange={() => {}} />,
);
- expect(screen.getByRole('spinbutton')).toHaveValue(null);
+ expect(screen.getByRole('spinbutton')).toHaveValue('');
});
it('forwards ref correctly', () => {
@@ -198,31 +198,127 @@ describe('NumberInput', () => {
expect(container.querySelector('svg')).not.toBeInTheDocument();
});
- describe('native number input attributes', () => {
- it('sets min attribute', () => {
+ describe('text-backed spinbutton attributes', () => {
+ it('uses a text input with decimal input mode by default', () => {
+ render(<NumberInput label="Price" value={5} onChange={() => {}} />);
+ const input = screen.getByRole('spinbutton');
+ expect(input).toHaveAttribute('type', 'text');
+ expect(input).toHaveAttribute('inputmode', 'decimal');
+ });
+
+ it('uses numeric input mode for integer-only values', () => {
+ render(
+ <NumberInput
+ label="Count"
+ value={5}
+ onChange={() => {}}
+ isIntegerOnly
+ />,
+ );
+ expect(screen.getByRole('spinbutton')).toHaveAttribute(
+ 'inputmode',
+ 'numeric',
+ );
+ });
+
+ it('exposes the minimum through spinbutton ARIA', () => {
render(
<NumberInput label="Age" value={null} onChange={() => {}} min={0} />,
);
- expect(screen.getByRole('spinbutton')).toHaveAttribute('min', '0');
+ expect(screen.getByRole('spinbutton')).toHaveAttribute(
+ 'aria-valuemin',
+ '0',
+ );
});
- it('sets max attribute', () => {
+ it('exposes the maximum through spinbutton ARIA', () => {
render(
<NumberInput label="Age" value={null} onChange={() => {}} max={120} />,
);
- expect(screen.getByRole('spinbutton')).toHaveAttribute('max', '120');
+ expect(screen.getByRole('spinbutton')).toHaveAttribute(
+ 'aria-valuemax',
+ '120',
+ );
+ });
+
+ it('exposes the current value through spinbutton ARIA', () => {
+ render(<NumberInput label="Age" value={42} onChange={() => {}} />);
+ expect(screen.getByRole('spinbutton')).toHaveAttribute(
+ 'aria-valuenow',
+ '42',
+ );
+ });
+ });
+
+ describe('formatted display values', () => {
+ it('shows the formatted value at rest and exposes it to assistive technology', () => {
+ render(
+ <NumberInput
+ label="Revenue"
+ value={1234}
+ onChange={() => {}}
+ formatValue={number => `$${number.toLocaleString('en-US')}`}
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+ expect(input).toHaveValue('$1,234');
+ expect(input).toHaveAttribute('aria-valuetext', '$1,234');
+ expect(input).toHaveAttribute('aria-valuenow', '1234');
+ });
+
+ it('shows the raw numeric value while focused and restores formatting on blur', () => {
+ render(
+ <NumberInput
+ label="Revenue"
+ value={1234}
+ onChange={() => {}}
+ formatValue={number => `$${number.toLocaleString('en-US')}`}
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+
+ fireEvent.focus(input);
+ expect(input).toHaveValue('1234');
+
+ fireEvent.blur(input);
+ expect(input).toHaveValue('$1,234');
+ });
+
+ it('preserves invalid pending text while focused, then restores the formatted true value', () => {
+ const onChange = vi.fn();
+ render(
+ <NumberInput
+ label="Quantity"
+ value={3}
+ onChange={onChange}
+ isIntegerOnly
+ formatValue={number => `${number} items`}
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+
+ fireEvent.focus(input);
+ fireEvent.change(input, {target: {value: '3.5'}});
+ expect(input).toHaveValue('3.5');
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expect(onChange).not.toHaveBeenCalledWith(3.5);
+
+ fireEvent.blur(input);
+ expect(input).toHaveValue('3 items');
});
- it('sets step attribute', () => {
+ it('does not call the formatter for an empty value', () => {
+ const formatValue = vi.fn((number: number) => String(number));
render(
<NumberInput
- label="Price"
+ label="Quantity"
value={null}
onChange={() => {}}
- step={0.01}
+ formatValue={formatValue}
/>,
);
- expect(screen.getByRole('spinbutton')).toHaveAttribute('step', '0.01');
+ expect(screen.getByRole('spinbutton')).toHaveValue('');
+ expect(formatValue).not.toHaveBeenCalled();
});
});
@@ -703,6 +799,22 @@ describe('NumberInput', () => {
expect(data.get('quantity')).toBe('42');
});
+ it('submits the raw number instead of the formatted display value', () => {
+ const {container} = render(
+ <form>
+ <NumberInput
+ label="Revenue"
+ htmlName="revenue"
+ value={1234}
+ onChange={() => {}}
+ formatValue={number => `$${number.toLocaleString('en-US')}`}
+ />
+ </form>,
+ );
+ const data = new FormData(container.querySelector('form')!);
+ expect(data.get('revenue')).toBe('1234');
+ });
+
it('is excluded from form data when disabled', () => {
const {container} = render(
<form>
@@ -816,6 +928,74 @@ describe('NumberInput', () => {
expect(screen.queryByRole('button')).not.toBeInTheDocument();
});
+ it('does not step on ArrowUp or ArrowDown', async () => {
+ const user = userEvent.setup();
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Quantity"
+ value={42}
+ onChange={handleChange}
+ isReadOnly
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+ input.focus();
+ await user.keyboard('{ArrowUp}{ArrowDown}');
+ expect(handleChange).not.toHaveBeenCalled();
+ expect(input).toHaveValue('42');
+ });
+
+ it('leaves wheel scrolling to the page instead of stepping', () => {
+ const onScrollableWheel = vi.fn();
+ const handleChange = vi.fn();
+ render(
+ <div onWheel={onScrollableWheel}>
+ <NumberInput
+ label="Quantity"
+ value={42}
+ onChange={handleChange}
+ isReadOnly
+ />
+ </div>,
+ );
+ const input = screen.getByRole('spinbutton');
+ input.focus();
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ deltaY: -100,
+ });
+ fireEvent(input, event);
+
+ expect(handleChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
+ expect(onScrollableWheel).toHaveBeenCalledTimes(1);
+ });
+
+ it('disables both number steppers', () => {
+ const handleChange = vi.fn();
+ render(
+ <NumberInput
+ label="Quantity"
+ value={42}
+ onChange={handleChange}
+ hasNumberSteppers
+ isReadOnly
+ />,
+ );
+ const increment = screen.getByRole('button', {
+ name: 'Increment Quantity',
+ });
+ expect(increment).toBeDisabled();
+ expect(
+ screen.getByRole('button', {name: 'Decrement Quantity'}),
+ ).toBeDisabled();
+
+ fireEvent.click(increment);
+ expect(handleChange).not.toHaveBeenCalled();
+ });
+
it('lets isDisabled win when both are set', () => {
const {container} = render(
<form>
@@ -1145,31 +1325,365 @@ describe('NumberInput statusVariant forwarding', () => {
'detached',
);
});
+});
+
+describe('NumberInput stepping', () => {
+ it('increments with ArrowUp and decrements with ArrowDown', () => {
+ const onChange = vi.fn();
+ render(<NumberInput label="Amount" value={5} onChange={onChange} />);
+ const input = screen.getByRole('spinbutton');
+
+ fireEvent.keyDown(input, {key: 'ArrowUp'});
+ expect(onChange).toHaveBeenLastCalledWith(6);
+
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ expect(onChange).toHaveBeenLastCalledWith(4);
+ });
+
+ it('lets onKeyDown cancel keyboard stepping', () => {
+ const onChange = vi.fn();
+ const onKeyDown = vi.fn((event: React.KeyboardEvent<HTMLInputElement>) =>
+ event.preventDefault(),
+ );
+ render(
+ <NumberInput
+ label="Amount"
+ value={5}
+ onChange={onChange}
+ onKeyDown={onKeyDown}
+ />,
+ );
+ fireEvent.keyDown(screen.getByRole('spinbutton'), {key: 'ArrowUp'});
+
+ expect(onKeyDown).toHaveBeenCalledTimes(1);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('uses decimal-safe step arithmetic', () => {
+ const onChange = vi.fn();
+ render(
+ <NumberInput label="Amount" value={0.2} onChange={onChange} step={0.1} />,
+ );
+ fireEvent.keyDown(screen.getByRole('spinbutton'), {key: 'ArrowUp'});
+ expect(onChange).toHaveBeenCalledWith(0.3);
+ });
+
+ it('aligns an off-step value in the requested direction', () => {
+ const onChange = vi.fn();
+ render(
+ <NumberInput
+ label="Amount"
+ value={0.25}
+ onChange={onChange}
+ step={0.1}
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+
+ fireEvent.keyDown(input, {key: 'ArrowUp'});
+ expect(onChange).toHaveBeenLastCalledWith(0.3);
+
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ expect(onChange).toHaveBeenLastCalledWith(0.2);
+ });
+
+ it('starts an empty value at the relevant boundary', () => {
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <NumberInput label="Amount" value={null} onChange={onChange} min={2} />,
+ );
+ fireEvent.keyDown(screen.getByRole('spinbutton'), {key: 'ArrowUp'});
+ expect(onChange).toHaveBeenLastCalledWith(2);
+
+ rerender(
+ <NumberInput label="Amount" value={null} onChange={onChange} max={8} />,
+ );
+ fireEvent.keyDown(screen.getByRole('spinbutton'), {key: 'ArrowDown'});
+ expect(onChange).toHaveBeenLastCalledWith(8);
+ });
+
+ it('keeps generated values integral when isIntegerOnly is set', () => {
+ const onChange = vi.fn();
+ render(
+ <NumberInput
+ label="Amount"
+ value={null}
+ onChange={onChange}
+ min={2.5}
+ isIntegerOnly
+ />,
+ );
+ fireEvent.keyDown(screen.getByRole('spinbutton'), {key: 'ArrowUp'});
+ expect(onChange).toHaveBeenCalledWith(3);
+ });
- it('stops wheel propagation while focused so ancestor containers do not scroll', () => {
+ it('does not step past min or max', () => {
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <NumberInput
+ label="Amount"
+ value={10}
+ onChange={onChange}
+ min={0}
+ max={10}
+ />,
+ );
+ fireEvent.keyDown(screen.getByRole('spinbutton'), {key: 'ArrowUp'});
+ expect(onChange).not.toHaveBeenCalled();
+
+ rerender(
+ <NumberInput
+ label="Amount"
+ value={0}
+ onChange={onChange}
+ min={0}
+ max={10}
+ />,
+ );
+ fireEvent.keyDown(screen.getByRole('spinbutton'), {key: 'ArrowDown'});
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('allows wheel stepping by default and consumes the focused gesture', () => {
+ const onScrollableWheel = vi.fn();
+ const onChange = vi.fn();
+ render(
+ <div onWheel={onScrollableWheel}>
+ <NumberInput label="Amount" value={5} onChange={onChange} />
+ </div>,
+ );
+ const input = screen.getByRole('spinbutton');
+ input.focus();
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ deltaY: -100,
+ });
+ fireEvent(input, event);
+
+ expect(onChange).toHaveBeenCalledWith(6);
+ expect(event.defaultPrevented).toBe(true);
+ expect(onScrollableWheel).not.toHaveBeenCalled();
+ });
+
+ it('leaves wheel scrolling alone when isWheelEnabled is false', () => {
const onScrollableWheel = vi.fn();
+ const onChange = vi.fn();
render(
<div onWheel={onScrollableWheel}>
- <NumberInput label="Amount" value={5} onChange={() => {}} />
+ <NumberInput
+ label="Amount"
+ value={5}
+ onChange={onChange}
+ isWheelEnabled={false}
+ />
+ </div>,
+ );
+ const input = screen.getByRole('spinbutton');
+ input.focus();
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ deltaY: -100,
+ });
+ fireEvent(input, event);
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
+ expect(onScrollableWheel).toHaveBeenCalledTimes(1);
+ });
+
+ it('updates the wheel listener when isWheelEnabled changes', () => {
+ const onScrollableWheel = vi.fn();
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <div onWheel={onScrollableWheel}>
+ <NumberInput
+ label="Amount"
+ value={5}
+ onChange={onChange}
+ isWheelEnabled={false}
+ />
</div>,
);
const input = screen.getByRole('spinbutton');
input.focus();
- fireEvent.wheel(input, {deltaY: 100});
+
+ rerender(
+ <div onWheel={onScrollableWheel}>
+ <NumberInput
+ label="Amount"
+ value={5}
+ onChange={onChange}
+ isWheelEnabled
+ />
+ </div>,
+ );
+ fireEvent.wheel(input, {deltaY: -100});
+ expect(onChange).toHaveBeenCalledWith(6);
expect(onScrollableWheel).not.toHaveBeenCalled();
+
+ onChange.mockClear();
+ rerender(
+ <div onWheel={onScrollableWheel}>
+ <NumberInput
+ label="Amount"
+ value={5}
+ onChange={onChange}
+ isWheelEnabled={false}
+ />
+ </div>,
+ );
+ fireEvent.wheel(input, {deltaY: -100});
+ expect(onChange).not.toHaveBeenCalled();
+ expect(onScrollableWheel).toHaveBeenCalledTimes(1);
});
- it('does not stop wheel propagation when the input is not focused', () => {
+ it('leaves wheel scrolling alone when the input is not focused', () => {
const onScrollableWheel = vi.fn();
+ const onChange = vi.fn();
render(
<div onWheel={onScrollableWheel}>
- <NumberInput label="Amount" value={5} onChange={() => {}} />
+ <NumberInput label="Amount" value={5} onChange={onChange} />
</div>,
);
const input = screen.getByRole('spinbutton');
- fireEvent.wheel(input, {deltaY: 100});
+ const event = new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ deltaY: 100,
+ });
+ fireEvent(input, event);
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
expect(onScrollableWheel).toHaveBeenCalledTimes(1);
});
+
+ it('leaves modified wheel gestures alone', () => {
+ const onScrollableWheel = vi.fn();
+ const onChange = vi.fn();
+ render(
+ <div onWheel={onScrollableWheel}>
+ <NumberInput label="Amount" value={5} onChange={onChange} />
+ </div>,
+ );
+ const input = screen.getByRole('spinbutton');
+ input.focus();
+ fireEvent.wheel(input, {deltaY: -100, ctrlKey: true});
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(onScrollableWheel).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves wheel scrolling alone when the input is aria-disabled', () => {
+ const onScrollableWheel = vi.fn();
+ const onChange = vi.fn();
+ render(
+ <div onWheel={onScrollableWheel}>
+ <NumberInput
+ label="Amount"
+ value={5}
+ onChange={onChange}
+ isDisabled
+ disabledMessage="This value is locked"
+ />
+ </div>,
+ );
+ const input = screen.getByRole('spinbutton');
+ input.focus();
+ fireEvent.wheel(input, {deltaY: -100});
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(onScrollableWheel).toHaveBeenCalledTimes(1);
+ });
+
+ describe('hasNumberSteppers', () => {
+ it('does not show stepper buttons by default', () => {
+ render(<NumberInput label="Quantity" value={5} onChange={() => {}} />);
+ expect(
+ screen.queryByRole('button', {name: 'Increment Quantity'}),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Decrement Quantity'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('shows localized increment and decrement buttons when enabled', () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ hasNumberSteppers
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Increment Quantity'}),
+ ).toHaveAttribute('tabindex', '-1');
+ expect(
+ screen.getByRole('button', {name: 'Decrement Quantity'}),
+ ).toHaveAttribute('tabindex', '-1');
+ });
+
+ it('steps the value and returns focus to the input', () => {
+ const onChange = vi.fn();
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={onChange}
+ hasNumberSteppers
+ />,
+ );
+ const input = screen.getByRole('spinbutton');
+
+ fireEvent.click(screen.getByRole('button', {name: 'Increment Quantity'}));
+ expect(onChange).toHaveBeenLastCalledWith(6);
+ expect(input).toHaveFocus();
+
+ fireEvent.click(screen.getByRole('button', {name: 'Decrement Quantity'}));
+ expect(onChange).toHaveBeenLastCalledWith(4);
+ expect(input).toHaveFocus();
+ });
+
+ it('disables only the stepper at the reached boundary', () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={10}
+ onChange={() => {}}
+ min={0}
+ max={10}
+ hasNumberSteppers
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Increment Quantity'}),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole('button', {name: 'Decrement Quantity'}),
+ ).not.toBeDisabled();
+ });
+
+ it('disables both steppers with the input', () => {
+ render(
+ <NumberInput
+ label="Quantity"
+ value={5}
+ onChange={() => {}}
+ hasNumberSteppers
+ isDisabled
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Increment Quantity'}),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole('button', {name: 'Decrement Quantity'}),
+ ).toBeDisabled();
+ });
+ });
});
describe('NumberInput disabled theme state', () => {
diff --git a/packages/core/src/NumberInput/NumberInput.tsx b/packages/core/src/NumberInput/NumberInput.tsx
index bcc9a6519a..70375ceaa3 100644
--- a/packages/core/src/NumberInput/NumberInput.tsx
+++ b/packages/core/src/NumberInput/NumberInput.tsx
@@ -30,8 +30,11 @@ import * as stylex from '@stylexjs/stylex';
import {
colorVars,
sizeVars,
+ spacingVars,
+ radiusVars,
typographyVars,
typeScaleVars,
+ borderVars,
} from '../theme/tokens.stylex';
import {
Field,
@@ -43,7 +46,7 @@ import {
inputStatusFocusWithinStyles,
type FieldStatusVariant,
} from '../Field';
-import {renderIconSlot, type IconType} from '../Icon';
+import {Icon, renderIconSlot, type IconType} from '../Icon';
import {VisuallyHidden} from '../VisuallyHidden';
import {useTooltip} from '../Tooltip';
import {getInputARIA} from '../utils';
@@ -56,6 +59,9 @@ const styles = stylex.create({
wrapper: {
zIndex: 1,
},
+ wrapperWithNumberSteppers: {
+ paddingInlineEnd: 0,
+ },
input: {
display: 'block',
flex: 1,
@@ -63,18 +69,6 @@ const styles = stylex.create({
borderWidth: 0,
borderStyle: 'none',
padding: 0,
- // Hide the browser's native number spinners; the component provides its own
- // affordances (keyboard entry, optional clear button) and the spinners
- // clash with the input's visual treatment and sizing.
- MozAppearance: 'textfield',
- '::-webkit-inner-spin-button': {
- WebkitAppearance: 'none',
- margin: 0,
- },
- '::-webkit-outer-spin-button': {
- WebkitAppearance: 'none',
- margin: 0,
- },
fontFamily: typographyVars['--font-family-body'],
fontSize: {
default: typeScaleVars['--text-body-size'],
@@ -101,6 +95,56 @@ const styles = stylex.create({
color: colorVars['--color-text-secondary'],
flexShrink: 0,
},
+ numberSteppers: {
+ alignSelf: 'stretch',
+ display: 'flex',
+ flexDirection: 'column',
+ flexShrink: 0,
+ width: spacingVars['--spacing-4'],
+ marginBlock: `calc(-1 * ${spacingVars['--spacing-1']})`,
+ borderInlineStartWidth: borderVars['--border-width'],
+ borderInlineStartStyle: 'solid',
+ borderInlineStartColor: colorVars['--color-border-emphasized'],
+ overflow: 'hidden',
+ borderStartEndRadius: radiusVars['--radius-element'],
+ borderEndEndRadius: radiusVars['--radius-element'],
+ },
+ numberStepperButton: {
+ boxSizing: 'border-box',
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flex: 1,
+ minHeight: 0,
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ color: colorVars['--color-icon-secondary'],
+ backgroundColor: colorVars['--color-background-surface'],
+ backgroundImage: {
+ default: null,
+ ':hover': {
+ '@media (hover: hover)': `linear-gradient(${colorVars['--color-overlay-hover']}, ${colorVars['--color-overlay-hover']})`,
+ },
+ ':active': `linear-gradient(${colorVars['--color-overlay-pressed']}, ${colorVars['--color-overlay-pressed']})`,
+ },
+ cursor: 'pointer',
+ outline: 'none',
+ },
+ numberStepperButtonDisabled: {
+ color: colorVars['--color-icon-disabled'],
+ cursor: 'not-allowed',
+ backgroundImage: 'none',
+ },
+ decrementButton: {
+ borderBlockStartWidth: borderVars['--border-width'],
+ borderBlockStartStyle: 'solid',
+ borderBlockStartColor: colorVars['--color-border-emphasized'],
+ },
+ incrementIcon: {
+ transform: 'rotate(180deg)',
+ },
});
const sizeStyles = stylex.create({
@@ -170,7 +214,9 @@ interface NumberInputPropsBase extends Omit<
* The value is shown at full opacity and still submits with the form, but
* cannot be edited. Unlike `isDisabled`, a read-only input is not dimmed and
* stays in the tab order — use it for a value the user should see and send
- * but not change. `isDisabled` takes precedence when both are set.
+ * but not change. Stepping is off in every form while read-only: arrow keys,
+ * the wheel, and the number steppers. `isDisabled` takes precedence when both
+ * are set.
* @default false
*/
isReadOnly?: boolean;
@@ -273,6 +319,21 @@ interface NumberInputPropsBase extends Omit<
* @default 1
*/
step?: number | null;
+ /**
+ * Formats the committed value while the input is not being edited.
+ * The raw numeric value is shown on focus so it remains editable.
+ */
+ formatValue?: (value: number) => string;
+ /**
+ * Whether scrolling the wheel over a focused input steps the value.
+ * @default true
+ */
+ isWheelEnabled?: boolean;
+ /**
+ * Whether to show increment and decrement buttons at the end of the input.
+ * @default false
+ */
+ hasNumberSteppers?: boolean;
/**
* Units text to display at the end of the input (e.g., "%" or "GB").
*/
@@ -364,6 +425,88 @@ function parseNumberInput(
return num;
}
+type StepDirection = -1 | 1;
+
+function getDecimalPlaces(value: number): number {
+ const [coefficient, exponentText] = String(value).toLowerCase().split('e');
+ const fractionLength = coefficient.split('.')[1]?.length ?? 0;
+ const exponent = exponentText == null ? 0 : Number(exponentText);
+ return Math.max(0, fractionLength - exponent);
+}
+
+function getEffectiveStep(
+ step: number | null | undefined,
+ isIntegerOnly: boolean,
+): number {
+ if (
+ step == null ||
+ !Number.isFinite(step) ||
+ step <= 0 ||
+ (isIntegerOnly && !Number.isInteger(step))
+ ) {
+ return 1;
+ }
+ return step;
+}
+
+function getSteppedValue({
+ currentValue,
+ direction,
+ min,
+ max,
+ step,
+ isIntegerOnly,
+}: {
+ currentValue: number | null;
+ direction: StepDirection;
+ min?: number | null;
+ max?: number | null;
+ step?: number | null;
+ isIntegerOnly: boolean;
+}): number | null {
+ const effectiveStep = getEffectiveStep(step, isIntegerOnly);
+ const stepBase =
+ min != null && (!isIntegerOnly || Number.isInteger(min)) ? min : 0;
+
+ let nextValue: number;
+ if (currentValue == null) {
+ nextValue = direction === 1 ? (min ?? 0) : (max ?? 0);
+ if (isIntegerOnly) {
+ nextValue =
+ direction === 1 ? Math.ceil(nextValue) : Math.floor(nextValue);
+ }
+ } else {
+ const stepPosition = (currentValue - stepBase) / effectiveStep;
+ const tolerance = Number.EPSILON * Math.max(1, Math.abs(stepPosition)) * 4;
+ const nextStepPosition =
+ direction === 1
+ ? Math.floor(stepPosition + tolerance) + 1
+ : Math.ceil(stepPosition - tolerance) - 1;
+ nextValue = stepBase + nextStepPosition * effectiveStep;
+ }
+
+ if (min != null) {
+ nextValue = Math.max(min, nextValue);
+ }
+ if (max != null) {
+ nextValue = Math.min(max, nextValue);
+ }
+
+ if (!Number.isFinite(nextValue)) {
+ return currentValue;
+ }
+
+ const precision = Math.min(
+ 12,
+ Math.max(getDecimalPlaces(effectiveStep), getDecimalPlaces(stepBase)),
+ );
+ const roundedValue = Number(nextValue.toFixed(precision));
+ if (isIntegerOnly && !Number.isInteger(roundedValue)) {
+ return currentValue;
+ }
+ return Object.is(roundedValue, -0) ? 0 : roundedValue;
+}
+
/**
* A number input component for collecting numeric user input.
* Only calls onChange when the entered value passes validation.
@@ -398,6 +541,9 @@ export function NumberInput({
min,
max,
step,
+ formatValue,
+ isWheelEnabled = true,
+ hasNumberSteppers = false,
units,
isIntegerOnly = false,
onFocus,
@@ -425,6 +571,7 @@ export function NumberInput({
// Pending input while user is typing (null = show formatted value)
const [pendingInput, setPendingInput] = useState<string | null>(null);
+ const [isFocused, setIsFocused] = useState(false);
// Disabled-reason tooltip. Disabled controls swallow pointer events, so the
// tooltip listeners attach to the input container (which already exists) and
@@ -465,8 +612,15 @@ export function NumberInput({
inputGroup,
);
- // Display value: pending input if typing, otherwise the raw value
- // Note: With type="number", we can't use formatted display values
+ const formattedValue = useMemo(() => {
+ if (value == null) {
+ return '';
+ }
+ return formatValue?.(value) ?? String(value);
+ }, [formatValue, value]);
+
+ // Preserve pending text while editing. Otherwise show the formatted value
+ // at rest and the raw numeric value while focused so it remains editable.
const displayValue = useMemo(() => {
if (pendingInput !== null) {
return pendingInput;
@@ -474,8 +628,8 @@ export function NumberInput({
if (value == null) {
return '';
}
- return String(value);
- }, [pendingInput, value]);
+ return isFocused ? String(value) : formattedValue;
+ }, [formattedValue, isFocused, pendingInput, value]);
// Check if current pending input is valid (for styling purposes)
const isInputValid = useMemo(() => {
@@ -509,6 +663,7 @@ export function NumberInput({
// Handle focus
const handleFocus = useCallback(
(e: FocusEvent<HTMLInputElement>) => {
+ setIsFocused(true);
onFocus?.(e);
},
[onFocus],
@@ -538,14 +693,69 @@ export function NumberInput({
// Clear pending input - display will revert to formatted value
setPendingInput(null);
+ setIsFocused(false);
onBlur?.(e);
},
[pendingInput, value, onChange, min, max, isIntegerOnly, onBlur, hasClear],
);
+ const valueForStepping = useMemo(() => {
+ if (pendingInput === null) {
+ return value ?? null;
+ }
+ if (pendingInput.trim() === '') {
+ return null;
+ }
+ return (
+ parseNumberInput(pendingInput, {min, max, isIntegerOnly}) ?? value ?? null
+ );
+ }, [isIntegerOnly, max, min, pendingInput, value]);
+
+ const getNextValue = useCallback(
+ (direction: StepDirection) =>
+ getSteppedValue({
+ currentValue: valueForStepping,
+ direction,
+ min,
+ max,
+ step,
+ isIntegerOnly,
+ }),
+ [isIntegerOnly, max, min, step, valueForStepping],
+ );
+
+ const stepValue = useCallback(
+ (direction: StepDirection) => {
+ // A read-only field is not steppable by any route: keyboard, wheel, or
+ // the stepper buttons all land here.
+ if (isDisabled || isReadOnly) {
+ return;
+ }
+ const nextValue = getNextValue(direction);
+ if (nextValue == null) {
+ return;
+ }
+ setPendingInput(null);
+ if (nextValue !== value) {
+ onChange(nextValue);
+ }
+ },
+ [getNextValue, isDisabled, isReadOnly, onChange, value],
+ );
+
// Handle keyboard events
const handleKeyDown = useCallback(
(e: KeyboardEvent<HTMLInputElement>) => {
+ const hasModifier = e.altKey || e.ctrlKey || e.metaKey || e.shiftKey;
+ if (!hasModifier && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {
+ onKeyDown?.(e);
+ if (e.defaultPrevented) {
+ return;
+ }
+ e.preventDefault();
+ stepValue(e.key === 'ArrowUp' ? 1 : -1);
+ return;
+ }
if (e.key === 'Enter') {
// Validate and commit on Enter
if (pendingInput !== null) {
@@ -580,18 +790,52 @@ export function NumberInput({
onEnter,
onKeyDown,
hasClear,
+ stepValue,
],
);
- // While focused, a wheel gesture steps the value — keep that gesture from
- // also bubbling up and scrolling an ancestor container (page, Dialog,
- // ScrollArea). When the input isn't focused the wheel isn't stepping the
- // value, so normal scrolling is left alone.
- const handleWheel = useCallback((e: React.WheelEvent<HTMLInputElement>) => {
- if (document.activeElement === e.currentTarget) {
- e.stopPropagation();
- }
- }, []);
+ // React's delegated wheel listener can be passive, so use a native,
+ // explicitly non-passive listener to prevent page scrolling only when this
+ // focused input is intentionally consuming the gesture to step its value.
+ const wheelListenerRef = useCallback(
+ (input: HTMLInputElement | null) => {
+ if (input == null || !isWheelEnabled) {
+ return;
+ }
+
+ const handleWheel = (event: WheelEvent) => {
+ // Bail before preventDefault so a read-only input never swallows the
+ // page scroll it cannot act on.
+ if (
+ document.activeElement !== input ||
+ isDisabled ||
+ isReadOnly ||
+ event.deltaY === 0 ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.shiftKey
+ ) {
+ return;
+ }
+ event.preventDefault();
+ event.stopPropagation();
+ stepValue(event.deltaY < 0 ? 1 : -1);
+ };
+
+ input.addEventListener('wheel', handleWheel, {passive: false});
+ return () => input.removeEventListener('wheel', handleWheel);
+ },
+ [isDisabled, isReadOnly, isWheelEnabled, stepValue],
+ );
+
+ const mergedInputRef = useMemo(
+ () => mergeRefs(ref, inputRef, wheelListenerRef),
+ [ref, wheelListenerRef],
+ );
+
+ const canIncrement = getNextValue(1) !== valueForStepping;
+ const canDecrement = getNextValue(-1) !== valueForStepping;
// Handle clear button click
const handleClear = useCallback(() => {
@@ -631,6 +875,7 @@ export function NumberInput({
stylex.props(
inputWrapperStyles.base,
styles.wrapper,
+ hasNumberSteppers && styles.wrapperWithNumberSteppers,
sizeStyles[size],
isDisabled && inputWrapperStyles.disabled,
status && inputStatusBorderStyles[status.type],
@@ -646,17 +891,18 @@ export function NumberInput({
{inputGroup && <VisuallyHidden id={inputLabelID}>{label}</VisuallyHidden>}
<input
{...rest}
- ref={mergeRefs(ref, inputRef)}
+ ref={mergedInputRef}
id={id}
- name={isDisabled ? undefined : htmlName}
- type="number"
+ name={isDisabled || formatValue ? undefined : htmlName}
+ type="text"
+ inputMode={isIntegerOnly ? 'numeric' : 'decimal'}
+ role="spinbutton"
autoComplete={autoComplete}
value={displayValue}
onChange={handleInputChange}
onFocus={handleFocus}
onBlur={handleBlur}
onKeyDown={handleKeyDown}
- onWheel={handleWheel}
placeholder={placeholder}
// With a disabledMessage the input keeps focusability via aria-disabled
// so the reason is focus-discoverable; readOnly + the handler guards
@@ -666,9 +912,12 @@ export function NumberInput({
readOnly={isReadOnly || showsDisabledMessage || undefined}
autoFocus={hasAutoFocus}
data-autofocus={hasAutoFocus || undefined}
- min={min ?? undefined}
- max={max ?? undefined}
- step={step ?? undefined}
+ aria-valuemin={min ?? undefined}
+ aria-valuemax={max ?? undefined}
+ aria-valuenow={value ?? undefined}
+ aria-valuetext={
+ value == null || !formatValue ? undefined : formattedValue
+ }
aria-describedby={ariaDescribedBy}
aria-required={isRequired === true ? 'true' : undefined}
aria-invalid={
@@ -681,6 +930,13 @@ export function NumberInput({
!isInputValid && styles.inputInvalid,
)}
/>
+ {formatValue && htmlName && !isDisabled && (
+ <input
+ type="hidden"
+ name={htmlName}
+ value={value == null ? '' : String(value)}
+ />
+ )}
{units && (
<span id={unitsID} {...stylex.props(styles.units)}>
{units}
@@ -701,6 +957,50 @@ export function NumberInput({
/>
)}
{statusIcon}
+ {hasNumberSteppers && (
+ <div {...stylex.props(styles.numberSteppers)}>
+ <button
+ type="button"
+ tabIndex={-1}
+ disabled={isDisabled || isReadOnly || !canIncrement}
+ aria-label={t('@astryx.numberInput.incrementLabel', {label})}
+ onPointerDown={event => event.preventDefault()}
+ onClick={() => {
+ inputRef.current?.focus();
+ stepValue(1);
+ }}
+ {...stylex.props(
+ styles.numberStepperButton,
+ (isDisabled || isReadOnly || !canIncrement) &&
+ styles.numberStepperButtonDisabled,
+ )}>
+ <Icon
+ icon="chevronDown"
+ size="xsm"
+ color="inherit"
+ xstyle={styles.incrementIcon}
+ />
+ </button>
+ <button
+ type="button"
+ tabIndex={-1}
+ disabled={isDisabled || isReadOnly || !canDecrement}
+ aria-label={t('@astryx.numberInput.decrementLabel', {label})}
+ onPointerDown={event => event.preventDefault()}
+ onClick={() => {
+ inputRef.current?.focus();
+ stepValue(-1);
+ }}
+ {...stylex.props(
+ styles.numberStepperButton,
+ styles.decrementButton,
+ (isDisabled || isReadOnly || !canDecrement) &&
+ styles.numberStepperButtonDisabled,
+ )}>
+ <Icon icon="chevronDown" size="xsm" color="inherit" />
+ </button>
+ </div>
+ )}
</div>
);
diff --git a/packages/core/src/Pagination/Pagination.test.tsx b/packages/core/src/Pagination/Pagination.test.tsx
index 73410c7609..e4427b3cef 100644
--- a/packages/core/src/Pagination/Pagination.test.tsx
+++ b/packages/core/src/Pagination/Pagination.test.tsx
@@ -572,7 +572,7 @@ describe('Pagination', () => {
);
const box = screen.getByRole('spinbutton', {name: 'Go to page'});
expect(box).toBeInTheDocument();
- expect(box).toHaveValue(3);
+ expect(box).toHaveValue('3');
// Visible leading "Page" label and trailing "/ N" total (10 pages).
expect(screen.getByText('Page')).toBeInTheDocument();
expect(screen.getByText('/ 10')).toBeInTheDocument();
@@ -609,8 +609,8 @@ describe('Pagination', () => {
// The box is a NumberInput (a spinbutton) whose min/max clamp entries to
// the valid page range without hand-rolled parsing in Pagination.
const box = screen.getByRole('spinbutton', {name: 'Go to page'});
- expect(box).toHaveAttribute('min', '1');
- expect(box).toHaveAttribute('max', '10');
+ expect(box).toHaveAttribute('aria-valuemin', '1');
+ expect(box).toHaveAttribute('aria-valuemax', '10');
});
it('commits a typed page on Enter and rejects an over-range entry', async () => {
@@ -676,13 +676,13 @@ describe('Pagination', () => {
await user.type(box, 'abc');
await user.tab();
expect(onChange).not.toHaveBeenCalled();
- expect(box).toHaveValue(3);
+ expect(box).toHaveValue('3');
// Emptying the box and blurring reverts to the committed page too.
await user.clear(box);
await user.tab();
expect(onChange).not.toHaveBeenCalled();
- expect(box).toHaveValue(3);
+ expect(box).toHaveValue('3');
});
it('announces the committed page to screen readers', async () => {
@@ -800,7 +800,7 @@ describe('Pagination', () => {
);
const box = screen.getByRole('spinbutton', {name: 'Go to page'});
// The box holds the page number, and committing drives page navigation.
- expect(box).toHaveValue(1);
+ expect(box).toHaveValue('1');
await user.clear(box);
await user.type(box, '4{Enter}');
expect(onChange).toHaveBeenCalledWith(4);
@@ -971,7 +971,7 @@ describe('Pagination', () => {
// The box still holds the 1-based page number.
expect(
screen.getByRole('spinbutton', {name: 'Go to page'}),
- ).toHaveValue(3);
+ ).toHaveValue('3');
});
it('keeps the input page-navigating with a custom label', async () => {