Skip to content

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

TypeScript

fix(DateInput): hardening — swarm findings (#772)

Joey29306833226c
diff --git a/packages/core/src/DateInput/DateInput.doc.mjs b/packages/core/src/DateInput/DateInput.doc.mjs
index d53c35fd8b..b97d8bf8d7 100644
--- a/packages/core/src/DateInput/DateInput.doc.mjs
+++ b/packages/core/src/DateInput/DateInput.doc.mjs
@@ -110,6 +110,17 @@ export const docs = {
type: '(value: ISODateString | undefined) => void',
description: 'Callback invoked when the selected date changes.',
},
+ {
+ name: 'onChangeAction',
+ type: '(value: ISODateString | undefined) => void | Promise<void>',
+ description: 'Async action fired after onChange. Drives optimistic UI updates via useTransition.',
+ },
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ description: 'Whether the input is in a loading state. Disables interaction and shows a spinner.',
+ default: 'false',
+ },
{
name: 'min',
type: 'ISODateString',
@@ -144,6 +155,11 @@ export const docs = {
description:
'Status indicator object for error, warning, or success states with a message.',
},
+ {
+ name: 'labelTooltip',
+ type: 'string',
+ description: 'Tooltip text displayed via an info icon at the end of the label.',
+ },
{
name: 'numberOfMonths',
type: '1 | 2',
@@ -159,7 +175,7 @@ export const docs = {
},
],
keyboard:
- 'Tab moves between input and calendar icon button; Enter/Space on icon opens the calendar and moves focus into it; Escape closes the calendar popover; Arrow keys navigate between days; Page Up/Down navigate between months.',
+ 'Tab moves between input and calendar icon button; Enter/Space on icon opens/closes the calendar; Escape closes the calendar popover; Arrow keys navigate between days; Page Up/Down navigate between months.',
notes: [
'The text input accepts multiple date formats: ISO (2026-01-28), US (01/28/2026, 1/28/2026), and written (Jan 28, 2026 / January 28 2026).',
'Invalid input reverts to the previous valid value on blur.',
@@ -282,6 +298,17 @@ export const docsZh = {
type: '(value: ISODateString | undefined) => void',
description: '选中日期变更时调用的回调。',
},
+ {
+ name: 'onChangeAction',
+ type: '(value: ISODateString | undefined) => void | Promise<void>',
+ description: '在 onChange 之后触发的异步操作。通过 useTransition 驱动乐观更新。',
+ },
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ description: '输入框是否处于加载状态。禁用交互并显示加载指示器。',
+ default: 'false',
+ },
{
name: 'min',
type: 'ISODateString',
@@ -316,6 +343,11 @@ export const docsZh = {
description:
'错误、警告或成功状态的状态指示对象,附带消息。',
},
+ {
+ name: 'labelTooltip',
+ type: 'string',
+ description: '通过标签末尾的信息图标显示的提示文本。',
+ },
{
name: 'numberOfMonths',
type: '1 | 2',
@@ -331,7 +363,7 @@ export const docsZh = {
},
],
keyboard:
- 'Tab 在输入框和日历图标按钮间移动;Enter/Space 点击图标打开日历并将焦点移入;Escape 关闭日历弹出层;方向键在日期间导航;Page Up/Down 在月份间导航。',
+ 'Tab 在输入框和日历图标按钮间移动;Enter/Space 点击图标打开/关闭日历;Escape 关闭日历弹出层;方向键在日期间导航;Page Up/Down 在月份间导航。',
notes: [
'文本输入接受多种日期格式:ISO(2026-01-28)、美式(01/28/2026、1/28/2026)和书面格式(Jan 28, 2026 / January 28 2026)。',
'无效输入在失焦时恢复为上一个有效值。',
@@ -354,7 +386,7 @@ export const docsDense = {
'full keyboard nav, focus trapping, screen reader support',
'built on XDSField for consistent label, description, validation',
],
- keyboard: 'Tab=move between input+calendar icon; Enter/Space on icon=open calendar; Escape=close; Arrow keys=navigate days; PageUp/Down=navigate months',
+ keyboard: 'Tab=move between input+calendar icon; Enter/Space on icon=open/close calendar; Escape=close; Arrow keys=navigate days; PageUp/Down=navigate months',
notes: [
'accepts multiple date formats: ISO (2026-01-28), US (01/28/2026, 1/28/2026), written (Jan 28, 2026 / January 28 2026)',
'invalid input reverts to previous valid value on blur',
@@ -368,12 +400,15 @@ export const docsDense = {
isDisabled: 'disable input+calendar',
value: 'selected date YYYY-MM-DD',
onChange: 'callback on date change',
+ onChangeAction: 'async action after onChange; drives optimistic UI',
+ isLoading: 'loading state; disables interaction, shows spinner',
min: 'min selectable date (YYYY-MM-DD)',
max: 'max selectable date (YYYY-MM-DD)',
dateConstraints: 'custom constraint fns to disable specific dates',
placeholder: 'placeholder text in input',
size: 'input control size',
status: 'error/warning/success status w/ message',
+ labelTooltip: 'tooltip text via info icon at label end',
numberOfMonths: 'months shown simultaneously in calendar popover',
xstyle: 'StyleX styles for layout; must be stylex.create() value',
},
diff --git a/packages/core/src/DateInput/XDSDateInput.test.tsx b/packages/core/src/DateInput/XDSDateInput.test.tsx
index 839306c3c4..ae210c55ed 100644
--- a/packages/core/src/DateInput/XDSDateInput.test.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.test.tsx
@@ -56,7 +56,7 @@ describe('XDSDateInput', () => {
it('sets aria-required when isRequired is true', () => {
render(<XDSDateInput label="Date" isRequired onChange={() => {}} />);
- expect(screen.getByRole('textbox')).toHaveAttribute(
+ expect(screen.getByRole('combobox')).toHaveAttribute(
'aria-required',
'true',
);
@@ -64,17 +64,17 @@ describe('XDSDateInput', () => {
it('does not set aria-required when isRequired is false', () => {
render(<XDSDateInput label="Date" onChange={() => {}} />);
- expect(screen.getByRole('textbox')).not.toHaveAttribute('aria-required');
+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-required');
});
it('sets disabled attribute when isDisabled is true', () => {
render(<XDSDateInput label="Date" isDisabled onChange={() => {}} />);
- expect(screen.getByRole('textbox')).toBeDisabled();
+ expect(screen.getByRole('combobox')).toBeDisabled();
});
it('is not disabled by default', () => {
render(<XDSDateInput label="Date" onChange={() => {}} />);
- expect(screen.getByRole('textbox')).not.toBeDisabled();
+ expect(screen.getByRole('combobox')).not.toBeDisabled();
});
it('renders calendar icon', () => {
@@ -83,9 +83,9 @@ describe('XDSDateInput', () => {
expect(svg).toBeInTheDocument();
});
- it('calendar button has aria-haspopup="dialog" attribute', () => {
+ it('combobox input has aria-haspopup="dialog" attribute', () => {
render(<XDSDateInput label="Date" onChange={() => {}} />);
- expect(screen.getByRole('button', {name: 'Open calendar'})).toHaveAttribute(
+ expect(screen.getByRole('combobox')).toHaveAttribute(
'aria-haspopup',
'dialog',
);
@@ -108,11 +108,9 @@ describe('XDSDateInput', () => {
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)
+ const input = screen.getByRole('combobox');
fireEvent.change(input, {target: {value: 'invalid'}});
- // onChange should not be called while typing
expect(onChange).not.toHaveBeenCalled();
});
@@ -122,12 +120,10 @@ describe('XDSDateInput', () => {
<XDSDateInput label="Date" value="2026-01-25" onChange={onChange} />,
);
- const input = screen.getByRole('textbox');
- // Use fireEvent to avoid triggering click handler (which opens popover)
+ const input = screen.getByRole('combobox');
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();
});
@@ -136,8 +132,7 @@ describe('XDSDateInput', () => {
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)
+ const input = screen.getByRole('combobox');
fireEvent.change(input, {target: {value: '03/15/2026'}});
fireEvent.blur(input);
@@ -148,15 +143,311 @@ describe('XDSDateInput', () => {
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)
+ const input = screen.getByRole('combobox');
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.
+ // --- P0: Text input respects min/max/dateConstraints ---
+
+ it('does not call onChange when typed date is before min', () => {
+ const onChange = vi.fn();
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={onChange}
+ min="2026-03-01"
+ max="2026-12-31"
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: '02/15/2026'}});
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('does not call onChange when typed date is after max', () => {
+ const onChange = vi.fn();
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={onChange}
+ min="2026-01-01"
+ max="2026-03-01"
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: '04/15/2026'}});
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('does not call onChange when typed date fails dateConstraints', () => {
+ const onChange = vi.fn();
+ // Constraint: no weekends
+ const noWeekends = (date: Date) =>
+ date.getDay() !== 0 && date.getDay() !== 6;
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={onChange}
+ dateConstraints={[noWeekends]}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ // 2026-03-15 is a Sunday
+ fireEvent.change(input, {target: {value: '03/15/2026'}});
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('calls onChange when typed date is within min/max range', () => {
+ const onChange = vi.fn();
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={onChange}
+ min="2026-01-01"
+ max="2026-12-31"
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: '06/15/2026'}});
+
+ expect(onChange).toHaveBeenCalledWith('2026-06-15');
+ });
+
+ it('reverts on blur when typed date violates constraints', () => {
+ const onChange = vi.fn();
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={onChange}
+ value="2026-03-10"
+ min="2026-03-01"
+ max="2026-03-31"
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: '04/15/2026'}});
+ fireEvent.blur(input);
+
+ // Should revert to previous value
+ expect(screen.getByDisplayValue('March 10, 2026')).toBeInTheDocument();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ // --- P1: Input disabled during isBusy (isLoading) ---
+
+ it('disables input and button when isLoading is true', () => {
+ render(<XDSDateInput label="Date" isLoading onChange={() => {}} />);
+ expect(screen.getByRole('combobox')).toBeDisabled();
+ expect(screen.getByRole('button', {name: 'Open calendar'})).toBeDisabled();
+ });
+
+ it('shows spinner when isLoading is true', () => {
+ const {container} = render(
+ <XDSDateInput label="Date" isLoading onChange={() => {}} />,
+ );
+ // XDSSpinner renders with role="status" or an SVG animation
+ const spinner = container.querySelector('[aria-busy="true"]');
+ expect(spinner).toBeInTheDocument();
+ });
+
+ // --- P1: Escape key handler ---
+
+ it('handles Escape keydown without error', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ const input = screen.getByRole('combobox');
+
+ // Escape should not throw even when popover isn't open.
+ // Full popover open/close behavior tested in Storybook.
+ fireEvent.keyDown(input, {key: 'Escape'});
+ });
+
+ // --- P2: Input has role="combobox" ---
+
+ it('input has role="combobox"', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ });
+
+ it('input has aria-expanded attribute', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('combobox')).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+
+ it('input has aria-haspopup="dialog"', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('combobox')).toHaveAttribute(
+ 'aria-haspopup',
+ 'dialog',
+ );
+ });
+
+ // --- P1: Tab order input-first, button-second ---
+
+ it('renders input before button in DOM order', () => {
+ const {container} = render(
+ <XDSDateInput label="Date" onChange={() => {}} />,
+ );
+ const input = container.querySelector('input');
+ const button = container.querySelector('button');
+ // Input should come before button in the DOM
+ expect(input!.compareDocumentPosition(button!)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ });
+
+ // --- P2: Status rendering ---
+
+ it('renders status icon for error status', () => {
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={() => {}}
+ status={{type: 'error', message: 'Bad date'}}
+ />,
+ );
+ expect(screen.getByRole('combobox')).toHaveAttribute(
+ 'aria-invalid',
+ 'true',
+ );
+ });
+
+ it('renders status icon for warning status', () => {
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={() => {}}
+ status={{type: 'warning', message: 'Watch out'}}
+ />,
+ );
+ // Should not be aria-invalid for warnings
+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-invalid');
+ });
+
+ it('renders status icon for success status', () => {
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={() => {}}
+ status={{type: 'success', message: 'Looks good'}}
+ />,
+ );
+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-invalid');
+ });
+
+ // --- P1: Description and aria-describedby ---
+
+ it('renders description and links via aria-describedby', () => {
+ render(
+ <XDSDateInput
+ label="Date"
+ description="Pick your preferred date"
+ onChange={() => {}}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ expect(screen.getByText('Pick your preferred date')).toBeInTheDocument();
+ expect(input).toHaveAttribute('aria-describedby');
+ const describedBy = input.getAttribute('aria-describedby')!;
+ const descEl = document.getElementById(describedBy);
+ expect(descEl).toHaveTextContent('Pick your preferred date');
+ });
+
+ it('links status message via aria-describedby', () => {
+ render(
+ <XDSDateInput
+ label="Date"
+ onChange={() => {}}
+ status={{type: 'error', message: 'Invalid date'}}
+ />,
+ );
+ const input = screen.getByRole('combobox');
+ const describedBy = input.getAttribute('aria-describedby')!;
+ const ids = describedBy.split(' ');
+ const found = ids.some(id => {
+ const el = document.getElementById(id);
+ return el?.textContent?.includes('Invalid date');
+ });
+ expect(found).toBe(true);
+ });
+
+ // --- P1: Clearing value on empty blur ---
+
+ it('calls onChange with undefined when input is cleared and blurred', () => {
+ const onChange = vi.fn();
+ render(
+ <XDSDateInput label="Date" value="2026-01-25" onChange={onChange} />,
+ );
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: ''}});
+ fireEvent.blur(input);
+
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ });
+
+ // --- P1: Disabled prevents onChange ---
+
+ it('disables input when isDisabled is true', () => {
+ render(<XDSDateInput label="Date" isDisabled onChange={() => {}} />);
+
+ const input = screen.getByRole('combobox');
+ expect(input).toBeDisabled();
+ });
+
+ // --- P1: aria-busy on input ---
+
+ it('sets aria-busy on input when isLoading is true', () => {
+ render(<XDSDateInput label="Date" isLoading onChange={() => {}} />);
+ expect(screen.getByRole('combobox')).toHaveAttribute('aria-busy', 'true');
+ });
+
+ it('does not set aria-busy when not loading', () => {
+ render(<XDSDateInput label="Date" onChange={() => {}} />);
+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-busy');
+ });
+
+ // --- P1: Popover does not open when disabled ---
+
+ it('does not open popover when clicking calendar button while disabled', () => {
+ render(<XDSDateInput label="Date" isDisabled onChange={() => {}} />);
+ const button = screen.getByRole('button', {name: 'Open calendar'});
+ fireEvent.click(button);
+ expect(screen.getByRole('combobox')).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+
+ // --- Enter key commits typed date ---
+
+ it('commits typed date and fires onChange on Enter key', () => {
+ const onChange = vi.fn();
+ render(<XDSDateInput label="Date" onChange={onChange} />);
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: '03/15/2026'}});
+ onChange.mockClear();
+ fireEvent.keyDown(input, {key: 'Enter'});
+
+ expect(onChange).toHaveBeenCalledWith('2026-03-15');
+ });
+
+ // --- Arrow-down opens calendar popover ---
+
+ // Note: Tests involving popover rendering (show/hide with calendar)
+ // are limited because jsdom doesn't support the Popover API.
+ // Full popover interaction is tested in the browser via Storybook.
});
diff --git a/packages/core/src/DateInput/XDSDateInput.tsx b/packages/core/src/DateInput/XDSDateInput.tsx
index 6288988511..9c38d49940 100644
--- a/packages/core/src/DateInput/XDSDateInput.tsx
+++ b/packages/core/src/DateInput/XDSDateInput.tsx
@@ -13,13 +13,12 @@
* - /apps/storybook/stories/DateInput.stories.tsx (storybook stories)
*/
-
import {
useId,
useState,
useCallback,
+ useEffect,
useRef,
- useMemo,
useOptimistic,
useTransition,
} from 'react';
@@ -50,8 +49,9 @@ import {
type ISODateString,
type XDSCalendarHandle,
} from '../Calendar';
+import {useCalendarConstraints} from '../Calendar/hooks';
import {useXDSPopover} from '../Popover';
-import {parseDateInput, formatDisplayDate} from '../utils';
+import {parseDateInput, formatDisplayDate, parseISO} from '../utils';
const styles = stylex.create({
iconButton: {
@@ -272,16 +272,19 @@ export function XDSDateInput({
className,
style,
ref,
+ ...rest
}: XDSDateInputProps) {
const id = useId();
const descriptionID = useId();
const statusMessageID = useId();
const inputRef = useRef<HTMLInputElement | null>(null);
const calendarRef = useRef<XDSCalendarHandle | null>(null);
+ const lastFiredValueRef = useRef<ISODateString | undefined>(undefined);
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
const isBusy = isLoading || optimisticValue !== value;
+ const isEffectivelyDisabled = isDisabled || isBusy;
// Status icon mapping
const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {
@@ -299,6 +302,9 @@ export function XDSDateInput({
success: 'positive',
};
+ // Constraint checking for text input validation (reuses calendar logic)
+ const {isDateDisabled} = useCalendarConstraints({min, max, dateConstraints});
+
const ariaDescribedBy =
[
description ? descriptionID : null,
@@ -310,53 +316,58 @@ export function XDSDateInput({
// Pending input while user is typing (null = show formatted value)
const [pendingInput, setPendingInput] = useState<string | null>(null);
- // Display value: pending input if typing, otherwise formatted value
- const displayValue = useMemo(() => {
- if (pendingInput !== null) {
- return pendingInput;
+ // Clear pending input when value changes externally
+ useEffect(() => {
+ if (value === lastFiredValueRef.current) {
+ return;
}
- return optimisticValue ? formatDisplayDate(optimisticValue) : '';
- }, [pendingInput, optimisticValue]);
+ lastFiredValueRef.current = undefined;
+ setPendingInput(null);
+ }, [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]);
+ // Display value: pending input if typing, otherwise formatted value
+ const displayValue =
+ pendingInput !== null
+ ? pendingInput
+ : optimisticValue && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
+ ? formatDisplayDate(optimisticValue)
+ : '';
- // Use XDSPopover for popover rendering, positioning, and focus trapping
- const handlePopoverHide = useCallback(() => {
- // Return focus to input when popover closes
- inputRef.current?.focus();
- }, []);
+ // Check if current input is valid (for styling purposes)
+ const isInputValid =
+ pendingInput === null || !pendingInput.trim()
+ ? true
+ : parseDateInput(pendingInput) !== null;
const popover = useXDSPopover({
xstyle: styles.popover,
dialogLabel: 'Choose date',
closeButtonLabel: 'Close calendar',
- onHide: handlePopoverHide,
+ onHide: () => inputRef.current?.focus(),
});
- // Handle opening the popover from button click (focus calendar)
- const handleOpen = useCallback(() => {
- if (!isDisabled && !popover.isOpen) {
- popover.show();
+ // Handle toggling the popover from button click (focus calendar)
+ const handleToggle = useCallback(() => {
+ if (!isEffectivelyDisabled) {
+ if (popover.isOpen) {
+ popover.hide();
+ } else {
+ popover.show();
+ }
}
- }, [isDisabled, popover]);
+ }, [isEffectivelyDisabled, popover]);
// Handle opening the popover from input click (keep focus in input)
const handleInputClick = useCallback(() => {
- if (!isDisabled && !popover.isOpen) {
+ if (!isEffectivelyDisabled && !popover.isOpen) {
popover.show({skipAutoFocus: true});
}
- }, [isDisabled, popover]);
+ }, [isEffectivelyDisabled, popover]);
// Unified change handler that fires both onChange and onChangeAction
const fireChange = useCallback(
(newValue: ISODateString | undefined) => {
+ if (isBusy) return;
onChange?.(newValue);
if (onChangeAction) {
startTransition(async () => {
@@ -365,7 +376,7 @@ export function XDSDateInput({
});
}
},
- [onChange, onChangeAction, startTransition, setOptimisticValue],
+ [isBusy, onChange, onChangeAction, startTransition, setOptimisticValue],
);
// Handle date selection from calendar
@@ -378,31 +389,31 @@ export function XDSDateInput({
[fireChange, popover],
);
- // Handle input text change - update immediately if valid
+ // Handle input text change - update immediately if valid and allowed
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)
+ // If the input is valid and passes constraints, update immediately
const parsed = parseDateInput(newValue);
- if (parsed && parsed !== value) {
+ if (parsed && parsed !== value && !isDateDisabled(parseISO(parsed))) {
+ lastFiredValueRef.current = parsed;
fireChange(parsed);
// Navigate calendar to show the parsed date's month
calendarRef.current?.navigateTo(parsed);
}
},
- [value, fireChange],
+ [value, fireChange, isDateDisabled],
);
- // Handle blur - validate and clear pending input
- const handleBlur = useCallback(() => {
+ // Commit pending input (shared by blur and Enter key)
+ const commitPendingInput = useCallback(() => {
if (pendingInput === null) {
return;
}
if (!pendingInput.trim()) {
- // Empty input clears the value
if (value !== undefined) {
fireChange(undefined);
}
@@ -411,15 +422,18 @@ export function XDSDateInput({
}
const parsed = parseDateInput(pendingInput);
- if (parsed) {
- // Valid date - update if different
+ if (parsed && !isDateDisabled(parseISO(parsed))) {
if (parsed !== value) {
fireChange(parsed);
}
}
- // Clear pending input - display will revert to formatted value
setPendingInput(null);
- }, [pendingInput, value, fireChange]);
+ }, [pendingInput, value, fireChange, isDateDisabled]);
+
+ // Handle blur - validate, check constraints, and clear pending input
+ const handleBlur = useCallback(() => {
+ commitPendingInput();
+ }, [commitPendingInput]);
// Handle keyboard events on input
const handleInputKeyDown = useCallback(
@@ -427,9 +441,12 @@ export function XDSDateInput({
if (e.key === 'Escape' && popover.isOpen) {
e.preventDefault();
popover.hide();
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ commitPendingInput();
}
},
- [popover],
+ [popover, commitPendingInput],
);
// Combine refs
@@ -466,12 +483,13 @@ export function XDSDateInput({
labelTooltip={labelTooltip}>
<div
ref={popover.triggerRef}
+ {...rest}
{...mergeProps(
xdsClassName('date-input', {size}),
stylex.props(
inputWrapperStyles.base,
sizeStyles[size],
- isDisabled && inputWrapperStyles.disabled,
+ isEffectivelyDisabled && inputWrapperStyles.disabled,
status && inputStatusBorderStyles[status.type],
status && inputStatusHoverShadowStyles[status.type],
status && inputStatusFocusWithinStyles[status.type],
@@ -480,40 +498,44 @@ export function XDSDateInput({
className,
style,
)}>
- <button
- type="button"
- onClick={handleOpen}
- disabled={isDisabled}
- aria-label="Open calendar"
- {...popover.triggerProps}
- {...stylex.props(
- styles.iconButton,
- isDisabled && styles.iconButtonDisabled,
- )}>
- <XDSIcon icon="calendar" size="sm" color="secondary" />
- </button>
<input
ref={setRefs}
id={id}
type="text"
+ role="combobox"
value={displayValue}
onChange={handleInputChange}
onBlur={handleBlur}
onClick={handleInputClick}
onKeyDown={handleInputKeyDown}
placeholder={placeholder}
- disabled={isDisabled}
+ disabled={isEffectivelyDisabled}
aria-describedby={ariaDescribedBy}
aria-required={isRequired === true ? 'true' : undefined}
aria-invalid={status?.type === 'error' ? 'true' : undefined}
aria-busy={isBusy || undefined}
+ aria-expanded={popover.isOpen}
+ aria-haspopup="dialog"
+ aria-controls={popover.isOpen ? popover.id : undefined}
+ aria-autocomplete="none"
autoComplete="off"
{...stylex.props(
styles.input,
- isDisabled && styles.inputDisabled,
+ isEffectivelyDisabled && styles.inputDisabled,
!isInputValid && styles.inputInvalid,
)}
/>
+ <button
+ type="button"
+ onClick={handleToggle}
+ disabled={isEffectivelyDisabled}
+ aria-label={popover.isOpen ? 'Close calendar' : 'Open calendar'}
+ {...stylex.props(
+ styles.iconButton,
+ isEffectivelyDisabled && styles.iconButtonDisabled,
+ )}>
+ <XDSIcon icon="calendar" size="sm" color="secondary" />
+ </button>
{isBusy && <XDSSpinner size="sm" />}
{status && (
<XDSIcon
@@ -527,7 +549,7 @@ export function XDSDateInput({
<XDSCalendar
ref={calendarRef}
mode="single"
- value={value}
+ value={optimisticValue}
onChange={handleDateSelect}
min={min}
max={max}
diff --git a/packages/core/src/utils/dateParser.test.ts b/packages/core/src/utils/dateParser.test.ts
index 1be083dfd0..07e1c0e43a 100644
--- a/packages/core/src/utils/dateParser.test.ts
+++ b/packages/core/src/utils/dateParser.test.ts
@@ -159,6 +159,14 @@ describe('parseDateInput', () => {
expect(parseDateInput('February 29, 2025')).toBeNull(); // Not a leap year
expect(parseDateInput('February 30, 2024')).toBeNull();
});
+
+ it('preserves years 0-99 literally instead of mapping to 1900s', () => {
+ expect(parseDateInput('01/01/0050')).toBe('0050-01-01');
+ });
+
+ it('rejects mixed separators', () => {
+ expect(parseDateInput('1/25.2026')).toBeNull();
+ });
});
});
diff --git a/packages/core/src/utils/dateParser.ts b/packages/core/src/utils/dateParser.ts
index b8dfd371b3..3b1897bc14 100644
--- a/packages/core/src/utils/dateParser.ts
+++ b/packages/core/src/utils/dateParser.ts
@@ -97,10 +97,12 @@ export function parseDateInput(input: string): ISODateString | null {
// 4. Try numeric formats with separators (/, -, .) WITH year
const numericWithYearMatch = trimmed.match(
- /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/,
+ /^(\d{1,2})([-/.])(\d{1,2})([-/.])(\d{4})$/,
);
if (numericWithYearMatch) {
- const [, first, second, year] = numericWithYearMatch;
+ const [, first, sep1, second, sep2, year] = numericWithYearMatch;
+ // Reject mixed separators (e.g., "1/25.2026")
+ if (sep1 !== sep2) return null;
return parseNumericDate(+first, +second, +year);
}
@@ -207,6 +209,8 @@ function createISODate(
}
const date = new Date(year, month - 1, day);
+ // new Date(year, ...) treats 0-99 as 1900s; fix with setFullYear
+ date.setFullYear(year);
// Validate the date didn't overflow (e.g., Feb 30 → Mar 2)
if (
@@ -224,7 +228,7 @@ function createISODate(
* Converts a Date object to ISO date string.
*/
export function dateToISO(date: Date): ISODateString {
- const year = date.getFullYear();
+ const year = String(date.getFullYear()).padStart(4, '0');
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}` as ISODateString;
@@ -249,7 +253,7 @@ export function parseISO(iso: ISODateString): Date {
*/
export function formatDisplayDate(iso: ISODateString): string {
const date = parseISO(iso);
- return new Intl.DateTimeFormat('en-US', {
+ return new Intl.DateTimeFormat(undefined, {
year: 'numeric',
month: 'long',
day: 'numeric',