Skip to content

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

TypeScript

XDSTimeInput (#68)

Cindy Zhangc1d26a63c11f
diff --git a/.context/decisions/input-props-convention.md b/.context/decisions/input-props-convention.md
new file mode 100644
index 0000000000..345fbc219b
--- /dev/null
+++ b/.context/decisions/input-props-convention.md
@@ -0,0 +1,128 @@
+# Input Component Props Convention
+
+This document defines the standard props that all XDS input components should implement for consistency.
+
+## Core Field Props
+
+All input components that represent a form field should include these props:
+
+| Prop | Type | Default | Required | Description |
+| --------------- | --------- | ------- | -------- | ------------------------------------------------------------------ |
+| `label` | `string` | - | ✓ | Accessible label text (always rendered for screen readers) |
+| `isLabelHidden` | `boolean` | `false` | | Visually hide the label while keeping it accessible |
+| `description` | `string` | - | | Helper text displayed between label and input |
+| `isOptional` | `boolean` | `false` | | Shows "(Optional)" indicator. Mutually exclusive with `isRequired` |
+| `isRequired` | `boolean` | `false` | | Marks field as required. Mutually exclusive with `isOptional` |
+| `isDisabled` | `boolean` | `false` | | Disables the input |
+
+## Value Props
+
+| Prop | Type | Description |
+| ---------- | ------------------------- | --------------------------------- |
+| `value` | varies | The controlled value of the input |
+| `onChange` | `(value, event?) => void` | Callback when value changes |
+
+### onChange Signature Convention
+
+- **Text-based inputs** (TextInput, TextArea): Include the event for access to the DOM element
+
+ ```ts
+ onChange: (value: string, e: ChangeEvent<HTMLInputElement>) => void
+ ```
+
+- **Parsed value inputs** (DateInput, TimeInput): Event is omitted since value is parsed/transformed
+
+ ```ts
+ onChange: (value: ISODateString | undefined) => void
+ onChange: (value: ISOTimeString | undefined) => void
+ ```
+
+- **Boolean inputs** (CheckboxInput): Include the event
+ ```ts
+ onChange: (checked: boolean, e: ChangeEvent<HTMLInputElement>) => void
+ ```
+
+## Optional Common Props
+
+| Prop | Type | Default | Applicable To | Description |
+| -------------- | ------------------ | ------- | -------------------------- | ---------------------------------- |
+| `placeholder` | `string` | varies | Text-based inputs | Placeholder text when empty |
+| `size` | `'sm' \| 'md'` | `'md'` | Most inputs | Size variant |
+| `status` | `{type, message?}` | - | Inputs with validation | Error/warning/success state |
+| `labelTooltip` | `string` | - | Inputs needing explanation | Tooltip on info icon next to label |
+| `startIcon` | `XDSIconType` | - | Inputs with icon support | Icon at start of input |
+
+## Size Variants
+
+Standard sizes across components:
+
+| Size | Input Height | Use Case |
+| ---- | ------------ | -------------------------------- |
+| `sm` | 18px | Compact UIs, tables, dense forms |
+| `md` | 26px | Default, most forms |
+
+## Status Object
+
+For inputs that support validation status, use the shared `XDSInputStatus` type from `@xds/core`:
+
+```ts
+import type {XDSInputStatus, XDSInputStatusType} from '@xds/core';
+
+// XDSInputStatusType = 'error' | 'warning' | 'success'
+
+interface XDSInputStatus {
+ type: XDSInputStatusType;
+ message?: string; // Optional message displayed below input
+}
+```
+
+Each input component re-exports these types with component-specific aliases for convenience:
+
+- `XDSTextInputStatus`, `XDSTextInputStatusType`
+- `XDSDateInputStatus`, `XDSDateInputStatusType`
+- `XDSTimeInputStatus`, `XDSTimeInputStatusType`
+
+## Current Implementation Status
+
+| Component | label | isLabelHidden | description | isOptional | isRequired | isDisabled | size | status | placeholder |
+| ---------------- | ----- | ------------- | ----------- | ---------- | ---------- | ---------- | ---- | ------ | ----------- |
+| XDSTextInput | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
+| XDSTextArea | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | - | - | ✓ |
+| XDSCheckboxInput | ✓ | ✓ | ✓ | - | ✓ | ✓ | ✓ | - | - |
+| XDSDateInput | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
+| XDSTimeInput | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
+
+### Gaps to Address
+
+1. **status**: Add to TextArea for validation feedback
+2. **isOptional**: Add to CheckboxInput for consistency
+3. **size**: Add to TextArea for consistency
+4. **labelTooltip**: Consider adding to all field-based inputs
+
+## Boolean Prop Naming
+
+All boolean props must be prefixed with `is` or `has`:
+
+- `is` prefix: State or condition (`isDisabled`, `isRequired`, `isOptional`, `isLabelHidden`)
+- `has` prefix: Feature toggle (`hasSeconds`, `hasClear`, `hasAutoFocus`)
+
+## forwardRef Pattern
+
+All input components should use `forwardRef` to expose the underlying input element:
+
+```tsx
+export const XDSInput = forwardRef<HTMLInputElement, Props>((props, ref) => {
+ // ...
+ return <input ref={ref} ... />;
+});
+
+XDSInput.displayName = 'XDSInput';
+```
+
+## Accessibility Requirements
+
+1. **Label**: Always associate label with input via `htmlFor`/`id`
+2. **Description**: Use `aria-describedby` to link description to input
+3. **Required**: Set `aria-required="true"` when `isRequired` is true
+4. **Invalid**: Set `aria-invalid="true"` when status type is `'error'`
+5. **Disabled**: Use native `disabled` attribute (provides correct semantics)
diff --git a/apps/storybook/stories/DatePicker.stories.tsx b/apps/storybook/stories/DateInput.stories.tsx
similarity index 67%
rename from apps/storybook/stories/DatePicker.stories.tsx
rename to apps/storybook/stories/DateInput.stories.tsx
index 9f10ccd7f1..b6d1983972 100644
--- a/apps/storybook/stories/DatePicker.stories.tsx
+++ b/apps/storybook/stories/DateInput.stories.tsx
@@ -1,11 +1,11 @@
import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
-import {XDSDatePicker} from '@xds/core/DatePicker';
+import {XDSDateInput} from '@xds/core/DateInput';
import type {ISODateString} from '@xds/core/Calendar';
-const meta: Meta<typeof XDSDatePicker> = {
- title: 'Core/XDSDatePicker',
- component: XDSDatePicker,
+const meta: Meta<typeof XDSDateInput> = {
+ title: 'Core/XDSDateInput',
+ component: XDSDateInput,
tags: ['autodocs'],
argTypes: {
label: {
@@ -53,12 +53,12 @@ const meta: Meta<typeof XDSDatePicker> = {
};
export default meta;
-type Story = StoryObj<typeof XDSDatePicker>;
+type Story = StoryObj<typeof XDSDateInput>;
export const Default: Story = {
render: args => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Date',
@@ -71,7 +71,7 @@ export const WithValue: Story = {
const [value, setValue] = useState<ISODateString | undefined>(
'2026-01-25' as ISODateString,
);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Event date',
@@ -81,7 +81,7 @@ export const WithValue: Story = {
export const WithDescription: Story = {
render: args => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Birthday',
@@ -93,7 +93,7 @@ export const WithDescription: Story = {
export const WithHiddenLabel: Story = {
render: args => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Date',
@@ -105,7 +105,7 @@ export const WithHiddenLabel: Story = {
export const Optional: Story = {
render: args => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Preferred date',
@@ -117,7 +117,7 @@ export const Optional: Story = {
export const Required: Story = {
render: args => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Start date',
@@ -131,7 +131,7 @@ export const Disabled: Story = {
const [value, setValue] = useState<ISODateString | undefined>(
'2026-01-25' as ISODateString,
);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Locked date',
@@ -142,7 +142,7 @@ export const Disabled: Story = {
export const SmallSize: Story = {
render: args => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Date',
@@ -154,7 +154,7 @@ export const SmallSize: Story = {
export const WithMinMax: Story = {
render: args => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Booking date',
@@ -168,7 +168,7 @@ export const WithMinMax: Story = {
export const TwoMonthCalendar: Story = {
render: args => {
const [value, setValue] = useState<ISODateString | undefined>(undefined);
- return <XDSDatePicker {...args} value={value} onChange={setValue} />;
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
},
args: {
label: 'Travel date',
@@ -177,6 +177,54 @@ export const TwoMonthCalendar: Story = {
},
};
+export const WithErrorStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(
+ '2026-01-25' as ISODateString,
+ );
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Event date',
+ status: {
+ type: 'error',
+ message: 'This date is not available',
+ },
+ },
+};
+
+export const WithWarningStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(
+ '2026-01-01' as ISODateString,
+ );
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Meeting date',
+ status: {
+ type: 'warning',
+ message: 'This is a holiday - are you sure?',
+ },
+ },
+};
+
+export const WithSuccessStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISODateString | undefined>(
+ '2026-02-10' as ISODateString,
+ );
+ return <XDSDateInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Appointment date',
+ status: {
+ type: 'success',
+ message: 'Date is available',
+ },
+ },
+};
+
export const AllVariations: Story = {
render: () => {
const [value1, setValue1] = useState<ISODateString | undefined>(undefined);
@@ -189,6 +237,9 @@ export const AllVariations: Story = {
const [value6, setValue6] = useState<ISODateString | undefined>(
'2026-03-10' as ISODateString,
);
+ const [value7, setValue7] = useState<ISODateString | undefined>(
+ '2026-01-25' as ISODateString,
+ );
return (
<div
@@ -198,40 +249,49 @@ export const AllVariations: Story = {
gap: '16px',
maxWidth: '300px',
}}>
- <XDSDatePicker
+ <XDSDateInput
label="Default"
value={value1}
onChange={setValue1}
placeholder="Select a date"
/>
- <XDSDatePicker label="With value" value={value2} onChange={setValue2} />
- <XDSDatePicker
+ <XDSDateInput label="With value" value={value2} onChange={setValue2} />
+ <XDSDateInput
label="With description"
description="Pick your preferred date"
value={value3}
onChange={setValue3}
placeholder="Select a date"
/>
- <XDSDatePicker
+ <XDSDateInput
label="Optional field"
isOptional
value={value4}
onChange={setValue4}
placeholder="Select a date (optional)"
/>
- <XDSDatePicker
+ <XDSDateInput
label="Required field"
isRequired
value={value5}
onChange={setValue5}
placeholder="Select a date"
/>
- <XDSDatePicker
+ <XDSDateInput
label="Disabled"
isDisabled
value={value6}
onChange={setValue6}
/>
+ <XDSDateInput
+ label="With error"
+ value={value7}
+ onChange={setValue7}
+ status={{
+ type: 'error',
+ message: 'Invalid date selection',
+ }}
+ />
</div>
);
},
diff --git a/apps/storybook/stories/TimeInput.stories.tsx b/apps/storybook/stories/TimeInput.stories.tsx
new file mode 100644
index 0000000000..3e163de4aa
--- /dev/null
+++ b/apps/storybook/stories/TimeInput.stories.tsx
@@ -0,0 +1,345 @@
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSTimeInput} from '@xds/core/TimeInput';
+import type {ISOTimeString} from '@xds/core';
+
+const meta: Meta<typeof XDSTimeInput> = {
+ title: 'Core/XDSTimeInput',
+ component: XDSTimeInput,
+ 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',
+ },
+ 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',
+ },
+ size: {
+ control: 'radio',
+ options: ['sm', 'md'],
+ description: 'Size of the input',
+ },
+ hourFormat: {
+ control: 'radio',
+ options: ['12h', '24h'],
+ description: 'Hour format for display',
+ },
+ hasSeconds: {
+ control: 'boolean',
+ description: 'Whether to include seconds in the time',
+ },
+ hasClear: {
+ control: 'boolean',
+ description: 'Whether to show a clear button',
+ },
+ increment: {
+ control: 'number',
+ description: 'Minutes to increment/decrement with arrow keys',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSTimeInput>;
+
+export const Default: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(undefined);
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Time',
+ placeholder: 'Select a time',
+ },
+};
+
+export const WithValue: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '14:30' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Meeting time',
+ },
+};
+
+export const TwentyFourHourFormat: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '14:30' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Time (24h)',
+ hourFormat: '24h',
+ },
+};
+
+export const WithSeconds: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '14:30:45' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Precise time',
+ hasSeconds: true,
+ },
+};
+
+export const WithClearButton: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '09:00' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Start time',
+ hasClear: true,
+ },
+};
+
+export const WithDescription: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(undefined);
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Alarm time',
+ description: 'When should we wake you up?',
+ placeholder: 'Set alarm time',
+ },
+};
+
+export const WithMinMax: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(undefined);
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Appointment time',
+ min: '09:00' as ISOTimeString,
+ max: '17:00' as ISOTimeString,
+ description: 'Business hours: 9 AM - 5 PM',
+ placeholder: 'Select appointment time',
+ },
+};
+
+export const WithIncrement: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '09:00' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Time slot',
+ increment: 15,
+ description: 'Use arrow keys to change by 15 minutes',
+ },
+};
+
+export const Optional: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(undefined);
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Preferred time',
+ isOptional: true,
+ placeholder: 'Select a time (optional)',
+ },
+};
+
+export const Required: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(undefined);
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Start time',
+ isRequired: true,
+ placeholder: 'Select a start time',
+ },
+};
+
+export const Disabled: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '10:00' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Locked time',
+ isDisabled: true,
+ },
+};
+
+export const SmallSize: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(undefined);
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Time',
+ size: 'sm',
+ placeholder: 'Select a time',
+ },
+};
+
+export const WithErrorStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '22:00' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Event time',
+ status: {
+ type: 'error',
+ message: 'Time must be during business hours',
+ },
+ },
+};
+
+export const WithWarningStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '07:00' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Meeting time',
+ status: {
+ type: 'warning',
+ message: 'Early morning meeting - are you sure?',
+ },
+ },
+};
+
+export const WithSuccessStatus: Story = {
+ render: args => {
+ const [value, setValue] = useState<ISOTimeString | undefined>(
+ '10:00' as ISOTimeString,
+ );
+ return <XDSTimeInput {...args} value={value} onChange={setValue} />;
+ },
+ args: {
+ label: 'Scheduled time',
+ status: {
+ type: 'success',
+ message: 'Time slot is available',
+ },
+ },
+};
+
+export const AllVariations: Story = {
+ render: () => {
+ const [value1, setValue1] = useState<ISOTimeString | undefined>(undefined);
+ const [value2, setValue2] = useState<ISOTimeString | undefined>(
+ '14:30' as ISOTimeString,
+ );
+ const [value3, setValue3] = useState<ISOTimeString | undefined>(
+ '09:15:30' as ISOTimeString,
+ );
+ const [value4, setValue4] = useState<ISOTimeString | undefined>(undefined);
+ const [value5, setValue5] = useState<ISOTimeString | undefined>(undefined);
+ const [value6, setValue6] = useState<ISOTimeString | undefined>(
+ '10:00' as ISOTimeString,
+ );
+ const [value7, setValue7] = useState<ISOTimeString | undefined>(
+ '22:00' as ISOTimeString,
+ );
+
+ return (
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '16px',
+ maxWidth: '300px',
+ }}>
+ <XDSTimeInput
+ label="Default (12h)"
+ value={value1}
+ onChange={setValue1}
+ placeholder="Select a time"
+ />
+ <XDSTimeInput
+ label="24-hour format"
+ value={value2}
+ onChange={setValue2}
+ hourFormat="24h"
+ />
+ <XDSTimeInput
+ label="With seconds"
+ value={value3}
+ onChange={setValue3}
+ hasSeconds
+ />
+ <XDSTimeInput
+ label="With clear button"
+ value={value4}
+ onChange={setValue4}
+ hasClear
+ placeholder="Select a time"
+ />
+ <XDSTimeInput
+ label="With description"
+ description="Pick your preferred time"
+ value={value5}
+ onChange={setValue5}
+ placeholder="Select a time"
+ />
+ <XDSTimeInput
+ label="Disabled"
+ isDisabled
+ value={value6}
+ onChange={setValue6}
+ />
+ <XDSTimeInput
+ label="With error"
+ value={value7}
+ onChange={setValue7}
+ status={{
+ type: 'error',
+ message: 'Invalid time selection',
+ }}
+ />
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/Calendar/XDSCalendar.tsx b/packages/core/src/Calendar/XDSCalendar.tsx
index d428dbc3ca..7c9c7df4ec 100644
--- a/packages/core/src/Calendar/XDSCalendar.tsx
+++ b/packages/core/src/Calendar/XDSCalendar.tsx
@@ -17,6 +17,7 @@ import {
useMemo,
useCallback,
useEffect,
+ useImperativeHandle,
type HTMLAttributes,
} from 'react';
import * as stylex from '@stylexjs/stylex';
@@ -64,6 +65,12 @@ export interface DateRange {
end: ISODateString;
}
+/** Imperative handle for XDSCalendar ref */
+export interface XDSCalendarHandle {
+ /** Navigate the calendar to show the month containing the given date */
+ navigateTo: (date: ISODateString) => void;
+}
+
// ─── Base Props (shared across all modes) ─────────────────────
interface XDSCalendarBaseProps extends Omit<
@@ -159,31 +166,9 @@ export type XDSCalendarProps = XDSCalendarSingleProps | XDSCalendarRangeProps;
* A calendar component for selecting dates or date ranges.
*
* @example
- * ```tsx
- * // Single date selection
- * <XDSCalendar
- * value={selectedDate}
- * onChange={(date) => setSelectedDate(date)}
- * />
- *
- * // Date range selection
- * <XDSCalendar
- * mode="range"
- * value={dateRange}
- * onChange={(range) => setDateRange(range)}
- * />
- *
- * // With constraints
- * <XDSCalendar
- * min="2026-01-01"
- * max="2026-12-31"
- * dateConstraints={[(date) => date.getDay() !== 0]} // No Sundays
- * value={selectedDate}
- * onChange={setSelectedDate}
- * />
- * ```
+ * <XDSCalendar value={selectedDate} onChange={setSelectedDate} />
*/
-export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
+export const XDSCalendar = forwardRef<XDSCalendarHandle, XDSCalendarProps>(
(props, ref) => {
const {
mode = 'single',
@@ -246,6 +231,21 @@ export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
? parseISO(focusDateProp)
: internalFocusDate;
+ // Expose imperative handle for external navigation
+ useImperativeHandle(
+ ref,
+ () => ({
+ navigateTo: (date: ISODateString) => {
+ if (isControlledFocus) {
+ onFocusDateChange?.(date);
+ } else {
+ setInternalFocusDate(parseISO(date));
+ }
+ },
+ }),
+ [isControlledFocus, onFocusDateChange],
+ );
+
// Base month (first day of focus month)
const baseMonth = useMemo(() => {
const d = new Date(focusDate);
@@ -337,7 +337,7 @@ export const XDSCalendar = forwardRef<HTMLDivElement, XDSCalendarProps>(
);
return (
- <div ref={ref} {...stylex.props(calendarStyles.calendar)} {...rest}>
+ <div {...stylex.props(calendarStyles.calendar)} {...rest}>
{/* Header with navigation */}
<div {...stylex.props(calendarStyles.header)}>
<XDSButton
@@ -781,9 +781,7 @@ function DayCell({
previewRoundLeft && dayCellStyles.previewBgRadiusLeft,
previewRoundRight && dayCellStyles.previewBgRadiusRight,
isPreviewStart && dayCellStyles.previewStart,
- isPreviewStart && roundRight && dayCellStyles.rangeInsetRight,
isPreviewEnd && dayCellStyles.previewEnd,
- isPreviewEnd && roundLeft && dayCellStyles.rangeInsetLeft,
)}
/>
)}
diff --git a/packages/core/src/Calendar/index.ts b/packages/core/src/Calendar/index.ts
index 34d7aab1e3..86dc69a2da 100644
--- a/packages/core/src/Calendar/index.ts
+++ b/packages/core/src/Calendar/index.ts
@@ -10,6 +10,7 @@
export {XDSCalendar} from './XDSCalendar';
export type {
XDSCalendarProps,
+ XDSCalendarHandle,
ISODateString,
DayOfWeek,
DateRange,
diff --git a/packages/core/src/Calendar/styles.ts b/packages/core/src/Calendar/styles.ts
index 1bcd553b3c..8c57322a9b 100644
--- a/packages/core/src/Calendar/styles.ts
+++ b/packages/core/src/Calendar/styles.ts
@@ -190,6 +190,15 @@ export const dayCellStyles = stylex.create({
zIndex: 1,
transitionProperty: 'background-color, color',
transitionDuration: transitionVars['--transition-fast'],
+ // Expand hit target by 2px on each side to prevent gaps
+ '::before': {
+ content: '""',
+ position: 'absolute',
+ top: '-2px',
+ right: '-2px',
+ bottom: '-2px',
+ left: '-2px',
+ },
},
// State modifiers - structural only
@@ -214,20 +223,9 @@ export const dayCellTheme = stylex.create({
backgroundColor: colorVars['--color-accent-deemphasized'],
},
- // Preview background (dotted border style)
+ // Preview background (muted overlay)
previewBg: {
- borderTopWidth: 1,
- borderTopStyle: 'dotted',
- borderTopColor: colorVars['--color-divider-emphasized'],
- borderBottomWidth: 1,
- borderBottomStyle: 'dotted',
- borderBottomColor: colorVars['--color-divider-emphasized'],
- borderLeftWidth: 1,
- borderLeftStyle: 'dotted',
- borderLeftColor: colorVars['--color-divider-emphasized'],
- borderRightWidth: 1,
- borderRightStyle: 'dotted',
- borderRightColor: colorVars['--color-divider-emphasized'],
+ backgroundColor: colorVars['--color-hover-overlay'],
},
// Day button - default state
diff --git a/packages/core/src/DatePicker/README.md b/packages/core/src/DateInput/README.md
similarity index 54%
rename from packages/core/src/DatePicker/README.md
rename to packages/core/src/DateInput/README.md
index 619bff95bc..7a9719ad03 100644
--- a/packages/core/src/DatePicker/README.md
+++ b/packages/core/src/DateInput/README.md
@@ -1,29 +1,30 @@
-# /packages/core/src/DatePicker
+# /packages/core/src/DateInput
-XDSDatePicker component combining a text input with a calendar popover for date selection.
+XDSDateInput component combining a text input with a calendar popover for date selection.
## Features
- **Text Input**: Manual date entry with flexible parsing (supports various formats)
- **Calendar Popover**: Click icon or use keyboard to open calendar picker
- **Date Constraints**: `min`, `max`, and custom `dateConstraints` functions
+- **Status Indicators**: Error, warning, and success states with messages
- **Accessibility**: Full keyboard navigation, focus trapping, screen reader support
- **Field Integration**: Built on XDSField for consistent label, description, and validation states
## Usage
```tsx
-import { XDSDatePicker } from '@xds/core/DatePicker';
+import { XDSDateInput } from '@xds/core/DateInput';
// Basic usage
-<XDSDatePicker
+<XDSDateInput
label="Event date"
value={date}
onChange={setDate}
/>
// With constraints
-<XDSDatePicker
+<XDSDateInput
label="Departure date"
value={date}
onChange={setDate}
@@ -33,7 +34,7 @@ import { XDSDatePicker } from '@xds/core/DatePicker';
/>
// Two-month calendar
-<XDSDatePicker
+<XDSDateInput
label="Check-in date"
value={date}
onChange={setDate}
@@ -41,33 +42,45 @@ import { XDSDatePicker } from '@xds/core/DatePicker';
/>
// With description and required
-<XDSDatePicker
+<XDSDateInput
label="Due date"
description="When should this task be completed?"
isRequired
value={date}
onChange={setDate}
/>
+
+// With error status
+<XDSDateInput
+ label="Event date"
+ value={date}
+ onChange={setDate}
+ status={{
+ type: 'error',
+ message: 'This date is not available',
+ }}
+/>
```
## Props
-| Prop | Type | Default | Description |
-| --------------- | --------------------------------------------- | ----------------- | -------------------------------- |
-| label | `string` | — | Label text (required) |
-| isLabelHidden | `boolean` | `false` | Visually hide label |
-| description | `string` | — | Helper text below label |
-| isOptional | `boolean` | `false` | Show "(optional)" indicator |
-| isRequired | `boolean` | `false` | Mark field as required |
-| isDisabled | `boolean` | `false` | Disable input and calendar |
-| value | `ISODateString` | — | Selected date (YYYY-MM-DD) |
-| onChange | `(value: ISODateString \| undefined) => void` | — | Selection callback |
-| min | `ISODateString` | — | Minimum selectable date |
-| max | `ISODateString` | — | Maximum selectable date |
-| dateConstraints | `Array<(date: Date) => boolean>` | — | Custom constraint functions |
-| placeholder | `string` | `"Select a date"` | Input placeholder text |
-| size | `'sm' \| 'md'` | `'md'` | Input size |
-| numberOfMonths | `1 \| 2` | `1` | Months shown in calendar popover |
+| Prop | Type | Default | Description |
+| --------------- | --------------------------------------------- | ----------------- | ---------------------------------------- |
+| label | `string` | — | Label text (required) |
+| isLabelHidden | `boolean` | `false` | Visually hide label |
+| description | `string` | — | Helper text below label |
+| isOptional | `boolean` | `false` | Show "(optional)" indicator |
+| isRequired | `boolean` | `false` | Mark field as required |
+| isDisabled | `boolean` | `false` | Disable input and calendar |
+| value | `ISODateString` | — | Selected date (YYYY-MM-DD) |
+| onChange | `(value: ISODateString \| undefined) => void` | — | Selection callback |
+| min | `ISODateString` | — | Minimum selectable date |
+| max | `ISODateString` | — | Maximum selectable date |
+| dateConstraints | `Array<(date: Date) => boolean>` | — | Custom constraint functions |
+| placeholder | `string` | `"Select a date"` | Input placeholder text |
+| size | `'sm' \| 'md'` | `'md'` | Input size |
+| status | `XDSInputStatus` | — | Status indicator (error/warning/success) |
+| numberOfMonths | `1 \| 2` | `1` | Months shown in calendar popover |
## Keyboard Navigation
@@ -89,9 +102,9 @@ Invalid input reverts to the previous valid value on blur.
## Files
-| File | Role | Purpose |
-| ---------------------- | ------ | ------------------------ |
-| XDSDatePicker.tsx | Core | Component implementation |
-| XDSDatePicker.test.tsx | Test | Unit tests |
-| index.ts | Export | Public API exports |
-| README.md | Docs | This documentation |
+| File | Role | Purpose |
+| --------------------- | ------ | ------------------------ |
+| XDSDateInput.tsx | Core | Component implementation |
+| XDSDateInput.test.tsx | Test | Unit tests |
+| index.ts | Export | Public API exports |
+| README.md | Docs | This documentation |
diff --git a/packages/core/src/DateInput/XDSDateInput.test.tsx b/packages/core/src/DateInput/XDSDateInput.test.tsx
new file mode 100644
index 0000000000..1dc6746423
--- /dev/null
+++ b/packages/core/src/DateInput/XDSDateInput.test.tsx
@@ -0,0 +1,163 @@
+/**
+ * @file XDSDateInput.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSDateInput component
+ * @output Unit tests for XDSDateInput component behavior
+ * @position Testing; validates XDSDateInput.tsx implementation
+ *
+ * SYNC: When XDSDateInput.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSDateInput} from './XDSDateInput';
+
+describe('XDSDateInput', () => {
+ it('renders with label', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ expect(screen.getByLabelText('Date')).toBeInTheDocument();
+ });
+
+ it('renders with placeholder', () => {
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={() => {}}
+ placeholder="Pick a date"
+ />,
+ );
+ expect(screen.getByPlaceholderText('Pick a date')).toBeInTheDocument();
+ });
+
+ it('displays formatted date when value is provided', () => {
+ render(
+ <XDSDateInput label="Date" value="2026-01-25" onChange={() => {}} />,
+ );
+ expect(screen.getByDisplayValue('January 25, 2026')).toBeInTheDocument();
+ });
+
+ it('forwards ref correctly', () => {
+ const ref = vi.fn();
+ render(<XDSDateInput ref={ref} label="Date" onChange={() => {}} />);
+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));
+ });
+
+ it('visually hides label when isLabelHidden is true', () => {
+ render(<XDSDateInput label="Date" isLabelHidden onChange={() => {}} />);
+ const label = screen.getByText('Date');
+ expect(label).toBeInTheDocument();
+ expect(screen.getByLabelText('Date')).toBeInTheDocument();
+ });
+
+ it('shows label visually by default', () => {
+ render(<XDSDateInput label="Event date" onChange={() => {}} />);
+ const label = screen.getByText('Event date');
+ expect(label).toBeVisible();
+ });
+
+ it('sets aria-required when isRequired is true', () => {
+ render(<XDSDateInput label="Date" isRequired onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).toHaveAttribute(
+ 'aria-required',
+ 'true',
+ );
+ });
+
+ it('does not set aria-required when isRequired is false', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-required');
+ });
+
+ it('sets disabled attribute when isDisabled is true', () => {
+ render(<XDSDateInput label="Date" isDisabled onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).toBeDisabled();
+ });
+
+ it('is not disabled by default', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).not.toBeDisabled();
+ });
+
+ it('renders calendar icon', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ const svg = document.querySelector('svg');
+ expect(svg).toBeInTheDocument();
+ });
+
+ it('calendar button has aria-haspopup="dialog" attribute', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('button', {name: 'Open calendar'})).toHaveAttribute(
+ 'aria-haspopup',
+ 'dialog',
+ );
+ });
+
+ it('calendar button is focusable and clickable', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ const button = screen.getByRole('button', {name: 'Open calendar'});
+ expect(button).toBeInTheDocument();
+ expect(button).not.toBeDisabled();
+ });
+
+ it('calendar button is disabled when isDisabled is true', () => {
+ render(<XDSDateInput label="Date" isDisabled onChange={() => {}} />);
+ const button = screen.getByRole('button', {name: 'Open calendar'});
+ expect(button).toBeDisabled();
+ });
+
+ it('does not call onChange while typing invalid input', async () => {
+ const onChange = vi.fn();
+ render(<XDSDateInput label="Date" onChange={onChange} />);
+
+ const input = screen.getByRole('textbox');
+ // Use fireEvent to avoid triggering click handler (which opens popover)
+ fireEvent.change(input, {target: {value: 'invalid'}});
+
+ // onChange should not be called while typing
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('reverts to previous value on blur when input is invalid', async () => {
+ const onChange = vi.fn();
+ render(
+ <XDSDateInput label="Date" value="2026-01-25" onChange={onChange} />,
+ );
+
+ const input = screen.getByRole('textbox');
+ // Use fireEvent to avoid triggering click handler (which opens popover)
+ fireEvent.change(input, {target: {value: 'not a date'}});
+ fireEvent.blur(input);
+
+ // Should revert to the original value, not call onChange
+ expect(screen.getByDisplayValue('January 25, 2026')).toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('calls onChange on blur when input is valid', async () => {
+ const onChange = vi.fn();
+ render(<XDSDateInput label="Date" onChange={onChange} />);
+
+ const input = screen.getByRole('textbox');
+ // Use fireEvent to avoid triggering click handler (which opens popover)
+ fireEvent.change(input, {target: {value: '03/15/2026'}});
+ fireEvent.blur(input);
+
+ expect(onChange).toHaveBeenCalledWith('2026-03-15');
+ });
+
+ it('calls onChange immediately when input becomes valid', async () => {
+ const onChange = vi.fn();
+ render(<XDSDateInput label="Date" onChange={onChange} />);
+
+ const input = screen.getByRole('textbox');
+ // Use fireEvent to avoid triggering click handler (which opens popover)
+ fireEvent.change(input, {target: {value: '03/15/2026'}});
+
+ // onChange should be called immediately when input is valid, not waiting for blur
+ expect(onChange).toHaveBeenCalledWith('2026-03-15');
+ });
+
+ // Note: Tests involving blur that trigger popover are skipped because
+ // jsdom doesn't support the Popover API (showPopover is not a function).
+ // These behaviors are tested in the browser via Storybook.
+});
diff --git a/packages/core/src/DatePicker/XDSDatePicker.tsx b/packages/core/src/DateInput/XDSDateInput.tsx
similarity index 62%
rename from packages/core/src/DatePicker/XDSDatePicker.tsx
rename to packages/core/src/DateInput/XDSDateInput.tsx
index aabf9bde53..055716feaf 100644
--- a/packages/core/src/DatePicker/XDSDatePicker.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.tsx
@@ -1,26 +1,24 @@
/**
- * @file XDSDatePicker.tsx
+ * @file XDSDateInput.tsx
* @input Uses React forwardRef, useId, useState, useEffect, useCallback, useRef, XDSField, XDSIcon, XDSCalendar, useXDSPopover
- * @output Exports XDSDatePicker component, XDSDatePickerProps
- * @position Core implementation; consumed by index.ts, tested by XDSDatePicker.test.tsx
+ * @output Exports XDSDateInput component, XDSDateInputProps
+ * @position Core implementation; consumed by index.ts, tested by XDSDateInput.test.tsx
*
* SYNC: When modified, update these files to stay in sync:
- * - /packages/core/src/DatePicker/README.md (props table, features, implementation notes)
- * - /packages/core/src/DatePicker/XDSDatePicker.test.tsx (tests for new/changed behavior)
- * - /packages/core/src/DatePicker/index.ts (exports if types change)
- * - /apps/storybook/stories/DatePicker.stories.tsx (storybook stories)
+ * - /packages/core/src/DateInput/README.md (props table, features, implementation notes)
+ * - /packages/core/src/DateInput/XDSDateInput.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/DateInput/index.ts (exports if types change)
+ * - /apps/storybook/stories/DateInput.stories.tsx (storybook stories)
*/
-import {
- forwardRef,
- useId,
- useState,
- useEffect,
- useCallback,
- useRef,
-} from 'react';
+import {forwardRef, useId, useState, useCallback, useRef, useMemo} from 'react';
import * as stylex from '@stylexjs/stylex';
import {CalendarDaysIcon} from '@heroicons/react/24/outline';
+import {
+ CheckCircleIcon,
+ ExclamationTriangleIcon,
+ XCircleIcon,
+} from '@heroicons/react/24/solid';
import {
colorVars,
spacingVars,
@@ -31,14 +29,19 @@ import {
lineHeightVars,
elevationVars,
} from '../theme/tokens.stylex';
-import {XDSField} from '../Field';
+import {XDSField, type XDSInputStatus, type XDSInputStatusType} from '../Field';
import {XDSIcon} from '../Icon';
-import {XDSCalendar, type ISODateString} from '../Calendar';
+import {
+ XDSCalendar,
+ type ISODateString,
+ type XDSCalendarHandle,
+} from '../Calendar';
import {useXDSPopover} from '../Layer';
import {parseDateInput, formatDisplayDate} from '../utils';
const styles = stylex.create({
wrapper: {
+ position: 'relative',
display: 'flex',
alignItems: 'center',
gap: spacingVars['--spacing-2'],
@@ -108,6 +111,9 @@ const styles = stylex.create({
inputDisabled: {
cursor: 'not-allowed',
},
+ inputInvalid: {
+ color: colorVars['--color-text-secondary'],
+ },
popover: {
backgroundColor: colorVars['--color-popover'],
borderRadius: radiusVars['--radius-container'],
@@ -124,9 +130,27 @@ const sizeStyles = stylex.create({
},
});
-export type XDSDatePickerSize = keyof typeof sizeStyles;
+const statusBorderStyles = stylex.create({
+ warning: {
+ borderColor: colorVars['--color-warning'],
+ },
+ error: {
+ borderColor: colorVars['--color-negative'],
+ },
+ success: {
+ borderColor: colorVars['--color-positive'],
+ },
+});
+
+export type XDSDateInputSize = keyof typeof sizeStyles;
-export interface XDSDatePickerProps {
+// Re-export shared types for convenience
+export type {
+ XDSInputStatus as XDSDateInputStatus,
+ XDSInputStatusType as XDSDateInputStatusType,
+} from '../Field';
+
+export interface XDSDateInputProps {
/**
* Label text for the input (required for accessibility).
*/
@@ -199,7 +223,14 @@ export interface XDSDatePickerProps {
* - 'md': Default size (26px height)
* @default 'md'
*/
- size?: XDSDatePickerSize;
+ size?: XDSDateInputSize;
+
+ /**
+ * Status indicator for the input.
+ * When set, displays a colored border and status icon.
+ * If message is provided, displays below the input.
+ */
+ status?: XDSInputStatus;
/**
* Number of months to display in the calendar popover.
@@ -213,14 +244,14 @@ export interface XDSDatePickerProps {
*
* @example
* ```tsx
- * <XDSDatePicker
+ * <XDSDateInput
* label="Event date"
* value={date}
* onChange={setDate}
* />
* ```
*/
-export const XDSDatePicker = forwardRef<HTMLInputElement, XDSDatePickerProps>(
+export const XDSDateInput = forwardRef<HTMLInputElement, XDSDateInputProps>(
(
{
label,
@@ -236,16 +267,60 @@ export const XDSDatePicker = forwardRef<HTMLInputElement, XDSDatePickerProps>(
dateConstraints,
placeholder = 'Select a date',
size = 'md',
+ status,
numberOfMonths = 1,
},
ref,
) => {
const id = useId();
const descriptionID = useId();
+ const statusMessageID = useId();
const inputRef = useRef<HTMLInputElement | null>(null);
+ const calendarRef = useRef<XDSCalendarHandle | null>(null);
+
+ // Status icon mapping
+ const statusIconMap: Record<XDSInputStatusType, typeof CalendarDaysIcon> = {
+ 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;
+
+ // Pending input while user is typing (null = show formatted value)
+ const [pendingInput, setPendingInput] = useState<string | null>(null);
- // Track input text separately from value for manual editing
- const [inputValue, setInputValue] = useState('');
+ // Display value: pending input if typing, otherwise formatted value
+ const displayValue = useMemo(() => {
+ if (pendingInput !== null) {
+ return pendingInput;
+ }
+ return value ? formatDisplayDate(value) : '';
+ }, [pendingInput, value]);
+
+ // Check if current input is valid (for styling purposes)
+ const isInputValid = useMemo(() => {
+ // Only check pending input for validity styling
+ if (pendingInput === null || !pendingInput.trim()) {
+ return true;
+ }
+ return parseDateInput(pendingInput) !== null;
+ }, [pendingInput]);
// Use XDSPopover for popover rendering, positioning, and focus trapping
const popover = useXDSPopover({
@@ -258,64 +333,72 @@ export const XDSDatePicker = forwardRef<HTMLInputElement, XDSDatePickerProps>(
},
});
- // Sync input value with controlled value
- useEffect(() => {
- if (value) {
- setInputValue(formatDisplayDate(value));
- } else {
- setInputValue('');
- }
- }, [value]);
-
- // Handle opening the popover
+ // Handle opening the popover from button click (focus calendar)
const handleOpen = useCallback(() => {
if (!isDisabled && !popover.isOpen) {
popover.show();
}
}, [isDisabled, popover]);
+ // Handle opening the popover from input click (keep focus in input)
+ const handleInputClick = useCallback(() => {
+ if (!isDisabled && !popover.isOpen) {
+ popover.show({skipAutoFocus: true});
+ }
+ }, [isDisabled, popover]);
+
// Handle date selection from calendar
const handleDateSelect = useCallback(
(selectedDate: ISODateString) => {
onChange(selectedDate);
+ setPendingInput(null);
popover.hide();
},
[onChange, popover],
);
- // Handle input text change
+ // Handle input text change - update immediately if valid
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
- setInputValue(e.target.value);
+ const newValue = e.target.value;
+ setPendingInput(newValue);
+
+ // If the input is valid, update immediately (don't wait for blur)
+ const parsed = parseDateInput(newValue);
+ if (parsed && parsed !== value) {
+ onChange(parsed);
+ // Navigate calendar to show the parsed date's month
+ calendarRef.current?.navigateTo(parsed);
+ }
},
- [],
+ [value, onChange],
);
- // Handle blur - parse the input and validate
+ // Handle blur - validate and clear pending input
const handleBlur = useCallback(() => {
- if (!inputValue.trim()) {
+ if (pendingInput === null) {
+ return;
+ }
+
+ if (!pendingInput.trim()) {
// Empty input clears the value
if (value !== undefined) {
onChange(undefined);
}
+ setPendingInput(null);
return;
}
- const parsed = parseDateInput(inputValue);
+ const parsed = parseDateInput(pendingInput);
if (parsed) {
// Valid date - update if different
if (parsed !== value) {
onChange(parsed);
}
- } else {
- // Invalid date - revert to previous value
- if (value) {
- setInputValue(formatDisplayDate(value));
- } else {
- setInputValue('');
- }
}
- }, [inputValue, value, onChange]);
+ // Clear pending input - display will revert to formatted value
+ setPendingInput(null);
+ }, [pendingInput, value, onChange]);
// Handle keyboard events on input
const handleInputKeyDown = useCallback(
@@ -349,12 +432,22 @@ export const XDSDatePicker = forwardRef<HTMLInputElement, XDSDatePickerProps>(
inputID={id}
descriptionID={description ? descriptionID : undefined}
isOptional={isOptional}
- isRequired={isRequired}>
+ isRequired={isRequired}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }>
<div
ref={popover.triggerRef}
{...stylex.props(
styles.wrapper,
isDisabled && styles.wrapperDisabled,
+ status && statusBorderStyles[status.type],
)}>
<button
type="button"
@@ -372,24 +465,34 @@ export const XDSDatePicker = forwardRef<HTMLInputElement, XDSDatePickerProps>(
ref={setRefs}
id={id}
type="text"
- value={inputValue}
+ value={displayValue}
onChange={handleInputChange}
onBlur={handleBlur}
- onClick={handleOpen}
+ onClick={handleInputClick}
onKeyDown={handleInputKeyDown}
placeholder={placeholder}
disabled={isDisabled}
- aria-describedby={description ? descriptionID : undefined}
+ aria-describedby={ariaDescribedBy}
aria-required={isRequired === true ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
{...stylex.props(
styles.input,
sizeStyles[size],
isDisabled && styles.inputDisabled,
+ !isInputValid && styles.inputInvalid,
)}
/>
+ {status && (
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
+ />
+ )}
</div>
{popover.render(
<XDSCalendar
+ ref={calendarRef}
mode="single"
value={value}
onChange={handleDateSelect}
@@ -397,7 +500,6 @@ export const XDSDatePicker = forwardRef<HTMLInputElement, XDSDatePickerProps>(
max={max}
dateConstraints={dateConstraints}
numberOfMonths={numberOfMonths}
- focusDate={value}
/>,
{placement: 'below', alignment: 'start'},
)}
@@ -406,4 +508,4 @@ export const XDSDatePicker = forwardRef<HTMLInputElement, XDSDatePickerProps>(
},
);
-XDSDatePicker.displayName = 'XDSDatePicker';
+XDSDateInput.displayName = 'XDSDateInput';
diff --git a/packages/core/src/DateInput/index.ts b/packages/core/src/DateInput/index.ts
new file mode 100644
index 0000000000..9be7e2e6cc
--- /dev/null
+++ b/packages/core/src/DateInput/index.ts
@@ -0,0 +1,14 @@
+/**
+ * @file index.ts
+ * @input DateInput component exports
+ * @output Re-exports XDSDateInput and types
+ * @position Package entry point for DateInput
+ */
+
+export {XDSDateInput} from './XDSDateInput';
+export type {
+ XDSDateInputProps,
+ XDSDateInputSize,
+ XDSDateInputStatus,
+ XDSDateInputStatusType,
+} from './XDSDateInput';
diff --git a/packages/core/src/DatePicker/XDSDatePicker.test.tsx b/packages/core/src/DatePicker/XDSDatePicker.test.tsx
deleted file mode 100644
index 0a6a0d4350..0000000000
--- a/packages/core/src/DatePicker/XDSDatePicker.test.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * @file XDSDatePicker.test.tsx
- * @input Uses vitest, @testing-library/react, XDSDatePicker component
- * @output Unit tests for XDSDatePicker component behavior
- * @position Testing; validates XDSDatePicker.tsx implementation
- *
- * SYNC: When XDSDatePicker.tsx changes, update tests to match new behavior
- */
-
-import {describe, it, expect} from 'vitest';
-import {render, screen} from '@testing-library/react';
-import {XDSDatePicker} from './XDSDatePicker';
-
-describe('XDSDatePicker', () => {
- it('renders with label', () => {
- render(<XDSDatePicker label="Date" onChange={() => {}} />);
- expect(screen.getByLabelText('Date')).toBeInTheDocument();
- });
-
- it('renders with placeholder', () => {
- render(
- <XDSDatePicker
- label="Date"
- onChange={() => {}}
- placeholder="Pick a date"
- />,
- );
- expect(screen.getByPlaceholderText('Pick a date')).toBeInTheDocument();
- });
-
- it('displays formatted date when value is provided', () => {
- render(
- <XDSDatePicker label="Date" value="2026-01-25" onChange={() => {}} />,
- );
- expect(screen.getByDisplayValue('January 25, 2026')).toBeInTheDocument();
- });
-
- it('forwards ref correctly', () => {
- const ref = vi.fn();
- render(<XDSDatePicker ref={ref} label="Date" onChange={() => {}} />);
- expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));
- });
-
- it('visually hides label when isLabelHidden is true', () => {
- render(<XDSDatePicker label="Date" isLabelHidden onChange={() => {}} />);
- const label = screen.getByText('Date');
- expect(label).toBeInTheDocument();
- expect(screen.getByLabelText('Date')).toBeInTheDocument();
- });
-
- it('shows label visually by default', () => {
- render(<XDSDatePicker label="Event date" onChange={() => {}} />);
- const label = screen.getByText('Event date');
- expect(label).toBeVisible();
- });
-
- it('sets aria-required when isRequired is true', () => {
- render(<XDSDatePicker label="Date" isRequired onChange={() => {}} />);
- expect(screen.getByRole('textbox')).toHaveAttribute(
- 'aria-required',
- 'true',
- );
- });
-
- it('does not set aria-required when isRequired is false', () => {
- render(<XDSDatePicker label="Date" onChange={() => {}} />);
- expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-required');
- });
-
- it('sets disabled attribute when isDisabled is true', () => {
- render(<XDSDatePicker label="Date" isDisabled onChange={() => {}} />);
- expect(screen.getByRole('textbox')).toBeDisabled();
- });
-
- it('is not disabled by default', () => {
- render(<XDSDatePicker label="Date" onChange={() => {}} />);
- expect(screen.getByRole('textbox')).not.toBeDisabled();
- });
-
- it('renders calendar icon', () => {
- render(<XDSDatePicker label="Date" onChange={() => {}} />);
- const svg = document.querySelector('svg');
- expect(svg).toBeInTheDocument();
- });
-
- it('calendar button has aria-haspopup="dialog" attribute', () => {
- render(<XDSDatePicker label="Date" onChange={() => {}} />);
- expect(screen.getByRole('button', {name: 'Open calendar'})).toHaveAttribute(
- 'aria-haspopup',
- 'dialog',
- );
- });
-
- it('calendar button is focusable and clickable', () => {
- render(<XDSDatePicker label="Date" onChange={() => {}} />);
- const button = screen.getByRole('button', {name: 'Open calendar'});
- expect(button).toBeInTheDocument();
- expect(button).not.toBeDisabled();
- });
-
- it('calendar button is disabled when isDisabled is true', () => {
- render(<XDSDatePicker label="Date" isDisabled onChange={() => {}} />);
- const button = screen.getByRole('button', {name: 'Open calendar'});
- expect(button).toBeDisabled();
- });
-
- // Note: Tests involving blur that trigger popover are skipped because
- // jsdom doesn't support the Popover API (showPopover is not a function).
- // These behaviors are tested in the browser via Storybook.
-});
diff --git a/packages/core/src/DatePicker/index.ts b/packages/core/src/DatePicker/index.ts
deleted file mode 100644
index 566ad50980..0000000000
--- a/packages/core/src/DatePicker/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- * @file index.ts
- * @input DatePicker component exports
- * @output Re-exports XDSDatePicker and types
- * @position Package entry point for DatePicker
- */
-
-export {XDSDatePicker} from './XDSDatePicker';
-export type {XDSDatePickerProps, XDSDatePickerSize} from './XDSDatePicker';
diff --git a/packages/core/src/Field/index.ts b/packages/core/src/Field/index.ts
index d511570922..0d5b54d714 100644
--- a/packages/core/src/Field/index.ts
+++ b/packages/core/src/Field/index.ts
@@ -15,3 +15,6 @@ export type {
} from './XDSField';
export {XDSFieldLabel} from './XDSFieldLabel';
export type {XDSFieldLabelProps} from './XDSFieldLabel';
+
+// Shared input types
+export type {XDSInputStatus, XDSInputStatusType, XDSInputSize} from './types';
diff --git a/packages/core/src/Field/types.ts b/packages/core/src/Field/types.ts
new file mode 100644
index 0000000000..b17f8a4949
--- /dev/null
+++ b/packages/core/src/Field/types.ts
@@ -0,0 +1,38 @@
+/**
+ * @file types.ts
+ * @input None
+ * @output Exports shared input component types
+ * @position Shared types used across input components
+ *
+ * SYNC: When adding new shared types, update this file
+ */
+
+/**
+ * Status type for input validation states.
+ */
+export type XDSInputStatusType = 'warning' | 'error' | 'success';
+
+/**
+ * Status indicator for input components.
+ * Used by TextInput, TextArea, DatePicker, TimePicker, etc.
+ */
+export interface XDSInputStatus {
+ /**
+ * The type of status to display.
+ * - 'error': Invalid input, prevents form submission
+ * - 'warning': Caution, but allows submission
+ * - 'success': Valid input confirmation
+ */
+ type: XDSInputStatusType;
+
+ /**
+ * Optional message to display below the input.
+ * When provided, shows a colored message box.
+ */
+ message?: string;
+}
+
+/**
+ * Standard size options for input components.
+ */
+export type XDSInputSize = 'sm' | 'md';
diff --git a/packages/core/src/Layer/useXDSPopover.tsx b/packages/core/src/Layer/useXDSPopover.tsx
index 1020dfb458..dca6c41367 100644
--- a/packages/core/src/Layer/useXDSPopover.tsx
+++ b/packages/core/src/Layer/useXDSPopover.tsx
@@ -159,9 +159,11 @@ export interface UseXDSPopoverReturn {
anchorId: string;
/**
- * Show the popover
+ * Show the popover.
+ * @param options.skipAutoFocus - If true, don't auto-focus the first element.
+ * Useful when triggered by mouse click on an input that should retain focus.
*/
- show: () => void;
+ show: (options?: {skipAutoFocus?: boolean}) => void;
/**
* Hide the popover
@@ -270,6 +272,9 @@ export function useXDSPopover(
// Track the trigger element for returning focus
const triggerElementRef = useRef<HTMLElement | null>(null);
+ // Track whether to skip auto-focus for the current open event
+ const skipAutoFocusRef = useRef(false);
+
// Core layer for popover positioning
const layer = useXDSLayer({
mode: 'context',
@@ -285,14 +290,18 @@ export function useXDSPopover(
onEscape: layer.hide,
});
- // Auto-focus first element when popover opens
+ // Auto-focus first element when popover opens (unless skipped)
useEffect(() => {
- if (layer.isOpen && hasAutoFocus) {
+ if (layer.isOpen && hasAutoFocus && !skipAutoFocusRef.current) {
// Use requestAnimationFrame to ensure DOM is ready
requestAnimationFrame(() => {
focusFirst();
});
}
+ // Reset the skip flag after the effect runs
+ if (!layer.isOpen) {
+ skipAutoFocusRef.current = false;
+ }
}, [layer.isOpen, hasAutoFocus, focusFirst]);
// Reset close button focus state when popover closes
@@ -311,14 +320,23 @@ export function useXDSPopover(
[layer],
);
+ // Show function with optional skipAutoFocus
+ const show = useCallback(
+ (showOptions?: {skipAutoFocus?: boolean}) => {
+ skipAutoFocusRef.current = showOptions?.skipAutoFocus ?? false;
+ layer.show();
+ },
+ [layer],
+ );
+
// Toggle function
const toggle = useCallback(() => {
if (layer.isOpen) {
layer.hide();
} else {
- layer.show();
+ show();
}
- }, [layer]);
+ }, [layer, show]);
// ARIA attributes for the trigger
const triggerProps = {
@@ -370,7 +388,7 @@ export function useXDSPopover(
triggerRef,
contentRef,
anchorId: layer.anchorId,
- show: layer.show,
+ show,
hide: layer.hide,
toggle,
isOpen: layer.isOpen,
diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsx
index 328074086f..21b5cfcec1 100644
--- a/packages/core/src/TextInput/XDSTextInput.tsx
+++ b/packages/core/src/TextInput/XDSTextInput.tsx
@@ -25,7 +25,7 @@ import {
transitionVars,
typographyVars,
} from '../theme/tokens.stylex';
-import {XDSField} from '../Field';
+import {XDSField, type XDSInputStatus, type XDSInputStatusType} from '../Field';
import {XDSIcon, type XDSIconType} from '../Icon';
const styles = stylex.create({
@@ -105,18 +105,11 @@ const statusBorderStyles = stylex.create({
export type XDSTextInputSize = keyof typeof sizeStyles;
-export type XDSTextInputStatusType = 'warning' | 'error' | 'success';
-
-export interface XDSTextInputStatus {
- /**
- * The type of status to display.
- */
- type: XDSTextInputStatusType;
- /**
- * Optional message to display below the input.
- */
- message?: string;
-}
+// Re-export shared types for convenience
+export type {
+ XDSInputStatus as XDSTextInputStatus,
+ XDSInputStatusType as XDSTextInputStatusType,
+} from '../Field';
export interface XDSTextInputProps {
/**
@@ -157,7 +150,7 @@ export interface XDSTextInputProps {
* When set, displays a colored border and status icon.
* If message is provided, displays a floating message box below the input.
*/
- status?: XDSTextInputStatus;
+ status?: XDSInputStatus;
/**
* The size of the input.
* - 'sm': Compact size (18px height)
@@ -221,20 +214,20 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(
hasAutoFocus = false,
htmlName,
},
- ref
+ ref,
) => {
const id = useId();
const descriptionID = useId();
const statusMessageID = useId();
- const statusIconMap: Record<XDSTextInputStatusType, XDSIconType> = {
+ const statusIconMap: Record<XDSInputStatusType, XDSIconType> = {
warning: ExclamationTriangleIcon,
error: XCircleIcon,
success: CheckCircleIcon,
};
const statusIconColorMap: Record<
- XDSTextInputStatusType,
+ XDSInputStatusType,
'warning' | 'negative' | 'positive'
> = {
warning: 'warning',
@@ -273,7 +266,7 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(
{...stylex.props(
styles.wrapper,
isDisabled && styles.wrapperDisabled,
- status && statusBorderStyles[status.type]
+ status && statusBorderStyles[status.type],
)}>
{startIcon && <XDSIcon icon={startIcon} size="sm" color="primary" />}
<input
@@ -292,7 +285,7 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(
{...stylex.props(
styles.input,
sizeStyles[size],
- isDisabled && styles.inputDisabled
+ isDisabled && styles.inputDisabled,
)}
/>
{status && (
@@ -305,7 +298,7 @@ export const XDSTextInput = forwardRef<HTMLInputElement, XDSTextInputProps>(
</div>
</XDSField>
);
- }
+ },
);
XDSTextInput.displayName = 'XDSTextInput';
diff --git a/packages/core/src/TimeInput/XDSTimeInput.test.tsx b/packages/core/src/TimeInput/XDSTimeInput.test.tsx
new file mode 100644
index 0000000000..c0c964df7a
--- /dev/null
+++ b/packages/core/src/TimeInput/XDSTimeInput.test.tsx
@@ -0,0 +1,187 @@
+/**
+ * @file XDSTimeInput.test.tsx
+ * @input Uses vitest, @testing-library/react, XDSTimeInput component
+ * @output Unit tests for XDSTimeInput component behavior
+ * @position Testing; validates XDSTimeInput.tsx implementation
+ *
+ * SYNC: When XDSTimeInput.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 {XDSTimeInput} from './XDSTimeInput';
+import type {ISOTimeString} from '../utils';
+
+describe('XDSTimeInput', () => {
+ it('renders with label', () => {
+ render(<XDSTimeInput label="Time" onChange={() => {}} />);
+ expect(screen.getByLabelText('Time')).toBeInTheDocument();
+ });
+
+ it('renders with placeholder', () => {
+ render(
+ <XDSTimeInput
+ label="Time"
+ onChange={() => {}}
+ placeholder="Pick a time"
+ />,
+ );
+ expect(screen.getByPlaceholderText('Pick a time')).toBeInTheDocument();
+ });
+
+ it('displays formatted time in 12h format', () => {
+ render(
+ <XDSTimeInput
+ label="Time"
+ value={'14:30' as ISOTimeString}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByDisplayValue('2:30 PM')).toBeInTheDocument();
+ });
+
+ it('displays formatted time in 24h format', () => {
+ render(
+ <XDSTimeInput
+ label="Time"
+ value={'14:30' as ISOTimeString}
+ onChange={() => {}}
+ hourFormat="24h"
+ />,
+ );
+ expect(screen.getByDisplayValue('14:30')).toBeInTheDocument();
+ });
+
+ it('displays time with seconds', () => {
+ render(
+ <XDSTimeInput
+ label="Time"
+ value={'14:30:45' as ISOTimeString}
+ onChange={() => {}}
+ hasSeconds
+ />,
+ );
+ expect(screen.getByDisplayValue('2:30:45 PM')).toBeInTheDocument();
+ });
+
+ it('forwards ref correctly', () => {
+ const ref = vi.fn();
+ render(<XDSTimeInput ref={ref} label="Time" onChange={() => {}} />);
+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));
+ });
+
+ it('visually hides label when isLabelHidden is true', () => {
+ render(<XDSTimeInput label="Time" isLabelHidden onChange={() => {}} />);
+ const label = screen.getByText('Time');
+ expect(label).toBeInTheDocument();
+ expect(screen.getByLabelText('Time')).toBeInTheDocument();
+ });
+
+ it('sets aria-required when isRequired is true', () => {
+ render(<XDSTimeInput label="Time" isRequired onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).toHaveAttribute(
+ 'aria-required',
+ 'true',
+ );
+ });
+
+ it('disables input when isDisabled is true', () => {
+ render(<XDSTimeInput label="Time" isDisabled onChange={() => {}} />);
+ expect(screen.getByRole('textbox')).toBeDisabled();
+ });
+
+ it('shows clear button when hasClear is true and value exists', () => {
+ render(
+ <XDSTimeInput
+ label="Time"
+ value={'14:30' as ISOTimeString}
+ onChange={() => {}}
+ hasClear
+ />,
+ );
+ expect(
+ screen.getByRole('button', {name: 'Clear time'}),
+ ).toBeInTheDocument();
+ });
+
+ it('does not show clear button when value is empty', () => {
+ render(<XDSTimeInput label="Time" onChange={() => {}} hasClear />);
+ expect(
+ screen.queryByRole('button', {name: 'Clear time'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('calls onChange with undefined when clear button is clicked', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <XDSTimeInput
+ label="Time"
+ value={'14:30' as ISOTimeString}
+ onChange={onChange}
+ hasClear
+ />,
+ );
+
+ await user.click(screen.getByRole('button', {name: 'Clear time'}));
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ });
+
+ it('does not call onChange while typing invalid input', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(<XDSTimeInput label="Time" onChange={onChange} />);
+
+ const input = screen.getByRole('textbox');
+ await user.type(input, 'invalid');
+
+ // onChange should not be called while typing
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('reverts to previous value on blur when input is invalid', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(
+ <XDSTimeInput
+ label="Time"
+ value={'14:30' as ISOTimeString}
+ onChange={onChange}
+ />,
+ );
+
+ const input = screen.getByRole('textbox');
+ await user.clear(input);
+ await user.type(input, 'not a time');
+ await user.tab(); // blur
+
+ // Should revert to the original value, not call onChange
+ expect(screen.getByDisplayValue('2:30 PM')).toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('calls onChange on blur when input is valid', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(<XDSTimeInput label="Time" onChange={onChange} />);
+
+ const input = screen.getByRole('textbox');
+ await user.type(input, '3:45 pm');
+ await user.tab(); // blur
+
+ expect(onChange).toHaveBeenCalledWith('15:45');
+ });
+
+ it('calls onChange immediately when input becomes valid', async () => {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ render(<XDSTimeInput label="Time" onChange={onChange} />);
+
+ const input = screen.getByRole('textbox');
+ await user.type(input, '3:45 pm');
+
+ // onChange should be called immediately when input is valid, not waiting for blur
+ expect(onChange).toHaveBeenCalledWith('15:45');
+ });
+});
diff --git a/packages/core/src/TimeInput/XDSTimeInput.tsx b/packages/core/src/TimeInput/XDSTimeInput.tsx
new file mode 100644
index 0000000000..1a79c0d42c
--- /dev/null
+++ b/packages/core/src/TimeInput/XDSTimeInput.tsx
@@ -0,0 +1,542 @@
+/**
+ * @file XDSTimeInput.tsx
+ * @input Uses React forwardRef, useId, useState, useEffect, useCallback, useRef, XDSField, XDSIcon
+ * @output Exports XDSTimeInput component, XDSTimeInputProps
+ * @position Core implementation; consumed by index.ts, tested by XDSTimeInput.test.tsx
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/TimeInput/README.md (props table, features, implementation notes)
+ * - /packages/core/src/TimeInput/XDSTimeInput.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/TimeInput/index.ts (exports if types change)
+ * - /apps/storybook/stories/TimeInput.stories.tsx (storybook stories)
+ */
+
+import {
+ forwardRef,
+ useId,
+ useState,
+ useCallback,
+ useRef,
+ useMemo,
+ type KeyboardEvent,
+ type FocusEvent,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {ClockIcon, XMarkIcon} from '@heroicons/react/24/outline';
+import {
+ CheckCircleIcon,
+ ExclamationTriangleIcon,
+ XCircleIcon,
+} from '@heroicons/react/24/solid';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ transitionVars,
+ typographyVars,
+ textSizeVars,
+ lineHeightVars,
+} from '../theme/tokens.stylex';
+import {XDSField, type XDSInputStatus, type XDSInputStatusType} from '../Field';
+import {XDSIcon} from '../Icon';
+import {
+ type ISOTimeString,
+ parseTimeInput,
+ formatDisplayTime12h,
+ formatDisplayTime24h,
+ formatISOTime,
+ adjustTime,
+ isTimeInRange,
+} from '../utils';
+
+const styles = stylex.create({
+ wrapper: {
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-1'],
+ paddingInline: spacingVars['--spacing-2'],
+ borderWidth: 1,
+ 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'],
+ },
+ icon: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ flexShrink: 0,
+ },
+ input: {
+ display: 'block',
+ flex: 1,
+ minWidth: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ padding: 0,
+ fontFamily: typographyVars['--font-body'],
+ fontSize: textSizeVars['--text-base'],
+ lineHeight: lineHeightVars['--leading-normal'],
+ color: colorVars['--color-text-primary'],
+ backgroundColor: 'transparent',
+ outline: 'none',
+ '::placeholder': {
+ color: colorVars['--color-text-placeholder'],
+ },
+ },
+ inputDisabled: {
+ cursor: 'not-allowed',
+ },
+ inputInvalid: {
+ color: colorVars['--color-text-secondary'],
+ },
+ clearButton: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 0,
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ cursor: 'pointer',
+ borderRadius: radiusVars['--radius-element'],
+ outline: {
+ default: 'none',
+ ':focus-visible': `2px solid ${colorVars['--color-focus-outline']}`,
+ },
+ outlineOffset: 1,
+ },
+});
+
+const sizeStyles = stylex.create({
+ sm: {
+ height: 18,
+ },
+ md: {
+ height: 26,
+ },
+});
+
+const statusBorderStyles = stylex.create({
+ warning: {
+ borderColor: colorVars['--color-warning'],
+ },
+ error: {
+ borderColor: colorVars['--color-negative'],
+ },
+ success: {
+ borderColor: colorVars['--color-positive'],
+ },
+});
+
+export type XDSTimeInputSize = keyof typeof sizeStyles;
+export type XDSTimeInputHourFormat = '12h' | '24h';
+
+// Re-export shared types for convenience
+export type {
+ XDSInputStatus as XDSTimeInputStatus,
+ XDSInputStatusType as XDSTimeInputStatusType,
+} from '../Field';
+
+export interface XDSTimeInputProps {
+ /**
+ * Label text for the input (required 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;
+
+ /**
+ * The selected time in ISO format (HH:MM or HH:MM:SS).
+ */
+ value?: ISOTimeString;
+
+ /**
+ * Callback fired when the time changes.
+ * Called with undefined when input is cleared.
+ */
+ onChange: (value: ISOTimeString | undefined) => void;
+
+ /**
+ * Minimum selectable time in ISO format.
+ */
+ min?: ISOTimeString;
+
+ /**
+ * Maximum selectable time in ISO format.
+ */
+ max?: ISOTimeString;
+
+ /**
+ * Whether to include seconds in the time input.
+ * @default false
+ */
+ hasSeconds?: boolean;
+
+ /**
+ * Whether to show a clear button when a value is set.
+ * @default false
+ */
+ hasClear?: boolean;
+
+ /**
+ * Hour format for display.
+ * - '12h': Display as 12-hour with AM/PM (e.g., "2:30 PM")
+ * - '24h': Display as 24-hour (e.g., "14:30")
+ * @default '12h'
+ */
+ hourFormat?: XDSTimeInputHourFormat;
+
+ /**
+ * Increment in minutes when using arrow keys.
+ * @default 1
+ */
+ increment?: number;
+
+ /**
+ * Placeholder text shown when no time is selected.
+ * @default "Select a time"
+ */
+ placeholder?: string;
+
+ /**
+ * The size of the input.
+ * - 'sm': Compact size (18px height)
+ * - 'md': Default size (26px height)
+ * @default 'md'
+ */
+ size?: XDSTimeInputSize;
+
+ /**
+ * Status indicator for the input.
+ * When set, displays a colored border and status icon.
+ * If message is provided, displays below the input.
+ */
+ status?: XDSInputStatus;
+}
+
+/**
+ * A time input component with text input and keyboard navigation.
+ *
+ * @example
+ * ```tsx
+ * <XDSTimeInput
+ * label="Start time"
+ * value={time}
+ * onChange={setTime}
+ * hourFormat="12h"
+ * hasClear
+ * />
+ * ```
+ */
+export const XDSTimeInput = forwardRef<HTMLInputElement, XDSTimeInputProps>(
+ (
+ {
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ value,
+ onChange,
+ min,
+ max,
+ hasSeconds = false,
+ hasClear = false,
+ hourFormat = '12h',
+ increment = 1,
+ placeholder = 'Select a time',
+ size = 'md',
+ status,
+ },
+ ref,
+ ) => {
+ const id = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ // Status icon mapping
+ const statusIconMap: Record<XDSInputStatusType, typeof XCircleIcon> = {
+ 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;
+
+ // Pending input while user is typing (null = show formatted value)
+ const [pendingInput, setPendingInput] = useState<string | null>(null);
+ const [isFocused, setIsFocused] = useState(false);
+
+ // Format function based on hourFormat
+ const formatDisplayTime =
+ hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;
+
+ // Display value: pending input if typing, otherwise formatted value
+ const displayValue = useMemo(() => {
+ if (pendingInput !== null) {
+ return pendingInput;
+ }
+ return value ? formatDisplayTime(value, hasSeconds) : '';
+ }, [pendingInput, value, formatDisplayTime, hasSeconds]);
+
+ // Check if current input is valid (for styling purposes)
+ const isInputValid = useMemo(() => {
+ // Only check pending input for validity styling
+ if (pendingInput === null || !pendingInput.trim()) {
+ return true;
+ }
+ const parsed = parseTimeInput(pendingInput, hasSeconds);
+ if (!parsed) {
+ return false;
+ }
+ // Also check min/max range
+ return isTimeInRange(parsed, min, max);
+ }, [pendingInput, hasSeconds, min, max]);
+
+ // Placeholder that shows format hint when focused and empty
+ const displayPlaceholder = useMemo(() => {
+ if (isFocused && !displayValue) {
+ return hourFormat === '12h' ? 'e.g., 2:30 PM' : 'e.g., 14:30';
+ }
+ return placeholder;
+ }, [isFocused, displayValue, hourFormat, placeholder]);
+
+ // 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 (don't wait for blur)
+ const parsed = parseTimeInput(newValue, hasSeconds);
+ if (parsed && isTimeInRange(parsed, min, max) && parsed !== value) {
+ onChange(parsed);
+ }
+ },
+ [hasSeconds, min, max, value, onChange],
+ );
+
+ // Handle focus
+ const handleFocus = useCallback(() => {
+ setIsFocused(true);
+ }, []);
+
+ // Handle blur - validate and clear pending input
+ const handleBlur = useCallback(
+ (e: FocusEvent<HTMLInputElement>) => {
+ setIsFocused(false);
+
+ if (pendingInput === null) {
+ return;
+ }
+
+ if (!pendingInput.trim()) {
+ // Empty input clears the value
+ if (value !== undefined) {
+ onChange(undefined);
+ }
+ setPendingInput(null);
+ return;
+ }
+
+ const parsed = parseTimeInput(pendingInput, hasSeconds);
+ if (parsed && isTimeInRange(parsed, min, max)) {
+ // Valid time - update if different
+ if (parsed !== value) {
+ onChange(parsed);
+ }
+ }
+ // Clear pending input - display will revert to formatted value
+ setPendingInput(null);
+ },
+ [pendingInput, value, onChange, hasSeconds, min, max],
+ );
+
+ // Handle keyboard navigation on input
+ const handleInputKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
+ e.preventDefault();
+
+ // Get current time or default to now
+ let currentTime = value;
+ if (!currentTime) {
+ const now = new Date();
+ currentTime = formatISOTime(
+ {
+ hour: now.getHours(),
+ minute: now.getMinutes(),
+ second: now.getSeconds(),
+ },
+ hasSeconds,
+ );
+ }
+
+ const delta = e.key === 'ArrowUp' ? increment : -increment;
+ const newTime = adjustTime(currentTime, delta, hasSeconds);
+
+ // Check if within range
+ if (isTimeInRange(newTime, min, max)) {
+ onChange(newTime);
+ }
+ }
+ },
+ [value, hasSeconds, increment, min, max, onChange],
+ );
+
+ // Handle clear button click
+ const handleClear = useCallback(() => {
+ onChange(undefined);
+ inputRef.current?.focus();
+ }, [onChange]);
+
+ // 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}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }>
+ <div
+ {...stylex.props(
+ styles.wrapper,
+ isDisabled && styles.wrapperDisabled,
+ status && statusBorderStyles[status.type],
+ )}>
+ <div {...stylex.props(styles.icon)}>
+ <XDSIcon icon={ClockIcon} size="sm" color="secondary" />
+ </div>
+ <input
+ ref={setRefs}
+ id={id}
+ type="text"
+ value={displayValue}
+ onChange={handleInputChange}
+ onFocus={handleFocus}
+ onBlur={handleBlur}
+ onKeyDown={handleInputKeyDown}
+ placeholder={displayPlaceholder}
+ disabled={isDisabled}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isRequired === true ? 'true' : undefined}
+ aria-invalid={status?.type === 'error' ? 'true' : undefined}
+ {...stylex.props(
+ styles.input,
+ sizeStyles[size],
+ isDisabled && styles.inputDisabled,
+ !isInputValid && styles.inputInvalid,
+ )}
+ />
+ {hasClear && value && !isDisabled && (
+ <button
+ type="button"
+ onClick={handleClear}
+ aria-label="Clear time"
+ {...stylex.props(styles.clearButton)}>
+ <XDSIcon icon={XMarkIcon} size="sm" color="secondary" />
+ </button>
+ )}
+ {status && (
+ <XDSIcon
+ icon={statusIconMap[status.type]}
+ size="md"
+ color={statusIconColorMap[status.type]}
+ />
+ )}
+ </div>
+ </XDSField>
+ );
+ },
+);
+
+XDSTimeInput.displayName = 'XDSTimeInput';
diff --git a/packages/core/src/TimeInput/index.ts b/packages/core/src/TimeInput/index.ts
new file mode 100644
index 0000000000..199efc953b
--- /dev/null
+++ b/packages/core/src/TimeInput/index.ts
@@ -0,0 +1,17 @@
+/**
+ * @file index.ts
+ * @input Imports TimeInput components and types
+ * @output Exports XDSTimeInput and related types
+ * @position Component entry point; re-exported by /packages/core/src/index.ts
+ *
+ * SYNC: When modified, update this header and /packages/core/src/TimeInput/README.md
+ */
+
+export {XDSTimeInput} from './XDSTimeInput';
+export type {
+ XDSTimeInputProps,
+ XDSTimeInputSize,
+ XDSTimeInputHourFormat,
+ XDSTimeInputStatus,
+ XDSTimeInputStatusType,
+} from './XDSTimeInput';
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index ea3aaaefd3..4949e3fa40 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -14,14 +14,15 @@ export * from './Button';
export * from './Calendar';
export * from './Center';
export * from './CheckboxInput';
-export * from './DatePicker';
export * from './Divider';
+export * from './DateInput';
export * from './Field';
export * from './Grid';
export * from './Icon';
export * from './Text';
export * from './TextInput';
export * from './TextArea';
+export * from './TimeInput';
// Layout utilities and components (includes XDSHStack, XDSVStack)
export * from './Layout';
diff --git a/packages/core/src/utils/dateParser.test.ts b/packages/core/src/utils/dateParser.test.ts
index 3311a2792a..1be083dfd0 100644
--- a/packages/core/src/utils/dateParser.test.ts
+++ b/packages/core/src/utils/dateParser.test.ts
@@ -78,6 +78,43 @@ describe('parseDateInput', () => {
});
});
+ describe('formats without year (defaults to current year)', () => {
+ const currentYear = new Date().getFullYear();
+
+ it('parses "January 25" (month-first without year)', () => {
+ expect(parseDateInput('January 25')).toBe(`${currentYear}-01-25`);
+ });
+
+ it('parses "Jan 25" (abbreviated month without year)', () => {
+ expect(parseDateInput('Jan 25')).toBe(`${currentYear}-01-25`);
+ });
+
+ it('parses "25 January" (day-first without year)', () => {
+ expect(parseDateInput('25 January')).toBe(`${currentYear}-01-25`);
+ });
+
+ it('parses "25 Jan" (day-first abbreviated without year)', () => {
+ expect(parseDateInput('25 Jan')).toBe(`${currentYear}-01-25`);
+ });
+
+ it('parses "1/25" (numeric without year)', () => {
+ expect(parseDateInput('1/25')).toBe(`${currentYear}-01-25`);
+ });
+
+ it('parses "25/1" (numeric day-first without year)', () => {
+ expect(parseDateInput('25/1')).toBe(`${currentYear}-01-25`);
+ });
+
+ it('parses "12-31" (numeric with dash without year)', () => {
+ expect(parseDateInput('12-31')).toBe(`${currentYear}-12-31`);
+ });
+
+ it('handles all months without year', () => {
+ expect(parseDateInput('Feb 15')).toBe(`${currentYear}-02-15`);
+ expect(parseDateInput('Dec 25')).toBe(`${currentYear}-12-25`);
+ });
+ });
+
describe('numeric formats with heuristics', () => {
it('detects day when first number > 12', () => {
expect(parseDateInput('25/1/2026')).toBe('2026-01-25');
diff --git a/packages/core/src/utils/dateParser.ts b/packages/core/src/utils/dateParser.ts
index 21e367a88b..442e932761 100644
--- a/packages/core/src/utils/dateParser.ts
+++ b/packages/core/src/utils/dateParser.ts
@@ -28,7 +28,9 @@ export function isLocaleDayFirst(): boolean {
* Supports:
* - ISO format: "2026-01-25"
* - Full month names: "January 25, 2026", "25 January 2026"
+ * - Full month names without year: "January 25", "25 January" (defaults to current year)
* - Numeric formats: "1/25/2026", "25/1/2026" (locale-aware with heuristics)
+ * - Numeric formats without year: "1/25", "25/1" (defaults to current year)
*
* For ambiguous numeric formats (both numbers ≤ 12), uses locale preference.
*
@@ -38,6 +40,8 @@ export function parseDateInput(input: string): ISODateString | null {
const trimmed = input.trim();
if (!trimmed) return null;
+ const currentYear = new Date().getFullYear();
+
// 1. Try ISO format first (YYYY-MM-DD) - always unambiguous
const isoMatch = trimmed.match(/^(\d{4})-(\d{1,2})-(\d{1,2})$/);
if (isoMatch) {
@@ -45,13 +49,13 @@ export function parseDateInput(input: string): ISODateString | null {
return createISODate(+year, +month, +day);
}
- // 2. Try full month name formats
+ // 2. Try full month name formats with year
// "January 25, 2026" or "Jan 25, 2026"
- const monthFirstMatch = trimmed.match(
+ const monthFirstWithYearMatch = trimmed.match(
/^([A-Za-z]+)\s+(\d{1,2}),?\s+(\d{4})$/,
);
- if (monthFirstMatch) {
- const [, monthName, day, year] = monthFirstMatch;
+ if (monthFirstWithYearMatch) {
+ const [, monthName, day, year] = monthFirstWithYearMatch;
const month = parseMonthName(monthName);
if (month !== null) {
return createISODate(+year, month, +day);
@@ -59,23 +63,55 @@ export function parseDateInput(input: string): ISODateString | null {
}
// "25 January 2026" or "25 Jan 2026"
- const dayFirstMatch = trimmed.match(/^(\d{1,2})\s+([A-Za-z]+),?\s+(\d{4})$/);
- if (dayFirstMatch) {
- const [, day, monthName, year] = dayFirstMatch;
+ const dayFirstWithYearMatch = trimmed.match(
+ /^(\d{1,2})\s+([A-Za-z]+),?\s+(\d{4})$/,
+ );
+ if (dayFirstWithYearMatch) {
+ const [, day, monthName, year] = dayFirstWithYearMatch;
const month = parseMonthName(monthName);
if (month !== null) {
return createISODate(+year, month, +day);
}
}
- // 3. Try numeric formats with separators (/, -, .)
- const numericMatch = trimmed.match(/^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/);
- if (numericMatch) {
- const [, first, second, year] = numericMatch;
+ // 3. Try full month name formats WITHOUT year (defaults to current year)
+ // "January 25" or "Jan 25"
+ const monthFirstNoYearMatch = trimmed.match(/^([A-Za-z]+)\s+(\d{1,2})$/);
+ if (monthFirstNoYearMatch) {
+ const [, monthName, day] = monthFirstNoYearMatch;
+ const month = parseMonthName(monthName);
+ if (month !== null) {
+ return createISODate(currentYear, month, +day);
+ }
+ }
+
+ // "25 January" or "25 Jan"
+ const dayFirstNoYearMatch = trimmed.match(/^(\d{1,2})\s+([A-Za-z]+)$/);
+ if (dayFirstNoYearMatch) {
+ const [, day, monthName] = dayFirstNoYearMatch;
+ const month = parseMonthName(monthName);
+ if (month !== null) {
+ return createISODate(currentYear, month, +day);
+ }
+ }
+
+ // 4. Try numeric formats with separators (/, -, .) WITH year
+ const numericWithYearMatch = trimmed.match(
+ /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/,
+ );
+ if (numericWithYearMatch) {
+ const [, first, second, year] = numericWithYearMatch;
return parseNumericDate(+first, +second, +year);
}
- // 4. Fall back to native Date parsing for other formats
+ // 5. Try numeric formats WITHOUT year (defaults to current year)
+ const numericNoYearMatch = trimmed.match(/^(\d{1,2})[-/.](\d{1,2})$/);
+ if (numericNoYearMatch) {
+ const [, first, second] = numericNoYearMatch;
+ return parseNumericDate(+first, +second, currentYear);
+ }
+
+ // 6. Fall back to native Date parsing for other formats
const parsed = new Date(trimmed);
if (!isNaN(parsed.getTime())) {
return dateToISO(parsed);
diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts
index dd1f7096d4..60399f35eb 100644
--- a/packages/core/src/utils/index.ts
+++ b/packages/core/src/utils/index.ts
@@ -12,3 +12,17 @@ export {
parseISO,
isLocaleDayFirst,
} from './dateParser';
+
+export {
+ parseISOTime,
+ formatISOTime,
+ formatDisplayTime12h,
+ formatDisplayTime24h,
+ parseTimeInput,
+ compareTime,
+ isTimeInRange,
+ clampTime,
+ adjustTime,
+ createISOTimeString,
+} from './timeParser';
+export type {ISOTimeString, ParsedTime} from './timeParser';
diff --git a/packages/core/src/utils/timeParser.test.ts b/packages/core/src/utils/timeParser.test.ts
new file mode 100644
index 0000000000..165742005f
--- /dev/null
+++ b/packages/core/src/utils/timeParser.test.ts
@@ -0,0 +1,254 @@
+/**
+ * @file timeParser.test.ts
+ * @input Uses vitest, timeParser utilities
+ * @output Unit tests for time parsing and formatting
+ * @position Testing; validates timeParser.ts implementation
+ *
+ * SYNC: When timeParser.ts changes, update tests to match new behavior
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ parseISOTime,
+ formatISOTime,
+ formatDisplayTime12h,
+ formatDisplayTime24h,
+ parseTimeInput,
+ compareTime,
+ isTimeInRange,
+ adjustTime,
+ type ISOTimeString,
+} from './timeParser';
+
+describe('parseISOTime', () => {
+ it('parses HH:MM format', () => {
+ expect(parseISOTime('14:30')).toEqual({hour: 14, minute: 30, second: 0});
+ expect(parseISOTime('00:00')).toEqual({hour: 0, minute: 0, second: 0});
+ expect(parseISOTime('23:59')).toEqual({hour: 23, minute: 59, second: 0});
+ });
+
+ it('parses HH:MM:SS format', () => {
+ expect(parseISOTime('14:30:45')).toEqual({
+ hour: 14,
+ minute: 30,
+ second: 45,
+ });
+ expect(parseISOTime('00:00:00')).toEqual({hour: 0, minute: 0, second: 0});
+ expect(parseISOTime('23:59:59')).toEqual({
+ hour: 23,
+ minute: 59,
+ second: 59,
+ });
+ });
+
+ it('returns null for invalid formats', () => {
+ expect(parseISOTime('')).toBeNull();
+ expect(parseISOTime('14')).toBeNull();
+ expect(parseISOTime('14:30:45:00')).toBeNull();
+ expect(parseISOTime('25:00')).toBeNull();
+ expect(parseISOTime('14:60')).toBeNull();
+ expect(parseISOTime('14:30:60')).toBeNull();
+ expect(parseISOTime('abc')).toBeNull();
+ });
+});
+
+describe('formatISOTime', () => {
+ it('formats without seconds', () => {
+ expect(formatISOTime({hour: 14, minute: 30, second: 0})).toBe('14:30');
+ expect(formatISOTime({hour: 0, minute: 0, second: 0})).toBe('00:00');
+ expect(formatISOTime({hour: 9, minute: 5, second: 0})).toBe('09:05');
+ });
+
+ it('formats with seconds', () => {
+ expect(formatISOTime({hour: 14, minute: 30, second: 45}, true)).toBe(
+ '14:30:45',
+ );
+ expect(formatISOTime({hour: 0, minute: 0, second: 0}, true)).toBe(
+ '00:00:00',
+ );
+ expect(formatISOTime({hour: 9, minute: 5, second: 3}, true)).toBe(
+ '09:05:03',
+ );
+ });
+});
+
+describe('formatDisplayTime12h', () => {
+ it('formats AM times', () => {
+ expect(formatDisplayTime12h('00:00' as ISOTimeString)).toBe('12:00 AM');
+ expect(formatDisplayTime12h('01:30' as ISOTimeString)).toBe('1:30 AM');
+ expect(formatDisplayTime12h('11:59' as ISOTimeString)).toBe('11:59 AM');
+ });
+
+ it('formats PM times', () => {
+ expect(formatDisplayTime12h('12:00' as ISOTimeString)).toBe('12:00 PM');
+ expect(formatDisplayTime12h('13:30' as ISOTimeString)).toBe('1:30 PM');
+ expect(formatDisplayTime12h('23:59' as ISOTimeString)).toBe('11:59 PM');
+ });
+
+ it('formats with seconds', () => {
+ expect(formatDisplayTime12h('14:30:45' as ISOTimeString, true)).toBe(
+ '2:30:45 PM',
+ );
+ });
+
+ it('handles undefined', () => {
+ expect(formatDisplayTime12h(undefined)).toBe('');
+ });
+});
+
+describe('formatDisplayTime24h', () => {
+ it('formats times', () => {
+ expect(formatDisplayTime24h('00:00' as ISOTimeString)).toBe('00:00');
+ expect(formatDisplayTime24h('14:30' as ISOTimeString)).toBe('14:30');
+ expect(formatDisplayTime24h('23:59' as ISOTimeString)).toBe('23:59');
+ });
+
+ it('formats with seconds', () => {
+ expect(formatDisplayTime24h('14:30:45' as ISOTimeString, true)).toBe(
+ '14:30:45',
+ );
+ });
+
+ it('handles undefined', () => {
+ expect(formatDisplayTime24h(undefined)).toBe('');
+ });
+});
+
+describe('parseTimeInput', () => {
+ it('parses 12-hour format with AM/PM', () => {
+ expect(parseTimeInput('2:30 PM')).toBe('14:30');
+ expect(parseTimeInput('2:30pm')).toBe('14:30');
+ expect(parseTimeInput('2:30 pm')).toBe('14:30');
+ expect(parseTimeInput('12:00 AM')).toBe('00:00');
+ expect(parseTimeInput('12:00 PM')).toBe('12:00');
+ expect(parseTimeInput('11:59 PM')).toBe('23:59');
+ });
+
+ it('parses 24-hour format', () => {
+ expect(parseTimeInput('14:30')).toBe('14:30');
+ expect(parseTimeInput('00:00')).toBe('00:00');
+ expect(parseTimeInput('23:59')).toBe('23:59');
+ });
+
+ it('parses compact formats', () => {
+ expect(parseTimeInput('1430')).toBe('14:30');
+ expect(parseTimeInput('0000')).toBe('00:00');
+ });
+
+ it('parses hour-only with meridiem', () => {
+ expect(parseTimeInput('2pm')).toBe('14:00');
+ expect(parseTimeInput('2 PM')).toBe('14:00');
+ expect(parseTimeInput('12am')).toBe('00:00');
+ expect(parseTimeInput('12pm')).toBe('12:00');
+ });
+
+ it('returns null for invalid input', () => {
+ expect(parseTimeInput('')).toBeNull();
+ expect(parseTimeInput('abc')).toBeNull();
+ expect(parseTimeInput('25:00')).toBeNull();
+ expect(parseTimeInput('13:00 PM')).toBeNull(); // 13 is invalid in 12h format
+ });
+});
+
+describe('compareTime', () => {
+ it('compares times correctly', () => {
+ expect(
+ compareTime('14:30' as ISOTimeString, '14:30' as ISOTimeString),
+ ).toBe(0);
+ expect(
+ compareTime('14:30' as ISOTimeString, '14:31' as ISOTimeString),
+ ).toBeLessThan(0);
+ expect(
+ compareTime('14:31' as ISOTimeString, '14:30' as ISOTimeString),
+ ).toBeGreaterThan(0);
+ expect(
+ compareTime('00:00' as ISOTimeString, '23:59' as ISOTimeString),
+ ).toBeLessThan(0);
+ });
+
+ it('handles undefined', () => {
+ expect(compareTime(undefined, undefined)).toBe(0);
+ expect(compareTime('14:30' as ISOTimeString, undefined)).toBeGreaterThan(0);
+ expect(compareTime(undefined, '14:30' as ISOTimeString)).toBeLessThan(0);
+ });
+});
+
+describe('isTimeInRange', () => {
+ it('returns true when in range', () => {
+ expect(
+ isTimeInRange(
+ '14:30' as ISOTimeString,
+ '09:00' as ISOTimeString,
+ '18:00' as ISOTimeString,
+ ),
+ ).toBe(true);
+ expect(
+ isTimeInRange(
+ '09:00' as ISOTimeString,
+ '09:00' as ISOTimeString,
+ '18:00' as ISOTimeString,
+ ),
+ ).toBe(true);
+ expect(
+ isTimeInRange(
+ '18:00' as ISOTimeString,
+ '09:00' as ISOTimeString,
+ '18:00' as ISOTimeString,
+ ),
+ ).toBe(true);
+ });
+
+ it('returns false when out of range', () => {
+ expect(
+ isTimeInRange(
+ '08:59' as ISOTimeString,
+ '09:00' as ISOTimeString,
+ '18:00' as ISOTimeString,
+ ),
+ ).toBe(false);
+ expect(
+ isTimeInRange(
+ '18:01' as ISOTimeString,
+ '09:00' as ISOTimeString,
+ '18:00' as ISOTimeString,
+ ),
+ ).toBe(false);
+ });
+
+ it('handles undefined min/max', () => {
+ expect(isTimeInRange('14:30' as ISOTimeString, undefined, undefined)).toBe(
+ true,
+ );
+ expect(
+ isTimeInRange(
+ '14:30' as ISOTimeString,
+ '09:00' as ISOTimeString,
+ undefined,
+ ),
+ ).toBe(true);
+ expect(
+ isTimeInRange(
+ '14:30' as ISOTimeString,
+ undefined,
+ '18:00' as ISOTimeString,
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('adjustTime', () => {
+ it('adds minutes', () => {
+ expect(adjustTime('14:30' as ISOTimeString, 15)).toBe('14:45');
+ expect(adjustTime('14:30' as ISOTimeString, 30)).toBe('15:00');
+ });
+
+ it('subtracts minutes', () => {
+ expect(adjustTime('14:30' as ISOTimeString, -15)).toBe('14:15');
+ expect(adjustTime('14:30' as ISOTimeString, -30)).toBe('14:00');
+ });
+
+ it('wraps around midnight', () => {
+ expect(adjustTime('23:30' as ISOTimeString, 60)).toBe('00:30');
+ expect(adjustTime('00:30' as ISOTimeString, -60)).toBe('23:30');
+ });
+});
diff --git a/packages/core/src/utils/timeParser.ts b/packages/core/src/utils/timeParser.ts
new file mode 100644
index 0000000000..47157644fa
--- /dev/null
+++ b/packages/core/src/utils/timeParser.ts
@@ -0,0 +1,314 @@
+/**
+ * @file timeParser.ts
+ * @input Uses string parsing
+ * @output Exports time parsing and formatting utilities
+ * @position Shared utility; used by TimePicker
+ *
+ * SYNC: When modified, update this header
+ */
+
+/**
+ * ISO time string in HH:MM or HH:MM:SS format (24-hour).
+ * Examples: "14:30", "09:15:00", "23:59:59"
+ */
+export type ISOTimeString = string & {readonly __brand: 'ISOTimeString'};
+
+/**
+ * Parsed time object for internal manipulation.
+ */
+export interface ParsedTime {
+ hour: number; // 0-23
+ minute: number; // 0-59
+ second: number; // 0-59
+}
+
+/**
+ * Validates and creates an ISOTimeString from a string.
+ * Returns null if the string is not a valid time format.
+ */
+export function createISOTimeString(value: string): ISOTimeString | null {
+ const parsed = parseISOTime(value);
+ if (!parsed) return null;
+ return formatISOTime(parsed, value.split(':').length === 3);
+}
+
+/**
+ * Parses an ISO time string into a ParsedTime object.
+ * Accepts HH:MM or HH:MM:SS format.
+ */
+export function parseISOTime(time: string): ParsedTime | null {
+ if (!time) return null;
+
+ const parts = time.split(':');
+ if (parts.length < 2 || parts.length > 3) return null;
+
+ const hour = parseInt(parts[0], 10);
+ const minute = parseInt(parts[1], 10);
+ const second = parts.length === 3 ? parseInt(parts[2], 10) : 0;
+
+ if (
+ isNaN(hour) ||
+ isNaN(minute) ||
+ isNaN(second) ||
+ hour < 0 ||
+ hour > 23 ||
+ minute < 0 ||
+ minute > 59 ||
+ second < 0 ||
+ second > 59
+ ) {
+ return null;
+ }
+
+ return {hour, minute, second};
+}
+
+/**
+ * Formats a ParsedTime object into an ISOTimeString.
+ */
+export function formatISOTime(
+ time: ParsedTime,
+ includeSeconds: boolean = false,
+): ISOTimeString {
+ const hh = time.hour.toString().padStart(2, '0');
+ const mm = time.minute.toString().padStart(2, '0');
+
+ if (includeSeconds) {
+ const ss = time.second.toString().padStart(2, '0');
+ return `${hh}:${mm}:${ss}` as ISOTimeString;
+ }
+
+ return `${hh}:${mm}` as ISOTimeString;
+}
+
+/**
+ * Formats a time for display in 12-hour format.
+ * Example: "14:30" -> "2:30 PM"
+ */
+export function formatDisplayTime12h(
+ time: ISOTimeString | undefined,
+ includeSeconds: boolean = false,
+): string {
+ if (!time) return '';
+
+ const parsed = parseISOTime(time);
+ if (!parsed) return '';
+
+ const hour12 =
+ parsed.hour === 0 ? 12 : parsed.hour > 12 ? parsed.hour - 12 : parsed.hour;
+ const meridiem = parsed.hour < 12 ? 'AM' : 'PM';
+ const mm = parsed.minute.toString().padStart(2, '0');
+
+ if (includeSeconds) {
+ const ss = parsed.second.toString().padStart(2, '0');
+ return `${hour12}:${mm}:${ss} ${meridiem}`;
+ }
+
+ return `${hour12}:${mm} ${meridiem}`;
+}
+
+/**
+ * Formats a time for display in 24-hour format.
+ * Example: "14:30" -> "14:30"
+ */
+export function formatDisplayTime24h(
+ time: ISOTimeString | undefined,
+ includeSeconds: boolean = false,
+): string {
+ if (!time) return '';
+
+ const parsed = parseISOTime(time);
+ if (!parsed) return '';
+
+ const hh = parsed.hour.toString().padStart(2, '0');
+ const mm = parsed.minute.toString().padStart(2, '0');
+
+ if (includeSeconds) {
+ const ss = parsed.second.toString().padStart(2, '0');
+ return `${hh}:${mm}:${ss}`;
+ }
+
+ return `${hh}:${mm}`;
+}
+
+/**
+ * Parses user input into an ISOTimeString.
+ * Accepts various formats:
+ * - "2:30 PM", "2:30pm", "2:30 pm"
+ * - "14:30", "1430"
+ * - "2pm", "2 PM"
+ */
+export function parseTimeInput(
+ input: string,
+ includeSeconds: boolean = false,
+): ISOTimeString | null {
+ if (!input) return null;
+
+ const trimmed = input.trim().toLowerCase();
+
+ // Check for AM/PM
+ const hasMeridiem = /[ap]m?\s*$/i.test(trimmed);
+ const isPM = /p\.?m?\.?\s*$/i.test(trimmed);
+ const isAM = /a\.?m?\.?\s*$/i.test(trimmed);
+
+ // Remove AM/PM suffix
+ const timeStr = trimmed.replace(/\s*[ap]\.?m?\.?\s*$/i, '').trim();
+
+ // Handle formats like "2pm" -> "2"
+ if (/^\d{1,2}$/.test(timeStr)) {
+ const hour = parseInt(timeStr, 10);
+ if (hour >= 1 && hour <= 12 && hasMeridiem) {
+ let hour24 = hour;
+ if (isPM && hour !== 12) hour24 = hour + 12;
+ if (isAM && hour === 12) hour24 = 0;
+ return formatISOTime(
+ {hour: hour24, minute: 0, second: 0},
+ includeSeconds,
+ );
+ }
+ if (hour >= 0 && hour <= 23 && !hasMeridiem) {
+ return formatISOTime({hour, minute: 0, second: 0}, includeSeconds);
+ }
+ return null;
+ }
+
+ // Handle "1430" format
+ if (/^\d{4}$/.test(timeStr)) {
+ const hour = parseInt(timeStr.slice(0, 2), 10);
+ const minute = parseInt(timeStr.slice(2, 4), 10);
+ if (hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59) {
+ return formatISOTime({hour, minute, second: 0}, includeSeconds);
+ }
+ return null;
+ }
+
+ // Handle "143000" format (with seconds)
+ if (/^\d{6}$/.test(timeStr)) {
+ const hour = parseInt(timeStr.slice(0, 2), 10);
+ const minute = parseInt(timeStr.slice(2, 4), 10);
+ const second = parseInt(timeStr.slice(4, 6), 10);
+ if (
+ hour >= 0 &&
+ hour <= 23 &&
+ minute >= 0 &&
+ minute <= 59 &&
+ second >= 0 &&
+ second <= 59
+ ) {
+ return formatISOTime({hour, minute, second}, includeSeconds);
+ }
+ return null;
+ }
+
+ // Handle colon-separated formats
+ const colonParts = timeStr.split(':');
+ if (colonParts.length >= 2 && colonParts.length <= 3) {
+ let hour = parseInt(colonParts[0], 10);
+ const minute = parseInt(colonParts[1], 10);
+ const second = colonParts.length === 3 ? parseInt(colonParts[2], 10) : 0;
+
+ if (isNaN(hour) || isNaN(minute) || isNaN(second)) return null;
+ if (minute < 0 || minute > 59 || second < 0 || second > 59) return null;
+
+ // Convert 12h to 24h if meridiem present
+ if (hasMeridiem) {
+ if (hour < 1 || hour > 12) return null;
+ if (isPM && hour !== 12) hour += 12;
+ if (isAM && hour === 12) hour = 0;
+ } else {
+ if (hour < 0 || hour > 23) return null;
+ }
+
+ return formatISOTime({hour, minute, second}, includeSeconds);
+ }
+
+ return null;
+}
+
+/**
+ * Compares two times. Returns:
+ * - negative if a < b
+ * - 0 if a === b
+ * - positive if a > b
+ */
+export function compareTime(
+ a: ISOTimeString | undefined,
+ b: ISOTimeString | undefined,
+): number {
+ if (!a && !b) return 0;
+ if (!a) return -1;
+ if (!b) return 1;
+
+ const parsedA = parseISOTime(a);
+ const parsedB = parseISOTime(b);
+
+ if (!parsedA && !parsedB) return 0;
+ if (!parsedA) return -1;
+ if (!parsedB) return 1;
+
+ const totalA = parsedA.hour * 3600 + parsedA.minute * 60 + parsedA.second;
+ const totalB = parsedB.hour * 3600 + parsedB.minute * 60 + parsedB.second;
+
+ return totalA - totalB;
+}
+
+/**
+ * Checks if a time is within a min/max range (inclusive).
+ */
+export function isTimeInRange(
+ time: ISOTimeString,
+ min?: ISOTimeString,
+ max?: ISOTimeString,
+): boolean {
+ if (min && compareTime(time, min) < 0) return false;
+ if (max && compareTime(time, max) > 0) return false;
+ return true;
+}
+
+/**
+ * Clamps a time to a min/max range.
+ */
+export function clampTime(
+ time: ISOTimeString,
+ min?: ISOTimeString,
+ max?: ISOTimeString,
+ includeSeconds: boolean = false,
+): ISOTimeString {
+ const parsed = parseISOTime(time);
+ if (!parsed) return time;
+
+ if (min && compareTime(time, min) < 0) {
+ return formatISOTime(parseISOTime(min)!, includeSeconds);
+ }
+ if (max && compareTime(time, max) > 0) {
+ return formatISOTime(parseISOTime(max)!, includeSeconds);
+ }
+
+ return time;
+}
+
+/**
+ * Adjusts a time by adding/subtracting minutes.
+ */
+export function adjustTime(
+ time: ISOTimeString,
+ deltaMinutes: number,
+ includeSeconds: boolean = false,
+): ISOTimeString {
+ const parsed = parseISOTime(time);
+ if (!parsed) return time;
+
+ let totalMinutes = parsed.hour * 60 + parsed.minute + deltaMinutes;
+
+ // Wrap around midnight
+ while (totalMinutes < 0) totalMinutes += 24 * 60;
+ totalMinutes = totalMinutes % (24 * 60);
+
+ const newHour = Math.floor(totalMinutes / 60);
+ const newMinute = totalMinutes % 60;
+
+ return formatISOTime(
+ {hour: newHour, minute: newMinute, second: parsed.second},
+ includeSeconds,
+ );
+}