An open source design system that's fully customizable and agent ready
TypeScript
feat(core): add mobile DateTimeInput picker (#5582)
Xinzi Zhoud51dbad80096
diff --git a/.changeset/datetime-input-mobile-sheet.md b/.changeset/datetime-input-mobile-sheet.mdnew file mode 100644index 0000000000..06aed687d6--- /dev/null+++ b/.changeset/datetime-input-mobile-sheet.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] Add a coarse-pointer DateTimeInput bottom-sheet picker with separate closed Date/Time segments, direct section opening, and a two-step Save date → Save flow.++@imdreamrunnerdiff --git a/apps/storybook/stories/DateTimeInput.stories.tsx b/apps/storybook/stories/DateTimeInput.stories.tsxindex ec597cf253..90c6893c37 100644--- a/apps/storybook/stories/DateTimeInput.stories.tsx+++ b/apps/storybook/stories/DateTimeInput.stories.tsx@@ -10,6 +10,16 @@ const meta: Meta<typeof DateTimeInput> = {title: 'Core/DateTimeInput',component: DateTimeInput,tags: ['autodocs'],+ parameters: {+ docs: {+ description: {+ component:+ 'A date-time field that fits the pointer it is used with. On a mouse or trackpad it renders the existing side-by-side date and time inputs: the date half opens a calendar popover, and the time half accepts typed entry plus optional preset times.\n\n' ++ "Where the primary pointer is a finger (`pointer: coarse`), the closed control still renders separate Date and Time segments; tapping either segment opens a bottom sheet directly to the matching section. A segmented Date/Time pill stays at the top of the sheet for switching; Date reuses Astryx's custom swipable month picker and month/year wheels, its Save date action advances to Time, and Time uses accessible hour/minute/second wheels with the final Save action. The public props are the same on both surfaces.\n\n" ++ '**Seeing the touch surface:** open any story on a phone/tablet or in device emulation reporting a coarse pointer. No separate story is needed because the same component chooses the surface at runtime.',+ },+ },+ },argTypes: {label: {control: 'text',@@ -71,7 +81,8 @@ const meta: Meta<typeof DateTimeInput> = {},timeIncrement: {control: 'number',- description: 'Minutes to increment/decrement with arrow keys',+ description:+ 'Desktop only: minutes to increment/decrement with arrow keys. Mobile touch uses wheels.',},},};diff --git a/packages/cli/assets/templates/blocks/components/DateTimeInput/DateTimeInputShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/DateTimeInput/DateTimeInputShowcase.doc.mjsindex bb177334c0..7d43d50f6e 100644--- a/packages/cli/assets/templates/blocks/components/DateTimeInput/DateTimeInputShowcase.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/DateTimeInput/DateTimeInputShowcase.doc.mjs@@ -7,7 +7,7 @@ export const doc = {name: 'DateTimeInput',displayName: 'Date Time Input',description:- 'A combined date and time picker. Click to open a calendar popover with a time input below.',+ 'A combined date and time picker. Desktop opens a calendar popover with a time input; touch devices open a Date/Time bottom sheet.',isReady: true,isShowcase: true,aspectRatio: 1,diff --git a/packages/core/locales/en.json b/packages/core/locales/en.jsonindex 370f635837..3834113dc6 100644--- a/packages/core/locales/en.json+++ b/packages/core/locales/en.json@@ -780,8 +780,52 @@"description": "Grey placeholder inside an empty DateTimeInput field. Note: the English says only \"date\" though the field is date+time — do not add \"and time\" unless natural."},"@astryx.dateTimeInput.dialogLabel": {- "defaultMessage": "Choose date",- "description": "Screen-reader-only accessible name for the DateTimeInput picker dialog. Same English-only \"date\" phrasing as the placeholder — don't add \"and time\" unless natural."+ "defaultMessage": "Choose date and time",+ "description": "Screen-reader-only accessible name for the DateTimeInput picker dialog. On desktop this labels the date calendar popover inside the date+time field; on touch devices it labels the full Date/Time bottom sheet."+ },+ "@astryx.dateTimeInput.pickerMode": {+ "defaultMessage": "Date/time section",+ "description": "Screen-reader-only label for the segmented Date/Time switch at the top of the mobile DateTimeInput bottom sheet."+ },+ "@astryx.dateTimeInput.dateTab": {+ "defaultMessage": "Date",+ "description": "Visible label for the Date segment in the mobile DateTimeInput bottom sheet."+ },+ "@astryx.dateTimeInput.timeTab": {+ "defaultMessage": "Time",+ "description": "Visible label for the Time segment in the mobile DateTimeInput bottom sheet."+ },+ "@astryx.dateTimeInput.openTimePicker": {+ "defaultMessage": "Open {label}",+ "description": "Aria label for the clock button in the mobile DateTimeInput closed time segment. `{label}` is the accessible name of the time input, for example `Meeting time`."+ },+ "@astryx.dateTimeInput.saveDatePicking": {+ "defaultMessage": "Save date",+ "description": "Primary button at the bottom of the Date panel in the mobile DateTimeInput bottom sheet. It does not close the sheet; it accepts the date step and moves to the Time panel. Use sentence case in English and title case only when appropriate for the locale."+ },+ "@astryx.dateTimeInput.hourWheel": {+ "defaultMessage": "Hour",+ "description": "Accessible name for the hour wheel in the mobile DateTimeInput bottom sheet."+ },+ "@astryx.dateTimeInput.minuteWheel": {+ "defaultMessage": "Minute",+ "description": "Accessible name for the minute wheel in the mobile DateTimeInput bottom sheet."+ },+ "@astryx.dateTimeInput.secondWheel": {+ "defaultMessage": "Second",+ "description": "Accessible name for the optional seconds wheel in the mobile DateTimeInput bottom sheet."+ },+ "@astryx.dateTimeInput.meridiemWheel": {+ "defaultMessage": "AM/PM",+ "description": "Accessible name for the AM/PM wheel in the mobile DateTimeInput bottom sheet when using 12-hour time."+ },+ "@astryx.dateTimeInput.meridiemAM": {+ "defaultMessage": "AM",+ "description": "Label for the morning half of the AM/PM wheel in the mobile DateTimeInput bottom sheet. Use the locale's concise ante-meridiem marker."+ },+ "@astryx.dateTimeInput.meridiemPM": {+ "defaultMessage": "PM",+ "description": "Label for the afternoon/evening half of the AM/PM wheel in the mobile DateTimeInput bottom sheet. Use the locale's concise post-meridiem marker."},"@astryx.link.newTab": {"defaultMessage": "(opens in new tab)",diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsxindex f6816fa7ae..6201b5c766 100644--- a/packages/core/src/DateInput/MonthScroller.tsx+++ b/packages/core/src/DateInput/MonthScroller.tsx@@ -25,6 +25,7 @@** SYNC: When modified, update:* - /packages/core/src/DateInput/TouchDateField.tsx+ * - /packages/core/src/DateTimeInput/TouchDateTimeField.tsx* - /packages/core/src/DateInput/DateInput.doc.mjs* - /packages/core/src/DateInput/DateInputTouch.test.tsx*/diff --git a/packages/core/src/DateInput/MonthYearWheels.tsx b/packages/core/src/DateInput/MonthYearWheels.tsxindex d59b252f95..abd8ba7fe6 100644--- a/packages/core/src/DateInput/MonthYearWheels.tsx+++ b/packages/core/src/DateInput/MonthYearWheels.tsx@@ -17,6 +17,7 @@** SYNC: When modified, update:* - /packages/core/src/DateInput/TouchDateField.tsx+ * - /packages/core/src/DateTimeInput/TouchDateTimeField.tsx* - /packages/core/src/DateInput/DateInput.doc.mjs* - /packages/core/src/DateInput/DateInputTouch.test.tsx*/diff --git a/packages/core/src/DateInput/Wheel.tsx b/packages/core/src/DateInput/Wheel.tsxindex ba22d8b82a..8da6ef8bf5 100644--- a/packages/core/src/DateInput/Wheel.tsx+++ b/packages/core/src/DateInput/Wheel.tsx@@ -28,6 +28,7 @@** SYNC: When modified, update:* - /packages/core/src/DateInput/TouchDateField.tsx+ * - /packages/core/src/DateTimeInput/TouchDateTimeField.tsx* - /packages/core/src/DateInput/DateInput.doc.mjs* - /packages/core/src/DateInput/DateInputTouch.test.tsx*/diff --git a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjsindex 250a232976..58b8c06761 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs+++ b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs@@ -120,14 +120,14 @@ export const docs = {name: 'timeIncrement',type: '1 | 5 | 10 | 15 | 30',description:- 'Minutes to add or subtract when using arrow keys in the time input.',+ 'Minutes to add or subtract when using arrow keys in the desktop time input. Ignored on the mobile touch sheet, where time is changed with wheels.',default: '1',},{name: 'timeOptionInterval',type: '5 | 10 | 15 | 30 | 60',description:- 'Minute cadence for a dropdown of preset times on the time portion. Set it to turn the time field into a combobox listing every valid time at that cadence (60 gives a 12 AM to 11 PM list). Omitted, the time field stays a plain text input and gains no combobox semantics. Typed entry keeps working either way, so a time between two options is still reachable. Independent of timeIncrement, which governs arrow-key stepping.',+ 'Minute cadence for a dropdown of preset times on the desktop time portion. Set it to turn the desktop time field into a combobox listing every valid time at that cadence (60 gives a 12 AM to 11 PM list). Omitted, the desktop time field stays a plain text input and gains no combobox semantics. Typed entry keeps working either way, so a time between two options is still reachable. Ignored on the mobile touch sheet, where the wheels expose every hour/minute/second.',},{name: 'hasClear',@@ -146,7 +146,7 @@ export const docs = {name: 'timePlaceholder',type: 'string',description:- 'Placeholder text shown in the time portion when no time is selected.',+ 'Placeholder text shown in the time portion when no time is selected. On touch, this appears in the closed time segment before a time is chosen.',default: "'Select a time'",},{@@ -176,7 +176,8 @@ export const docs = {{name: 'numberOfMonths',type: '1 | 2',- description: 'Number of months displayed simultaneously in the calendar.',+ description:+ 'Number of months displayed simultaneously in the desktop calendar popover. Ignored on the mobile touch sheet, whose Date panel always shows one swipe-paged month at a time.',default: '1',},{@@ -201,7 +202,11 @@ export const docs = {],theming: {targets: [- {className: 'astryx-date-time-input', visualProps: ['size', 'status'], states: ['disabled']},+ {+ className: 'astryx-date-time-input',+ visualProps: ['size', 'status'],+ states: ['disabled'],+ },{className: 'astryx-date-time-input-date-segment',visualProps: ['size', 'status'],@@ -218,7 +223,7 @@ export const docs = {},usage: {description:- 'DateTimeInput 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.',+ 'DateTimeInput combines date and time selection in one field. On mouse/trackpad devices it uses a calendar popover plus text time input; on coarse-pointer devices the closed control still has separate Date and Time segments, and either segment opens a bottom sheet with Date and Time sections, a swipable month calendar, and accessible time wheels. Use it for scheduling, event creation, deadline setting, or any form field that needs a specific datetime.',bestPractices: [{guidance: true,@@ -283,19 +288,19 @@ export const docs = {name: 'Calendar popover',required: false,description:- 'A month grid that appears when the icon is clicked or the date input is focused.',+ 'A month grid that appears in a popover on desktop, or in the mobile bottom sheet on coarse-pointer devices.',},{name: 'Time input',required: true,description:- 'A text input for entering the time, displayed beside the date input.',+ "A text input for entering the time on desktop; a read-only time segment opening accessible hour/minute/second wheels on touch. The touch Date panel's Save date action advances to Time; the Time panel's Save closes the sheet.",},{name: 'Time options popover',required: false,description:- 'A list of preset times at the timeOptionInterval cadence, shown when that prop is set and the time input is clicked or opened with Alt+ArrowDown.',+ 'A desktop-only list of preset times at the timeOptionInterval cadence, shown when that prop is set and the time input is clicked or opened with Alt+ArrowDown.',},{name: 'Clear button',@@ -317,7 +322,7 @@ export const docsZh = {displayName: 'Date Time Input',usage: {description:- 'DateTimeInput 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.',+ 'DateTimeInput combines date and time selection in one field. On mouse/trackpad devices it uses a calendar popover plus text time input; on coarse-pointer devices the closed control still has separate Date and Time segments, and either segment opens a bottom sheet with Date and Time sections, a swipable month calendar, and accessible time wheels. Use it for scheduling, event creation, deadline setting, or any form field that needs a specific datetime.',bestPractices: [{guidance: true,@@ -451,7 +456,8 @@ export const docsZh = {{name: 'timeIncrement',type: '1 | 5 | 10 | 15 | 30',- description: '在时间输入中按箭头键时增减的分钟数。',+ description:+ '在桌面时间输入中按箭头键时增减的分钟数。在移动触摸面板中会被忽略,时间通过滚轮更改。',default: '1',},{@@ -469,7 +475,8 @@ export const docsZh = {{name: 'timePlaceholder',type: 'string',- description: '时间部分未选择时间时显示的占位符文本。',+ description:+ '时间部分未选择时间时显示的占位符文本。在触摸设备上,这会显示在未选择时间的闭合时间段中。',default: "'Select a time'",},{@@ -497,13 +504,15 @@ export const docsZh = {{name: 'numberOfMonths',type: '1 | 2',- description: '日历中同时显示的月份数量。',+ description:+ '桌面日历弹出层中同时显示的月份数量。在移动触摸面板中会被忽略,日期面板一次显示一个可滑动月份。',default: '1',},{name: 'weekStartsOn',type: "0 | 1 | 2 | 3 | 4 | 5 | 6 | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'",- description: '日历中每周的起始日。可为数字(0=周日……6=周六)或三字母星期缩写。',+ description:+ '日历中每周的起始日。可为数字(0=周日……6=周六)或三字母星期缩写。',default: '0',},{@@ -515,7 +524,11 @@ export const docsZh = {],theming: {targets: [- {className: 'astryx-date-time-input', visualProps: ['size', 'status'], states: ['disabled']},+ {+ className: 'astryx-date-time-input',+ visualProps: ['size', 'status'],+ states: ['disabled'],+ },{className: 'astryx-date-time-input-date-segment',visualProps: ['size', 'status'],@@ -538,7 +551,7 @@ export const docsDense = {'combined date + time picker with calendar popover and time input',usage: {description:- 'DateTimeInput 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.',+ 'DateTimeInput combines date and time selection. Desktop uses a calendar popover plus time input; coarse pointers show separate Date/Time closed segments that open a bottom sheet with matching sections, a Save date step, and final time-wheel Save. Use for scheduling, events, deadlines, or any form field needing a datetime.',bestPractices: [{guidance: true,@@ -600,19 +613,23 @@ export const docsDense = {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',+ timeIncrement:+ 'desktop only: minutes to add/subtract on arrow keys in time input; mobile uses wheels',timeOptionInterval:- 'minute cadence for a preset-time dropdown on the time input; omitted = plain text input, no combobox. typed entry still works',+ 'desktop only: minute cadence for a preset-time dropdown on the time input; omitted = plain text input, no combobox. mobile uses wheels',hasClear: 'Shows clear button when datetime is set',placeholder: 'date-portion placeholder when empty',- timePlaceholder: 'time-portion placeholder when empty',+ timePlaceholder:+ 'time-portion placeholder when empty; shown on touch closed time segment',timeLabel:'accessible label for the time input; defaults to "{label} time"',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',- weekStartsOn: 'first day of week in calendar (0=Sunday, or name e.g. "mon")',+ numberOfMonths:+ 'desktop calendar months shown simultaneously; ignored on mobile touch sheet',+ weekStartsOn:+ 'first day of week in calendar (0=Sunday, or name e.g. "mon")',xstyle: 'StyleX styles for layout; must be stylex.create() value',},};diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsxindex 32d9153485..b143403fa8 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx@@ -4,13 +4,14 @@/*** @file DateTimeInput.tsx- * @input Uses React, Field, Calendar, usePopover, useAnnounce, time parsing utilities+ * @input Uses React, Field, Calendar, usePopover, useAnnounce, time parsing utilities, TouchDateTimeField* @output Exports DateTimeInput component, DateTimeInputProps* @position Core implementation; consumed by index.ts, tested by DateTimeInput.test.tsx** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/DateTimeInput/DateTimeInput.doc.mjs (props table, features, implementation notes)- * - /packages/core/src/DateTimeInput/DateTimeInput.test.tsx (tests for new/changed behavior)+ * - /packages/core/src/DateTimeInput/DateTimeInput.test.tsx (desktop tests for new/changed behavior)+ * - /packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx (touch-surface tests)* - /packages/core/src/DateTimeInput/index.ts (exports if types change)* - /apps/storybook/stories/DateTimeInput.stories.tsx (storybook stories)* - /packages/cli/assets/templates/blocks/components/DateTimeInput/ (showcase blocks)@@ -37,7 +38,6 @@ import {typographyVars,typeScaleVars,fontWeightVars,- borderVars,} from '../theme/tokens.stylex';import {Field,@@ -87,6 +87,7 @@ import {import type {BaseProps} from '../BaseProps';import type {SizeValue} from '../utils/types';import {useAnnounce} from '../hooks/useAnnounce';+import {useMediaQuery} from '../hooks/useMediaQuery';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {useSize} from '../SizeContext/SizeContext';import {themeProps} from '../utils/themeProps';@@ -94,6 +95,7 @@ import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {useLocale, useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';+import {TouchDateTimeField} from './TouchDateTimeField';export type ISODateTimeString = string & {readonly __brand: 'ISODateTimeString';};@@ -361,25 +363,28 @@ export interface DateTimeInputProps extends Omit<hourFormat?: DateTimeInputHourFormat;/**- * Minutes added or subtracted when stepping the time field with the arrow- * keys. Constrained to a set of sensible increments.+ * Minutes added or subtracted when stepping the desktop time field with the+ * arrow keys. Ignored on the mobile touch sheet, where time is changed with+ * wheels. Constrained to a set of sensible increments.* @default 1*/timeIncrement?: DateTimeInputTimeIncrement;/**- * Minute cadence for a dropdown of preset times on the time field. Set it to- * turn the time field into a combobox listing every valid time at that+ * Minute cadence for a dropdown of preset times on the desktop time field. Set+ * it to turn the time field into a combobox listing every valid time at that* cadence (`60` gives the 12 AM - 11 PM list, `15` a quarter-hour list).*- * Omitted, the time field stays a plain text input: typed entry and+ * Omitted, the desktop time field stays a plain text input: typed entry and* arrow-key stepping only, with no combobox semantics added to the- * accessibility tree. Typed entry keeps working when the dropdown is on —- * the list is a shortcut, not a restriction, so a time between two options- * can still be typed.+ * accessibility tree. Typed entry keeps working when the dropdown is on — the+ * list is a shortcut, not a restriction, so a time between two options can+ * still be typed.*- * Independent of `timeIncrement`, which governs arrow-key stepping. Setting- * both to the same value is the usual choice for scheduling flows.+ * Ignored on the mobile touch sheet, where the wheels expose every+ * hour/minute/second. Independent of `timeIncrement`, which governs desktop+ * arrow-key stepping. Setting both to the same value is the usual choice for+ * scheduling flows on desktop.*/timeOptionInterval?: DateTimeInputTimeOptionInterval;@@ -397,6 +402,7 @@ export interface DateTimeInputProps extends Omit</*** Placeholder text shown in the time portion when no time is selected.+ * On touch, this appears in the closed time segment before a time is chosen.* @default "Select a time"*/timePlaceholder?: string;@@ -431,7 +437,9 @@ export interface DateTimeInputProps extends Omit<labelTooltip?: string;/**- * Number of months to display in the calendar.+ * Number of months to display in the desktop calendar popover. Ignored on the+ * mobile touch sheet, whose Date panel always shows one swipe-paged month at a+ * time.* @default 1*/numberOfMonths?: 1 | 2;@@ -496,7 +504,7 @@ function getDefaultTime(hasSeconds: boolean): ISOTimeString {* />* ```*/-export function DateTimeInput({+function PointerDateTimeField({label,isLabelHidden = false,description,@@ -1689,4 +1697,24 @@ export function DateTimeInput({);}+PointerDateTimeField.displayName = 'PointerDateTimeField';++const TOUCH_POINTER_QUERY = '(pointer: coarse)';++/**+ * A combined date and time picker that keeps the desktop text-entry surface on+ * mouse/trackpad devices and uses Astryx's custom bottom-sheet picker on coarse+ * pointers. Unlike DateInput, this never hands touch picking to the browser/OS:+ * the mobile flow has to coordinate date and time together, preserve drafted+ * time before a date exists, and enforce datetime min/max across both panels.+ */+export function DateTimeInput(props: DateTimeInputProps) {+ const isTouch = useMediaQuery(TOUCH_POINTER_QUERY);+ return isTouch ? (+ <TouchDateTimeField {...props} />+ ) : (+ <PointerDateTimeField {...props} />+ );+}+DateTimeInput.displayName = 'DateTimeInput';diff --git a/packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx b/packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsxnew file mode 100644index 0000000000..537c243a24--- /dev/null+++ b/packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx@@ -0,0 +1,949 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DateTimeInputTouch.test.tsx+ * @input Uses vitest, @testing-library/react, DateTimeInput touch surface+ * @output Focused coverage for DateTimeInput's coarse-pointer bottom-sheet picker+ * @position Test file for /packages/core/src/DateTimeInput/+ *+ * The touch surface reuses DateInput's sheet/calendar primitives, so this file+ * keeps coverage at the DateTimeInput integration seams: surface selection,+ * segmented switching, date/time combination, constraints, and field parity.+ */++import {+ describe,+ it,+ expect,+ vi,+ beforeAll,+ afterAll,+ beforeEach,+ afterEach,+} from 'vitest';+import {useState} from 'react';+import {readFileSync} from 'node:fs';+import {render, screen, fireEvent, within} from '@testing-library/react';+import {DateTimeInput} from './DateTimeInput';+import type {ISODateTimeString} from './DateTimeInput';++class MockResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+}++const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;+const SCROLLPORT_WIDTH = 360;++function stubMedia(pointer: 'coarse' | 'fine', anyPointer = pointer): void {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: /any-pointer:\s*coarse/.test(query)+ ? anyPointer === 'coarse'+ : /pointer:\s*coarse/.test(query)+ ? pointer === 'coarse'+ : /pointer:\s*fine/.test(query)+ ? pointer === 'fine'+ : HOVER_CAPABLE.test(query),+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ }));+}++function withMonthLayout<T>(fn: () => T): T {+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', {+ configurable: true,+ get(this: HTMLElement) {+ return this.dataset?.scroller === 'months' ? SCROLLPORT_WIDTH : 0;+ },+ });+ try {+ return fn();+ } finally {+ delete (HTMLElement.prototype as {clientWidth?: unknown}).clientWidth;+ }+}++function dateField(label = 'Meeting'): HTMLElement {+ return screen.getByRole('combobox', {name: label});+}++function timeField(label = 'Meeting time'): HTMLElement {+ return screen.getByRole('combobox', {name: label});+}++function dateSegment(): HTMLElement {+ const segment = document.querySelector(+ '.astryx-date-time-input-date-segment',+ );+ if (!(segment instanceof HTMLElement)) {+ throw new Error('date segment not found');+ }+ return segment;+}++function timeSegment(): HTMLElement {+ const segment = document.querySelector(+ '.astryx-date-time-input-time-segment',+ );+ if (!(segment instanceof HTMLElement)) {+ throw new Error('time segment not found');+ }+ return segment;+}++function openDateSheet(label = 'Meeting'): HTMLElement {+ const field = dateField(label);+ fireEvent.click(field);+ return field;+}++function openTimeSheet(label = 'Meeting time'): HTMLElement {+ const field = timeField(label);+ fireEvent.click(field);+ return field;+}++function switchToTimePanel(): void {+ fireEvent.click(screen.getByRole('radio', {name: 'Time'}));+}++function optionIn(listName: string, optionName: string): HTMLElement {+ return within(screen.getByRole('listbox', {name: listName})).getByRole(+ 'option',+ {name: optionName},+ );+}++function ControlledDateTimeInput({+ initialValue,+}: {+ initialValue?: ISODateTimeString;+}) {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ initialValue,+ );+ return <DateTimeInput label="Meeting" value={value} onChange={setValue} />;+}++beforeAll(() => {+ window.scrollTo = vi.fn();+ Element.prototype.scrollTo = vi.fn();+ Element.prototype.scrollIntoView = vi.fn();+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.open = true;+ });+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {+ this.open = true;+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.open = false;+ });+});++afterAll(() => {+ vi.useRealTimers();+});++beforeEach(() => {+ vi.setSystemTime(new Date(2026, 2, 15, 9, 30, 45));+ vi.stubGlobal('ResizeObserver', MockResizeObserver);+ stubMedia('coarse');+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('DateTimeInput touch surface', () => {+ it('uses the bottom-sheet picker on a coarse pointer', () => {+ withMonthLayout(() => {+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);+ const field = dateField();++ expect(field).toHaveAttribute('readonly');+ expect(field).toHaveAttribute('inputmode', 'none');+ expect(field).toHaveAttribute('aria-expanded', 'false');++ fireEvent.click(field);+ expect(field).toHaveAttribute('aria-expanded', 'true');+ expect(+ screen.getByRole('radiogroup', {name: 'Date/time section'}),+ ).toBeInTheDocument();+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ });+ });++ it('keeps the desktop two-field surface on a fine primary pointer', () => {+ stubMedia('fine', 'coarse');+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);++ expect(screen.getByRole('combobox')).not.toHaveAttribute('readonly');+ expect(screen.getByLabelText('Meeting time')).toBeInTheDocument();+ });++ it('closed touch fields display separate values and placeholders', () => {+ const {rerender} = render(+ <DateTimeInput label="Meeting" onChange={() => {}} />,+ );+ expect(dateField()).toHaveAttribute('placeholder', 'Select a date');+ expect(timeField()).toHaveAttribute('placeholder', 'Select a time');+ expect(dateField()).toHaveValue('');+ expect(timeField()).toHaveValue('');++ rerender(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ expect(dateField()).toHaveValue('March 15, 2026');+ expect(timeField()).toHaveValue('2:30 PM');+ expect(dateField()).not.toHaveValue('March 15, 2026, 2:30 PM');+ });++ it('uses a custom timePlaceholder on the touch time segment', () => {+ render(+ <DateTimeInput+ label="Meeting"+ timePlaceholder="Pick a time"+ onChange={() => {}}+ />,+ );+ expect(timeField()).toHaveAttribute('placeholder', 'Pick a time');+ });++ it('does not wire focus to reopen the sheet after dismissal', () => {+ const source = readFileSync(+ 'packages/core/src/DateTimeInput/TouchDateTimeField.tsx',+ 'utf8',+ );+ expect(source).not.toContain('onFocus=');+ expect(source).not.toContain('handleDateFocus');+ expect(source).not.toContain('handleTimeFocus');+ });++ it('opens directly to Date from the date segment and calendar icon', () => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T09:30' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ fireEvent.click(dateField());+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ expect(dateField()).toHaveAttribute('aria-expanded', 'true');+ expect(timeField()).toHaveAttribute('aria-expanded', 'false');++ fireEvent.click(screen.getByRole('button', {name: 'Save date'}));+ expect(screen.getByRole('radio', {name: 'Time'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ fireEvent.click(screen.getByRole('button', {name: 'Open calendar'}));+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ });++ it('opens directly to Time from the time segment and clock affordance with no date', () => {+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);+ fireEvent.click(timeField());+ expect(screen.getByRole('radio', {name: 'Time'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ expect(dateField()).toHaveAttribute('aria-expanded', 'false');+ expect(timeField()).toHaveAttribute('aria-expanded', 'true');++ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ fireEvent.click(screen.getByRole('button', {name: 'Open Meeting time'}));+ expect(screen.getByRole('radio', {name: 'Time'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ });++ it('opens from date and time segment padding clicks', () => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T09:30' as ISODateTimeString}+ onChange={() => {}}+ />,+ );++ fireEvent.click(dateSegment());+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ fireEvent.click(screen.getByRole('button', {name: 'Save date'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));++ fireEvent.click(timeSegment());+ expect(screen.getByRole('radio', {name: 'Time'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ });++ it('keyboard activation opens the corresponding touch panel', () => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T09:30' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ fireEvent.keyDown(dateField(), {key: 'Enter'});+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );++ fireEvent.click(screen.getByRole('button', {name: 'Save date'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ fireEvent.keyDown(timeField(), {key: ' '});+ expect(screen.getByRole('radio', {name: 'Time'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ });++ it('switches between inert date and time panels with the pill control', () => {+ withMonthLayout(() => {+ const {container} = render(+ <DateTimeInput label="Meeting" onChange={() => {}} />,+ );+ openDateSheet();++ const datePanel = container.querySelector(+ '[data-panel="date"]',+ ) as HTMLElement;+ const timePanel = container.querySelector(+ '[data-panel="time"]',+ ) as HTMLElement;+ expect(datePanel).not.toHaveAttribute('aria-hidden');+ expect(timePanel).toHaveAttribute('aria-hidden', 'true');++ switchToTimePanel();+ expect(datePanel).toHaveAttribute('aria-hidden', 'true');+ expect(timePanel).not.toHaveAttribute('aria-hidden');+ expect(screen.getByRole('radio', {name: 'Time'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ expect(dateField()).toHaveAttribute('aria-expanded', 'false');+ expect(timeField()).toHaveAttribute('aria-expanded', 'true');+ });+ });++ it('selects a date with the drafted/default time and leaves the Date panel active', () => {+ const onChange = vi.fn();+ withMonthLayout(() => {+ render(<DateTimeInput label="Meeting" onChange={onChange} />);+ openDateSheet();++ fireEvent.click(+ screen.getByRole('button', {name: 'Saturday, March 21, 2026'}),+ );++ expect(onChange).toHaveBeenCalledWith('2026-03-21T09:30');+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ });+ });++ it('does not lose a time chosen before the date exists', () => {+ const onChange = vi.fn();+ withMonthLayout(() => {+ render(<DateTimeInput label="Meeting" onChange={onChange} />);+ openTimeSheet();++ fireEvent.click(optionIn('AM/PM', 'PM'));+ fireEvent.click(optionIn('Hour', '3'));+ fireEvent.click(optionIn('Minute', '45'));+ expect(timeField()).toHaveValue('3:45 PM');+ expect(dateField()).toHaveValue('');+ expect(onChange).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('radio', {name: 'Date'}));+ fireEvent.click(+ screen.getByRole('button', {name: 'Saturday, March 21, 2026'}),+ );+ expect(onChange).toHaveBeenCalledWith('2026-03-21T15:45');+ });+ });++ it('keeps an uncommitted time draft across Date and Time tab switches', () => {+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);+ openTimeSheet();++ fireEvent.click(optionIn('AM/PM', 'PM'));+ fireEvent.click(optionIn('Hour', '3'));+ fireEvent.click(optionIn('Minute', '45'));+ fireEvent.click(screen.getByRole('radio', {name: 'Date'}));+ expect(timeField()).toHaveValue('3:45 PM');++ switchToTimePanel();+ expect(timeField()).toHaveValue('3:45 PM');+ });++ it('clears an uncommitted time draft when Time Save closes without a date', () => {+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);+ openTimeSheet();++ fireEvent.click(optionIn('AM/PM', 'PM'));+ fireEvent.click(optionIn('Hour', '3'));+ fireEvent.click(optionIn('Minute', '45'));+ expect(timeField()).toHaveValue('3:45 PM');++ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(timeField()).toHaveValue('');+ });++ it('clears an uncommitted time draft when dismissed with Escape', () => {+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);+ openTimeSheet();++ fireEvent.click(optionIn('AM/PM', 'PM'));+ fireEvent.click(optionIn('Hour', '3'));+ fireEvent.click(optionIn('Minute', '45'));+ expect(timeField()).toHaveValue('3:45 PM');++ fireEvent.keyDown(screen.getByRole('dialog'), {key: 'Escape'});+ expect(timeField()).toHaveValue('');+ });++ it('clears an uncommitted time draft when dismissed from the scrim', () => {+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);+ openTimeSheet();++ fireEvent.click(optionIn('AM/PM', 'PM'));+ fireEvent.click(optionIn('Hour', '3'));+ fireEvent.click(optionIn('Minute', '45'));+ expect(timeField()).toHaveValue('3:45 PM');++ fireEvent.click(screen.getByRole('dialog'));+ expect(timeField()).toHaveValue('');+ });++ it('commits 12-hour wheel changes against the controlled date', () => {+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ />,+ );+ openDateSheet();+ switchToTimePanel();++ fireEvent.click(optionIn('Hour', '3'));+ expect(onChange).toHaveBeenCalledWith('2026-03-15T15:30');+ });++ it('commits 24-hour wheel changes', () => {+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ hourFormat="24h"+ onChange={onChange}+ />,+ );+ openDateSheet();+ switchToTimePanel();++ fireEvent.click(optionIn('Hour', '09'));+ expect(onChange).toHaveBeenCalledWith('2026-03-15T09:30');+ });++ it('commits seconds when hasSeconds is set', () => {+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30:00' as ISODateTimeString}+ hasSeconds+ onChange={onChange}+ />,+ );+ openDateSheet();+ switchToTimePanel();++ fireEvent.click(optionIn('Second', '45'));+ expect(onChange).toHaveBeenCalledWith('2026-03-15T14:30:45');+ });++ it('disables out-of-range hours on the min/max boundary date', () => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T10:00' as ISODateTimeString}+ min={'2026-03-15T09:00' as ISODateTimeString}+ max={'2026-03-15T17:00' as ISODateTimeString}+ hourFormat="24h"+ onChange={() => {}}+ />,+ );+ openDateSheet();+ switchToTimePanel();++ expect(optionIn('Hour', '08')).toHaveAttribute('aria-disabled', 'true');+ expect(optionIn('Hour', '09')).not.toHaveAttribute('aria-disabled');+ expect(optionIn('Hour', '18')).toHaveAttribute('aria-disabled', 'true');+ });++ it('preserves the browsed month when switching Date to Time and back', () => {+ withMonthLayout(() => {+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);+ openDateSheet();++ fireEvent.click(screen.getByRole('button', {name: 'Next month'}));+ expect(screen.getByText('April 2026')).toBeInTheDocument();++ switchToTimePanel();+ fireEvent.click(screen.getByRole('radio', {name: 'Date'}));+ expect(screen.getByText('April 2026')).toBeInTheDocument();+ expect(document.querySelector('[data-scroller="months"]')).not.toBeNull();+ });+ });++ it('bounds grid panel min-content width so MonthScroller cannot feed back through its spacer', () => {+ const source = readFileSync(+ 'packages/core/src/DateTimeInput/TouchDateTimeField.tsx',+ 'utf8',+ );+ const styleBlock = (name: string): string => {+ const match = new RegExp(`${name}: \\{([\\s\\S]*?)\\n \\},`).exec(+ source,+ );+ if (match == null) {+ throw new Error(`missing style block ${name}`);+ }+ return match[1];+ };++ for (const name of [+ 'touchRow',+ 'touchSheetBody',+ 'touchSurface',+ 'touchPanelStack',+ 'touchPanel',+ 'touchDateSurfaceStack',+ 'touchDateSurface',+ 'touchTimeWheels',+ ]) {+ expect(styleBlock(name)).toContain("inlineSize: '100%'");+ expect(styleBlock(name)).toContain('minInlineSize: 0');+ }+ for (const name of ['touchDateWrapper', 'touchTimeWrapper']) {+ expect(styleBlock(name)).toContain('minInlineSize: 0');+ }+ });++ it('keeps accepting in-sheet edits while a changeAction is pending', () => {+ const onChange = vi.fn();+ const changeAction = vi.fn(async () => new Promise<void>(() => {}));+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ changeAction={changeAction}+ />,+ );+ openDateSheet();+ switchToTimePanel();++ fireEvent.click(optionIn('Hour', '3'));+ expect(onChange).toHaveBeenCalledWith('2026-03-15T15:30');+ expect(dateField()).toHaveAttribute('aria-busy', 'true');++ fireEvent.click(optionIn('Minute', '45'));+ expect(onChange).toHaveBeenCalledWith('2026-03-15T15:45');+ expect(changeAction).toHaveBeenCalledTimes(2);+ });++ it('clamps drafted time to the selected date boundary', () => {+ const onChange = vi.fn();+ withMonthLayout(() => {+ render(+ <DateTimeInput+ label="Meeting"+ min={'2026-03-21T09:00' as ISODateTimeString}+ onChange={onChange}+ />,+ );+ openDateSheet();+ switchToTimePanel();+ fireEvent.click(optionIn('Hour', '3'));++ fireEvent.click(screen.getByRole('radio', {name: 'Date'}));+ fireEvent.click(+ screen.getByRole('button', {name: 'Saturday, March 21, 2026'}),+ );++ expect(onChange).toHaveBeenCalledWith('2026-03-21T09:00');+ });+ });++ it('honors dateConstraints in the Date panel', () => {+ const onChange = vi.fn();+ withMonthLayout(() => {+ render(+ <DateTimeInput+ label="Meeting"+ dateConstraints={[date => date.getDate() !== 21]}+ onChange={onChange}+ />,+ );+ openDateSheet();+ const disabledDay = screen.getByRole('button', {+ name: 'Saturday, March 21, 2026',+ });++ expect(disabledDay).toHaveAttribute('aria-disabled', 'true');+ fireEvent.click(disabledDay);+ expect(onChange).not.toHaveBeenCalled();+ });+ });++ it('Reset clears the value and leaves the sheet open on the Date panel', () => {+ const onChange = vi.fn();+ withMonthLayout(() => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T10:00' as ISODateTimeString}+ onChange={onChange}+ />,+ );+ const field = openDateSheet();++ fireEvent.click(screen.getByRole('button', {name: 'Reset'}));+ expect(onChange).toHaveBeenCalledWith(undefined);+ expect(field).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ });+ });++ it('keeps Save date disabled until a valid date exists', () => {+ withMonthLayout(() => {+ render(<ControlledDateTimeInput />);+ openDateSheet();+ const saveDateButton = screen.getByRole('button', {name: 'Save date'});++ expect(saveDateButton).toBeDisabled();+ fireEvent.click(saveDateButton);+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ expect(timeField()).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('enables Save date after a controlled date selection updates value', () => {+ vi.useFakeTimers();+ withMonthLayout(() => {+ render(<ControlledDateTimeInput />);+ openDateSheet();+ const saveDateButton = screen.getByRole('button', {name: 'Save date'});+ expect(saveDateButton).toBeDisabled();++ fireEvent.click(+ screen.getByRole('button', {name: 'Saturday, March 21, 2026'}),+ );+ expect(dateField()).toHaveValue('March 21, 2026');+ expect(saveDateButton).not.toBeDisabled();++ fireEvent.click(saveDateButton);+ expect(dateField()).toHaveAttribute('aria-expanded', 'false');+ expect(timeField()).toHaveAttribute('aria-expanded', 'true');+ const timeTab = screen.getByRole('radio', {name: 'Time'});+ expect(timeTab).toHaveAttribute('aria-checked', 'true');++ vi.runAllTimers();+ expect(timeTab).toHaveFocus();+ });+ vi.useRealTimers();+ });++ it('disables Save date after Reset clears the controlled date', () => {+ withMonthLayout(() => {+ render(+ <ControlledDateTimeInput+ initialValue={'2026-03-15T10:00' as ISODateTimeString}+ />,+ );+ openDateSheet();+ const saveDateButton = screen.getByRole('button', {name: 'Save date'});+ expect(saveDateButton).not.toBeDisabled();++ fireEvent.click(screen.getByRole('button', {name: 'Reset'}));+ expect(dateField()).toHaveValue('');+ expect(saveDateButton).toBeDisabled();++ fireEvent.click(saveDateButton);+ expect(screen.getByRole('radio', {name: 'Date'})).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ expect(timeField()).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('Save date advances to Time, focuses the Time tab, and does not change the value', () => {+ vi.useFakeTimers();+ const onChange = vi.fn();+ withMonthLayout(() => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T10:00' as ISODateTimeString}+ onChange={onChange}+ />,+ );+ openDateSheet();+ const timeTab = screen.getByRole('radio', {name: 'Time'});++ fireEvent.click(screen.getByRole('button', {name: 'Save date'}));++ expect(dateField()).toHaveAttribute('aria-expanded', 'false');+ expect(timeField()).toHaveAttribute('aria-expanded', 'true');+ expect(timeTab).toHaveAttribute('aria-checked', 'true');+ expect(document.querySelector('[data-panel="time"]')).not.toHaveAttribute(+ 'aria-hidden',+ );+ expect(onChange).not.toHaveBeenCalled();++ vi.runAllTimers();+ expect(timeTab).toHaveFocus();+ });+ vi.useRealTimers();+ });++ it('Save after keyboard opening does not refocus-reopen the sheet', () => {+ withMonthLayout(() => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T10:00' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ const field = dateField();+ field.focus();+ fireEvent.keyDown(field, {key: 'Enter'});+ expect(field).toHaveAttribute('aria-expanded', 'true');++ fireEvent.click(screen.getByRole('button', {name: 'Save date'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(field).toHaveAttribute('aria-expanded', 'false');+ expect(timeField()).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('Time Save closes the sheet without changing the value', () => {+ const onChange = vi.fn();+ withMonthLayout(() => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T10:00' as ISODateTimeString}+ onChange={onChange}+ />,+ );+ openDateSheet();+ fireEvent.click(screen.getByRole('button', {name: 'Save date'}));++ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(dateField()).toHaveAttribute('aria-expanded', 'false');+ expect(timeField()).toHaveAttribute('aria-expanded', 'false');+ expect(onChange).not.toHaveBeenCalled();+ });+ });++ it('disables out-of-range seconds on the min/max boundary time', () => {+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30:30' as ISODateTimeString}+ min={'2026-03-15T14:30:30' as ISODateTimeString}+ max={'2026-03-15T14:30:30' as ISODateTimeString}+ hasSeconds+ onChange={() => {}}+ />,+ );+ openDateSheet();+ switchToTimePanel();++ expect(optionIn('Second', '29')).toHaveAttribute('aria-disabled', 'true');+ expect(optionIn('Second', '30')).not.toHaveAttribute('aria-disabled');+ expect(optionIn('Second', '31')).toHaveAttribute('aria-disabled', 'true');+ });++ it('reflects controlled value changes in the closed field', () => {+ const {rerender} = render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T10:00' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ expect(dateField()).toHaveValue('March 15, 2026');+ expect(timeField()).toHaveValue('10:00 AM');++ rerender(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-16T18:45' as ISODateTimeString}+ onChange={() => {}}+ />,+ );+ expect(dateField()).toHaveValue('March 16, 2026');+ expect(timeField()).toHaveValue('6:45 PM');+ });++ it('clears the whole datetime and restores focus on the next task', () => {+ vi.useFakeTimers();+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T10:00' as ISODateTimeString}+ hasClear+ onChange={onChange}+ />,+ );+ const field = dateField();+ const focusSpy = vi.spyOn(field, 'focus');++ fireEvent.click(screen.getByRole('button', {name: 'Clear Meeting'}));+ expect(onChange).toHaveBeenCalledWith(undefined);+ expect(field).toHaveAttribute('aria-expanded', 'false');+ expect(focusSpy).not.toHaveBeenCalled();++ vi.runAllTimers();+ expect(focusSpy).toHaveBeenCalledWith({preventScroll: true});+ vi.useRealTimers();+ });++ it('blocks opening, clearing and in-sheet edits while loading', () => {+ const onChange = vi.fn();+ const {rerender} = render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ isLoading+ hasClear+ onChange={onChange}+ />,+ );+ const loadingField = dateField();+ fireEvent.click(loadingField);+ expect(loadingField).toHaveAttribute('aria-expanded', 'false');+ expect(+ screen.queryByRole('button', {name: 'Clear Meeting'}),+ ).not.toBeInTheDocument();++ rerender(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ hasClear+ onChange={onChange}+ />,+ );+ const field = dateField();+ fireEvent.click(field);+ switchToTimePanel();+ expect(field).toHaveAttribute('aria-expanded', 'false');+ expect(timeField()).toHaveAttribute('aria-expanded', 'true');++ rerender(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ isLoading+ hasClear+ onChange={onChange}+ />,+ );+ expect(field).toHaveAttribute('aria-expanded', 'false');+ expect(onChange).not.toHaveBeenCalled();+ });++ it('clicking the pending spinner inside an enabled date segment does not open the sheet', () => {+ const onChange = vi.fn();+ const changeAction = vi.fn(async () => new Promise<void>(() => {}));+ const {container} = render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ changeAction={changeAction}+ onChange={onChange}+ />,+ );+ openTimeSheet();+ fireEvent.click(optionIn('Minute', '45'));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ const spinner = container.querySelector(+ '.astryx-date-time-input-date-segment .astryx-spinner',+ ) as HTMLElement;+ expect(spinner).not.toBeNull();+ expect(dateField()).not.toBeDisabled();++ fireEvent.click(spinner);++ expect(dateField()).toHaveAttribute('aria-expanded', 'false');+ expect(timeField()).toHaveAttribute('aria-expanded', 'false');+ });++ it('keeps a disabled reason reachable while blocking activation', () => {+ render(+ <DateTimeInput+ label="Meeting"+ isDisabled+ disabledMessage="Choose a project first"+ onChange={() => {}}+ />,+ );+ const field = dateField();++ expect(field).not.toBeDisabled();+ expect(field).toHaveAttribute('aria-disabled', 'true');+ expect(field.getAttribute('aria-describedby')).toContain(+ screen.getByRole('tooltip', {hidden: true}).id,+ );+ fireEvent.click(field);+ expect(field).toHaveAttribute('aria-expanded', 'false');+ });+});diff --git a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx b/packages/core/src/DateTimeInput/TouchDateTimeField.tsxnew file mode 100644index 0000000000..3f6436315d--- /dev/null+++ b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx@@ -0,0 +1,1434 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file TouchDateTimeField.tsx+ * @input Uses React, Field, BottomSheet, SegmentedControl, DateInput month picker primitives, Wheel+ * @output Exports TouchDateTimeField — the coarse-pointer surface behind DateTimeInput+ * @position Internal component; consumed by DateTimeInput.tsx+ *+ * The touch half of `DateTimeInput`, holding `DateTimeInput`'s whole prop+ * contract so the desktop and touch surfaces are interchangeable. The desktop+ * only props `timeIncrement` and `timeOptionInterval` remain accepted but are+ * intentionally ignored here: time is selected with wheels instead of a typed+ * field or preset list.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/DateTimeInput/DateTimeInput.tsx+ * - /packages/core/src/DateTimeInput/DateTimeInput.doc.mjs+ * - /packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx+ * - /apps/storybook/stories/DateTimeInput.stories.tsx+ * - /packages/cli/assets/templates/blocks/components/DateTimeInput/+ */++import {+ use,+ useCallback,+ useEffect,+ useId,+ useMemo,+ useOptimistic,+ useRef,+ useState,+ useTransition,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import {BottomSheet} from '../BottomSheet';+import {Button} from '../Button';+import {useCalendarConstraints, type ISODateString} from '../Calendar';+import {+ Field,+ InputClearButton,+ inputWrapperStyles,+ inputStatusBorderStyles,+ inputStatusHoverShadowStyles,+ inputStatusFocusWithinStyles,+} from '../Field';+import {useInputStatusIcon, useMergedRefs} from '../hooks';+import {useResolvedRequired} from '../hooks/useResolvedRequired';+import {Icon} from '../Icon';+import {IconButton} from '../IconButton';+import {useTranslator, InternationalizationContext} from '../i18n';+import {SegmentedControl, SegmentedControlItem} from '../SegmentedControl';+import {useSize} from '../SizeContext/SizeContext';+import {Spinner} from '../Spinner';+import {useTooltip} from '../Tooltip';+import {+ colorVars,+ fontWeightVars,+ radiusVars,+ sizeVars,+ spacingVars,+ typeScaleVars,+ typographyVars,+} from '../theme/tokens.stylex';+import {focusOutlineStyles} from '../utils/focusOutline.stylex';+import {rtlStyles} from '../utils/rtlStyles';+import {themeProps} from '../utils/themeProps';+import {normalizeDayOfWeek} from '../utils/dateTypes';+import {+ formatDisplayTime12h,+ formatDisplayTime24h,+ formatISOTime,+ isImeKeyEvent,+ isRenderable,+ isTimeInRange,+ clampTime,+ mergeProps,+ parseISOTime,+ type ISOTimeString,+} from '../utils';+import {+ DATE_FORMAT_LONG,+ DATE_FORMAT_MONTH_YEAR,+ DATE_FORMAT_WEEKDAY_ONLY,+ plainDateFormat,+ plainDateFromISO,+ plainDateToday,+ type PlainDate,+} from '../utils/plainDate';+import {+ MonthScroller,+ type MonthScrollerHandle,+} from '../DateInput/MonthScroller';+import {MonthYearWheels} from '../DateInput/MonthYearWheels';+import {Wheel, type WheelOption} from '../DateInput/Wheel';+import {+ dateInputTouchGeometry,+ dateInputTouchSizes,+} from '../DateInput/tokens.stylex';+import {+ DEFAULT_MONTH_REACH,+ clampIndex,+ fromMonthIndex,+ monthIndexOf,+} from '../DateInput/monthGeometry';+import type {DateTimeInputProps, ISODateTimeString} from './DateTimeInput';++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,+ );+}++const sizeStyles = stylex.create({+ sm: {+ height: sizeVars['--size-element-sm'],+ },+ md: {+ height: sizeVars['--size-element-md'],+ },+ lg: {+ height: sizeVars['--size-element-lg'],+ },+});++const styles = stylex.create({+ iconButton: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ padding: 0,+ margin: 0,+ borderWidth: 0,+ borderStyle: 'none',+ backgroundColor: 'transparent',+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ borderRadius: radiusVars['--radius-element'],+ },+ iconButtonDisabled: {+ cursor: 'default',+ },+ 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: 'default',+ },+ touchRow: {+ display: 'flex',+ inlineSize: '100%',+ minInlineSize: 0,+ gap: spacingVars['--spacing-2'],+ },+ touchDateWrapper: {+ flex: 1,+ flexBasis: 0,+ minInlineSize: 0,+ },+ touchTimeWrapper: {+ flex: 1,+ flexBasis: 0,+ minInlineSize: 0,+ },+ touchInput: {+ caretColor: 'transparent',+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ userSelect: 'none',+ },+ touchSheetBody: {+ boxSizing: 'border-box',+ inlineSize: '100%',+ minInlineSize: 0,+ paddingInline: spacingVars['--spacing-4'],+ paddingBlockStart: spacingVars['--spacing-6'],+ paddingBlockEnd: spacingVars['--spacing-4'],+ },+ touchSurface: {+ display: 'flex',+ flexDirection: 'column',+ inlineSize: '100%',+ minInlineSize: 0,+ gap: spacingVars['--spacing-3'],+ },+ touchPanelStack: {+ display: 'grid',+ inlineSize: '100%',+ minInlineSize: 0,+ },+ touchPanel: {+ gridArea: '1 / 1',+ display: 'flex',+ inlineSize: '100%',+ minInlineSize: 0,+ flexDirection: 'column',+ gap: spacingVars['--spacing-2'],+ },+ touchPanelHidden: {+ visibility: 'hidden',+ opacity: 0,+ pointerEvents: 'none',+ },+ touchHeader: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ blockSize: sizeVars['--size-element-lg'],+ },+ touchTitle: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-1'],+ minInlineSize: 0,+ paddingInline: spacingVars['--spacing-2'],+ borderWidth: 0,+ borderStyle: 'none',+ borderRadius: radiusVars['--radius-element'],+ backgroundColor: 'transparent',+ color: colorVars['--color-text-primary'],+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-large-size'],+ fontWeight: fontWeightVars['--font-weight-semibold'],+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ },+ touchTitleText: {+ minInlineSize: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ touchHeaderActions: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-0-5'],+ marginInlineStart: 'auto',+ },+ touchHeaderActionsHidden: {+ visibility: 'hidden',+ opacity: 0,+ pointerEvents: 'none',+ },+ touchArrow: {+ minBlockSize: {+ default: null,+ '@media (pointer: coarse)': dateInputTouchSizes.daySize,+ },+ minInlineSize: {+ default: null,+ '@media (pointer: coarse)': dateInputTouchSizes.daySize,+ },+ },+ touchArrowUnavailable: {+ visibility: 'hidden',+ },+ touchArrowIcon: {+ display: 'inline-flex',+ },+ touchResetButton: {+ minBlockSize: {+ default: null,+ '@media (pointer: coarse)': dateInputTouchSizes.daySize,+ },+ },+ touchDateSurfaceStack: {+ display: 'grid',+ inlineSize: '100%',+ minInlineSize: 0,+ },+ touchDateSurface: {+ gridArea: '1 / 1',+ display: 'flex',+ inlineSize: '100%',+ minInlineSize: 0,+ flexDirection: 'column',+ gap: spacingVars['--spacing-2'],+ },+ touchDateSurfaceHidden: {+ visibility: 'hidden',+ opacity: 0,+ pointerEvents: 'none',+ },+ touchWeekdays: {+ display: 'grid',+ gridTemplateColumns: 'repeat(7, 1fr)',+ blockSize: sizeVars['--size-element-sm'],+ alignItems: 'center',+ },+ touchWeekday: {+ textAlign: 'center',+ fontSize: typeScaleVars['--text-supporting-size'],+ fontWeight: fontWeightVars['--font-weight-normal'],+ color: colorVars['--color-text-secondary'],+ },+ touchWheelSpacer: {+ blockSize: sizeVars['--size-element-sm'],+ },+ touchTimeWheels: {+ display: 'flex',+ inlineSize: '100%',+ minInlineSize: 0,+ blockSize: dateInputTouchGeometry.paneBlockSize,+ gap: spacingVars['--spacing-2'],+ },+ touchFooter: {+ display: 'flex',+ marginBlockStart: 'auto',+ paddingBlockStart: spacingVars['--spacing-1'],+ },+});++const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;++function parseValidISODate(date: ISODateString | undefined): PlainDate | null {+ if (date == null || !ISO_DATE.test(date)) {+ return null;+ }+ try {+ return plainDateFromISO(date);+ } catch {+ return null;+ }+}++function normalizeISOTime(+ time: ISOTimeString | undefined,+ hasSeconds: boolean,+): ISOTimeString | undefined {+ if (time === undefined) {+ return undefined;+ }+ const parsed = parseISOTime(time);+ return parsed ? formatISOTime(parsed, hasSeconds) : undefined;+}++function timeToSeconds(time: ISOTimeString | undefined): number | null {+ if (time === undefined) {+ return null;+ }+ const parsed = parseISOTime(time);+ return parsed == null+ ? null+ : parsed.hour * 3600 + parsed.minute * 60 + parsed.second;+}++function twoDigits(value: number): string {+ return String(value).padStart(2, '0');+}++function hour12From24(hour: number): number {+ return hour === 0 ? 12 : hour > 12 ? hour - 12 : hour;+}++function hour24From12(hour: number, meridiem: number): number {+ if (meridiem === 0) {+ return hour === 12 ? 0 : hour;+ }+ return hour === 12 ? 12 : hour + 12;+}++function rangeOverlaps(+ startSecond: number,+ endSecond: number,+ min: ISOTimeString | undefined,+ max: ISOTimeString | undefined,+): boolean {+ const minSecond = timeToSeconds(min);+ const maxSecond = timeToSeconds(max);+ return (+ (minSecond == null || endSecond >= minSecond) &&+ (maxSecond == null || startSecond <= maxSecond)+ );+}++type TouchDateTimePanel = 'date' | 'time';++export function TouchDateTimeField({+ label,+ isLabelHidden = false,+ description,+ isOptional = false,+ isRequired = false,+ isDisabled = false,+ disabledMessage,+ value,+ onChange,+ changeAction,+ isLoading = false,+ min,+ max,+ dateConstraints,+ hasSeconds = false,+ hourFormat = '12h',+ // Desktop-only: mobile uses wheels instead of typed arrow stepping or a preset list.+ timeIncrement: _timeIncrement,+ timeOptionInterval: _timeOptionInterval,+ hasClear = false,+ placeholder: placeholderFromProps,+ timePlaceholder: timePlaceholderFromProps,+ timeLabel,+ size: sizeProp,+ status,+ labelTooltip,+ // Desktop-only: the touch Date panel shows one swipe-paged month at a time.+ numberOfMonths: _numberOfMonths,+ weekStartsOn: weekStartsOnProp = 0,+ width,+ xstyle,+ className,+ style,+ ref,+ ...rest+}: DateTimeInputProps) {+ const t = useTranslator();+ const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});+ const {locale} = use(InternationalizationContext);+ const placeholder =+ placeholderFromProps ?? t('@astryx.dateTimeInput.placeholder');+ const timePlaceholder =+ timePlaceholderFromProps ?? t('@astryx.dateTimeInput.timePlaceholder');+ const resolvedTimeLabel =+ timeLabel ?? t('@astryx.dateTimeInput.timeSuffix', {label});+ const size = useSize(sizeProp, 'md');+ 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 timeSegmentRef = useRef<HTMLButtonElement | null>(null);+ const mergedDateInputRef = useMergedRefs(ref, dateInputRef);+ const scrollerHandleRef = useRef<MonthScrollerHandle | null>(null);++ const [, startTransition] = useTransition();+ const [optimisticValue, setOptimisticValue] = useOptimistic(value);+ const isPendingChange = optimisticValue !== value;+ const isBusy = isLoading || isPendingChange;+ const isEffectivelyDisabled = isDisabled || isLoading;++ const showsDisabledMessage = isDisabled && !!disabledMessage;+ const disabledMessageTooltip = useTooltip({+ placement: 'above',+ focusTrigger: 'always',+ isEnabled: showsDisabledMessage,+ });++ const {statusIcon, describedBy: statusTooltipDescribedBy} =+ useInputStatusIcon({+ status,+ statusVariant: 'detached',+ });++ const ariaDescribedBy =+ [+ description ? descriptionID : null,+ status?.message ? statusMessageID : null,+ statusTooltipDescribedBy,+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,+ ]+ .filter(Boolean)+ .join(' ') || undefined;++ const minParts = useMemo(() => splitDateTime(min), [min]);+ const maxParts = useMemo(() => splitDateTime(max), [max]);+ const valueParts = useMemo(+ () => splitDateTime(optimisticValue),+ [optimisticValue],+ );+ const calendarMin = minParts.date;+ const calendarMax = maxParts.date;+ const {isDateDisabled} = useCalendarConstraints({+ min: calendarMin,+ max: calendarMax,+ dateConstraints,+ });++ const [isSheetOpen, setIsSheetOpen] = useState(false);+ const [activePanel, setActivePanel] = useState<TouchDateTimePanel>('date');+ const [isWheelOpen, setIsWheelOpen] = useState(false);+ const [draftTime, setDraftTime] = useState<ISOTimeString | undefined>(() =>+ normalizeISOTime(splitDateTime(value).time, hasSeconds),+ );++ const today = useMemo(() => plainDateToday(), []);+ const selectedDate = useMemo(+ () => parseValidISODate(valueParts.date),+ [valueParts.date],+ );+ const fallbackTime = useMemo(() => getDefaultTime(hasSeconds), [hasSeconds]);+ const normalizedValueTime = normalizeISOTime(valueParts.time, hasSeconds);+ const timeForWheels = normalizedValueTime ?? draftTime ?? fallbackTime;+ const parsedWheelTime = useMemo(+ () =>+ parseISOTime(timeForWheels) ?? {+ hour: 0,+ minute: 0,+ second: 0,+ },+ [timeForWheels],+ );+ const weekStartsOn = normalizeDayOfWeek(weekStartsOnProp);++ useEffect(() => {+ if (normalizedValueTime !== undefined) {+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- mirrors an externally controlled time into the sheet-local draft+ setDraftTime(normalizedValueTime);+ } else if (optimisticValue === undefined) {+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- external clear resets the sheet-local draft too+ setDraftTime(undefined);+ }+ }, [normalizedValueTime, optimisticValue]);++ const [anchorMonthIndex] = useState(() =>+ monthIndexOf(selectedDate ?? plainDateToday()),+ );+ const minMonthIndex =+ calendarMin != null+ ? monthIndexOf(plainDateFromISO(calendarMin))+ : anchorMonthIndex - DEFAULT_MONTH_REACH;+ const maxMonthIndex =+ calendarMax != null+ ? monthIndexOf(plainDateFromISO(calendarMax))+ : anchorMonthIndex + DEFAULT_MONTH_REACH;+ const [monthIndex, setMonthIndex] = useState(() =>+ clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex),+ );+ const {year, month} = fromMonthIndex(monthIndex);+ const canStepBack = monthIndex > minMonthIndex;+ const canStepForward = monthIndex < maxMonthIndex;++ useEffect(() => {+ const clamped = clampIndex(monthIndex, minMonthIndex, maxMonthIndex);+ if (clamped !== monthIndex) {+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- min/max can change underneath the mounted sheet; keep the visible month in range+ setMonthIndex(clamped);+ scrollerHandleRef.current?.scrollToMonth(clamped, 'auto');+ }+ }, [monthIndex, minMonthIndex, maxMonthIndex]);++ const dayNames = useMemo(+ () =>+ Array.from({length: 7}, (_, offset) =>+ plainDateFormat(+ {year: 1970, month: 1, day: 4 + ((weekStartsOn + offset) % 7)},+ DATE_FORMAT_WEEKDAY_ONLY,+ locale,+ ),+ ),+ [weekStartsOn, locale],+ );+ const monthYearLabel = plainDateFormat(+ {year, month, day: 1},+ DATE_FORMAT_MONTH_YEAR,+ locale,+ );++ const dateDisplayValue = useMemo(() => {+ if (selectedDate == null) {+ return '';+ }+ return plainDateFormat(selectedDate, DATE_FORMAT_LONG, locale);+ }, [selectedDate, locale]);++ const timeDisplayValue = useMemo(() => {+ const displayTime = normalizedValueTime ?? draftTime;+ return displayTime+ ? (hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h)(+ displayTime,+ hasSeconds,+ )+ : '';+ }, [draftTime, normalizedValueTime, hourFormat, hasSeconds]);++ const timeBoundsForDate = useCallback(+ (date: ISODateString | undefined) => ({+ min:+ date != null && minParts.date === date && minParts.time+ ? minParts.time+ : undefined,+ max:+ date != null && maxParts.date === date && maxParts.time+ ? maxParts.time+ : undefined,+ }),+ [minParts.date, minParts.time, maxParts.date, maxParts.time],+ );++ const clampTimeForDate = useCallback(+ (date: ISODateString | undefined, time: ISOTimeString): ISOTimeString => {+ const bounds = timeBoundsForDate(date);+ return clampTime(time, bounds.min, bounds.max, hasSeconds);+ },+ [hasSeconds, timeBoundsForDate],+ );++ const fireChange = useCallback(+ (newValue: ISODateTimeString | undefined) => {+ if (isEffectivelyDisabled) {+ return;+ }+ onChange(newValue);+ if (changeAction) {+ startTransition(async () => {+ setOptimisticValue(newValue);+ await changeAction(newValue);+ });+ }+ },+ [+ isEffectivelyDisabled,+ onChange,+ changeAction,+ startTransition,+ setOptimisticValue,+ ],+ );++ const openSheet = useCallback(+ (panel: TouchDateTimePanel) => {+ if (!isEffectivelyDisabled) {+ setIsWheelOpen(false);+ setActivePanel(panel);+ setIsSheetOpen(true);+ }+ },+ [isEffectivelyDisabled],+ );++ const closeSheet = useCallback(() => {+ if (selectedDate == null) {+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- The shared close path is also used by the disabled/loading effect.+ setDraftTime(undefined);+ }+ // eslint-disable-next-line @eslint-react/set-state-in-effect -- The shared close path is also used by the disabled/loading effect.+ setIsSheetOpen(false);+ }, [selectedDate]);++ const handleSheetOpenChange = useCallback(+ (nextOpen: boolean) => {+ if (nextOpen) {+ setIsSheetOpen(true);+ } else {+ closeSheet();+ }+ },+ [closeSheet],+ );++ useEffect(() => {+ if (isEffectivelyDisabled && isSheetOpen) {+ closeSheet();+ }+ }, [closeSheet, isEffectivelyDisabled, isSheetOpen]);++ const stepMonth = useCallback(+ (delta: number) => {+ const target = clampIndex(+ monthIndex + delta,+ minMonthIndex,+ maxMonthIndex,+ );+ if (target === monthIndex) {+ return;+ }+ setMonthIndex(target);+ scrollerHandleRef.current?.scrollToMonth(target, 'smooth');+ },+ [monthIndex, minMonthIndex, maxMonthIndex],+ );++ const handleResetInSheet = useCallback(() => {+ fireChange(undefined);+ setDraftTime(undefined);+ const currentMonth = monthIndexOf(today);+ if (currentMonth < minMonthIndex || currentMonth > maxMonthIndex) {+ return;+ }+ setMonthIndex(currentMonth);+ scrollerHandleRef.current?.scrollToMonth(currentMonth, 'smooth');+ }, [fireChange, today, minMonthIndex, maxMonthIndex]);++ const handleDateSelect = useCallback(+ (nextDate: ISODateString) => {+ const nextTime = clampTimeForDate(nextDate, timeForWheels);+ setDraftTime(nextTime);+ const combined = combineDateTime(nextDate, nextTime);+ if (combined && combined !== optimisticValue) {+ fireChange(combined);+ }+ },+ [clampTimeForDate, fireChange, optimisticValue, timeForWheels],+ );++ const commitWheelTime = useCallback(+ (rawTime: ISOTimeString) => {+ const nextTime = clampTimeForDate(valueParts.date, rawTime);+ setDraftTime(nextTime);+ if (valueParts.date != null) {+ const combined = combineDateTime(valueParts.date, nextTime);+ if (combined && combined !== optimisticValue) {+ fireChange(combined);+ }+ }+ },+ [clampTimeForDate, fireChange, optimisticValue, valueParts.date],+ );++ const composeWheelTime = useCallback(+ ({+ hour24,+ hour12,+ minute,+ second,+ meridiem,+ }: {+ hour24?: number;+ hour12?: number;+ minute?: number;+ second?: number;+ meridiem?: number;+ }): ISOTimeString => {+ const currentMeridiem = parsedWheelTime.hour < 12 ? 0 : 1;+ let hour = parsedWheelTime.hour;+ if (hourFormat === '24h') {+ hour = hour24 ?? hour;+ } else {+ hour = hour24From12(+ hour12 ?? hour12From24(hour),+ meridiem ?? currentMeridiem,+ );+ }+ return formatISOTime(+ {+ hour,+ minute: minute ?? parsedWheelTime.minute,+ second: hasSeconds ? (second ?? parsedWheelTime.second) : 0,+ },+ hasSeconds,+ );+ },+ [hasSeconds, hourFormat, parsedWheelTime],+ );++ const timeBounds = timeBoundsForDate(valueParts.date);+ const hourOptions: WheelOption[] = useMemo(() => {+ if (hourFormat === '24h') {+ return Array.from({length: 24}, (_, hour) => ({+ value: hour,+ label: twoDigits(hour),+ isDisabled: !rangeOverlaps(+ hour * 3600,+ hour * 3600 + 3599,+ timeBounds.min,+ timeBounds.max,+ ),+ }));+ }+ const meridiem = parsedWheelTime.hour < 12 ? 0 : 1;+ // In 12-hour mode the hour column is interpreted inside the active AM/PM+ // half, so disabled rows describe reachability within that half only.+ return Array.from({length: 12}, (_, index) => {+ const hour = index + 1;+ const hour24 = hour24From12(hour, meridiem);+ return {+ value: hour,+ label: String(hour),+ isDisabled: !rangeOverlaps(+ hour24 * 3600,+ hour24 * 3600 + 3599,+ timeBounds.min,+ timeBounds.max,+ ),+ };+ });+ }, [hourFormat, parsedWheelTime.hour, timeBounds.min, timeBounds.max]);++ const minuteOptions: WheelOption[] = useMemo(+ () =>+ Array.from({length: 60}, (_, minute) => {+ const start = parsedWheelTime.hour * 3600 + minute * 60;+ return {+ value: minute,+ label: twoDigits(minute),+ isDisabled: !rangeOverlaps(+ start,+ start + (hasSeconds ? 59 : 0),+ timeBounds.min,+ timeBounds.max,+ ),+ };+ }),+ [hasSeconds, parsedWheelTime.hour, timeBounds.min, timeBounds.max],+ );++ const secondOptions: WheelOption[] = useMemo(+ () =>+ Array.from({length: 60}, (_, second) => ({+ value: second,+ label: twoDigits(second),+ isDisabled: !isTimeInRange(+ formatISOTime(+ {+ hour: parsedWheelTime.hour,+ minute: parsedWheelTime.minute,+ second,+ },+ true,+ ),+ timeBounds.min,+ timeBounds.max,+ ),+ })),+ [+ parsedWheelTime.hour,+ parsedWheelTime.minute,+ timeBounds.min,+ timeBounds.max,+ ],+ );++ const meridiemOptions: WheelOption[] = useMemo(+ () => [+ {+ value: 0,+ label: t('@astryx.dateTimeInput.meridiemAM'),+ isDisabled: !rangeOverlaps(+ 0,+ 11 * 3600 + 3599,+ timeBounds.min,+ timeBounds.max,+ ),+ },+ {+ value: 1,+ label: t('@astryx.dateTimeInput.meridiemPM'),+ isDisabled: !rangeOverlaps(+ 12 * 3600,+ 23 * 3600 + 3599,+ timeBounds.min,+ timeBounds.max,+ ),+ },+ ],+ [t, timeBounds.min, timeBounds.max],+ );++ const handleVisibleMonthChange = useCallback(+ (next: number) => {+ if (activePanel === 'date' && !isWheelOpen) {+ setMonthIndex(next);+ }+ },+ [activePanel, isWheelOpen],+ );++ const monthIndexRef = useRef(monthIndex);+ monthIndexRef.current = monthIndex;+ useEffect(() => {+ if (activePanel === 'date' && !isWheelOpen) {+ scrollerHandleRef.current?.scrollToMonth(monthIndexRef.current, 'auto');+ }+ }, [activePanel, isWheelOpen]);++ const handleInputKeyDown = useCallback(+ (event: React.KeyboardEvent, panel: TouchDateTimePanel) => {+ if (isImeKeyEvent(event.nativeEvent)) {+ return;+ }+ if (+ event.key === 'ArrowDown' ||+ event.key === 'Enter' ||+ event.key === ' ' ||+ event.key === 'Spacebar'+ ) {+ event.preventDefault();+ openSheet(panel);+ }+ },+ [openSheet],+ );++ const clearFocusTimerRef = useRef<number | null>(null);+ useEffect(+ () => () => {+ if (clearFocusTimerRef.current != null) {+ clearTimeout(clearFocusTimerRef.current);+ }+ },+ [],+ );++ const timeSegmentFocusTimerRef = useRef<number | null>(null);+ useEffect(+ () => () => {+ if (timeSegmentFocusTimerRef.current != null) {+ clearTimeout(timeSegmentFocusTimerRef.current);+ }+ },+ [],+ );++ const handleClear = useCallback(+ (event: React.MouseEvent<HTMLButtonElement>) => {+ event.stopPropagation();+ fireChange(undefined);+ setDraftTime(undefined);+ setIsSheetOpen(false);+ const field = dateInputRef.current;+ if (field == null) {+ return;+ }+ clearFocusTimerRef.current = window.setTimeout(() => {+ clearFocusTimerRef.current = null;+ field.focus({preventScroll: true});+ }, 0);+ },+ [fireChange],+ );++ const surface = (+ <div {...stylex.props(styles.touchSurface)}>+ <SegmentedControl+ value={activePanel}+ onChange={nextPanel => {+ setActivePanel(nextPanel as TouchDateTimePanel);+ setIsWheelOpen(false);+ }}+ label={t('@astryx.dateTimeInput.pickerMode')}+ layout="fill">+ <SegmentedControlItem+ value="date"+ label={t('@astryx.dateTimeInput.dateTab')}+ />+ <SegmentedControlItem+ ref={timeSegmentRef}+ value="time"+ label={t('@astryx.dateTimeInput.timeTab')}+ />+ </SegmentedControl>++ <div {...stylex.props(styles.touchPanelStack)}>+ <div+ data-panel="date"+ aria-hidden={activePanel !== 'date' ? 'true' : undefined}+ inert={activePanel !== 'date' ? true : undefined}+ {...stylex.props(+ styles.touchPanel,+ activePanel !== 'date' && styles.touchPanelHidden,+ )}>+ <div {...stylex.props(styles.touchHeader)}>+ <button+ type="button"+ onClick={() => setIsWheelOpen(open => !open)}+ aria-expanded={isWheelOpen}+ aria-label={t('@astryx.dateInput.chooseMonthYear', {+ monthYear: monthYearLabel,+ })}+ {...stylex.props(+ styles.touchTitle,+ focusOutlineStyles.focusVisible,+ )}>+ <span {...stylex.props(styles.touchTitleText)}>+ {monthYearLabel}+ </span>+ <Icon icon="chevronDown" size="sm" color="secondary" />+ </button>+ <span+ inert={isWheelOpen ? true : undefined}+ {...stylex.props(+ styles.touchHeaderActions,+ isWheelOpen && styles.touchHeaderActionsHidden,+ )}>+ <IconButton+ variant="ghost"+ size="sm"+ xstyle={[+ styles.touchArrow,+ !canStepBack && styles.touchArrowUnavailable,+ ]}+ isDisabled={!canStepBack}+ onClick={() => stepMonth(-1)}+ label={t('@astryx.calendar.previousMonth')}+ icon={+ <span+ {...stylex.props(styles.touchArrowIcon, rtlStyles.mirror)}>+ <Icon icon="chevronLeft" size="sm" color="inherit" />+ </span>+ }+ />+ <IconButton+ variant="ghost"+ size="sm"+ xstyle={[+ styles.touchArrow,+ !canStepForward && styles.touchArrowUnavailable,+ ]}+ isDisabled={!canStepForward}+ onClick={() => stepMonth(1)}+ label={t('@astryx.calendar.nextMonth')}+ icon={+ <span+ {...stylex.props(styles.touchArrowIcon, rtlStyles.mirror)}>+ <Icon icon="chevronRight" size="sm" color="inherit" />+ </span>+ }+ />+ <Button+ variant="ghost"+ size="sm"+ xstyle={styles.touchResetButton}+ label={t('@astryx.dateInput.resetPicking')}+ onClick={handleResetInSheet}+ />+ </span>+ </div>++ <div {...stylex.props(styles.touchDateSurfaceStack)}>+ <div+ data-date-surface="calendar"+ aria-hidden={isWheelOpen ? 'true' : undefined}+ inert={isWheelOpen ? true : undefined}+ {...stylex.props(+ styles.touchDateSurface,+ isWheelOpen && styles.touchDateSurfaceHidden,+ )}>+ <div aria-hidden="true" {...stylex.props(styles.touchWeekdays)}>+ {dayNames.map(name => (+ <div key={name} {...stylex.props(styles.touchWeekday)}>+ {name}+ </div>+ ))}+ </div>+ <MonthScroller+ key={`${minMonthIndex}:${maxMonthIndex}`}+ handleRef={scrollerHandleRef}+ minMonthIndex={minMonthIndex}+ maxMonthIndex={maxMonthIndex}+ initialMonthIndex={monthIndex}+ onVisibleMonthChange={handleVisibleMonthChange}+ selectedDate={selectedDate}+ today={today}+ isDateDisabled={isDateDisabled}+ weekStartsOn={weekStartsOn}+ onSelect={handleDateSelect}+ />+ <div {...stylex.props(styles.touchFooter)}>+ <Button+ variant="primary"+ size="md"+ width="100%"+ label={t('@astryx.dateTimeInput.saveDatePicking')}+ isDisabled={selectedDate == null}+ onClick={() => {+ setIsWheelOpen(false);+ setActivePanel('time');+ if (timeSegmentFocusTimerRef.current != null) {+ clearTimeout(timeSegmentFocusTimerRef.current);+ }+ timeSegmentFocusTimerRef.current = window.setTimeout(() => {+ timeSegmentFocusTimerRef.current = null;+ timeSegmentRef.current?.focus({preventScroll: true});+ }, 0);+ }}+ />+ </div>+ </div>++ <div+ data-date-surface="wheels"+ aria-hidden={!isWheelOpen ? 'true' : undefined}+ inert={!isWheelOpen ? true : undefined}+ {...stylex.props(+ styles.touchDateSurface,+ !isWheelOpen && styles.touchDateSurfaceHidden,+ )}>+ <div+ aria-hidden="true"+ {...stylex.props(styles.touchWheelSpacer)}+ />+ <MonthYearWheels+ monthIndex={monthIndex}+ minMonthIndex={minMonthIndex}+ maxMonthIndex={maxMonthIndex}+ onChange={next => {+ setMonthIndex(next);+ scrollerHandleRef.current?.scrollToMonth(next, 'auto');+ }}+ monthLabel={t('@astryx.dateInput.monthWheel')}+ yearLabel={t('@astryx.dateInput.yearWheel')}+ isActive={activePanel === 'date' && isWheelOpen}+ />+ <div {...stylex.props(styles.touchFooter)}>+ <Button+ variant="secondary"+ size="md"+ width="100%"+ label={t('@astryx.dateInput.doneChoosingMonth')}+ onClick={() => setIsWheelOpen(false)}+ />+ </div>+ </div>+ </div>+ </div>++ <div+ data-panel="time"+ role="group"+ aria-label={resolvedTimeLabel}+ aria-hidden={activePanel !== 'time' ? 'true' : undefined}+ inert={activePanel !== 'time' ? true : undefined}+ {...stylex.props(+ styles.touchPanel,+ activePanel !== 'time' && styles.touchPanelHidden,+ )}>+ <div {...stylex.props(styles.touchTimeWheels)}>+ <Wheel+ label={t('@astryx.dateTimeInput.hourWheel')}+ options={hourOptions}+ value={+ hourFormat === '24h'+ ? parsedWheelTime.hour+ : hour12From24(parsedWheelTime.hour)+ }+ isActive={activePanel === 'time'}+ onChange={hour =>+ commitWheelTime(+ hourFormat === '24h'+ ? composeWheelTime({hour24: hour})+ : composeWheelTime({hour12: hour}),+ )+ }+ />+ <Wheel+ label={t('@astryx.dateTimeInput.minuteWheel')}+ options={minuteOptions}+ value={parsedWheelTime.minute}+ isActive={activePanel === 'time'}+ onChange={minute => commitWheelTime(composeWheelTime({minute}))}+ />+ {hasSeconds && (+ <Wheel+ label={t('@astryx.dateTimeInput.secondWheel')}+ options={secondOptions}+ value={parsedWheelTime.second}+ isActive={activePanel === 'time'}+ onChange={second => commitWheelTime(composeWheelTime({second}))}+ />+ )}+ {hourFormat === '12h' && (+ <Wheel+ label={t('@astryx.dateTimeInput.meridiemWheel')}+ options={meridiemOptions}+ value={parsedWheelTime.hour < 12 ? 0 : 1}+ isActive={activePanel === 'time'}+ onChange={meridiem =>+ commitWheelTime(composeWheelTime({meridiem}))+ }+ />+ )}+ </div>+ <div {...stylex.props(styles.touchFooter)}>+ <Button+ variant="primary"+ size="md"+ width="100%"+ label={t('@astryx.dateInput.savePicking')}+ onClick={closeSheet}+ />+ </div>+ </div>+ </div>+ </div>+ );++ return (+ <Field+ 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"+ width={width}>+ <div+ ref={el => {+ disabledMessageTooltip.ref(el);+ }}+ {...rest}+ {...mergeProps(+ themeProps('date-time-input', {+ size,+ status: status?.type ?? null,+ disabled: isDisabled ? 'disabled' : null,+ }),+ stylex.props(styles.touchRow, xstyle),+ className,+ style,+ )}>+ <div+ onClick={event => {+ if (event.target === event.currentTarget) {+ openSheet('date');+ }+ }}+ {...mergeProps(+ themeProps('date-time-input-date-segment', {+ size,+ status: status?.type ?? null,+ }),+ stylex.props(+ inputWrapperStyles.base,+ sizeStyles[size],+ styles.touchDateWrapper,+ isEffectivelyDisabled && inputWrapperStyles.disabled,+ status && inputStatusBorderStyles[status.type],+ status &&+ !isEffectivelyDisabled &&+ inputStatusHoverShadowStyles[status.type],+ status && inputStatusFocusWithinStyles[status.type],+ ),+ )}>+ <button+ type="button"+ onClick={() => openSheet('date')}+ disabled={isEffectivelyDisabled}+ aria-label={t('@astryx.dateInput.openCalendar')}+ tabIndex={-1}+ {...stylex.props(+ focusOutlineStyles.focusVisible,+ styles.iconButton,+ isEffectivelyDisabled && styles.iconButtonDisabled,+ )}>+ <Icon+ icon="calendar"+ size="sm"+ color="secondary"+ {...themeProps('date-time-input-toggle-icon', {+ state: isSheetOpen ? 'expanded' : 'collapsed',+ })}+ />+ </button>+ <input+ ref={mergedDateInputRef}+ id={dateInputId}+ type="text"+ role="combobox"+ value={dateDisplayValue}+ readOnly+ inputMode="none"+ onChange={() => {}}+ onClick={() => openSheet('date')}+ onKeyDown={event => handleInputKeyDown(event, 'date')}+ placeholder={placeholder}+ disabled={isEffectivelyDisabled && !showsDisabledMessage}+ aria-disabled={showsDisabledMessage ? 'true' : undefined}+ aria-describedby={ariaDescribedBy}+ aria-required={isEffectivelyRequired ? 'true' : undefined}+ aria-invalid={status?.type === 'error' ? 'true' : undefined}+ aria-busy={isBusy || undefined}+ aria-expanded={isSheetOpen && activePanel === 'date'}+ aria-haspopup="dialog"+ aria-autocomplete="none"+ autoComplete="off"+ {...stylex.props(+ styles.input,+ styles.touchInput,+ isEffectivelyDisabled && styles.inputDisabled,+ )}+ />+ {hasClear && value !== undefined && !isEffectivelyDisabled && (+ <InputClearButton+ label={t('@astryx.dateInput.clear', {label})}+ onClick={handleClear}+ />+ )}+ {isBusy && <Spinner size="sm" />}+ {isRenderable(statusIcon) && statusIcon}+ </div>++ <div+ onClick={event => {+ if (event.target === event.currentTarget) {+ openSheet('time');+ }+ }}+ {...mergeProps(+ themeProps('date-time-input-time-segment', {+ size,+ status: status?.type ?? null,+ }),+ stylex.props(+ inputWrapperStyles.base,+ sizeStyles[size],+ styles.touchTimeWrapper,+ isEffectivelyDisabled && inputWrapperStyles.disabled,+ status && inputStatusBorderStyles[status.type],+ status &&+ !isEffectivelyDisabled &&+ inputStatusHoverShadowStyles[status.type],+ status && inputStatusFocusWithinStyles[status.type],+ ),+ )}>+ <button+ type="button"+ onClick={() => openSheet('time')}+ disabled={isEffectivelyDisabled}+ aria-label={t('@astryx.dateTimeInput.openTimePicker', {+ label: resolvedTimeLabel,+ })}+ tabIndex={-1}+ {...stylex.props(+ focusOutlineStyles.focusVisible,+ styles.iconButton,+ isEffectivelyDisabled && styles.iconButtonDisabled,+ )}>+ <Icon+ icon="clock"+ size="sm"+ color="secondary"+ {...themeProps('date-time-input-clock-icon')}+ />+ </button>+ <input+ ref={timeInputRef}+ id={timeInputId}+ type="text"+ role="combobox"+ value={timeDisplayValue}+ readOnly+ inputMode="none"+ onChange={() => {}}+ onClick={() => openSheet('time')}+ onKeyDown={event => handleInputKeyDown(event, 'time')}+ placeholder={timePlaceholder}+ disabled={isEffectivelyDisabled && !showsDisabledMessage}+ aria-disabled={showsDisabledMessage ? 'true' : undefined}+ aria-label={resolvedTimeLabel}+ aria-describedby={ariaDescribedBy}+ aria-required={isEffectivelyRequired ? 'true' : undefined}+ aria-invalid={status?.type === 'error' ? 'true' : undefined}+ aria-busy={isBusy || undefined}+ aria-expanded={isSheetOpen && activePanel === 'time'}+ aria-haspopup="dialog"+ aria-autocomplete="none"+ autoComplete="off"+ {...stylex.props(+ styles.input,+ styles.touchInput,+ isEffectivelyDisabled && styles.inputDisabled,+ )}+ />+ </div>+ <BottomSheet+ isOpen={isSheetOpen}+ onOpenChange={handleSheetOpenChange}+ label={t('@astryx.dateTimeInput.dialogLabel')}+ height="hug">+ <div {...stylex.props(styles.touchSheetBody)}>{surface}</div>+ </BottomSheet>+ {showsDisabledMessage &&+ disabledMessageTooltip.renderTooltip(disabledMessage)}+ </div>+ </Field>+ );+}++TouchDateTimeField.displayName = 'TouchDateTimeField';