An open source design system that's fully customizable and agent ready
TypeScript
XDSNumberInput (#95)
Andrey Goder972f3278186a
diff --git a/apps/storybook/stories/NumberInput.stories.tsx b/apps/storybook/stories/NumberInput.stories.tsxnew file mode 100644index 0000000000..c7c6d3a01e--- /dev/null+++ b/apps/storybook/stories/NumberInput.stories.tsx@@ -0,0 +1,510 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSNumberInput} from '@xds/core/NumberInput';+import {HashtagIcon, CurrencyDollarIcon} from '@heroicons/react/24/outline';++const meta: Meta<typeof XDSNumberInput> = {+ title: 'Core/XDSNumberInput',+ component: XDSNumberInput,+ tags: ['autodocs'],+ argTypes: {+ label: {+ control: 'text',+ description: 'Label text (required)',+ },+ isLabelHidden: {+ control: 'boolean',+ description:+ 'Visually hide the label (still accessible to screen readers)',+ },+ placeholder: {+ control: 'text',+ description: 'Placeholder text',+ },+ description: {+ control: 'text',+ description: 'Description text displayed between the label and input',+ },+ value: {+ control: 'number',+ description: 'Current input value (number, null, or undefined)',+ },+ size: {+ control: 'select',+ options: ['sm', 'md', 'lg'],+ description: 'Size variant',+ },+ isOptional: {+ control: 'boolean',+ description:+ 'Whether the field is optional (mutually exclusive with isRequired)',+ },+ isRequired: {+ control: 'boolean',+ description:+ 'Whether the field is required (mutually exclusive with isOptional)',+ },+ isDisabled: {+ control: 'boolean',+ description: 'Whether the input is disabled',+ },+ status: {+ control: 'object',+ description:+ 'Status indicator with type (warning/error/success) and optional message',+ },+ tooltip: {+ control: 'text',+ description:+ 'Tooltip text to display in an info icon at the end of the label',+ },+ min: {+ control: 'number',+ description: 'Minimum value allowed',+ },+ max: {+ control: 'number',+ description: 'Maximum value allowed',+ },+ step: {+ control: 'number',+ description: 'Step increment for the input',+ },+ units: {+ control: 'text',+ description:+ 'Units text to display at the end of the input (e.g., "%" or "GB")',+ },+ isIntegerOnly: {+ control: 'boolean',+ description: 'Only allow integer values (no floating point)',+ },+ autoComplete: {+ control: 'text',+ description: 'HTML autocomplete attribute',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSNumberInput>;++export const Default: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Quantity',+ placeholder: 'Enter quantity',+ },+};++export const WithDescription: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Age',+ description: 'Enter your age in years',+ placeholder: 'Enter your age',+ },+};++export const WithMinMax: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Rating',+ placeholder: '1-5',+ min: 1,+ max: 5,+ description: 'Rate from 1 to 5',+ },+};++export const WithStep: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Price',+ placeholder: '0.00',+ min: 0,+ step: 0.01,+ startIcon: CurrencyDollarIcon,+ },+};++export const WithUnits: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? 50);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Discount',+ placeholder: 'Enter discount',+ min: 0,+ max: 100,+ units: '%',+ },+};++export const WithUnitsGB: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? 128);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Storage',+ placeholder: 'Enter storage',+ min: 0,+ units: 'GB',+ },+};++export const IntegerOnly: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Count',+ placeholder: 'Enter count',+ isIntegerOnly: true,+ description: 'Only accepts whole numbers',+ },+};++export const WithValue: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? 42);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Quantity',+ value: 42,+ },+};++export const AllVariations: Story = {+ render: () => {+ const [value1, setValue1] = useState<number | null>(null);+ const [value2, setValue2] = useState<number | null>(null);+ const [value3, setValue3] = useState<number | null>(100);+ const [value4, setValue4] = useState<number | null>(null);+ const [value5, setValue5] = useState<number | null>(null);+ const [value6, setValue6] = useState<number | null>(null);+ const [value7, setValue7] = useState<number | null>(null);+ const [value8, setValue8] = useState<number | null>(50);+ const [value9, setValue9] = useState<number | null>(75);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '300px',+ }}>+ <XDSNumberInput+ label="Visible label"+ value={value1}+ onChange={setValue1}+ placeholder="Enter number..."+ />+ <XDSNumberInput+ label="With description"+ description="Helpful description text"+ value={value4}+ onChange={setValue4}+ placeholder="Enter number..."+ />+ <XDSNumberInput+ label="Hidden label"+ isLabelHidden+ value={value2}+ onChange={setValue2}+ placeholder="Hidden label input"+ />+ <XDSNumberInput+ label="With value"+ value={value3}+ onChange={setValue3}+ />+ <XDSNumberInput+ label="Optional field"+ isOptional+ value={value5}+ onChange={setValue5}+ placeholder="Optional..."+ />+ <XDSNumberInput+ label="Required field"+ isRequired+ value={value6}+ onChange={setValue6}+ placeholder="Required..."+ />+ <XDSNumberInput+ label="With min/max"+ description="Enter a value between 1 and 10"+ min={1}+ max={10}+ value={value7}+ onChange={setValue7}+ placeholder="1-10"+ />+ <XDSNumberInput+ label="Disabled field"+ isDisabled+ value={value8}+ onChange={setValue8}+ />+ <XDSNumberInput+ label="With units"+ value={value9}+ onChange={setValue9}+ units="%"+ />+ </div>+ );+ },+};++export const OptionalField: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Phone Extension',+ isOptional: true,+ placeholder: 'Enter extension',+ },+};++export const RequiredField: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Quantity',+ isRequired: true,+ placeholder: 'Enter quantity',+ },+};++export const Disabled: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? 100);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Locked Amount',+ isDisabled: true,+ value: 100,+ },+};++export const WithStartIcon: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Count',+ placeholder: 'Enter count...',+ startIcon: HashtagIcon,+ },+};++export const SizeVariants: Story = {+ render: () => {+ const [sm, setSm] = useState<number | null>(null);+ const [md, setMd] = useState<number | null>(null);+ const [lg, setLg] = useState<number | null>(null);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '300px',+ }}>+ <XDSNumberInput+ label="Small (28px)"+ value={sm}+ onChange={setSm}+ placeholder="Small size"+ size="sm"+ />+ <XDSNumberInput+ label="Medium (32px)"+ value={md}+ onChange={setMd}+ placeholder="Medium size (default)"+ size="md"+ />+ <XDSNumberInput+ label="Large (36px)"+ value={lg}+ onChange={setLg}+ placeholder="Large size"+ size="lg"+ />+ </div>+ );+ },+};++export const ErrorStatus: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? -5);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Age',+ placeholder: 'Enter your age',+ min: 0,+ status: {type: 'error', message: 'Age must be a positive number'},+ },+};++export const WarningStatus: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? 150);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Age',+ placeholder: 'Enter your age',+ status: {type: 'warning', message: 'This value seems unusually high'},+ },+};++export const SuccessStatus: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? 25);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Age',+ placeholder: 'Enter your age',+ status: {type: 'success', message: 'Valid age'},+ },+};++export const StatusVariations: Story = {+ render: () => {+ const [error, setError] = useState<number | null>(-5);+ const [warning, setWarning] = useState<number | null>(150);+ const [success, setSuccess] = useState<number | null>(25);+ const [errorNoMsg, setErrorNoMsg] = useState<number | null>(0);+ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '300px',+ }}>+ <XDSNumberInput+ label="Error with message"+ value={error}+ onChange={setError}+ status={{type: 'error', message: 'Must be positive'}}+ />+ <XDSNumberInput+ label="Warning with message"+ value={warning}+ onChange={setWarning}+ status={{type: 'warning', message: 'Value seems high'}}+ />+ <XDSNumberInput+ label="Success with message"+ value={success}+ onChange={setSuccess}+ status={{type: 'success', message: 'Looks good'}}+ />+ <XDSNumberInput+ label="Error without message"+ value={errorNoMsg}+ onChange={setErrorNoMsg}+ status={{type: 'error'}}+ />+ </div>+ );+ },+};++export const WithTooltip: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'API Rate Limit',+ placeholder: 'Enter rate limit',+ tooltip: 'Maximum number of API requests per minute',+ },+};++export const DecimalInput: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ return <XDSNumberInput {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Price',+ placeholder: '0.00',+ min: 0,+ step: 0.01,+ startIcon: CurrencyDollarIcon,+ description: 'Enter amount in dollars',+ },+};++export const WithEventHandlers: Story = {+ render: args => {+ const [value, setValue] = useState<number | null>(args.value ?? null);+ const [events, setEvents] = useState<string[]>([]);++ const addEvent = (event: string) => {+ setEvents(prev => [...prev.slice(-4), event]);+ };++ return (+ <div style={{maxWidth: '300px'}}>+ <XDSNumberInput+ {...args}+ value={value}+ onChange={v => {+ setValue(v);+ addEvent(`onChange: ${v}`);+ }}+ onFocus={() => addEvent('onFocus')}+ onBlur={() => addEvent('onBlur')}+ onEnter={() => addEvent('onEnter')}+ />+ <div style={{marginTop: '16px', fontSize: '12px', color: '#666'}}>+ <strong>Events:</strong>+ <ul style={{margin: '4px 0', paddingLeft: '20px'}}>+ {events.map((event, i) => (+ <li key={i}>{event}</li>+ ))}+ </ul>+ </div>+ </div>+ );+ },+ args: {+ label: 'Interactive',+ placeholder: 'Type and press Enter',+ description: 'Events are logged below',+ },+};diff --git a/packages/core/src/NumberInput/README.md b/packages/core/src/NumberInput/README.mdnew file mode 100644index 0000000000..78f56a32ac--- /dev/null+++ b/packages/core/src/NumberInput/README.md@@ -0,0 +1,124 @@+# /packages/core/src/NumberInput++A number input component for collecting numeric user input with validation.++<!-- SYNC: When files in this directory change, update this document. -->++## Features++- **Label Support**: Required label for accessibility (can be visually hidden)+- **Description**: Optional description text displayed between the label and input+- **Optional/Required Indicators**: Display "Optional" or "Required" text with bullet separator+- **Label Tooltip**: Optional info icon with tooltip at end of label+- **Label Icon**: Optional icon before the label text+- **Accessible**: Label properly associated with input via htmlFor/id+- **Styled with StyleX**: Uses XDS design tokens for consistent styling+- **Size Variants**: Three sizes (sm, md, lg) for different contexts+- **Status Handling**: Error, warning, and success states with messages+- **Number Constraints**: Support for min, max, and step attributes+- **Validated onChange**: Only calls onChange when the entered value passes validation+- **Units Display**: Optional units suffix (e.g., "%" or "GB")+- **Integer Mode**: Option to restrict to integers only+- **Native Controls**: Uses `type="number"` for browser step controls+- **Event Callbacks**: onFocus, onBlur, and onEnter handlers++## Usage++```tsx+import { XDSNumberInput } from '@xds/core/NumberInput';++// Basic input with label+<XDSNumberInput label="Quantity" value={quantity} onChange={setQuantity} />++// With placeholder+<XDSNumberInput label="Age" value={age} onChange={setAge} placeholder="Enter your age" />++// With min/max constraints+<XDSNumberInput label="Rating" value={rating} onChange={setRating} min={1} max={5} />++// With step for decimals+<XDSNumberInput label="Price" value={price} onChange={setPrice} min={0} step={0.01} />++// With units display+<XDSNumberInput label="Discount" value={discount} onChange={setDiscount} units="%" />++// Integer only+<XDSNumberInput label="Count" value={count} onChange={setCount} isIntegerOnly />++// With description+<XDSNumberInput label="Quantity" description="Enter the number of items" value={qty} onChange={setQty} />++// Optional field+<XDSNumberInput label="Phone Extension" isOptional value={ext} onChange={setExt} />++// Required field+<XDSNumberInput label="Amount" isRequired value={amount} onChange={setAmount} />++// With validation status (error, warning, or success)+<XDSNumberInput+ label="Age"+ value={age}+ onChange={setAge}+ status={{ type: 'error', message: 'Age must be between 18 and 120' }}+/>++// With event handlers+<XDSNumberInput+ label="Search"+ value={search}+ onChange={setSearch}+ onEnter={() => handleSearch()}+ onFocus={() => console.log('focused')}+ onBlur={() => console.log('blurred')}+/>+```++## Props++| Prop | Type | Required | Description |+| --------------- | --------------------------------------------------------- | -------- | ------------------------------------------------------------------ |+| `label` | `string` | Yes | Label text for the input (always rendered for accessibility) |+| `value` | `number \| null \| undefined` | Yes | Current value of the input |+| `onChange` | `(value: number) => void` | Yes | Callback fired when input value changes (only on valid input) |+| `size` | `'sm' \| 'md' \| 'lg'` | No | Size variant (default: `'md'`) |+| `isLabelHidden` | `boolean` | No | Visually hide the label (still accessible to screen readers) |+| `description` | `string` | No | Description text displayed between the label and input |+| `isOptional` | `boolean` | No | Whether the field is optional (mutually exclusive with isRequired) |+| `isRequired` | `boolean` | No | Whether the field is required (mutually exclusive with isOptional) |+| `isDisabled` | `boolean` | No | Whether the input is disabled |+| `placeholder` | `string` | No | Placeholder text |+| `tooltip` | `string` | No | Tooltip text to display in an info icon at the end of the label |+| `startIcon` | `XDSIconType` | No | Icon to display at the start of the input |+| `labelIcon` | `XDSIconType` | No | Icon to display before the label text |+| `status` | `{type: 'error'\|'warning'\|'success', message?: string}` | No | Validation status with optional message |+| `min` | `number \| null` | No | Minimum value allowed |+| `max` | `number \| null` | No | Maximum value allowed |+| `step` | `number \| null` | No | Step increment for the input (default: 1) |+| `units` | `string \| null` | No | Units text to display at the end of the input (e.g., "%" or "GB") |+| `isIntegerOnly` | `boolean` | No | Only allow integer values (no floating point) |+| `htmlName` | `string` | No | HTML name attribute for form submissions |+| `autoComplete` | `string` | No | HTML autocomplete attribute |+| `hasAutoFocus` | `boolean` | No | Whether to focus the input on mount |+| `onFocus` | `(e: FocusEvent<HTMLInputElement>) => void` | No | Callback fired when the input receives focus |+| `onBlur` | `(e: FocusEvent<HTMLInputElement>) => void` | No | Callback fired when the input loses focus |+| `onEnter` | `() => void` | No | Callback fired when the user presses the Enter key |++## Files++| File | Role | Purpose |+| ------------------------- | ----- | --------------------------- |+| `index.ts` | Entry | Exports component and types |+| `XDSNumberInput.tsx` | Core | Component implementation |+| `XDSNumberInput.test.tsx` | Test | Unit tests |++## Implementation Notes++- Uses `useId` hook for accessible label-input association+- Label is always rendered for accessibility; use `isLabelHidden` to hide visually+- Hidden label uses CSS technique that remains accessible to screen readers+- Wraps `XDSField` component for label, description, and optional/required handling+- `isOptional` and `isRequired` are mutually exclusive; setting both will show "Optional"+- Uses `type="number"` to enable native browser step controls (up/down arrows)+- **Validated onChange**: Only calls `onChange` when the entered value is a valid number that passes min/max/integer constraints+- Uses internal pending state to allow free-form typing while validating+- Units are displayed as a lighter grey suffix after the input valuediff --git a/packages/core/src/NumberInput/XDSNumberInput.test.tsx b/packages/core/src/NumberInput/XDSNumberInput.test.tsxnew file mode 100644index 0000000000..cb0b29dbaf--- /dev/null+++ b/packages/core/src/NumberInput/XDSNumberInput.test.tsx@@ -0,0 +1,578 @@+/**+ * @file XDSNumberInput.test.tsx+ * @input Uses vitest, @testing-library/react, XDSNumberInput component+ * @output Unit tests for XDSNumberInput component behavior+ * @position Testing; validates XDSNumberInput.tsx implementation+ *+ * SYNC: When XDSNumberInput.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {HashtagIcon} from '@heroicons/react/24/outline';+import {XDSNumberInput} from './XDSNumberInput';++describe('XDSNumberInput', () => {+ it('renders with label', () => {+ render(+ <XDSNumberInput label="Quantity" value={null} onChange={() => {}} />,+ );+ expect(screen.getByLabelText('Quantity')).toBeInTheDocument();+ });++ it('renders with placeholder', () => {+ render(+ <XDSNumberInput+ label="Quantity"+ value={null}+ onChange={() => {}}+ placeholder="Enter number"+ />,+ );+ expect(screen.getByPlaceholderText('Enter number')).toBeInTheDocument();+ });++ it('displays controlled value as number', () => {+ render(<XDSNumberInput label="Quantity" value={456} onChange={() => {}} />);+ expect(screen.getByRole('spinbutton')).toHaveValue(456);+ });++ it('displays null for null value', () => {+ render(+ <XDSNumberInput label="Quantity" value={null} onChange={() => {}} />,+ );+ expect(screen.getByRole('spinbutton')).toHaveValue(null);+ });++ it('displays null for undefined value', () => {+ render(+ <XDSNumberInput label="Quantity" value={undefined} onChange={() => {}} />,+ );+ expect(screen.getByRole('spinbutton')).toHaveValue(null);+ });++ it('forwards ref correctly', () => {+ const ref = vi.fn();+ render(+ <XDSNumberInput+ ref={ref}+ label="Quantity"+ value={null}+ onChange={() => {}}+ />,+ );+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));+ });++ it('visually hides label when isLabelHidden is true', () => {+ render(+ <XDSNumberInput+ label="Quantity"+ isLabelHidden+ value={null}+ onChange={() => {}}+ />,+ );+ const label = screen.getByText('Quantity');+ expect(label).toBeInTheDocument();+ expect(screen.getByLabelText('Quantity')).toBeInTheDocument();+ });++ it('shows label visually by default', () => {+ render(<XDSNumberInput label="Amount" value={null} onChange={() => {}} />);+ const label = screen.getByText('Amount');+ expect(label).toBeVisible();+ });++ it('sets aria-required when isRequired is true', () => {+ render(+ <XDSNumberInput+ label="Quantity"+ isRequired+ value={null}+ onChange={() => {}}+ />,+ );+ expect(screen.getByRole('spinbutton')).toHaveAttribute(+ 'aria-required',+ 'true',+ );+ });++ it('does not set aria-required when isRequired is false', () => {+ render(+ <XDSNumberInput label="Quantity" value={null} onChange={() => {}} />,+ );+ expect(screen.getByRole('spinbutton')).not.toHaveAttribute('aria-required');+ });++ it('sets disabled attribute when isDisabled is true', () => {+ render(+ <XDSNumberInput+ label="Quantity"+ isDisabled+ value={null}+ onChange={() => {}}+ />,+ );+ expect(screen.getByRole('spinbutton')).toBeDisabled();+ });++ it('does not fire onChange when disabled', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSNumberInput+ label="Quantity"+ isDisabled+ value={null}+ onChange={handleChange}+ />,+ );++ const input = screen.getByRole('spinbutton');+ await user.type(input, '123');+ expect(handleChange).not.toHaveBeenCalled();+ });++ it('is not disabled by default', () => {+ render(+ <XDSNumberInput label="Quantity" value={null} onChange={() => {}} />,+ );+ expect(screen.getByRole('spinbutton')).not.toBeDisabled();+ });++ it('renders with startIcon', () => {+ render(+ <XDSNumberInput+ label="Count"+ value={null}+ onChange={() => {}}+ startIcon={HashtagIcon}+ />,+ );+ expect(screen.getByRole('spinbutton')).toBeInTheDocument();+ const svg = document.querySelector('svg');+ expect(svg).toBeInTheDocument();+ });++ it('renders without icon wrapper when startIcon is not provided', () => {+ const {container} = render(+ <XDSNumberInput label="Quantity" value={null} onChange={() => {}} />,+ );+ expect(container.querySelector('svg')).not.toBeInTheDocument();+ });++ describe('native number input attributes', () => {+ it('sets min attribute', () => {+ render(+ <XDSNumberInput label="Age" value={null} onChange={() => {}} min={0} />,+ );+ expect(screen.getByRole('spinbutton')).toHaveAttribute('min', '0');+ });++ it('sets max attribute', () => {+ render(+ <XDSNumberInput+ label="Age"+ value={null}+ onChange={() => {}}+ max={120}+ />,+ );+ expect(screen.getByRole('spinbutton')).toHaveAttribute('max', '120');+ });++ it('sets step attribute', () => {+ render(+ <XDSNumberInput+ label="Price"+ value={null}+ onChange={() => {}}+ step={0.01}+ />,+ );+ expect(screen.getByRole('spinbutton')).toHaveAttribute('step', '0.01');+ });+ });++ describe('onChange validation', () => {+ it('calls onChange with valid number when typing', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSNumberInput+ label="Quantity"+ value={null}+ onChange={handleChange}+ />,+ );++ const input = screen.getByRole('spinbutton');+ await user.click(input);+ await user.type(input, '42');++ expect(handleChange).toHaveBeenCalledWith(4);+ expect(handleChange).toHaveBeenCalledWith(42);+ });++ it('does not call onChange when value exceeds max', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSNumberInput+ label="Rating"+ value={null}+ onChange={handleChange}+ max={5}+ />,+ );++ const input = screen.getByRole('spinbutton');+ await user.click(input);+ await user.type(input, '10');++ // 1 is valid (<=5), but 10 is not+ expect(handleChange).toHaveBeenCalledWith(1);+ expect(handleChange).not.toHaveBeenCalledWith(10);+ });++ it('does not call onChange when value is below min', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSNumberInput+ label="Age"+ value={null}+ onChange={handleChange}+ min={0}+ />,+ );++ const input = screen.getByRole('spinbutton');+ await user.click(input);+ await user.type(input, '-5');++ // Neither -5 nor any partial input is valid with min=0+ expect(handleChange).not.toHaveBeenCalled();+ });++ it('does not call onChange for decimal when isIntegerOnly is true', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSNumberInput+ label="Count"+ value={null}+ onChange={handleChange}+ isIntegerOnly+ />,+ );++ const input = screen.getByRole('spinbutton');+ await user.click(input);+ await user.type(input, '3.5');++ // 3 is valid, but 3.5 is not+ expect(handleChange).toHaveBeenCalledWith(3);+ expect(handleChange).not.toHaveBeenCalledWith(3.5);+ });++ it('calls onChange for decimal when isIntegerOnly is false', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ render(+ <XDSNumberInput label="Price" value={null} onChange={handleChange} />,+ );++ const input = screen.getByRole('spinbutton');+ await user.click(input);+ await user.type(input, '3.5');++ expect(handleChange).toHaveBeenCalledWith(3.5);+ });+ });++ describe('units prop', () => {+ it('renders units text when provided', () => {+ render(+ <XDSNumberInput+ label="Discount"+ value={10}+ onChange={() => {}}+ units="%"+ />,+ );+ expect(screen.getByText('%')).toBeInTheDocument();+ });++ it('does not render units when not provided', () => {+ render(<XDSNumberInput label="Amount" value={100} onChange={() => {}} />);+ expect(screen.queryByText('%')).not.toBeInTheDocument();+ expect(screen.queryByText('GB')).not.toBeInTheDocument();+ });+ });++ describe('event callbacks', () => {+ it('calls onFocus when input receives focus', async () => {+ const user = userEvent.setup();+ const handleFocus = vi.fn();+ render(+ <XDSNumberInput+ label="Quantity"+ value={null}+ onChange={() => {}}+ onFocus={handleFocus}+ />,+ );++ await user.click(screen.getByRole('spinbutton'));+ expect(handleFocus).toHaveBeenCalledTimes(1);+ });++ it('calls onBlur when input loses focus', async () => {+ const user = userEvent.setup();+ const handleBlur = vi.fn();+ render(+ <XDSNumberInput+ label="Quantity"+ value={null}+ onChange={() => {}}+ onBlur={handleBlur}+ />,+ );++ const input = screen.getByRole('spinbutton');+ await user.click(input);+ await user.tab();+ expect(handleBlur).toHaveBeenCalledTimes(1);+ });++ it('calls onEnter when Enter key is pressed', async () => {+ const user = userEvent.setup();+ const handleEnter = vi.fn();+ render(+ <XDSNumberInput+ label="Quantity"+ value={null}+ onChange={() => {}}+ onEnter={handleEnter}+ />,+ );++ const input = screen.getByRole('spinbutton');+ await user.click(input);+ await user.keyboard('{Enter}');+ expect(handleEnter).toHaveBeenCalledTimes(1);+ });++ it('commits valid value on Enter key', async () => {+ const user = userEvent.setup();+ const handleChange = vi.fn();+ const handleEnter = vi.fn();+ render(+ <XDSNumberInput+ label="Quantity"+ value={null}+ onChange={handleChange}+ onEnter={handleEnter}+ />,+ );++ const input = screen.getByRole('spinbutton');+ await user.click(input);+ await user.type(input, '42');+ handleChange.mockClear();+ await user.keyboard('{Enter}');++ expect(handleEnter).toHaveBeenCalledTimes(1);+ });+ });++ describe('status prop', () => {+ it('renders with error status icon', () => {+ const {container} = render(+ <XDSNumberInput+ label="Amount"+ value={null}+ onChange={() => {}}+ status={{type: 'error'}}+ />,+ );+ expect(container.querySelector('svg')).toBeInTheDocument();+ });++ it('renders with warning status icon', () => {+ const {container} = render(+ <XDSNumberInput+ label="Amount"+ value={null}+ onChange={() => {}}+ status={{type: 'warning'}}+ />,+ );+ expect(container.querySelector('svg')).toBeInTheDocument();+ });++ it('renders with success status icon', () => {+ const {container} = render(+ <XDSNumberInput+ label="Amount"+ value={null}+ onChange={() => {}}+ status={{type: 'success'}}+ />,+ );+ expect(container.querySelector('svg')).toBeInTheDocument();+ });++ it('renders status message when provided', () => {+ render(+ <XDSNumberInput+ label="Amount"+ value={null}+ onChange={() => {}}+ status={{type: 'error', message: 'Value must be positive'}}+ />,+ );+ expect(screen.getByText('Value must be positive')).toBeInTheDocument();+ });++ it('does not render status message when not provided', () => {+ render(+ <XDSNumberInput+ label="Amount"+ value={null}+ onChange={() => {}}+ status={{type: 'error'}}+ />,+ );+ expect(screen.queryByText(/positive/i)).not.toBeInTheDocument();+ });++ it('sets aria-invalid when status type is error', () => {+ render(+ <XDSNumberInput+ label="Amount"+ value={null}+ onChange={() => {}}+ status={{type: 'error'}}+ />,+ );+ expect(screen.getByRole('spinbutton')).toHaveAttribute(+ 'aria-invalid',+ 'true',+ );+ });++ it('does not set aria-invalid for warning status', () => {+ render(+ <XDSNumberInput+ label="Amount"+ value={null}+ onChange={() => {}}+ status={{type: 'warning'}}+ />,+ );+ expect(screen.getByRole('spinbutton')).not.toHaveAttribute(+ 'aria-invalid',+ );+ });++ it('does not set aria-invalid for success status', () => {+ render(+ <XDSNumberInput+ label="Amount"+ value={null}+ onChange={() => {}}+ status={{type: 'success'}}+ />,+ );+ expect(screen.getByRole('spinbutton')).not.toHaveAttribute(+ 'aria-invalid',+ );+ });+ });++ it('renders tooltip info icon when tooltip is provided', () => {+ render(+ <XDSNumberInput+ label="Help"+ value={null}+ onChange={() => {}}+ tooltip="Helpful info"+ />,+ );+ expect(document.querySelector('svg')).toBeInTheDocument();+ });++ it('does not render tooltip icon when tooltip is not provided', () => {+ render(+ <XDSNumberInput label="Quantity" value={null} onChange={() => {}} />,+ );+ expect(document.querySelector('svg')).not.toBeInTheDocument();+ });++ describe('hasAutoFocus prop', () => {+ it('focuses the input when hasAutoFocus is true', () => {+ render(+ <XDSNumberInput+ label="Quantity"+ value={null}+ onChange={() => {}}+ hasAutoFocus+ />,+ );+ expect(screen.getByRole('spinbutton')).toHaveFocus();+ });++ it('does not focus when hasAutoFocus is false', () => {+ render(+ <XDSNumberInput label="Quantity" value={null} onChange={() => {}} />,+ );+ expect(screen.getByRole('spinbutton')).not.toHaveFocus();+ });+ });++ describe('htmlName prop', () => {+ it('sets name attribute when htmlName is provided', () => {+ render(+ <XDSNumberInput+ label="Quantity"+ value={null}+ onChange={() => {}}+ htmlName="quantity"+ />,+ );+ expect(screen.getByRole('spinbutton')).toHaveAttribute(+ 'name',+ 'quantity',+ );+ });++ it('does not set name attribute when htmlName is not provided', () => {+ render(+ <XDSNumberInput label="Quantity" value={null} onChange={() => {}} />,+ );+ expect(screen.getByRole('spinbutton')).not.toHaveAttribute('name');+ });+ });++ describe('autoComplete prop', () => {+ it('sets autocomplete attribute when autoComplete is provided', () => {+ render(+ <XDSNumberInput+ label="Age"+ value={null}+ onChange={() => {}}+ autoComplete="off"+ />,+ );+ expect(screen.getByRole('spinbutton')).toHaveAttribute(+ 'autocomplete',+ 'off',+ );+ });+ });+});diff --git a/packages/core/src/NumberInput/XDSNumberInput.tsx b/packages/core/src/NumberInput/XDSNumberInput.tsxnew file mode 100644index 0000000000..264b919856--- /dev/null+++ b/packages/core/src/NumberInput/XDSNumberInput.tsx@@ -0,0 +1,537 @@+/**+ * @file XDSNumberInput.tsx+ * @input Uses React forwardRef, useId, useState, useMemo, useCallback, XDSField, XDSIcon+ * @output Exports XDSNumberInput component, XDSNumberInputProps+ * @position Core implementation; consumed by index.ts, tested by XDSNumberInput.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/NumberInput/README.md (props table, features, implementation notes)+ * - /packages/core/src/NumberInput/XDSNumberInput.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/NumberInput/index.ts (exports if types change)+ * - /apps/storybook/stories/NumberInput.stories.tsx (storybook stories)+ */++import {+ forwardRef,+ useId,+ useState,+ useMemo,+ useCallback,+ useRef,+ type FocusEvent,+ type KeyboardEvent,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {+ CheckCircleIcon,+ ExclamationTriangleIcon,+ XCircleIcon,+} from '@heroicons/react/24/solid';+import {+ colorVars,+ sizeVars,+ spacingVars,+ radiusVars,+ transitionVars,+ typographyVars,+ textSizeVars,+ lineHeightVars,+} from '../theme/tokens.stylex';+import {XDSField, type XDSInputStatus, type XDSInputStatusType} from '../Field';+import {XDSIcon, type XDSIconType} from '../Icon';++const styles = stylex.create({+ wrapper: {+ position: 'relative',+ zIndex: 1,+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-2'],+ paddingBlock: spacingVars['--spacing-1'],+ paddingInline: spacingVars['--spacing-2'],+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: {+ default: colorVars['--color-divider-emphasized'],+ ':hover': colorVars['--color-divider-high-contrast'],+ },+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: colorVars['--color-surface'],+ transitionProperty: 'border-color, outline',+ transitionDuration: transitionVars['--transition-fast'],+ outline: {+ default: 'none',+ ':focus-within': `2px solid ${colorVars['--color-focus-outline']}`,+ },+ outlineOffset: {+ default: '0',+ ':focus-within': '1px',+ },+ },+ wrapperDisabled: {+ cursor: 'not-allowed',+ opacity: 0.5,+ borderColor: colorVars['--color-divider-emphasized'],+ },+ input: {+ display: 'block',+ flex: 1,+ minWidth: 0,+ border: 0,+ padding: 0,+ fontFamily: typographyVars['--font-body'],+ fontSize: textSizeVars['--text-base'],+ lineHeight: lineHeightVars['--leading-base'],+ color: colorVars['--color-text-primary'],+ backgroundColor: 'transparent',+ outline: 0,+ '::placeholder': {+ color: colorVars['--color-text-placeholder'],+ },+ },+ inputDisabled: {+ cursor: 'not-allowed',+ },+ inputInvalid: {+ color: colorVars['--color-text-secondary'],+ },+ units: {+ fontFamily: typographyVars['--font-body'],+ fontSize: textSizeVars['--text-base'],+ lineHeight: lineHeightVars['--leading-base'],+ color: colorVars['--color-text-secondary'],+ flexShrink: 0,+ },+});++const sizeStyles = stylex.create({+ sm: {+ height: sizeVars['--size-sm'],+ },+ md: {+ height: sizeVars['--size-md'],+ },+ lg: {+ height: sizeVars['--size-lg'],+ },+});++const statusBorderStyles = stylex.create({+ warning: {+ borderColor: colorVars['--color-warning'],+ },+ error: {+ borderColor: colorVars['--color-negative'],+ },+ success: {+ borderColor: colorVars['--color-positive'],+ },+});++export type XDSNumberInputSize = keyof typeof sizeStyles;++// Re-export shared types for convenience+export type {+ XDSInputStatus as XDSNumberInputStatus,+ XDSInputStatusType as XDSNumberInputStatusType,+} from '../Field';++export interface XDSNumberInputProps {+ /**+ * Label text for the input (always rendered for accessibility).+ */+ label: string;+ /**+ * Whether to visually hide the label (still accessible to screen readers).+ * @default false+ */+ isLabelHidden?: boolean;+ /**+ * Description text displayed between the label and input.+ */+ description?: string;+ /**+ * Whether the field is optional. Mutually exclusive with isRequired.+ * @default false+ */+ isOptional?: boolean;+ /**+ * Whether the field is required. Mutually exclusive with isOptional.+ * @default false+ */+ isRequired?: boolean;+ /**+ * Whether the input is disabled.+ * @default false+ */+ isDisabled?: boolean;+ /**+ * Icon to display at the start of the input.+ * Import from @heroicons/react/24/outline or @heroicons/react/24/solid.+ */+ startIcon?: XDSIconType;+ /**+ * Icon to display before the label text.+ */+ labelIcon?: XDSIconType;+ /**+ * Status indicator for the input.+ * When set, displays a colored border and status icon.+ * If message is provided, displays a floating message box below the input.+ */+ status?: XDSInputStatus;+ /**+ * The size of the input.+ * - 'sm': Compact size (28px height)+ * - 'md': Default size (32px height)+ * - 'lg': Large size (36px height)+ * @default 'md'+ */+ size?: XDSNumberInputSize;+ /**+ * Callback fired when the input value changes to a valid number.+ * Only called when the entered value passes validation.+ */+ onChange: (value: number) => void;+ /**+ * The current value of the input.+ * Use null or undefined to represent an empty/unset value.+ */+ value: number | null | undefined;+ /**+ * Placeholder text shown when the input is empty.+ */+ placeholder?: string;+ /**+ * Tooltip text to display in an info icon at the end of the label.+ */+ tooltip?: string;+ /**+ * Whether to automatically focus the input on mount.+ * @default false+ */+ hasAutoFocus?: boolean;+ /**+ * The HTML name attribute for the input.+ * Useful for form submissions.+ */+ htmlName?: string;+ /**+ * The HTML autocomplete attribute for the input.+ */+ autoComplete?: string;+ /**+ * The minimum value allowed.+ */+ min?: number | null;+ /**+ * The maximum value allowed.+ */+ max?: number | null;+ /**+ * The step increment for the input.+ * @default 1+ */+ step?: number | null;+ /**+ * Units text to display at the end of the input (e.g., "%" or "GB").+ */+ units?: string | null;+ /**+ * Whether to only allow integer values (no floating point).+ * @default false+ */+ isIntegerOnly?: boolean;+ /**+ * Callback fired when the input receives focus.+ */+ onFocus?: (e: FocusEvent<HTMLInputElement>) => void;+ /**+ * Callback fired when the input loses focus.+ */+ onBlur?: (e: FocusEvent<HTMLInputElement>) => void;+ /**+ * Callback fired when the user presses the Enter key.+ */+ onEnter?: () => void;+}++/**+ * 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;+ },+): number | null {+ const trimmed = input.trim();+ if (trimmed === '' || trimmed === '-') {+ return null;+ }++ const num = Number(trimmed);+ if (!Number.isFinite(num)) {+ return null;+ }++ // Check integer constraint+ if (options.isIntegerOnly && !Number.isInteger(num)) {+ return null;+ }++ // Check min constraint+ if (options.min != null && num < options.min) {+ return null;+ }++ // Check max constraint+ if (options.max != null && num > options.max) {+ return null;+ }++ return num;+}++/**+ * A number input component for collecting numeric user input.+ * Only calls onChange when the entered value passes validation.+ *+ * @example+ * ```tsx+ * <XDSNumberInput label="Quantity" value={quantity} onChange={setQuantity} />+ * <XDSNumberInput label="Price" value={price} onChange={setPrice} min={0} step={0.01} />+ * ```+ */+export const XDSNumberInput = forwardRef<HTMLInputElement, XDSNumberInputProps>(+ (+ {+ label,+ isLabelHidden = false,+ description,+ isOptional = false,+ isRequired = false,+ isDisabled = false,+ startIcon,+ labelIcon,+ status,+ size = 'md',+ onChange,+ value,+ placeholder,+ tooltip,+ hasAutoFocus = false,+ htmlName,+ autoComplete,+ min,+ max,+ step,+ units,+ isIntegerOnly = false,+ onFocus,+ onBlur,+ onEnter,+ },+ ref,+ ) => {+ const id = useId();+ const descriptionID = useId();+ const statusMessageID = useId();+ const inputRef = useRef<HTMLInputElement | null>(null);++ // Pending input while user is typing (null = show formatted value)+ const [pendingInput, setPendingInput] = useState<string | null>(null);++ const statusIconMap: Record<XDSInputStatusType, XDSIconType> = {+ warning: ExclamationTriangleIcon,+ error: XCircleIcon,+ success: CheckCircleIcon,+ };++ const statusIconColorMap: Record<+ XDSInputStatusType,+ 'warning' | 'negative' | 'positive'+ > = {+ warning: 'warning',+ error: 'negative',+ success: 'positive',+ };++ const ariaDescribedBy =+ [+ description ? descriptionID : null,+ status?.message ? statusMessageID : null,+ ]+ .filter(Boolean)+ .join(' ') || undefined;++ // Display value: pending input if typing, otherwise the raw value+ // Note: With type="number", we can't use formatted display values+ const displayValue = useMemo(() => {+ if (pendingInput !== null) {+ return pendingInput;+ }+ if (value == null) {+ return '';+ }+ return String(value);+ }, [pendingInput, value]);++ // Check if current pending input is valid (for styling purposes)+ const isInputValid = useMemo(() => {+ if (pendingInput === null || !pendingInput.trim()) {+ return true;+ }+ return parseNumberInput(pendingInput, {min, max, isIntegerOnly}) !== null;+ }, [pendingInput, min, max, isIntegerOnly]);++ // Handle input text change - update immediately if valid+ const handleInputChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const newValue = e.target.value;+ setPendingInput(newValue);++ // If the input is valid, update immediately+ const parsed = parseNumberInput(newValue, {min, max, isIntegerOnly});+ if (parsed !== null && parsed !== value) {+ onChange(parsed);+ }+ },+ [value, onChange, min, max, isIntegerOnly],+ );++ // Handle focus+ const handleFocus = useCallback(+ (e: FocusEvent<HTMLInputElement>) => {+ onFocus?.(e);+ },+ [onFocus],+ );++ // Handle blur - validate and clear pending input+ const handleBlur = useCallback(+ (e: FocusEvent<HTMLInputElement>) => {+ if (pendingInput !== null) {+ const parsed = parseNumberInput(pendingInput, {+ min,+ max,+ isIntegerOnly,+ });+ if (parsed !== null && parsed !== value) {+ onChange(parsed);+ }+ }++ // Clear pending input - display will revert to formatted value+ setPendingInput(null);+ onBlur?.(e);+ },+ [pendingInput, value, onChange, min, max, isIntegerOnly, onBlur],+ );++ // Handle keyboard events+ const handleKeyDown = useCallback(+ (e: KeyboardEvent<HTMLInputElement>) => {+ if (e.key === 'Enter') {+ // Validate and commit on Enter+ if (pendingInput !== null) {+ const parsed = parseNumberInput(pendingInput, {+ min,+ max,+ isIntegerOnly,+ });+ if (parsed !== null && parsed !== value) {+ onChange(parsed);+ }+ }+ onEnter?.();+ }+ },+ [pendingInput, value, onChange, min, max, isIntegerOnly, onEnter],+ );++ // Combine refs+ const setRefs = useCallback(+ (el: HTMLInputElement | null) => {+ inputRef.current = el;+ if (typeof ref === 'function') {+ ref(el);+ } else if (ref) {+ ref.current = el;+ }+ },+ [ref],+ );++ return (+ <XDSField+ label={label}+ isLabelHidden={isLabelHidden}+ description={description}+ inputID={id}+ descriptionID={description ? descriptionID : undefined}+ isOptional={isOptional}+ isRequired={isRequired}+ labelStartIcon={labelIcon}+ status={+ status+ ? {+ type: status.type,+ message: status.message,+ messageID: status.message ? statusMessageID : undefined,+ }+ : undefined+ }+ labelTooltip={tooltip}>+ <div+ {...stylex.props(+ styles.wrapper,+ sizeStyles[size],+ isDisabled && styles.wrapperDisabled,+ status && statusBorderStyles[status.type],+ )}>+ {startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}+ <input+ ref={setRefs}+ id={id}+ name={htmlName}+ type="number"+ autoComplete={autoComplete}+ value={displayValue}+ onChange={handleInputChange}+ onFocus={handleFocus}+ onBlur={handleBlur}+ onKeyDown={handleKeyDown}+ placeholder={placeholder}+ disabled={isDisabled}+ autoFocus={hasAutoFocus}+ min={min ?? undefined}+ max={max ?? undefined}+ step={step ?? undefined}+ aria-describedby={ariaDescribedBy}+ aria-required={isRequired === true ? 'true' : undefined}+ aria-invalid={status?.type === 'error' ? 'true' : undefined}+ {...stylex.props(+ styles.input,+ isDisabled && styles.inputDisabled,+ !isInputValid && styles.inputInvalid,+ )}+ />+ {units && <span {...stylex.props(styles.units)}>{units}</span>}+ {status && (+ <XDSIcon+ icon={statusIconMap[status.type]}+ size="md"+ color={statusIconColorMap[status.type]}+ />+ )}+ </div>+ </XDSField>+ );+ },+);++XDSNumberInput.displayName = 'XDSNumberInput';diff --git a/packages/core/src/NumberInput/index.ts b/packages/core/src/NumberInput/index.tsnew file mode 100644index 0000000000..b83c464db7--- /dev/null+++ b/packages/core/src/NumberInput/index.ts@@ -0,0 +1,16 @@+/**+ * @file index.ts+ * @input Imports XDSNumberInput component and types from XDSNumberInput.tsx+ * @output Exports XDSNumberInput, XDSNumberInputProps, XDSNumberInputSize, XDSNumberInputStatus, XDSNumberInputStatusType+ * @position Component entry point; re-exported by /packages/core/src/index.ts+ *+ * SYNC: When modified, update this header and /packages/core/src/NumberInput/README.md+ */++export {XDSNumberInput} from './XDSNumberInput';+export type {+ XDSNumberInputProps,+ XDSNumberInputSize,+ XDSNumberInputStatus,+ XDSNumberInputStatusType,+} from './XDSNumberInput';diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex e8c4f774e2..64035adf27 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -27,6 +27,7 @@ export * from './Text';export * from './TextInput';export * from './TextArea';export * from './TimeInput';+export * from './NumberInput';export * from './Table';// Layout utilities and components (includes XDSHStack, XDSVStack)