An open source design system that's fully customizable and agent ready
TypeScript
feat(DateTimePicker): add XDSDateTimePicker component (#183) (#2199)
Andrey Goder14191d8eaea6
diff --git a/apps/storybook/stories/DateTimePicker.stories.tsx b/apps/storybook/stories/DateTimePicker.stories.tsxnew file mode 100644index 0000000000..83afc98441--- /dev/null+++ b/apps/storybook/stories/DateTimePicker.stories.tsx@@ -0,0 +1,366 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSDateTimePicker} from '@xds/core/DateTimePicker';+import type {ISODateTimeString} from '@xds/core/DateTimePicker';++const meta: Meta<typeof XDSDateTimePicker> = {+ title: 'Core/Inputs/DateTimePicker',+ component: XDSDateTimePicker,+ 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',+ },+ numberOfMonths: {+ control: 'radio',+ options: [1, 2],+ description: 'Number of months to display in calendar',+ },+ timeIncrement: {+ control: 'number',+ description: 'Minutes to increment/decrement with arrow keys',+ },+ },+};++export default meta;+type Story = StoryObj<typeof XDSDateTimePicker>;++export const Default: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ undefined,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Meeting time',+ placeholder: 'Select a date',+ },+};++export const WithValue: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T14:30' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Event time',+ },+};++export const TwentyFourHourFormat: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T14:30' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Appointment',+ hourFormat: '24h',+ },+};++export const WithSeconds: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T14:30:45' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Log timestamp',+ hasSeconds: true,+ },+};++export const WithDescription: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ undefined,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Deadline',+ description: 'When is this task due?',+ placeholder: 'Select deadline',+ },+};++export const WithClearButton: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T09:00' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Start time',+ hasClear: true,+ },+};++export const WithMinMax: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ undefined,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Appointment',+ min: '2026-03-15T09:00' as ISODateTimeString,+ max: '2026-03-15T17:00' as ISODateTimeString,+ description: 'Available: Mar 15, 9 AM - 5 PM',+ },+};++export const WithTimeIncrement: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T09:00' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Time slot',+ timeIncrement: 15,+ description: 'Use arrow keys to change by 15 minutes',+ },+};++export const Optional: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ undefined,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Preferred time',+ isOptional: true,+ placeholder: 'Select a date (optional)',+ },+};++export const Required: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ undefined,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Start time',+ isRequired: true,+ },+};++export const Disabled: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T10:00' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Locked time',+ isDisabled: true,+ },+};++export const SmallSize: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ undefined,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Time',+ size: 'sm',+ },+};++export const TwoMonthCalendar: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ undefined,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Travel departure',+ numberOfMonths: 2,+ },+};++export const WithErrorStatus: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T14:30' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...args} value={value} onChange={setValue} />;+ },+ args: {+ label: 'Event time',+ status: {+ type: 'error',+ message: 'This time slot is not available',+ },+ },+};++export const WithWarningStatus: Story = {+ render: args => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T07:00' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...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<ISODateTimeString | undefined>(+ '2026-03-15T10:00' as ISODateTimeString,+ );+ return <XDSDateTimePicker {...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<ISODateTimeString | undefined>(+ undefined,+ );+ const [value2, setValue2] = useState<ISODateTimeString | undefined>(+ '2026-03-15T14:30' as ISODateTimeString,+ );+ const [value3, setValue3] = useState<ISODateTimeString | undefined>(+ '2026-03-15T14:30' as ISODateTimeString,+ );+ const [value4, setValue4] = useState<ISODateTimeString | undefined>(+ undefined,+ );+ const [value5, setValue5] = useState<ISODateTimeString | undefined>(+ '2026-03-15T10:00' as ISODateTimeString,+ );+ const [value6, setValue6] = useState<ISODateTimeString | undefined>(+ '2026-03-15T22:00' as ISODateTimeString,+ );++ return (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: '16px',+ maxWidth: '460px',+ }}>+ <XDSDateTimePicker+ label="Default"+ value={value1}+ onChange={setValue1}+ placeholder="Select a date"+ />+ <XDSDateTimePicker+ label="With value (12h)"+ value={value2}+ onChange={setValue2}+ />+ <XDSDateTimePicker+ label="24-hour format"+ value={value3}+ onChange={setValue3}+ hourFormat="24h"+ />+ <XDSDateTimePicker+ label="With description"+ description="Pick your preferred datetime"+ value={value4}+ onChange={setValue4}+ />+ <XDSDateTimePicker+ label="Disabled"+ isDisabled+ value={value5}+ onChange={setValue5}+ />+ <XDSDateTimePicker+ label="With error"+ value={value6}+ onChange={setValue6}+ status={{+ type: 'error',+ message: 'Invalid datetime selection',+ }}+ />+ </div>+ );+ },+};diff --git a/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.doc.mjs b/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.doc.mjsnew file mode 100644index 0000000000..54b7c2fdea--- /dev/null+++ b/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.doc.mjs@@ -0,0 +1,12 @@+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'DateTimePicker',+ name: 'DateTimePicker',+ description:+ 'A combined date and time picker. Click to open a calendar popover with a time input below.',+ isReady: true,+ isShowcase: true,+ aspectRatio: 1,+ componentsUsed: ['DateTimePicker', 'Layout'],+};diff --git a/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.tsx b/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.tsxnew file mode 100644index 0000000000..f27c94ba20--- /dev/null+++ b/packages/cli/templates/blocks/components/DateTimePicker/DateTimePickerShowcase.tsx@@ -0,0 +1,24 @@+'use client';++import {useState} from 'react';+import {XDSDateTimePicker} from '@xds/core/DateTimePicker';+import type {ISODateTimeString} from '@xds/core/DateTimePicker';+import {XDSStack} from '@xds/core/Layout';++export default function DateTimePickerShowcase() {+ const [dateTime, setDateTime] = useState<ISODateTimeString | undefined>(+ undefined,+ );++ return (+ <XDSStack direction="vertical" width="100%" style={{maxWidth: 400}}>+ <XDSDateTimePicker+ label="Meeting time"+ placeholder="Select a date"+ value={dateTime}+ onChange={setDateTime}+ hasClear+ />+ </XDSStack>+ );+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 791b0f8893..d79d2c464c 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -199,6 +199,12 @@"import": "./dist/DateInput/index.mjs","require": "./dist/DateInput/index.js"},+ "./DateTimePicker": {+ "source": "./src/DateTimePicker/index.ts",+ "types": "./dist/DateTimePicker/index.d.ts",+ "import": "./dist/DateTimePicker/index.mjs",+ "require": "./dist/DateTimePicker/index.js"+ },"./Dialog": {"source": "./src/Dialog/index.ts","types": "./dist/Dialog/index.d.ts",diff --git a/packages/core/src/DateInput/XDSDateInput.tsx b/packages/core/src/DateInput/XDSDateInput.tsxindex 046a34c4b9..c106041a7f 100644--- a/packages/core/src/DateInput/XDSDateInput.tsx+++ b/packages/core/src/DateInput/XDSDateInput.tsx@@ -107,12 +107,15 @@ const styles = stylex.create({const sizeStyles = stylex.create({sm: {height: sizeVars['--size-element-sm'],+ minWidth: 180,},md: {height: sizeVars['--size-element-md'],+ minWidth: 180,},lg: {height: sizeVars['--size-element-lg'],+ minWidth: 180,},});diff --git a/packages/core/src/DateTimePicker/DateTimePicker.doc.mjs b/packages/core/src/DateTimePicker/DateTimePicker.doc.mjsnew file mode 100644index 0000000000..36bc354bf6--- /dev/null+++ b/packages/core/src/DateTimePicker/DateTimePicker.doc.mjs@@ -0,0 +1,250 @@+/** @type {import('../docs-types').ComponentDoc} */++export const docs = {+ name: 'DateTimePicker',+ keywords: ["datetimepicker","datetime","datepicker","timepicker","calendar","schedule","event","deadline","timestamp"],+ props: [+ {+ name: 'label',+ type: 'string',+ description: 'Label text.',+ required: true,+ },+ {+ name: 'isLabelHidden',+ type: 'boolean',+ description: 'Visually hide the label.',+ default: 'false',+ },+ {+ name: 'description',+ type: 'string',+ description: 'Helper text displayed below the label.',+ },+ {+ name: 'isOptional',+ type: 'boolean',+ description: 'Show an "(optional)" indicator next to the label.',+ default: 'false',+ },+ {+ name: 'isRequired',+ type: 'boolean',+ description: 'Mark the field as required.',+ default: 'false',+ },+ {+ name: 'isDisabled',+ type: 'boolean',+ description: 'Disable the input and picker.',+ default: 'false',+ },+ {+ name: 'value',+ type: 'ISODateTimeString',+ description: 'Selected datetime in ISO 8601 format (YYYY-MM-DDTHH:MM or YYYY-MM-DDTHH:MM:SS).',+ },+ {+ name: 'onChange',+ type: '(value: ISODateTimeString | undefined) => void',+ description: 'Callback invoked when the selected datetime changes.',+ required: true,+ },+ {+ name: 'changeAction',+ type: '(value: ISODateTimeString | 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: 'ISODateTimeString',+ description: 'Minimum selectable datetime. Constrains both date and time selection.',+ },+ {+ name: 'max',+ type: 'ISODateTimeString',+ description: 'Maximum selectable datetime. Constrains both date and time selection.',+ },+ {+ name: 'dateConstraints',+ type: 'Array<(date: Date) => boolean>',+ description: 'Array of custom constraint functions that disable specific dates.',+ },+ {+ name: 'hasSeconds',+ type: 'boolean',+ description: 'Include seconds in the time portion.',+ default: 'false',+ },+ {+ name: 'hourFormat',+ type: "'12h' | '24h'",+ description: "Hour display format. '12h' shows AM/PM; '24h' uses 24-hour notation.",+ default: "'12h'",+ },+ {+ name: 'timeIncrement',+ type: 'number',+ description: 'Minutes to add or subtract when using arrow keys in the time input.',+ default: '1',+ },+ {+ name: 'hasClear',+ type: 'boolean',+ description: 'Shows a clear button when a datetime value is set.',+ default: 'false',+ },+ {+ name: 'placeholder',+ type: 'string',+ description: 'Placeholder text shown when no datetime is selected.',+ default: "'Select a date'",+ },+ {+ name: 'size',+ type: "'sm' | 'md'",+ description: 'Size of the input control.',+ default: "'md'",+ },+ {+ name: 'status',+ type: 'XDSInputStatus',+ 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',+ description: 'Number of months displayed simultaneously in the calendar.',+ default: '1',+ },+ {+ name: 'xstyle',+ type: 'StyleXStyles',+ description:+ 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value — not an inline style object like style={{}}.',+ },+ ],+ theming: {+ targets: [+ {className: 'xds-date-time-picker', visualProps: ['size', 'status']},+ ],+ },+ usage: {+ description: 'DateTimePicker combines a calendar popover with a time input for selecting both a date and time in a single interaction flow. Use it for scheduling, event creation, deadline setting, or any form field that needs a specific datetime.',+ bestPractices: [+ { guidance: true, description: 'Provide clear labels and descriptions so users understand what datetime is expected.' },+ { guidance: true, description: 'Use min and max to restrict selectable datetimes to valid ranges.' },+ { guidance: true, description: 'Use hasClear when the datetime is optional so the user can easily reset it.' },+ { guidance: true, description: 'Choose the hour format (12h or 24h) that matches your audience’s locale.' },+ { guidance: false, description: 'Use DateTimePicker when only a date is needed — use DateInput instead.' },+ { guidance: false, description: 'Use DateTimePicker when only a time is needed — use TimeInput instead.' },+ { guidance: false, description: 'Hide the label without surrounding context that makes the field purpose obvious.' },+ ],+ anatomy: [+ {name: 'Label', required: true, description: 'Text above the input describing what datetime is expected.'},+ {name: 'Date input', required: true, description: 'A text input where the user can type a date. Clicking opens a calendar popover.'},+ {name: 'Calendar icon', required: true, description: 'A button that opens the calendar popover.'},+ {name: 'Calendar popover', required: false, description: 'A month grid that appears when the icon is clicked or the date input is focused.'},+ {name: 'Time input', required: true, description: 'A text input for entering the time, displayed beside the date input.'},+ {name: 'Clear button', required: false, description: 'A × button that resets the datetime value.'},+ {name: 'Status message', required: false, description: 'An error, warning, or success message below the inputs.'},+ ],+ },+};++/** @type {import('../docs-types').ComponentDoc} */+export const docsZh = {+ name: 'DateTimePicker',+ usage: {+ description: 'DateTimePicker combines a calendar popover with a time input for selecting both a date and time in a single interaction flow. Use it for scheduling, event creation, deadline setting, or any form field that needs a specific datetime.',+ bestPractices: [+ { guidance: true, description: 'Provide clear labels and descriptions so users understand what datetime is expected.' },+ { guidance: true, description: 'Use min and max to restrict selectable datetimes to valid ranges.' },+ { guidance: true, description: 'Use hasClear when the datetime is optional so the user can easily reset it.' },+ { guidance: true, description: 'Choose the hour format (12h or 24h) that matches your audience’s locale.' },+ { guidance: false, description: 'Use DateTimePicker when only a date is needed — use DateInput instead.' },+ { guidance: false, description: 'Use DateTimePicker when only a time is needed — use TimeInput instead.' },+ { guidance: false, description: 'Hide the label without surrounding context that makes the field purpose obvious.' },+ ],+ },+ props: [+ {name: 'label', type: 'string', description: '标签文本。', required: true},+ {name: 'isLabelHidden', type: 'boolean', description: '视觉隐藏标签。', default: 'false'},+ {name: 'description', type: 'string', description: '显示在标签下方的辅助文本。'},+ {name: 'isOptional', type: 'boolean', description: '在标签旁显示"(optional)"指示器。', default: 'false'},+ {name: 'isRequired', type: 'boolean', description: '将字段标记为必填。', default: 'false'},+ {name: 'isDisabled', type: 'boolean', description: '禁用输入框和选择器。', default: 'false'},+ {name: 'value', type: 'ISODateTimeString', description: '选中的日期时间,ISO 8601 格式。'},+ {name: 'onChange', type: '(value: ISODateTimeString | undefined) => void', description: '选中日期时间变更时调用的回调。', required: true},+ {name: 'changeAction', type: '(value: ISODateTimeString | undefined) => void | Promise<void>', description: '在 onChange 之后触发的异步操作。通过 useTransition 驱动乐观更新。'},+ {name: 'isLoading', type: 'boolean', description: '输入框是否处于加载状态。禁用交互并显示加载指示器。', default: 'false'},+ {name: 'min', type: 'ISODateTimeString', description: '可选择的最早日期时间。同时约束日期和时间选择。'},+ {name: 'max', type: 'ISODateTimeString', description: '可选择的最晚日期时间。同时约束日期和时间选择。'},+ {name: 'dateConstraints', type: 'Array<(date: Date) => boolean>', description: '自定义约束函数数组,用于禁用特定日期。'},+ {name: 'hasSeconds', type: 'boolean', description: '在时间部分包含秒。', default: 'false'},+ {name: 'hourFormat', type: "'12h' | '24h'", description: "控制显示格式。'12h' 显示 AM/PM;'24h' 使用 24 小时制。", default: "'12h'"},+ {name: 'timeIncrement', type: 'number', description: '在时间输入中按箭头键时增减的分钟数。', default: '1'},+ {name: 'hasClear', type: 'boolean', description: '当有值时显示清除按钮。', default: 'false'},+ {name: 'placeholder', type: 'string', description: '未选择日期时显示的占位符文本。', default: "'Select a date'"},+ {name: 'size', type: "'sm' | 'md'", description: '输入控件的尺寸。', default: "'md'"},+ {name: 'status', type: 'XDSInputStatus', description: '错误、警告或成功状态的状态指示对象,附带消息。'},+ {name: 'labelTooltip', type: 'string', description: '通过标签末尾的信息图标显示的提示文本。'},+ {name: 'numberOfMonths', type: '1 | 2', description: '日历中同时显示的月份数量。', default: '1'},+ {name: 'xstyle', type: 'StyleXStyles', description: '用于布局自定义的 StyleX 样式。必须是 stylex.create() 的值。'},+ ],+ theming: {+ targets: [+ {className: 'xds-date-time-picker', visualProps: ['size', 'status']},+ ],+ },+};++/** @type {import('../docs-types').TranslationDoc} */+export const docsDense = {+ description: 'combined date + time picker with calendar popover and time input',+ usage: {+ description: 'DateTimePicker combines a calendar popover with a time input for selecting both a date and time. Use for scheduling, events, deadlines, or any form field needing a datetime.',+ bestPractices: [+ { guidance: true, description: 'Clear labels + descriptions. Use min/max for valid datetime ranges.' },+ { guidance: true, description: 'Use hasClear for optional datetimes. Choose hour format matching locale.' },+ { guidance: false, description: 'Use for date-only (use DateInput) or time-only (use TimeInput).' },+ { guidance: false, description: 'Hide the label without surrounding context.' },+ ],+ },+ propDescriptions: {+ label: 'label text',+ isLabelHidden: 'visually hide label',+ description: 'helper text below label',+ isOptional: 'show "(optional)" indicator',+ isRequired: 'mark field required',+ isDisabled: 'disable input+picker',+ value: 'selected datetime ISO 8601',+ onChange: 'callback on datetime change',+ changeAction: 'async action after onChange; drives optimistic UI',+ isLoading: 'loading state; disables interaction, shows spinner',+ min: 'min selectable datetime (ISO)',+ max: 'max selectable datetime (ISO)',+ dateConstraints: 'custom constraint fns to disable specific dates',+ hasSeconds: 'include seconds in time portion',+ hourFormat: "display format. '12h' shows AM/PM; '24h' uses 24-hour",+ timeIncrement: 'minutes to add/subtract on arrow keys in time input',+ hasClear: 'Shows clear button when datetime is set',+ placeholder: 'placeholder text when empty',+ 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',+ xstyle: 'StyleX styles for layout; must be stylex.create() value',+ },+};diff --git a/packages/core/src/DateTimePicker/XDSDateTimePicker.test.tsx b/packages/core/src/DateTimePicker/XDSDateTimePicker.test.tsxnew file mode 100644index 0000000000..bad4e63faf--- /dev/null+++ b/packages/core/src/DateTimePicker/XDSDateTimePicker.test.tsx@@ -0,0 +1,379 @@+/**+ * @file XDSDateTimePicker.test.tsx+ * @input Uses vitest, @testing-library/react, XDSDateTimePicker component+ * @output Unit tests for XDSDateTimePicker component behavior+ * @position Testing; validates XDSDateTimePicker.tsx implementation+ *+ * SYNC: When XDSDateTimePicker.tsx changes, update tests to match new behavior+ */++import {describe, it, expect, vi} from 'vitest';+import {render, screen, fireEvent} from '@testing-library/react';+import {XDSDateTimePicker} from './XDSDateTimePicker';+import type {ISODateTimeString} from './XDSDateTimePicker';++describe('XDSDateTimePicker', () => {+ it('renders with label', () => {+ render(<XDSDateTimePicker label="Meeting time" onChange={() => {}} />);+ expect(screen.getByLabelText('Meeting time')).toBeInTheDocument();+ });++ it('renders with placeholder', () => {+ render(+ <XDSDateTimePicker+ label="Time"+ onChange={() => {}}+ placeholder="Pick a date"+ />,+ );+ expect(screen.getByPlaceholderText('Pick a date')).toBeInTheDocument();+ });++ it('renders both date and time inputs', () => {+ render(<XDSDateTimePicker label="Meeting" onChange={() => {}} />);+ expect(screen.getByRole('combobox')).toBeInTheDocument();+ expect(screen.getByLabelText('Time')).toBeInTheDocument();+ });++ it('displays formatted date in date input when value is provided', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ expect(screen.getByDisplayValue('March 15, 2026')).toBeInTheDocument();+ });++ it('displays formatted time in time input when value is provided (12h)', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ expect(screen.getByDisplayValue('2:30 PM')).toBeInTheDocument();+ });++ it('displays formatted time in 24h format', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ hourFormat="24h"+ />,+ );+ expect(screen.getByDisplayValue('14:30')).toBeInTheDocument();+ });++ it('displays time with seconds', () => {+ render(+ <XDSDateTimePicker+ label="Timestamp"+ value={'2026-03-15T14:30:45' as ISODateTimeString}+ onChange={() => {}}+ hasSeconds+ />,+ );+ expect(screen.getByDisplayValue('2:30:45 PM')).toBeInTheDocument();+ });++ it('forwards ref to date input', () => {+ const ref = vi.fn();+ render(<XDSDateTimePicker ref={ref} label="Meeting" onChange={() => {}} />);+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));+ });++ it('visually hides label when isLabelHidden is true', () => {+ render(+ <XDSDateTimePicker label="Meeting" isLabelHidden onChange={() => {}} />,+ );+ const label = screen.getByText('Meeting');+ expect(label).toBeInTheDocument();+ expect(screen.getByLabelText('Meeting')).toBeInTheDocument();+ });++ it('sets aria-required when isRequired is true', () => {+ render(+ <XDSDateTimePicker label="Meeting" isRequired onChange={() => {}} />,+ );+ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-required',+ 'true',+ );+ });++ it('does not set aria-required when isRequired is false', () => {+ render(<XDSDateTimePicker label="Meeting" onChange={() => {}} />);+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-required');+ });++ it('sets disabled on both inputs when isDisabled is true', () => {+ render(+ <XDSDateTimePicker label="Meeting" isDisabled onChange={() => {}} />,+ );+ expect(screen.getByRole('combobox')).toBeDisabled();+ expect(screen.getByLabelText('Time')).toBeDisabled();+ });++ it('is not disabled by default', () => {+ render(<XDSDateTimePicker label="Meeting" onChange={() => {}} />);+ expect(screen.getByRole('combobox')).not.toBeDisabled();+ expect(screen.getByLabelText('Time')).not.toBeDisabled();+ });++ it('date input has role="combobox"', () => {+ render(<XDSDateTimePicker label="Meeting" onChange={() => {}} />);+ expect(screen.getByRole('combobox')).toBeInTheDocument();+ });++ it('date input has aria-haspopup="dialog"', () => {+ render(<XDSDateTimePicker label="Meeting" onChange={() => {}} />);+ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-haspopup',+ 'dialog',+ );+ });++ it('date input has aria-expanded=false by default', () => {+ render(<XDSDateTimePicker label="Meeting" onChange={() => {}} />);+ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-expanded',+ 'false',+ );+ });++ it('calendar button is focusable and clickable', () => {+ render(<XDSDateTimePicker label="Meeting" 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(+ <XDSDateTimePicker label="Meeting" isDisabled onChange={() => {}} />,+ );+ const button = screen.getByRole('button', {name: 'Open calendar'});+ expect(button).toBeDisabled();+ });++ it('disables inputs and button when isLoading is true', () => {+ render(<XDSDateTimePicker label="Meeting" isLoading onChange={() => {}} />);+ expect(screen.getByRole('combobox')).toBeDisabled();+ expect(screen.getByLabelText('Time')).toBeDisabled();+ expect(screen.getByRole('button', {name: 'Open calendar'})).toBeDisabled();+ });++ it('sets aria-busy when isLoading is true', () => {+ render(<XDSDateTimePicker label="Meeting" isLoading onChange={() => {}} />);+ expect(screen.getByRole('combobox')).toHaveAttribute('aria-busy', 'true');+ });++ it('does not set aria-busy when not loading', () => {+ render(<XDSDateTimePicker label="Meeting" onChange={() => {}} />);+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-busy');+ });++ it('renders status icon for error status', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ onChange={() => {}}+ status={{type: 'error', message: 'Invalid datetime'}}+ />,+ );+ expect(screen.getByRole('combobox')).toHaveAttribute(+ 'aria-invalid',+ 'true',+ );+ });++ it('does not set aria-invalid for warning status', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ onChange={() => {}}+ status={{type: 'warning', message: 'Watch out'}}+ />,+ );+ expect(screen.getByRole('combobox')).not.toHaveAttribute('aria-invalid');+ });++ it('renders description and links via aria-describedby', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ description="Pick the meeting datetime"+ onChange={() => {}}+ />,+ );+ const input = screen.getByRole('combobox');+ expect(screen.getByText('Pick the meeting datetime')).toBeInTheDocument();+ expect(input).toHaveAttribute('aria-describedby');+ });++ it('links status message via aria-describedby', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ onChange={() => {}}+ status={{type: 'error', message: 'Invalid datetime'}}+ />,+ );+ 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 datetime');+ });+ expect(found).toBe(true);+ });++ it('handles Escape keydown on date input without error', () => {+ render(<XDSDateTimePicker label="Meeting" onChange={() => {}} />);+ const input = screen.getByRole('combobox');+ fireEvent.keyDown(input, {key: 'Escape'});+ });++ // --- Date text input behavior ---++ it('calls onChange when valid date is typed', () => {+ const onChange = vi.fn();+ render(<XDSDateTimePicker label="Meeting" onChange={onChange} />);++ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: '03/15/2026'}});++ expect(onChange).toHaveBeenCalled();+ const calledValue = onChange.mock.calls[0][0] as string;+ expect(calledValue).toMatch(/^2026-03-15T/);+ });++ it('does not call onChange while typing invalid date', () => {+ const onChange = vi.fn();+ render(<XDSDateTimePicker label="Meeting" onChange={onChange} />);++ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: 'invalid'}});++ expect(onChange).not.toHaveBeenCalled();+ });++ it('reverts date input on blur when input is invalid', () => {+ const onChange = vi.fn();+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-01-25T10:00' as ISODateTimeString}+ onChange={onChange}+ />,+ );++ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: 'not a date'}});+ fireEvent.blur(input);++ expect(screen.getByDisplayValue('January 25, 2026')).toBeInTheDocument();+ expect(onChange).not.toHaveBeenCalled();+ });++ // --- Time input behavior ---++ it('does not call onChange for time when no date is set', () => {+ const onChange = vi.fn();+ render(<XDSDateTimePicker label="Meeting" onChange={onChange} />);++ const timeInput = screen.getByLabelText('Time');+ fireEvent.change(timeInput, {target: {value: '3:45 pm'}});++ expect(onChange).not.toHaveBeenCalled();+ });++ it('calls onChange for time when date is already set', () => {+ const onChange = vi.fn();+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-03-15T10:00' as ISODateTimeString}+ onChange={onChange}+ />,+ );++ const timeInput = screen.getByLabelText('Time');+ fireEvent.change(timeInput, {target: {value: '3:45 pm'}});++ expect(onChange).toHaveBeenCalledWith('2026-03-15T15:45');+ });++ describe('hasClear', () => {+ it('shows clear button when hasClear is true and value exists', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ hasClear+ />,+ );+ expect(+ screen.getByRole('button', {name: 'Clear Meeting'}),+ ).toBeInTheDocument();+ });++ it('does not show clear button when value is undefined', () => {+ render(+ <XDSDateTimePicker label="Meeting" onChange={() => {}} hasClear />,+ );+ expect(+ screen.queryByRole('button', {name: 'Clear Meeting'}),+ ).not.toBeInTheDocument();+ });++ it('does not show clear button when hasClear is false', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ expect(+ screen.queryByRole('button', {name: 'Clear Meeting'}),+ ).not.toBeInTheDocument();+ });++ it('does not show clear button when disabled', () => {+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ hasClear+ isDisabled+ />,+ );+ expect(+ screen.queryByRole('button', {name: 'Clear Meeting'}),+ ).not.toBeInTheDocument();+ });++ it('calls onChange with undefined when clear is clicked', () => {+ const onChange = vi.fn();+ render(+ <XDSDateTimePicker+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ hasClear+ />,+ );+ fireEvent.click(screen.getByRole('button', {name: 'Clear Meeting'}));+ expect(onChange).toHaveBeenCalledWith(undefined);+ });+ });+});diff --git a/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx b/packages/core/src/DateTimePicker/XDSDateTimePicker.tsxnew file mode 100644index 0000000000..c8af0b3bea--- /dev/null+++ b/packages/core/src/DateTimePicker/XDSDateTimePicker.tsx@@ -0,0 +1,884 @@+'use client';++/**+ * @file XDSDateTimePicker.tsx+ * @input Uses React, XDSField, XDSCalendar, useXDSPopover, time parsing utilities+ * @output Exports XDSDateTimePicker component, XDSDateTimePickerProps+ * @position Core implementation; consumed by index.ts, tested by XDSDateTimePicker.test.tsx+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/DateTimePicker/DateTimePicker.doc.mjs (props table, features, implementation notes)+ * - /packages/core/src/DateTimePicker/XDSDateTimePicker.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/DateTimePicker/index.ts (exports if types change)+ * - /apps/storybook/stories/DateTimePicker.stories.tsx (storybook stories)+ * - /packages/cli/templates/blocks/components/DateTimePicker/ (showcase blocks)+ */++import {+ useId,+ useState,+ useCallback,+ useEffect,+ useRef,+ useMemo,+ useOptimistic,+ useTransition,+ type KeyboardEvent,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {XDSIconName} from '../Icon';+import {+ colorVars,+ sizeVars,+ radiusVars,+ spacingVars,+ typographyVars,+ typeScaleVars,+ borderVars,+} from '../theme/tokens.stylex';+import {+ XDSField,+ type XDSInputStatus,+ type XDSInputStatusType,+ inputWrapperStyles,+ inputStatusBorderStyles,+ inputStatusHoverShadowStyles,+ inputStatusFocusWithinStyles,+} from '../Field';+import {XDSIcon} from '../Icon';+import {XDSSpinner} from '../Spinner';+import {+ XDSCalendar,+ type ISODateString,+ type XDSCalendarHandle,+} from '../Calendar';+import {useCalendarConstraints} from '../Calendar/hooks';+import {useXDSPopover} from '../Popover';+import {useInputContainer} from '../hooks/useInputContainer';+import {+ type ISOTimeString,+ parseDateInput,+ formatDisplayDate,+ parseISO,+ parseTimeInput,+ formatDisplayTime12h,+ formatDisplayTime24h,+ formatISOTime,+ isTimeInRange,+ adjustTime,+ xdsClassName,+ mergeProps,+} from '../utils';+import type {StyleXStyles} from '@stylexjs/stylex';+import type {XDSBaseProps} from '../XDSBaseProps';++export type ISODateTimeString = string & {+ readonly __brand: 'ISODateTimeString';+};++export type XDSDateTimePickerHourFormat = '12h' | '24h';++export type XDSDateTimePickerSize = 'sm' | 'md';++export type {+ XDSInputStatus as XDSDateTimePickerStatus,+ XDSInputStatusType as XDSDateTimePickerStatusType,+} from '../Field';++const styles = stylex.create({+ row: {+ display: 'flex',+ gap: spacingVars['--spacing-2'],+ },+ iconButton: {+ 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': `${borderVars['--border-width']} solid ${colorVars['--color-accent']}`,+ },+ outlineOffset: 1,+ },+ iconButtonDisabled: {+ cursor: 'not-allowed',+ },+ 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-family-body'],+ fontSize: {+ default: typeScaleVars['--text-body-size'],+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,+ },+ lineHeight: typeScaleVars['--text-body-leading'],+ color: colorVars['--color-text-primary'],+ backgroundColor: 'transparent',+ outline: 'none',+ '::placeholder': {+ color: colorVars['--color-text-secondary'],+ },+ },+ inputDisabled: {+ cursor: 'not-allowed',+ },+ inputInvalid: {+ color: colorVars['--color-text-secondary'],+ },+ dateWrapper: {+ flex: 1,+ flexBasis: 0,+ },+ timeWrapper: {+ flex: 1,+ flexBasis: 0,+ },+});++const sizeStyles = stylex.create({+ sm: {+ height: sizeVars['--size-element-sm'],+ },+ md: {+ height: sizeVars['--size-element-md'],+ },+});++export interface XDSDateTimePickerProps extends Omit<+ XDSBaseProps,+ 'onChange' | 'defaultValue'+> {+ /** Ref forwarded to the date input element */+ ref?: React.Ref<HTMLInputElement>;++ /**+ * 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 datetime in ISO 8601 format ("YYYY-MM-DDTHH:MM" or "YYYY-MM-DDTHH:MM:SS").+ */+ value?: ISODateTimeString;++ /**+ * Callback fired when the datetime changes.+ * Called with undefined when input is cleared.+ */+ onChange: (value: ISODateTimeString | undefined) => void;++ /**+ * Async action on change. Fires after onChange.+ */+ changeAction?: (value: ISODateTimeString | undefined) => void | Promise<void>;++ /**+ * Whether the input is in a loading state.+ * @default false+ */+ isLoading?: boolean;++ /**+ * Minimum selectable datetime in ISO format.+ * Constrains both date and time selection.+ */+ min?: ISODateTimeString;++ /**+ * Maximum selectable datetime in ISO format.+ * Constrains both date and time selection.+ */+ max?: ISODateTimeString;++ /**+ * Custom date constraint functions.+ * Date is disabled in the calendar if ANY function returns false.+ */+ dateConstraints?: ReadonlyArray<(date: Date) => boolean>;++ /**+ * Whether to include seconds in the time portion.+ * @default false+ */+ hasSeconds?: boolean;++ /**+ * Hour display format.+ * @default '12h'+ */+ hourFormat?: XDSDateTimePickerHourFormat;++ /**+ * Time increment in minutes when using arrow keys in the time input.+ * @default 1+ */+ timeIncrement?: number;++ /**+ * Whether to show a clear button when a value is set.+ * @default false+ */+ hasClear?: boolean;++ /**+ * Placeholder text shown when no date is selected.+ * @default "Select a date"+ */+ placeholder?: string;++ /**+ * The size of the inputs.+ * @default 'md'+ */+ size?: XDSDateTimePickerSize;++ /**+ * Status indicator for the input.+ */+ status?: XDSInputStatus;++ /**+ * Tooltip text to display in an info icon at the end of the label.+ */+ labelTooltip?: string;++ /**+ * Number of months to display in the calendar.+ * @default 1+ */+ numberOfMonths?: 1 | 2;++ /**+ * Style overrides applied to the outer row container.+ */+ xstyle?: StyleXStyles;+}++function splitDateTime(dt: ISODateTimeString | undefined): {+ date: ISODateString | undefined;+ time: ISOTimeString | undefined;+} {+ if (!dt) return {date: undefined, time: undefined};+ const tIndex = dt.indexOf('T');+ if (tIndex === -1)+ return {date: dt as unknown as ISODateString, time: undefined};+ return {+ date: dt.slice(0, tIndex) as ISODateString,+ time: dt.slice(tIndex + 1) as ISOTimeString,+ };+}++function combineDateTime(+ date: ISODateString | undefined,+ time: ISOTimeString | undefined,+): ISODateTimeString | undefined {+ if (!date || !time) return undefined;+ return `${date}T${time}` as ISODateTimeString;+}++function getDefaultTime(hasSeconds: boolean): ISOTimeString {+ const now = new Date();+ return formatISOTime(+ {hour: now.getHours(), minute: now.getMinutes(), second: now.getSeconds()},+ hasSeconds,+ );+}++/**+ * A combined date and time picker with side-by-side date input and+ * time input under a single label. The date input opens a calendar+ * popover; the time input supports typed entry and arrow-key adjustment.+ *+ * @example+ * ```+ * <XDSDateTimePicker+ * label="Meeting time"+ * value={dateTime}+ * onChange={setDateTime}+ * />+ * ```+ */+export function XDSDateTimePicker({+ label,+ isLabelHidden = false,+ description,+ isOptional = false,+ isRequired = false,+ isDisabled = false,+ value,+ onChange,+ changeAction,+ isLoading = false,+ min,+ max,+ dateConstraints,+ hasSeconds = false,+ hourFormat = '12h',+ timeIncrement = 1,+ hasClear = false,+ placeholder = 'Select a date',+ size = 'md',+ status,+ labelTooltip,+ numberOfMonths = 1,+ xstyle,+ className,+ style,+ ref,+ ...rest+}: XDSDateTimePickerProps) {+ const dateInputId = useId();+ const timeInputId = useId();+ const descriptionID = useId();+ const statusMessageID = useId();+ const dateInputRef = useRef<HTMLInputElement | null>(null);+ const timeInputRef = useRef<HTMLInputElement | null>(null);+ const timeContainerRef = useRef<HTMLDivElement | null>(null);+ const calendarRef = useRef<XDSCalendarHandle | null>(null);+ const lastFiredDateRef = useRef<ISODateString | undefined>(undefined);++ const [, startTransition] = useTransition();+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);+ const isBusy = isLoading || optimisticValue !== value;+ const isEffectivelyDisabled = isDisabled || isBusy;++ const statusIconMap: Record<XDSInputStatusType, XDSIconName> = {+ warning: 'warning',+ error: 'error',+ success: 'success',+ };++ 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;++ // Split min/max and current value+ const minParts = useMemo(() => splitDateTime(min), [min]);+ const maxParts = useMemo(() => splitDateTime(max), [max]);+ const valueParts = useMemo(+ () => splitDateTime(optimisticValue),+ [optimisticValue],+ );++ // Date constraints from min/max+ const calendarMin = minParts.date;+ const calendarMax = maxParts.date;+ const {isDateDisabled} = useCalendarConstraints({+ min: calendarMin,+ max: calendarMax,+ dateConstraints,+ });++ // Time constraints change depending on selected date+ const timeMin = useMemo(() => {+ if (!minParts.date || !minParts.time || !valueParts.date) return undefined;+ return valueParts.date === minParts.date ? minParts.time : undefined;+ }, [minParts.date, minParts.time, valueParts.date]);++ const timeMax = useMemo(() => {+ if (!maxParts.date || !maxParts.time || !valueParts.date) return undefined;+ return valueParts.date === maxParts.date ? maxParts.time : undefined;+ }, [maxParts.date, maxParts.time, valueParts.date]);++ // --- Date input state ---+ const [datePendingInput, setDatePendingInput] = useState<string | null>(null);++ useEffect(() => {+ if (valueParts.date === lastFiredDateRef.current) return;+ lastFiredDateRef.current = undefined;+ setDatePendingInput(null);+ }, [valueParts.date]);++ const dateDisplayValue =+ datePendingInput !== null+ ? datePendingInput+ : valueParts.date && /^\d{4}-\d{2}-\d{2}$/.test(valueParts.date)+ ? formatDisplayDate(valueParts.date)+ : '';++ const isDateInputValid =+ datePendingInput === null || !datePendingInput.trim()+ ? true+ : parseDateInput(datePendingInput) !== null;++ // --- Time input state ---+ const [timePendingInput, setTimePendingInput] = useState<string | null>(null);+ const [isTimeFocused, setIsTimeFocused] = useState(false);++ const formatDisplayTime =+ hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;++ const timeDisplayValue = useMemo(() => {+ if (timePendingInput !== null) return timePendingInput;+ return valueParts.time+ ? formatDisplayTime(valueParts.time, hasSeconds)+ : '';+ }, [timePendingInput, valueParts.time, formatDisplayTime, hasSeconds]);++ const isTimeInputValid = useMemo(() => {+ if (timePendingInput === null || !timePendingInput.trim()) return true;+ const parsed = parseTimeInput(timePendingInput, hasSeconds);+ if (!parsed) return false;+ return isTimeInRange(parsed, timeMin, timeMax);+ }, [timePendingInput, hasSeconds, timeMin, timeMax]);++ const timePlaceholder = useMemo(() => {+ if (isTimeFocused && !timeDisplayValue) {+ return hourFormat === '12h' ? 'e.g., 2:30 PM' : 'e.g., 14:30';+ }+ return 'Select a time';+ }, [isTimeFocused, timeDisplayValue, hourFormat]);++ // --- Unified change handler ---+ const fireChange = useCallback(+ (newValue: ISODateTimeString | undefined) => {+ if (isBusy) return;+ onChange(newValue);+ if (changeAction) {+ startTransition(async () => {+ setOptimisticValue(newValue);+ await changeAction(newValue);+ });+ }+ },+ [isBusy, onChange, changeAction, startTransition, setOptimisticValue],+ );++ // --- Popover ---+ const popover = useXDSPopover({+ dialogLabel: 'Choose date',+ closeButtonLabel: 'Close calendar',+ onHide: () => dateInputRef.current?.focus(),+ });++ const handleCalendarToggle = useCallback(() => {+ if (!isEffectivelyDisabled) {+ if (popover.isOpen) {+ popover.hide();+ } else {+ popover.show();+ }+ }+ }, [isEffectivelyDisabled, popover]);++ const handleDateInputClick = useCallback(() => {+ if (!isEffectivelyDisabled && !popover.isOpen) {+ popover.show({skipAutoFocus: true});+ }+ }, [isEffectivelyDisabled, popover]);++ // --- Date handlers ---+ const handleDateChange = useCallback(+ (newDate: ISODateString, source: 'calendar' | 'input') => {+ const currentTime = valueParts.time ?? getDefaultTime(hasSeconds);++ let effectiveTime = currentTime;+ if (minParts.date && newDate === minParts.date && minParts.time) {+ if (!isTimeInRange(effectiveTime, minParts.time, undefined)) {+ effectiveTime = minParts.time;+ }+ }+ if (maxParts.date && newDate === maxParts.date && maxParts.time) {+ if (!isTimeInRange(effectiveTime, undefined, maxParts.time)) {+ effectiveTime = maxParts.time;+ }+ }++ const combined = combineDateTime(newDate, effectiveTime);+ if (combined) {+ fireChange(combined);+ }+ if (source === 'calendar') {+ setDatePendingInput(null);+ popover.hide();+ }+ },+ [valueParts.time, hasSeconds, minParts, maxParts, fireChange, popover],+ );++ const handleDateInputChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const text = e.target.value;+ setDatePendingInput(text);++ const parsed = parseDateInput(text);+ if (+ parsed &&+ parsed !== valueParts.date &&+ !isDateDisabled(parseISO(parsed))+ ) {+ lastFiredDateRef.current = parsed;+ handleDateChange(parsed, 'input');+ calendarRef.current?.navigateTo(parsed);+ }+ },+ [valueParts.date, isDateDisabled, handleDateChange],+ );++ const commitDatePendingInput = useCallback(() => {+ if (datePendingInput === null) return;++ if (!datePendingInput.trim()) {+ if (value !== undefined) {+ fireChange(undefined);+ }+ setDatePendingInput(null);+ return;+ }++ const parsed = parseDateInput(datePendingInput);+ if (parsed && !isDateDisabled(parseISO(parsed))) {+ if (parsed !== valueParts.date) {+ handleDateChange(parsed, 'input');+ }+ }+ setDatePendingInput(null);+ }, [+ datePendingInput,+ value,+ valueParts.date,+ fireChange,+ isDateDisabled,+ handleDateChange,+ ]);++ const handleDateBlur = useCallback(() => {+ commitDatePendingInput();+ }, [commitDatePendingInput]);++ const handleDateKeyDown = useCallback(+ (e: React.KeyboardEvent) => {+ if (e.key === 'Escape' && popover.isOpen) {+ e.preventDefault();+ popover.hide();+ } else if (e.key === 'Enter') {+ e.preventDefault();+ commitDatePendingInput();+ }+ },+ [popover, commitDatePendingInput],+ );++ // --- Time handlers ---+ const handleTimeInputChange = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const text = e.target.value;+ setTimePendingInput(text);++ const parsed = parseTimeInput(text, hasSeconds);+ if (+ parsed &&+ isTimeInRange(parsed, timeMin, timeMax) &&+ parsed !== valueParts.time+ ) {+ if (valueParts.date) {+ const combined = combineDateTime(valueParts.date, parsed);+ if (combined) fireChange(combined);+ }+ }+ },+ [+ hasSeconds,+ timeMin,+ timeMax,+ valueParts.time,+ valueParts.date,+ fireChange,+ ],+ );++ const handleTimeFocus = useCallback(() => setIsTimeFocused(true), []);++ const handleTimeBlur = useCallback(() => {+ setIsTimeFocused(false);+ if (timePendingInput === null) return;++ if (!timePendingInput.trim()) {+ // Empty time: revert display to previous value (don't emit partial datetime)+ setTimePendingInput(null);+ return;+ }++ const parsed = parseTimeInput(timePendingInput, hasSeconds);+ if (parsed && isTimeInRange(parsed, timeMin, timeMax)) {+ if (parsed !== valueParts.time && valueParts.date) {+ const combined = combineDateTime(valueParts.date, parsed);+ if (combined) fireChange(combined);+ }+ }+ setTimePendingInput(null);+ }, [timePendingInput, hasSeconds, timeMin, timeMax, valueParts, fireChange]);++ const handleTimeKeyDown = useCallback(+ (e: KeyboardEvent<HTMLInputElement>) => {+ if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {+ e.preventDefault();++ let currentTime = valueParts.time;+ if (!currentTime) {+ const now = new Date();+ currentTime = formatISOTime(+ {+ hour: now.getHours(),+ minute: now.getMinutes(),+ second: now.getSeconds(),+ },+ hasSeconds,+ );+ }++ const delta = e.key === 'ArrowUp' ? timeIncrement : -timeIncrement;+ const newTime = adjustTime(currentTime, delta, hasSeconds);++ if (isTimeInRange(newTime, timeMin, timeMax) && valueParts.date) {+ const combined = combineDateTime(valueParts.date, newTime);+ if (combined) fireChange(combined);+ }+ }+ },+ [valueParts, hasSeconds, timeIncrement, timeMin, timeMax, fireChange],+ );++ // --- Clear ---+ const handleClear = useCallback(() => {+ fireChange(undefined);+ dateInputRef.current?.focus();+ }, [fireChange]);++ // --- Refs ---+ const setDateRefs = useCallback(+ (el: HTMLInputElement | null) => {+ dateInputRef.current = el;+ if (typeof ref === 'function') {+ ref(el);+ } else if (ref) {+ ref.current = el;+ }+ },+ [ref],+ );++ // Focus time input when clicking wrapper padding/icon+ const {onClick: handleTimeWrapperClick, onMouseUp: handleTimeWrapperMouseUp} =+ useInputContainer({+ containerRef: timeContainerRef,+ inputRef: timeInputRef,+ disabled: isEffectivelyDisabled,+ });++ return (+ <XDSField+ label={label}+ isLabelHidden={isLabelHidden}+ description={description}+ inputID={dateInputId}+ descriptionID={description ? descriptionID : undefined}+ isOptional={isOptional}+ isRequired={isRequired}+ isDisabled={isDisabled}+ status={+ status+ ? {+ type: status.type,+ message: status.message,+ messageID: status.message ? statusMessageID : undefined,+ }+ : undefined+ }+ labelTooltip={labelTooltip}+ statusVariant="detached">+ <div+ {...rest}+ {...mergeProps(+ xdsClassName('date-time-picker', {+ size,+ status: status?.type ?? null,+ }),+ stylex.props(styles.row, xstyle),+ className,+ style,+ )}>+ {/* Date input */}+ <div+ ref={popover.triggerRef}+ {...stylex.props(+ inputWrapperStyles.base,+ sizeStyles[size],+ styles.dateWrapper,+ isEffectivelyDisabled && inputWrapperStyles.disabled,+ status && inputStatusBorderStyles[status.type],+ status && inputStatusHoverShadowStyles[status.type],+ status && inputStatusFocusWithinStyles[status.type],+ )}>+ <input+ ref={setDateRefs}+ id={dateInputId}+ type="text"+ role="combobox"+ value={dateDisplayValue}+ onChange={handleDateInputChange}+ onBlur={handleDateBlur}+ onClick={handleDateInputClick}+ onKeyDown={handleDateKeyDown}+ placeholder={placeholder}+ 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,+ isEffectivelyDisabled && styles.inputDisabled,+ !isDateInputValid && styles.inputInvalid,+ )}+ />+ {hasClear && value !== undefined && !isEffectivelyDisabled && (+ <button+ type="button"+ onClick={handleClear}+ aria-label={`Clear ${label}`}+ {...stylex.props(styles.iconButton)}>+ <XDSIcon icon="close" size="sm" color="secondary" />+ </button>+ )}+ <button+ type="button"+ onClick={handleCalendarToggle}+ 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+ icon={statusIconMap[status.type]}+ size="md"+ color={statusIconColorMap[status.type]}+ />+ )}+ </div>++ {/* Time input */}+ <div+ ref={timeContainerRef}+ onClick={handleTimeWrapperClick}+ onMouseUp={handleTimeWrapperMouseUp}+ {...stylex.props(+ inputWrapperStyles.base,+ sizeStyles[size],+ styles.timeWrapper,+ isEffectivelyDisabled && inputWrapperStyles.disabled,+ status && inputStatusBorderStyles[status.type],+ status && inputStatusHoverShadowStyles[status.type],+ status && inputStatusFocusWithinStyles[status.type],+ )}>+ <div {...stylex.props(styles.icon)}>+ <XDSIcon icon="clock" size="sm" color="secondary" />+ </div>+ <input+ ref={timeInputRef}+ id={timeInputId}+ type="text"+ value={timeDisplayValue}+ onChange={handleTimeInputChange}+ onFocus={handleTimeFocus}+ onBlur={handleTimeBlur}+ onKeyDown={handleTimeKeyDown}+ placeholder={timePlaceholder}+ disabled={isEffectivelyDisabled}+ aria-label="Time"+ {...stylex.props(+ styles.input,+ isEffectivelyDisabled && styles.inputDisabled,+ !isTimeInputValid && styles.inputInvalid,+ )}+ />+ </div>+ </div>++ {popover.render(+ <XDSCalendar+ ref={calendarRef}+ mode="single"+ value={valueParts.date}+ onChange={(d: ISODateString) => handleDateChange(d, 'calendar')}+ min={calendarMin}+ max={calendarMax}+ dateConstraints={dateConstraints}+ numberOfMonths={numberOfMonths}+ />,+ {placement: 'below', alignment: 'start'},+ )}+ </XDSField>+ );+}++XDSDateTimePicker.displayName = 'XDSDateTimePicker';diff --git a/packages/core/src/DateTimePicker/index.ts b/packages/core/src/DateTimePicker/index.tsnew file mode 100644index 0000000000..8a5e893601--- /dev/null+++ b/packages/core/src/DateTimePicker/index.ts@@ -0,0 +1,18 @@+'use client';++/**+ * @file index.ts+ * @input DateTimePicker component exports+ * @output Re-exports XDSDateTimePicker and types+ * @position Package entry point for DateTimePicker+ */++export {XDSDateTimePicker} from './XDSDateTimePicker';+export type {+ XDSDateTimePickerProps,+ XDSDateTimePickerSize,+ XDSDateTimePickerHourFormat,+ XDSDateTimePickerStatus,+ XDSDateTimePickerStatusType,+ ISODateTimeString,+} from './XDSDateTimePicker';diff --git a/packages/core/src/TimeInput/XDSTimeInput.tsx b/packages/core/src/TimeInput/XDSTimeInput.tsxindex 50db6d4e96..4ab8361bfc 100644--- a/packages/core/src/TimeInput/XDSTimeInput.tsx+++ b/packages/core/src/TimeInput/XDSTimeInput.tsx@@ -118,12 +118,15 @@ const styles = stylex.create({const sizeStyles = stylex.create({sm: {height: sizeVars['--size-element-sm'],+ minWidth: 120,},md: {height: sizeVars['--size-element-md'],+ minWidth: 120,},lg: {height: sizeVars['--size-element-lg'],+ minWidth: 120,},});diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 6d0a4c50f4..7fba07b500 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -51,6 +51,7 @@ export * from './Slider';export * from './Stack';export * from './Switch';export * from './DateInput';+export * from './DateTimePicker';export * from './Field';export * from './FormLayout';export * from './Grid';