An open source design system that's fully customizable and agent ready
TypeScript
feat(DateTimeInput): add native picker option (#5620)
Xinzi Zhoua84d09cb59b4
diff --git a/.changeset/date-time-input-native-picker-option.md b/.changeset/date-time-input-native-picker-option.mdnew file mode 100644index 0000000000..c843b98a5c--- /dev/null+++ b/.changeset/date-time-input-native-picker-option.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[feat] Add `nativePicker` to DateTimeInput for browser and OS date/time pickers, with Astryx time fallbacks for seconds, custom increments, and preset options. Native fields follow DateInput's compact minimum sizing in fit-content layouts.+@imdreamrunnerdiff --git a/apps/storybook/stories/DateTimeInput.stories.tsx b/apps/storybook/stories/DateTimeInput.stories.tsxindex 1523caeb4e..ba0edc5b51 100644--- a/apps/storybook/stories/DateTimeInput.stories.tsx+++ b/apps/storybook/stories/DateTimeInput.stories.tsx@@ -74,6 +74,12 @@ const meta: Meta<typeof DateTimeInput> = {control: 'boolean',description: 'Whether to show a clear button',},+ nativePicker: {+ control: 'radio',+ options: ['touch', 'always', 'never'],+ description:+ "Date and time picker surfaces: native browser/OS controls on touch by default, native wherever compatible, or Astryx's surfaces everywhere",+ },numberOfMonths: {control: 'radio',options: [1, 2],@@ -132,6 +138,39 @@ export const WithValue: Story = {},};+export const NativePickerModes: Story = {+ render: () => {+ const [value, setValue] = useState<ISODateTimeString | undefined>(+ '2026-03-15T14:30' as ISODateTimeString,+ );+ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>+ <DateTimeInput+ label="nativePicker='touch' (default)"+ description="Native date and compatible time controls on a coarse primary pointer"+ value={value}+ onChange={setValue}+ nativePicker="touch"+ />+ <DateTimeInput+ label="nativePicker='always'"+ description="Native date and compatible time controls on every pointer type"+ value={value}+ onChange={setValue}+ nativePicker="always"+ />+ <DateTimeInput+ label="nativePicker='never'"+ description="Astryx bottom sheet on coarse pointers; calendar popover on fine pointers"+ value={value}+ onChange={setValue}+ nativePicker="never"+ />+ </div>+ );+ },+};+export const TwentyFourHourFormat: Story = {render: args => {const [value, setValue] = useState<ISODateTimeString | undefined>(@@ -366,6 +405,7 @@ export const TwoMonthCalendar: Story = {args: {label: 'Travel departure',numberOfMonths: 2,+ nativePicker: 'never',},};diff --git a/packages/cli/assets/templates/blocks/components/DateTimeInput/DateTimeInputShowcase.tsx b/packages/cli/assets/templates/blocks/components/DateTimeInput/DateTimeInputShowcase.tsxindex d7332bfae0..68102e9d32 100644--- a/packages/cli/assets/templates/blocks/components/DateTimeInput/DateTimeInputShowcase.tsx+++ b/packages/cli/assets/templates/blocks/components/DateTimeInput/DateTimeInputShowcase.tsx@@ -13,7 +13,10 @@ export default function DateTimeInputShowcase() {);return (- <Stack direction="vertical" width="100%" style={{maxWidth: 400}}>+ <Stack+ direction="vertical"+ width="100%"+ style={{minWidth: 240, maxWidth: 400}}><DateTimeInputlabel="Meeting time"placeholder="Select a date"diff --git a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjsindex 8e5864e595..525c18875a 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs+++ b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs@@ -106,7 +106,8 @@ export const docs = {{name: 'hasSeconds',type: 'boolean',- description: 'Include seconds in the time portion.',+ description:+ "Include seconds in the time portion. Keeps Astryx's time field even when nativePicker selects native surfaces, because iOS has no seconds wheel.",default: 'false',},{@@ -120,14 +121,14 @@ export const docs = {name: 'timeIncrement',type: '1 | 5 | 10 | 15 | 30',description:- '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.',+ 'Minute step for arrow keys in Astryx’s typed time field. A non-default value keeps the Astryx time field in nativePicker modes because iOS treats native step as validation, not picker cadence. Ignored by the Astryx touch sheet, which uses wheels.',default: '1',},{name: 'timeOptionInterval',type: '5 | 10 | 15 | 30 | 60',description:- '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.',+ 'Minute cadence for the preset-time combobox on Astryx’s fine-pointer time field. Setting it keeps that Astryx time field even in nativePicker modes because the OS picker has no equivalent preset list. The Astryx touch sheet uses wheels.',},{name: 'hasClear',@@ -177,16 +178,23 @@ export const docs = {name: 'numberOfMonths',type: '1 | 2',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.',+ "Number of months displayed simultaneously in Astryx's pointer calendar popover. Ignored by native date controls and the mobile touch sheet, whose Date panel always shows one swipe-paged month at a time.",default: '1',},{name: 'weekStartsOn',type: "0 | 1 | 2 | 3 | 4 | 5 | 6 | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'",description:- 'First day of week in the calendar. A number (0 = Sunday to 6 = Saturday) or a three-letter day name.',+ 'First day of week in Astryx calendars. A number (0 = Sunday to 6 = Saturday) or a three-letter day name. Ignored by native date controls.',default: '0',},+ {+ name: 'nativePicker',+ type: "'touch' | 'always' | 'never'",+ description:+ "Which surfaces draw the date and time pickers. 'touch' (the default) uses browser/OS controls on a coarse primary pointer; 'always' uses them wherever input type=date/time are supported; 'never' keeps Astryx's own surfaces everywhere. The native time control is used only for the default minute-precision contract: hasSeconds, non-default timeIncrement, or timeOptionInterval retain Astryx's time field because iOS cannot express them faithfully. Use 'never' when numberOfMonths, weekStartsOn, or visible dateConstraints behavior matters. Constraints are enforced on commit; min/max are forwarded as hints. hourFormat formats the closed time, while the OS picker follows the user's locale.",+ default: "'touch'",+ },{name: 'width',type: 'SizeValue',@@ -223,7 +231,7 @@ export const docs = {},usage: {description:- '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. The closed date and time segments stay side by side when at least 400px is available and wrap into full-width rows below 400px, independent of viewport width. 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. With nativePicker="touch" (the default), mouse/trackpad devices use Astryx typed fields and popovers, while coarse-pointer devices use browser/OS date and time controls in the same two-segment field. nativePicker="always" uses both native controls on every pointer; nativePicker="never" keeps Astryx\'s own surfaces — pointer fields on fine pointers and the coordinated Date/Time bottom sheet on coarse pointers. The closed segments stay side by side when at least 400px is available and wrap into full-width rows below 400px, independent of viewport width. Use it for scheduling, event creation, deadline setting, or any form field that needs a specific datetime.',bestPractices: [{guidance: true,@@ -277,30 +285,31 @@ export const docs = {name: 'Date input',required: true,description:- 'A text input where the user can type a date. Clicking opens a calendar popover.',+ 'A typed date field with calendar popover on the fine-pointer Astryx surface, a real input type=date in native modes, or a read-only segment opening the Astryx touch sheet when nativePicker is never on a coarse pointer.',},{name: 'Calendar icon',required: true,- description: 'A button that opens the calendar popover.',+ description:+ 'A button that opens the active date surface: the platform picker, Astryx calendar popover, or Astryx touch sheet.',},{- name: 'Calendar popover',+ name: 'Date picker',required: false,description:- 'A month grid that appears in a popover on desktop, or in the mobile bottom sheet on coarse-pointer devices.',+ 'The browser/OS picker in native modes, an Astryx month-grid popover on a fine pointer, or the Date panel of the Astryx bottom sheet on a coarse pointer with nativePicker="never".',},{name: 'Time input',required: true,description:- "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.",+ 'A real input type=time for the default minute-precision native mode, a text/combobox time field when seconds, custom increments, or preset options are requested, or a read-only segment opening accessible time wheels when nativePicker is never on a coarse pointer.',},{name: 'Time options popover',required: false,description:- '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.',+ 'A list of preset times at the timeOptionInterval cadence. Setting the prop retains Astryx’s text/combobox time field even when nativePicker otherwise selects native controls; the Astryx touch sheet uses wheels instead.',},{name: 'Clear button',@@ -322,7 +331,7 @@ export const docsZh = {displayName: 'Date Time Input',usage: {description:- '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. The closed date and time segments stay side by side when at least 400px is available and wrap into full-width rows below 400px, independent of viewport width. 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. With nativePicker="touch" (the default), mouse/trackpad devices use Astryx typed fields and popovers, while coarse-pointer devices use browser/OS date and time controls in the same two-segment field. nativePicker="always" uses both native controls on every pointer; nativePicker="never" keeps Astryx\'s own surfaces — pointer fields on fine pointers and the coordinated Date/Time bottom sheet on coarse pointers. The closed segments stay side by side when at least 400px is available and wrap into full-width rows below 400px, independent of viewport width. Use it for scheduling, event creation, deadline setting, or any form field that needs a specific datetime.',bestPractices: [{guidance: true,@@ -444,7 +453,8 @@ export const docsZh = {{name: 'hasSeconds',type: 'boolean',- description: '在时间部分包含秒。',+ description:+ '在时间部分包含秒。即使 nativePicker 选择原生界面,也会保留 Astryx 时间字段,因为 iOS 没有秒滚轮。',default: 'false',},{@@ -457,7 +467,7 @@ export const docsZh = {name: 'timeIncrement',type: '1 | 5 | 10 | 15 | 30',description:- '在桌面时间输入中按箭头键时增减的分钟数。在移动触摸面板中会被忽略,时间通过滚轮更改。',+ 'Astryx 可输入时间字段中箭头键的分钟步长。非默认值会在 nativePicker 模式下保留 Astryx 时间字段,因为 iOS 将原生 step 视为验证规则,而不是选择器步长。Astryx 触摸面板使用滚轮。',default: '1',},{@@ -505,16 +515,23 @@ export const docsZh = {name: 'numberOfMonths',type: '1 | 2',description:- '桌面日历弹出层中同时显示的月份数量。在移动触摸面板中会被忽略,日期面板一次显示一个可滑动月份。',+ 'Astryx 指针日历弹出层中同时显示的月份数量。原生日期控件和移动触摸面板会忽略此属性;触摸面板的日期部分一次显示一个可滑动月份。',default: '1',},{name: 'weekStartsOn',type: "0 | 1 | 2 | 3 | 4 | 5 | 6 | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'",description:- '日历中每周的起始日。可为数字(0=周日……6=周六)或三字母星期缩写。',+ 'Astryx 日历中每周的起始日。可为数字(0=周日……6=周六)或三字母星期缩写。原生日期控件会忽略此属性。',default: '0',},+ {+ name: 'nativePicker',+ type: "'touch' | 'always' | 'never'",+ description:+ "选择由哪些界面绘制日期和时间选择器。'touch'(默认)在粗略主指针设备上使用浏览器/操作系统的原生控件;'always' 在支持 input type=date/time 的浏览器中始终使用原生控件;'never' 始终使用 Astryx 自带的界面。原生时间控件仅用于默认的分钟精度:hasSeconds、非默认 timeIncrement 或 timeOptionInterval 会保留 Astryx 时间字段,因为 iOS 无法忠实表达这些行为。需要 numberOfMonths、weekStartsOn 或可见 dateConstraints 行为时请使用 'never'。约束会在提交时执行,min/max 作为提示传给原生控件。hourFormat 格式化关闭状态的时间,而操作系统选择器遵循用户区域设置。",+ default: "'touch'",+ },{name: 'xstyle',type: 'StyleXStyles',@@ -551,7 +568,7 @@ export const docsDense = {'combined date + time picker with calendar popover and time input',usage: {description:- '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. Closed segments stay side by side when at least 400px is available and wrap into full-width rows below 400px, independent of the viewport. Use for scheduling, events, deadlines, or any form field needing a datetime.',+ 'DateTimeInput combines date and time selection. nativePicker="touch" (default) uses browser/OS date+time controls on coarse pointers and Astryx pointer fields on fine pointers; "always" uses both native controls everywhere; "never" uses Astryx\'s coordinated bottom sheet on coarse pointers and pointer fields on fine pointers. Closed segments stay side by side when at least 400px is available and wrap below 400px.',bestPractices: [{guidance: true,@@ -611,12 +628,13 @@ export const docsDense = {min: 'min selectable datetime (ISO)',max: 'max selectable datetime (ISO)',dateConstraints: 'custom constraint fns to disable specific dates',- hasSeconds: 'include seconds in time portion',+ hasSeconds:+ 'include seconds; retains Astryx time field because iOS native picker has no seconds wheel',hourFormat: "display format. '12h' shows AM/PM; '24h' uses 24-hour",timeIncrement:- 'desktop only: minutes to add/subtract on arrow keys in time input; mobile uses wheels',+ 'minute step for Astryx typed field; non-default retains Astryx time field in native modes because iOS native step is validation-only',timeOptionInterval:- 'desktop only: minute cadence for a preset-time dropdown on the time input; omitted = plain text input, no combobox. mobile uses wheels',+ 'preset-time combobox cadence; setting it retains Astryx time field because native pickers have no equivalent list',hasClear: 'Shows clear button when datetime is set',placeholder: 'date-portion placeholder when empty',timePlaceholder:@@ -627,9 +645,11 @@ export const docsDense = {status: 'error/warning/success status w/ message',labelTooltip: 'tooltip text via info icon at label end',numberOfMonths:- 'desktop calendar months shown simultaneously; ignored on mobile touch sheet',+ 'Astryx pointer-calendar months shown simultaneously; ignored by native date controls and the mobile touch sheet',weekStartsOn:- 'first day of week in calendar (0=Sunday, or name e.g. "mon")',+ 'first day of week in Astryx calendars (0=Sunday, or name e.g. "mon"); ignored by native date controls',+ nativePicker:+ "date+time surfaces: 'touch' (default) = browser/OS controls on a coarse pointer, 'always' = native on every pointer, 'never' = Astryx calendar/time popovers on fine pointers and coordinated bottom sheet on coarse pointers. use 'never' for numberOfMonths/weekStartsOn/visible dateConstraints/timeOptionInterval; native mode enforces constraints on commit and forwards min/max.",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 83e32226af..a9a6a30c50 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx@@ -4,11 +4,14 @@/*** @file DateTimeInput.tsx- * @input Uses React, Field, Calendar, usePopover, useAnnounce, time parsing utilities, TouchDateTimeField, StyleX intrinsic flex layout- * @output Exports DateTimeInput component, DateTimeInputProps+ * @input Uses React, Field, Calendar, NativeDateSegment, NativeTimeSegment, TouchDateTimeField, usePopover, useAnnounce, time parsing utilities, StyleX intrinsic flex layout+ * @output Exports DateTimeInput component, DateTimeInputProps, and native picker type* @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/NativeDateSegment.tsx (native date surface)+ * - /packages/core/src/DateTimeInput/NativeTimeSegment.tsx (native time surface)+ * - /packages/core/src/DateTimeInput/NativePickerSegments.test.tsx (native surface tests)* - /packages/core/src/DateTimeInput/DateTimeInput.doc.mjs (props table, features, implementation notes)* - /packages/core/src/DateTimeInput/DateTimeInput.test.tsx (desktop tests for new/changed behavior)* - /packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx (touch-surface tests)@@ -95,11 +98,15 @@ import {focusOutlineStyles} from '../utils/focusOutline.stylex';import {useLocale, useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';+import {NativeDateSegment} from './NativeDateSegment';+import {NativeTimeSegment} from './NativeTimeSegment';import {TouchDateTimeField} from './TouchDateTimeField';export type ISODateTimeString = string & {readonly __brand: 'ISODateTimeString';};+export type DateTimeInputNativePicker = 'touch' | 'always' | 'never';+export type DateTimeInputHourFormat = '12h' | '24h';export type DateTimeInputSize = 'sm' | 'md' | 'lg';@@ -128,6 +135,11 @@ const styles = stylex.create({flexWrap: 'wrap',gap: spacingVars['--spacing-2'],},+ nativeRow: {+ // Match DateInput's closed-field floor. Without one, WebKit reports almost+ // no intrinsic width for appearance:none temporal inputs with overlays.+ minInlineSize: 180,+ },iconButton: {display: 'flex',alignItems: 'center',@@ -241,6 +253,8 @@ const timeOptionSizeStyles = stylex.create({},});+const TOUCH_POINTER_QUERY = '(pointer: coarse)';+const sizeStyles = stylex.create({sm: {height: sizeVars['--size-element-sm'],@@ -370,9 +384,10 @@ export interface DateTimeInputProps extends Omit<hourFormat?: DateTimeInputHourFormat;/**- * 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.+ * Minute step for the time field. Astryx's typed field uses it for arrow-key+ * stepping. The default value permits the native time picker; a non-default+ * value retains the Astryx time field because iOS does not apply native+ * `step` as picker cadence. Ignored by the Astryx touch sheet.* @default 1*/timeIncrement?: DateTimeInputTimeIncrement;@@ -388,10 +403,10 @@ export interface DateTimeInputProps extends Omit<* list is a shortcut, not a restriction, so a time between two options can* still be typed.*- * 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.+ * Setting this prop retains Astryx's typed/combobox time field even when+ * `nativePicker` otherwise selects native controls, because the OS picker has+ * no equivalent preset list. The Astryx touch sheet uses wheels instead.+ * Independent of `timeIncrement`, which governs arrow-key stepping.*/timeOptionInterval?: DateTimeInputTimeOptionInterval;@@ -458,6 +473,39 @@ export interface DateTimeInputProps extends Omit<* @default 0*/weekStartsOn?: DayOfWeek | DayOfWeekName;++ /**+ * When date and time picking are handed to the browser/OS instead of Astryx's+ * calendar and time surfaces.+ *+ * - `'touch'` (default): native date and time inputs on a coarse primary+ * pointer; Astryx's typed fields and popovers otherwise+ * - `'always'`: native date and time inputs wherever the browser supports them+ * - `'never'`: Astryx's own surfaces everywhere — typed fields on a fine+ * pointer and the coordinated Date/Time bottom sheet on a coarse pointer+ *+ * Native pickers cannot express `numberOfMonths`, `weekStartsOn`,+ * `dateConstraints`, or `timeOptionInterval`. Calendar-only options are+ * ignored in native mode and constraints are enforced on commit. The native+ * time control is used for the default minute-precision contract; requesting+ * `hasSeconds`, a non-default `timeIncrement`, or `timeOptionInterval` keeps+ * Astryx's time field because iOS cannot represent those behaviors faithfully.+ * `min` / `max` are forwarded to each native control as hints and enforced in+ * JavaScript. `hourFormat` formats the closed value; the OS picker follows the+ * user's locale.+ *+ * @default 'touch'+ * @example+ * ```+ * <DateTimeInput+ * label="Event time"+ * value={dateTime}+ * onChange={setDateTime}+ * nativePicker="never"+ * />+ * ```+ */+ nativePicker?: DateTimeInputNativePicker;}function splitDateTime(dt: ISODateTimeString | undefined): {@@ -539,6 +587,7 @@ function PointerDateTimeField({labelTooltip,numberOfMonths = 1,weekStartsOn,+ nativePicker = 'touch',width,xstyle,className,@@ -548,6 +597,17 @@ function PointerDateTimeField({}: DateTimeInputProps) {const t = useTranslator();const locale = useLocale();+ const isTouch = useMediaQuery(TOUCH_POINTER_QUERY);+ const usesNativePicker =+ nativePicker === 'always' || (nativePicker === 'touch' && isTouch);+ // iOS's native time picker has no seconds wheel, treats step as validation+ // rather than picker cadence, and cannot express our preset-time list. Keep+ // the Astryx time field for those explicit contracts instead of losing them.+ const usesNativeTimePicker =+ usesNativePicker &&+ !hasSeconds &&+ timeIncrement === 1 &&+ timeOptionInterval === undefined;const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});// Speaks arrow-key stepping results through the persistent live regions:// stepping programmatically rewrites a plain textbox's value, which screen@@ -563,6 +623,7 @@ function PointerDateTimeField({const descriptionID = useId();const statusMessageID = useId();const dateInputRef = useRef<HTMLInputElement | null>(null);+ const mergedDateInputRef = useMergedRefs(ref, dateInputRef);const timeInputRef = useRef<HTMLInputElement | null>(null);const timeContainerRef = useRef<HTMLDivElement | null>(null);const calendarRef = useRef<CalendarHandle | null>(null);@@ -570,8 +631,14 @@ function PointerDateTimeField({const [, startTransition] = useTransition();const [optimisticValue, setOptimisticValue] = useOptimistic(value);- const isBusy = isLoading || optimisticValue !== value;- const isEffectivelyDisabled = isDisabled || isBusy;+ const isPendingChange = optimisticValue !== value;+ const isBusy = isLoading || isPendingChange;+ // A native wheel emits several edits while it remains open. Disabling the+ // control after the first optimistic edit detaches the iOS picker, so pending+ // changeAction work stays interactive just like TouchDateTimeField. Explicit+ // loading still disables every surface.+ const isEffectivelyDisabled =+ isDisabled || isLoading || (!usesNativePicker && isPendingChange);// Disabled-reason tooltip. Disabled controls swallow pointer events, so the// tooltip listeners attach to the outer row container (which already exists)@@ -674,6 +741,19 @@ function PointerDateTimeField({// --- Time input state ---const [timePendingInput, setTimePendingInput] = useState<string | null>(null);const [isTimeFocused, setIsTimeFocused] = useState(false);+ // Native date and time are separate OS pickers. Hold a time chosen before the+ // date exists, then combine it when the date picker commits.+ const [nativeTimeDraft, setNativeTimeDraft] = useState<+ ISOTimeString | undefined+ >(undefined);+ const previousNativeValueRef = useRef(optimisticValue);+ if (optimisticValue !== previousNativeValueRef.current) {+ previousNativeValueRef.current = optimisticValue;+ if (nativeTimeDraft !== undefined) {+ setNativeTimeDraft(undefined);+ }+ }+ const nativeTimeValue = nativeTimeDraft ?? valueParts.time;const formatDisplayTime =hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;@@ -717,10 +797,11 @@ function PointerDateTimeField({// Opt-in: without timeOptionInterval the time field keeps exactly the// semantics it shipped with — a plain text input, no combobox role, no// second listbox in the accessibility tree.- const hasTimeOptions = timeOptionInterval !== undefined;+ const hasTimeOptions =+ !usesNativeTimePicker && timeOptionInterval !== undefined;const timeOptions = useMemo(() => {- if (timeOptionInterval === undefined) {+ if (!hasTimeOptions || timeOptionInterval === undefined) {return [];}const options: {time: ISOTimeString; label: string}[] = [];@@ -745,12 +826,19 @@ function PointerDateTimeField({options.push({time, label: formatDisplayTime(time, hasSeconds)});}return options;- }, [timeOptionInterval, hasSeconds, timeMin, timeMax, formatDisplayTime]);+ }, [+ hasTimeOptions,+ timeOptionInterval,+ hasSeconds,+ timeMin,+ timeMax,+ formatDisplayTime,+ ]);// --- Unified change handler ---const fireChange = useCallback((newValue: ISODateTimeString | undefined) => {- if (isBusy) {+ if (isEffectivelyDisabled) {return;}onChange(newValue);@@ -761,7 +849,13 @@ function PointerDateTimeField({});}},- [isBusy, onChange, changeAction, startTransition, setOptimisticValue],+ [+ isEffectivelyDisabled,+ onChange,+ changeAction,+ startTransition,+ setOptimisticValue,+ ],);// --- Popover ---@@ -801,7 +895,8 @@ function PointerDateTimeField({// --- Date handlers ---const handleDateChange = useCallback((newDate: ISODateString, source: 'calendar' | 'input') => {- const currentTime = valueParts.time ?? getDefaultTime(hasSeconds);+ const currentTime =+ valueParts.time ?? nativeTimeDraft ?? getDefaultTime(hasSeconds);let effectiveTime = currentTime;if (minParts.date && newDate === minParts.date && minParts.time) {@@ -824,7 +919,50 @@ function PointerDateTimeField({popover.hide();}},- [valueParts.time, hasSeconds, minParts, maxParts, fireChange, popover],+ [+ valueParts.time,+ nativeTimeDraft,+ hasSeconds,+ minParts,+ maxParts,+ fireChange,+ popover,+ ],+ );++ const handleNativeDateChange = useCallback(+ (newDate: ISODateString | undefined) => {+ if (newDate === undefined) {+ fireChange(undefined);+ return;+ }+ handleDateChange(newDate, 'input');+ },+ [fireChange, handleDateChange],+ );++ const handleNativeTimeChange = useCallback(+ (newTime: ISOTimeString | undefined) => {+ if (newTime === undefined) {+ setNativeTimeDraft(undefined);+ if (optimisticValue !== undefined) {+ fireChange(undefined);+ }+ return;+ }+ if (valueParts.date) {+ const combined = combineDateTime(valueParts.date, newTime);+ if (combined) {+ fireChange(combined);+ }+ return;+ }+ // A datetime cannot be emitted until its date exists, but the OS time+ // picker is independently reachable. Preserve this draft for the date+ // commit instead of making the user's first choice disappear.+ setNativeTimeDraft(newTime);+ },+ [fireChange, optimisticValue, valueParts.date],);const handleDateInputChange = useCallback(@@ -1389,9 +1527,12 @@ function PointerDateTimeField({// --- Clear ---const handleClear = useCallback(() => {+ setNativeTimeDraft(undefined);fireChange(undefined);- dateInputRef.current?.focus();- }, [fireChange]);+ if (!usesNativePicker) {+ dateInputRef.current?.focus();+ }+ }, [fireChange, usesNativePicker]);// Focus time input when clicking wrapper padding/iconconst {onClick: handleTimeWrapperClick, onMouseUp: handleTimeWrapperMouseUp} =@@ -1432,13 +1573,17 @@ function PointerDateTimeField({status: status?.type ?? null,disabled: isDisabled ? 'disabled' : null,}),- stylex.props(styles.row, xstyle),+ stylex.props(+ styles.row,+ usesNativePicker && styles.nativeRow,+ xstyle,+ ),className,style,)}>{/* Date input */}<div- ref={popover.triggerRef}+ ref={usesNativePicker ? undefined : popover.triggerRef}{...mergeProps(themeProps('date-time-input-date-segment', {size,@@ -1456,79 +1601,102 @@ function PointerDateTimeField({status && inputStatusFocusWithinStyles[status.type],),)}>- <button- type="button"- onClick={handleCalendarToggle}- disabled={isEffectivelyDisabled}- aria-label={- popover.isOpen- ? t('@astryx.dateInput.toggleCalendarClose')- : t('@astryx.dateInput.openCalendar')- }- {...stylex.props(- focusOutlineStyles.focusVisible,- styles.iconButton,- isEffectivelyDisabled && styles.iconButtonDisabled,- )}>- <Icon- icon="calendar"- size="sm"- color="secondary"- // Stable theme target on the calendar toggle glyph, so a theme- // can restyle just this icon (color, size, hover) — and each- // open/closed state — via `defineTheme`, mirroring- // `date-input-toggle-icon`. Same-element rules in- // @layer astryx-theme win over the icon's own base color/size,- // which a segment-level target could not reach.- {...themeProps('date-time-input-toggle-icon', {- state: popover.isOpen ? 'expanded' : 'collapsed',- })}+ {usesNativePicker ? (+ <NativeDateSegment+ id={dateInputId}+ inputRef={mergedDateInputRef}+ value={valueParts.date}+ onChange={handleNativeDateChange}+ placeholder={placeholder}+ min={calendarMin}+ max={calendarMax}+ isDateDisabled={isDateDisabled}+ isEffectivelyDisabled={isEffectivelyDisabled}+ hasDisabledMessage={showsDisabledMessage}+ isEffectivelyRequired={isEffectivelyRequired}+ isBusy={isBusy}+ statusType={status?.type}+ ariaDescribedBy={ariaDescribedBy}/>- </button>- <input- ref={useMergedRefs(ref, dateInputRef)}- id={dateInputId}- type="text"- role="combobox"- value={dateDisplayValue}- onChange={handleDateInputChange}- onBlur={handleDateBlur}- onClick={handleDateInputClick}- onKeyDown={handleDateKeyDown}- placeholder={placeholder}- // With a disabledMessage the input keeps focusability via- // aria-disabled so the reason is focus-discoverable; typing is- // blocked with readOnly and the mutation guards, and calendar- // activation is blocked by the isEffectivelyDisabled guards.- disabled={isEffectivelyDisabled && !showsDisabledMessage}- aria-disabled={showsDisabledMessage ? 'true' : undefined}- readOnly={showsDisabledMessage || undefined}- aria-describedby={ariaDescribedBy}- aria-required={isEffectivelyRequired ? 'true' : undefined}- aria-invalid={- status?.type === 'error' || !isDateInputValid ? '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,- )}- />- {/*+ ) : (+ <>+ <button+ type="button"+ onClick={handleCalendarToggle}+ disabled={isEffectivelyDisabled}+ aria-label={+ popover.isOpen+ ? t('@astryx.dateInput.toggleCalendarClose')+ : t('@astryx.dateInput.openCalendar')+ }+ {...stylex.props(+ focusOutlineStyles.focusVisible,+ styles.iconButton,+ isEffectivelyDisabled && styles.iconButtonDisabled,+ )}>+ <Icon+ icon="calendar"+ size="sm"+ color="secondary"+ // Stable theme target on the calendar toggle glyph, so a theme+ // can restyle just this icon (color, size, hover) — and each+ // open/closed state — via `defineTheme`, mirroring+ // `date-input-toggle-icon`. Same-element rules in+ // @layer astryx-theme win over the icon's own base color/size,+ // which a segment-level target could not reach.+ {...themeProps('date-time-input-toggle-icon', {+ state: popover.isOpen ? 'expanded' : 'collapsed',+ })}+ />+ </button>+ <input+ ref={mergedDateInputRef}+ id={dateInputId}+ type="text"+ role="combobox"+ value={dateDisplayValue}+ onChange={handleDateInputChange}+ onBlur={handleDateBlur}+ onClick={handleDateInputClick}+ onKeyDown={handleDateKeyDown}+ placeholder={placeholder}+ // With a disabledMessage the input keeps focusability via+ // aria-disabled so the reason is focus-discoverable; typing is+ // blocked with readOnly and the mutation guards, and calendar+ // activation is blocked by the isEffectivelyDisabled guards.+ disabled={isEffectivelyDisabled && !showsDisabledMessage}+ aria-disabled={showsDisabledMessage ? 'true' : undefined}+ readOnly={showsDisabledMessage || undefined}+ aria-describedby={ariaDescribedBy}+ aria-required={isEffectivelyRequired ? 'true' : undefined}+ aria-invalid={+ status?.type === 'error' || !isDateInputValid+ ? '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,+ )}+ />+ {/*Live region announcing invalid typed date input to assistivetechnology. The value silently reverts on blur, so without this ascreen-reader user would get no feedback that their entry wasrejected (WCAG 3.3.1).*/}- <VisuallyHidden as="div" role="alert" aria-live="assertive">- {!isDateInputValid ? t('@astryx.dateInput.invalidDate') : ''}- </VisuallyHidden>+ <VisuallyHidden as="div" role="alert" aria-live="assertive">+ {!isDateInputValid ? t('@astryx.dateInput.invalidDate') : ''}+ </VisuallyHidden>+ </>+ )}{hasClear && value !== undefined && !isEffectivelyDisabled && (<InputClearButtonlabel={t('@astryx.dateInput.clear', {label})}@@ -1542,8 +1710,10 @@ function PointerDateTimeField({{/* Time input */}<divref={timeContainerRef}- onClick={handleTimeWrapperClick}- onMouseUp={handleTimeWrapperMouseUp}+ onClick={usesNativeTimePicker ? undefined : handleTimeWrapperClick}+ onMouseUp={+ usesNativeTimePicker ? undefined : handleTimeWrapperMouseUp+ }// On the wrapper, not just the input: clicking the clock icon or the// padding is routed to the input as a synthetic click, which would// otherwise open the list mid-gesture and let light dismiss eat it.@@ -1565,89 +1735,118 @@ function PointerDateTimeField({status && inputStatusFocusWithinStyles[status.type],),)}>- <div {...stylex.props(styles.icon)}>- <Icon- icon="clock"- size="sm"- color="secondary"- // Stable theme target on the leading clock glyph, so a theme can- // restyle just this icon (color, size) via `defineTheme`. The- // time segment has no toggle button — the clock is a static- // leading affordance — so this carries no interactive state.- {...themeProps('date-time-input-clock-icon')}+ {usesNativeTimePicker ? (+ <NativeTimeSegment+ id={timeInputId}+ inputRef={timeInputRef}+ value={nativeTimeValue}+ onChange={handleNativeTimeChange}+ placeholder={timePlaceholder}+ label={resolvedTimeLabel}+ min={timeMin}+ max={timeMax}+ hourFormat={hourFormat}+ isEffectivelyDisabled={isEffectivelyDisabled}+ hasDisabledMessage={showsDisabledMessage}+ isEffectivelyRequired={isEffectivelyRequired}+ isBusy={isBusy}+ statusType={status?.type}+ ariaDescribedBy={ariaDescribedBy}/>- </div>- <input- ref={timeInputRef}- id={timeInputId}- type="text"- value={timeDisplayValue}- onChange={handleTimeInputChange}- onFocus={handleTimeFocus}- onBlur={handleTimeBlur}- onKeyDown={handleTimeKeyDown}- onClick={hasTimeOptions ? showTimeOptions : undefined}- onPointerDown={hasTimeOptions ? markTimePointerActive : undefined}- placeholder={resolvedTimePlaceholder}- // Combobox semantics appear only with the dropdown opted in, so a- // field without it keeps a single combobox on the date half.- role={hasTimeOptions ? 'combobox' : undefined}- aria-expanded={hasTimeOptions ? timePopover.isOpen : undefined}- aria-controls={- hasTimeOptions && timePopover.isOpen ? timeListboxId : undefined- }- aria-autocomplete={hasTimeOptions ? 'list' : undefined}- aria-activedescendant={- hasTimeOptions &&- timePopover.isOpen &&- activeTimeIndex >= 0 &&- activeTimeIndex < timeOptions.length- ? timeOptionId(activeTimeIndex)- : undefined- }- // With a disabledMessage the input keeps focusability via- // aria-disabled so the reason is focus-discoverable; typing is- // blocked with readOnly and the mutation guards.- disabled={isEffectivelyDisabled && !showsDisabledMessage}- aria-disabled={showsDisabledMessage ? 'true' : undefined}- readOnly={showsDisabledMessage || undefined}- aria-label={resolvedTimeLabel}- aria-describedby={ariaDescribedBy}- aria-required={isEffectivelyRequired ? 'true' : undefined}- aria-invalid={- status?.type === 'error' || !isTimeInputValid ? 'true' : undefined- }- aria-busy={isBusy || undefined}- {...stylex.props(- styles.input,- isEffectivelyDisabled && styles.inputDisabled,- !isTimeInputValid && styles.inputInvalid,- )}- />- {/*- Live region announcing invalid typed time input to assistive- technology (WCAG 3.3.1).- */}- <VisuallyHidden as="div" role="alert" aria-live="assertive">- {!isTimeInputValid ? t('@astryx.timeInput.invalidTime') : ''}- </VisuallyHidden>+ ) : (+ <>+ <div {...stylex.props(styles.icon)}>+ <Icon+ icon="clock"+ size="sm"+ color="secondary"+ // Stable theme target on the leading clock glyph, so a theme can+ // restyle just this icon (color, size) via `defineTheme`. The+ // time segment has no toggle button — the clock is a static+ // leading affordance — so this carries no interactive state.+ {...themeProps('date-time-input-clock-icon')}+ />+ </div>+ <input+ ref={timeInputRef}+ id={timeInputId}+ type="text"+ value={timeDisplayValue}+ onChange={handleTimeInputChange}+ onFocus={handleTimeFocus}+ onBlur={handleTimeBlur}+ onKeyDown={handleTimeKeyDown}+ onClick={hasTimeOptions ? showTimeOptions : undefined}+ onPointerDown={+ hasTimeOptions ? markTimePointerActive : undefined+ }+ placeholder={resolvedTimePlaceholder}+ // Combobox semantics appear only with the dropdown opted in, so a+ // field without it keeps a single combobox on the date half.+ role={hasTimeOptions ? 'combobox' : undefined}+ aria-expanded={hasTimeOptions ? timePopover.isOpen : undefined}+ aria-controls={+ hasTimeOptions && timePopover.isOpen+ ? timeListboxId+ : undefined+ }+ aria-autocomplete={hasTimeOptions ? 'list' : undefined}+ aria-activedescendant={+ hasTimeOptions &&+ timePopover.isOpen &&+ activeTimeIndex >= 0 &&+ activeTimeIndex < timeOptions.length+ ? timeOptionId(activeTimeIndex)+ : undefined+ }+ // With a disabledMessage the input keeps focusability via+ // aria-disabled so the reason is focus-discoverable; typing is+ // blocked with readOnly and the mutation guards.+ disabled={isEffectivelyDisabled && !showsDisabledMessage}+ aria-disabled={showsDisabledMessage ? 'true' : undefined}+ readOnly={showsDisabledMessage || undefined}+ aria-label={resolvedTimeLabel}+ aria-describedby={ariaDescribedBy}+ aria-required={isEffectivelyRequired ? 'true' : undefined}+ aria-invalid={+ status?.type === 'error' || !isTimeInputValid+ ? 'true'+ : undefined+ }+ aria-busy={isBusy || undefined}+ {...stylex.props(+ styles.input,+ isEffectivelyDisabled && styles.inputDisabled,+ !isTimeInputValid && styles.inputInvalid,+ )}+ />+ {/*+ Live region announcing invalid typed time input to assistive+ technology (WCAG 3.3.1).+ */}+ <VisuallyHidden as="div" role="alert" aria-live="assertive">+ {!isTimeInputValid ? t('@astryx.timeInput.invalidTime') : ''}+ </VisuallyHidden>+ </>+ )}</div></div>- {popover.render(- <Calendar- handleRef={calendarRef}- mode="single"- value={valueParts.date}- onChange={(d: ISODateString) => handleDateChange(d, 'calendar')}- min={calendarMin}- max={calendarMax}- dateConstraints={dateConstraints}- numberOfMonths={numberOfMonths}- weekStartsOn={weekStartsOn}- />,- {placement: 'below', alignment: 'start'},- )}+ {!usesNativePicker &&+ popover.render(+ <Calendar+ handleRef={calendarRef}+ mode="single"+ value={valueParts.date}+ onChange={(d: ISODateString) => handleDateChange(d, 'calendar')}+ min={calendarMin}+ max={calendarMax}+ dateConstraints={dateConstraints}+ numberOfMonths={numberOfMonths}+ weekStartsOn={weekStartsOn}+ />,+ {placement: 'below', alignment: 'start'},+ )}{hasTimeOptions &&timePopover.render(@@ -1706,21 +1905,25 @@ function PointerDateTimeField({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.+ * A combined date and time picker whose `nativePicker` prop chooses both+ * surfaces. Native modes use OS-owned date and time controls in Astryx field+ * chrome. With `nativePicker="never"`, fine pointers keep the typed fields and+ * popovers while coarse pointers get Astryx's coordinated Date/Time bottom+ * sheet.*/-export function DateTimeInput(props: DateTimeInputProps) {+export function DateTimeInput({+ nativePicker = 'touch',+ ...props+}: DateTimeInputProps) {const isTouch = useMediaQuery(TOUCH_POINTER_QUERY);- return isTouch ? (- <TouchDateTimeField {...props} />+ const usesNativePicker =+ nativePicker === 'always' || (nativePicker === 'touch' && isTouch);++ return usesNativePicker || !isTouch ? (+ <PointerDateTimeField {...props} nativePicker={nativePicker} />) : (- <PointerDateTimeField {...props} />+ <TouchDateTimeField {...props} />);}diff --git a/packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx b/packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsxindex 1fcbd752db..14f97c114d 100644--- a/packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx+++ b/packages/core/src/DateTimeInput/DateTimeInputTouch.test.tsx@@ -6,6 +6,10 @@* @output Focused coverage for DateTimeInput's coarse-pointer bottom-sheet picker* @position Test file for /packages/core/src/DateTimeInput/*+ * Every test renders through a wrapper that passes `nativePicker="never"`, so+ * this suite continues to exercise Astryx's coarse-pointer bottom sheet now+ * that DateTimeInput defaults to the platform date picker on touch.+ ** 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.@@ -25,8 +29,12 @@ import {useState} from 'react';import * as stylex from '@stylexjs/stylex';import {readFileSync} from 'node:fs';import {render, screen, fireEvent, within} from '@testing-library/react';-import {DateTimeInput} from './DateTimeInput';-import type {ISODateTimeString} from './DateTimeInput';+import {DateTimeInput as CoreDateTimeInput} from './DateTimeInput';+import type {DateTimeInputProps, ISODateTimeString} from './DateTimeInput';++function DateTimeInput(props: DateTimeInputProps) {+ return <CoreDateTimeInput {...props} nativePicker="never" />;+}class MockResizeObserver {observe() {}diff --git a/packages/core/src/DateTimeInput/NativeDateSegment.tsx b/packages/core/src/DateTimeInput/NativeDateSegment.tsxnew file mode 100644index 0000000000..b59177da45--- /dev/null+++ b/packages/core/src/DateTimeInput/NativeDateSegment.tsx@@ -0,0 +1,308 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file NativeDateSegment.tsx+ * @input Uses React, Icon, nativeDateSegments, and DateTimeInput's date state+ * @output Exports NativeDateSegment — the OS-picker date half of DateTimeInput+ * @position Internal DateTimeInput surface selected by `nativePicker`+ *+ * Hands date picking to the platform through `<input type="date">`. Its+ * sibling NativeTimeSegment hands time picking to `<input type="time">`, so+ * both halves of DateTimeInput follow the same `nativePicker` choice.+ *+ * The input is deliberately uncontrolled and observed through native event+ * listeners. On iOS, writing its value while the picker sheet is open can+ * detach the sheet, and React's synthetic change event does not reliably see+ * picker edits. External values therefore reconcile only while unfocused.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/DateTimeInput/DateTimeInput.tsx (surface selection)+ * - /packages/core/src/DateTimeInput/NativePickerSegments.test.tsx (tests)+ * - /packages/core/src/DateTimeInput/DateTimeInput.doc.mjs (prop docs)+ */++import {useCallback, useEffect, useRef, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {hasEditableDateSegments} from '../DateInput/nativeDateSegments';+import {useMediaQuery} from '../hooks/useMediaQuery';+import {useMergedRefs} from '../hooks/useMergedRefs';+import {Icon} from '../Icon';+import {useLocale, useTranslator} from '../i18n';+import {VisuallyHidden} from '../VisuallyHidden';+import {+ focusOutlineStyles,+ formatSharedDate,+ parseDateInput,+ plainDateFromISO,+ plainDateToISO,+ themeProps,+ type ISODateString,+} from '../utils';+import type {InputStatusType} from '../Field';+import {nativePickerSegmentStyles as styles} from './nativePickerSegmentStyles';++const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;++export type NativeDateSegmentProps = {+ id: string;+ inputRef: React.Ref<HTMLInputElement>;+ value?: ISODateString;+ onChange: (value: ISODateString | undefined) => void;+ placeholder: string;+ min?: ISODateString;+ max?: ISODateString;+ isDateDisabled: (date: ReturnType<typeof plainDateFromISO>) => boolean;+ isEffectivelyDisabled: boolean;+ hasDisabledMessage: boolean;+ isEffectivelyRequired: boolean;+ isBusy: boolean;+ statusType?: InputStatusType;+ ariaDescribedBy?: string;+};++/** The native date half rendered inside DateTimeInput's date wrapper. */+export function NativeDateSegment({+ id,+ inputRef,+ value,+ onChange,+ placeholder,+ min,+ max,+ isDateDisabled,+ isEffectivelyDisabled,+ hasDisabledMessage,+ isEffectivelyRequired,+ isBusy,+ statusType,+ ariaDescribedBy,+}: NativeDateSegmentProps) {+ const t = useTranslator();+ const locale = useLocale();+ const isTouchPointer = useMediaQuery('(pointer: coarse)');+ const internalInputRef = useRef<HTMLInputElement | null>(null);+ const mergedInputRef = useMergedRefs(inputRef, internalInputRef);++ const [rejectedValue, setRejectedValue] = useState<string | null>(null);+ const [isFocused, setIsFocused] = useState(false);+ const [isSegmentEditable, setIsSegmentEditable] = useState(false);+ const valueAtFocusRef = useRef<string | null>(null);+ const lastCommitRef = useRef<string | null>(null);++ const prevValueRef = useRef(value);+ if (value !== prevValueRef.current) {+ prevValueRef.current = value;+ // Keep the accepted DOM value cached while a native picker is open. An+ // optimistic rollback changes the prop but leaves the focused control alone;+ // clearing this cache would replay that rejected edit on blur.+ if (!isFocused) {+ lastCommitRef.current = null;+ }+ if (rejectedValue !== null) {+ setRejectedValue(null);+ }+ }++ const nativeValue = value && ISO_DATE.test(value) ? value : '';+ const isInputValid = rejectedValue === null;+ const overlayText = nativeValue+ ? formatSharedDate(plainDateFromISO(nativeValue), 'date_long', locale)+ : placeholder;+ const showsOverlay = !!overlayText && !(isFocused && isSegmentEditable);++ const commitValue = useCallback(+ (newValue: string) => {+ if (isEffectivelyDisabled) {+ return;+ }+ if (lastCommitRef.current === newValue) {+ return;+ }++ if (!newValue) {+ lastCommitRef.current = newValue;+ setRejectedValue(null);+ if (value !== undefined) {+ onChange(undefined);+ }+ return;+ }++ const parsed = parseDateInput(newValue, locale);+ if (!parsed) {+ return;+ }+ if (isDateDisabled(parsed)) {+ setRejectedValue(newValue);+ return;+ }++ setRejectedValue(null);+ lastCommitRef.current = newValue;+ const parsedISO = plainDateToISO(parsed);+ if (parsedISO !== value) {+ onChange(parsedISO);+ }+ },+ [isDateDisabled, isEffectivelyDisabled, locale, onChange, value],+ );++ const handleChange = useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ commitValue(event.target.value);+ },+ [commitValue],+ );++ // React's synthetic change system does not reliably observe iOS picker edits.+ const commitRef = useRef(commitValue);+ useEffect(() => {+ commitRef.current = commitValue;+ });+ useEffect(() => {+ const input = internalInputRef.current;+ if (!input) {+ return;+ }+ const handleNative = () => commitRef.current(input.value);+ input.addEventListener('input', handleNative);+ input.addEventListener('change', handleNative);+ return () => {+ input.removeEventListener('input', handleNative);+ input.removeEventListener('change', handleNative);+ };+ }, []);++ // React touches defaultValue after mount when the prop changes, so capture it+ // once. The effect below owns every later write and skips focused controls.+ const initialValueRef = useRef<string | null>(null);+ if (initialValueRef.current === null) {+ initialValueRef.current = nativeValue;+ }++ useEffect(() => {+ if (isFocused) {+ return;+ }+ const input = internalInputRef.current;+ if (input && input.value !== nativeValue) {+ input.value = nativeValue;+ }+ }, [isFocused, nativeValue]);++ const handleFocus = useCallback(() => {+ valueAtFocusRef.current = nativeValue;+ setIsSegmentEditable(hasEditableDateSegments(isTouchPointer));+ setIsFocused(true);+ }, [isTouchPointer, nativeValue]);++ const handleBlur = useCallback(() => {+ const domValue = internalInputRef.current?.value;+ const valueChangedWhileFocused =+ valueAtFocusRef.current !== null &&+ valueAtFocusRef.current !== nativeValue;+ const wasRejected = rejectedValue !== null;+ valueAtFocusRef.current = null;+ setIsFocused(false);+ setRejectedValue(null);+ if (+ !valueChangedWhileFocused &&+ !wasRejected &&+ domValue !== undefined &&+ domValue !== nativeValue+ ) {+ commitValue(domValue);+ }+ lastCommitRef.current = null;+ }, [commitValue, nativeValue, rejectedValue]);++ const openPicker = useCallback(() => {+ if (isEffectivelyDisabled) {+ return;+ }+ const input = internalInputRef.current;+ if (!input) {+ return;+ }+ input.focus();+ if (typeof input.showPicker === 'function') {+ try {+ input.showPicker();+ } catch {+ // Focus is the fallback when showPicker needs user activation or the+ // browser does not expose it for date controls.+ }+ }+ }, [isEffectivelyDisabled]);++ return (+ <>+ <button+ type="button"+ onClick={openPicker}+ 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: 'collapsed'})}+ />+ </button>+ <span {...stylex.props(styles.slot)}>+ <input+ ref={mergedInputRef}+ id={id}+ type="date"+ // UNCONTROLLED on purpose; see initialValueRef and the sync effect.+ defaultValue={initialValueRef.current ?? ''}+ onChange={handleChange}+ onFocus={handleFocus}+ onBlur={handleBlur}+ min={min}+ max={max}+ disabled={isEffectivelyDisabled && !hasDisabledMessage}+ aria-disabled={hasDisabledMessage ? 'true' : undefined}+ readOnly={hasDisabledMessage || undefined}+ aria-describedby={ariaDescribedBy}+ aria-required={isEffectivelyRequired ? 'true' : undefined}+ aria-invalid={+ statusType === 'error' || !isInputValid ? 'true' : undefined+ }+ aria-busy={isBusy || undefined}+ {...stylex.props(+ styles.input,+ showsOverlay && styles.inputTextHidden,+ isEffectivelyDisabled && styles.inputDisabled,+ !isInputValid && styles.inputInvalid,+ )}+ />+ {showsOverlay && (+ <span+ aria-hidden="true"+ {...stylex.props(+ styles.overlay,+ nativeValue ? styles.overlayValue : styles.overlayPlaceholder,+ isEffectivelyDisabled && styles.inputDisabled,+ !isInputValid && !!nativeValue && styles.inputInvalid,+ )}>+ {overlayText}+ </span>+ )}+ </span>+ <VisuallyHidden as="div" role="alert" aria-live="assertive">+ {!isInputValid ? t('@astryx.dateInput.invalidDate') : ''}+ </VisuallyHidden>+ </>+ );+}++NativeDateSegment.displayName = 'NativeDateSegment';diff --git a/packages/core/src/DateTimeInput/NativePickerSegments.test.tsx b/packages/core/src/DateTimeInput/NativePickerSegments.test.tsxnew file mode 100644index 0000000000..b41cae734a--- /dev/null+++ b/packages/core/src/DateTimeInput/NativePickerSegments.test.tsx@@ -0,0 +1,626 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file NativePickerSegments.test.tsx+ * @input Uses vitest, @testing-library/react, DateTimeInput+ * @output Unit tests for DateTimeInput's native date and time picker segments+ * @position Testing; validates NativeDateSegment, NativeTimeSegment, and surface selection+ *+ * Every test renders through DateTimeInput so the three-value `nativePicker`+ * switch is covered together with both native controls.+ *+ * SYNC: When either native picker segment changes, update these tests+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {act, fireEvent, render, screen} from '@testing-library/react';+import * as stylex from '@stylexjs/stylex';+import {DateTimeInput} from './DateTimeInput';+import type {ISODateTimeString} from './DateTimeInput';+import {resetDateSegmentProbe} from '../DateInput/nativeDateSegments';++const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;++// jsdom does not perform intrinsic flex layout. These classes pin the+// DateInput-aligned native field floor and confirm that value slots remain+// shrinkable rather than carrying their own preferred width.+const nativeSizingProbe = stylex.create({+ row: {minInlineSize: 180},+ slot: {flex: 1, minInlineSize: 0},+});++function expectProbeClasses(+ element: HTMLElement,+ style: (typeof nativeSizingProbe)[keyof typeof nativeSizingProbe],+): void {+ const classes = (stylex.props(style).className ?? '')+ .split(' ')+ .filter(className => className !== '' && !className.includes('__'));+ expect(classes.length).toBeGreaterThan(0);+ for (const className of classes) {+ expect(element).toHaveClass(className);+ }+}++class MockResizeObserver {+ observe() {}+ unobserve() {}+ disconnect() {}+}++function stubPointer(isCoarse: boolean): void {+ vi.stubGlobal('matchMedia', (query: string) => ({+ matches: /pointer:\s*coarse/.test(query)+ ? isCoarse+ : /pointer:\s*fine/.test(query)+ ? !isCoarse+ : HOVER_CAPABLE.test(query),+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ }));+}++function getNativeDateInput(): HTMLInputElement {+ const input = document.querySelector<HTMLInputElement>('input[type="date"]');+ if (!input) {+ throw new Error('DateTimeInput rendered no native date control');+ }+ return input;+}++function getNativeTimeInput(): HTMLInputElement {+ const input = document.querySelector<HTMLInputElement>('input[type="time"]');+ if (!input) {+ throw new Error('DateTimeInput rendered no native time control');+ }+ return input;+}++beforeEach(() => {+ vi.stubGlobal('ResizeObserver', MockResizeObserver);+});++afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ resetDateSegmentProbe();+});++describe('DateTimeInput nativePicker', () => {+ it('renders native date and time controls on touch by default', () => {+ stubPointer(true);+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);++ expect(getNativeDateInput()).toBeInTheDocument();+ expect(getNativeTimeInput()).toBe(screen.getByLabelText('Meeting time'));+ });++ it('uses DateInput’s native field floor with shrinkable value slots', () => {+ stubPointer(true);+ const {container} = render(+ <DateTimeInput label="Meeting" onChange={() => {}} />,+ );++ const row = container.querySelector('.astryx-date-time-input');+ expect(row).toBeInstanceOf(HTMLElement);+ expectProbeClasses(row as HTMLElement, nativeSizingProbe.row);++ for (const input of [getNativeDateInput(), getNativeTimeInput()]) {+ const slot = input.parentElement;+ expect(slot).toBeInstanceOf(HTMLElement);+ expectProbeClasses(slot as HTMLElement, nativeSizingProbe.slot);+ }+ });++ it('keeps Astryx text fields on a mouse device by default', () => {+ stubPointer(false);+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);++ expect(document.querySelector('input[type="date"]')).toBeNull();+ expect(document.querySelector('input[type="time"]')).toBeNull();+ expect(screen.getByRole('combobox')).toHaveAttribute('type', 'text');+ expect(screen.getByLabelText('Meeting time')).toHaveAttribute(+ 'type',+ 'text',+ );+ });++ it('uses Astryx’s coordinated touch sheet on touch when told never', () => {+ stubPointer(true);+ render(+ <DateTimeInput+ label="Meeting"+ nativePicker="never"+ onChange={() => {}}+ />,+ );++ expect(document.querySelector('input[type="date"]')).toBeNull();+ expect(document.querySelector('input[type="time"]')).toBeNull();+ expect(screen.getByRole('combobox', {name: 'Meeting'})).toHaveAttribute(+ 'readonly',+ );+ });++ it('uses both native controls on a mouse device when told always', () => {+ stubPointer(false);+ render(+ <DateTimeInput+ label="Meeting"+ nativePicker="always"+ onChange={() => {}}+ />,+ );++ expect(getNativeDateInput()).toBeInTheDocument();+ expect(getNativeTimeInput()).toBeInTheDocument();+ });++ it('drops in-page popup ARIA because the OS owns both pickers', () => {+ stubPointer(true);+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);++ for (const input of [getNativeDateInput(), getNativeTimeInput()]) {+ expect(input).not.toHaveAttribute('role', 'combobox');+ expect(input).not.toHaveAttribute('aria-expanded');+ expect(input).not.toHaveAttribute('aria-haspopup');+ expect(input).not.toHaveAttribute('aria-controls');+ }+ });++ it('keeps native values ISO and paints localized date/time text', () => {+ stubPointer(true);+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={() => {}}+ />,+ );++ expect(getNativeDateInput()).toHaveValue('2026-03-15');+ expect(getNativeTimeInput()).toHaveValue('14:30');+ expect(screen.getByText('March 15, 2026')).toBeInTheDocument();+ expect(screen.getByText('2:30 PM')).toBeInTheDocument();+ });++ it('changes the date while preserving the time', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ />,+ );++ fireEvent.change(getNativeDateInput(), {target: {value: '2026-03-21'}});++ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-21T14:30');+ });++ it('changes the time while preserving the date', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ />,+ );++ fireEvent.change(getNativeTimeInput(), {target: {value: '15:45'}});++ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-15T15:45');+ });++ it('reverts a native time edit when the controlled parent rejects it', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ />,+ );+ const timeInput = getNativeTimeInput();+ fireEvent.focus(timeInput);++ fireEvent.change(timeInput, {target: {value: '15:45'}});+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-15T15:45');+ fireEvent.blur(timeInput);++ expect(onChange).toHaveBeenCalledTimes(1);+ expect(timeInput).toHaveValue('14:30');+ });++ it.each([+ ['date', getNativeDateInput, '2026-03-21'],+ ['time', getNativeTimeInput, '15:45'],+ ] as const)(+ 'does not replay a rejected optimistic %s edit on blur',+ async (_name, getInput, editedValue) => {+ stubPointer(true);+ const onChange = vi.fn();+ let resolveAction: (() => void) | undefined;+ const changeAction = vi.fn(+ async () =>+ new Promise<void>(resolve => {+ resolveAction = resolve;+ }),+ );+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ changeAction={changeAction}+ />,+ );+ const input = getInput();+ fireEvent.focus(input);+ fireEvent.change(input, {target: {value: editedValue}});+ expect(onChange).toHaveBeenCalledTimes(1);++ await act(async () => resolveAction?.());+ fireEvent.blur(input);++ expect(onChange).toHaveBeenCalledTimes(1);+ expect(changeAction).toHaveBeenCalledTimes(1);+ },+ );++ it('keeps native picker edits enabled while changeAction is pending', () => {+ stubPointer(true);+ 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}+ />,+ );+ const timeInput = getNativeTimeInput();++ fireEvent.change(timeInput, {target: {value: '15:00'}});+ expect(timeInput).toHaveAttribute('aria-busy', 'true');+ expect(timeInput).not.toBeDisabled();++ fireEvent.change(timeInput, {target: {value: '15:30'}});++ expect(onChange).toHaveBeenCalledWith('2026-03-15T15:00');+ expect(onChange).toHaveBeenCalledWith('2026-03-15T15:30');+ expect(changeAction).toHaveBeenCalledTimes(2);+ });++ it('retains a native time chosen before the date exists', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(<DateTimeInput label="Meeting" onChange={onChange} />);++ fireEvent.change(getNativeTimeInput(), {target: {value: '09:45'}});+ expect(onChange).not.toHaveBeenCalled();+ expect(getNativeTimeInput()).toHaveValue('09:45');++ fireEvent.change(getNativeDateInput(), {target: {value: '2026-03-21'}});++ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-21T09:45');+ });++ it('clamps a time chosen before the date to that date’s boundary', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ min={'2026-03-21T09:00' as ISODateTimeString}+ onChange={onChange}+ />,+ );++ fireEvent.change(getNativeTimeInput(), {target: {value: '08:00'}});+ expect(onChange).not.toHaveBeenCalled();+ fireEvent.change(getNativeDateInput(), {target: {value: '2026-03-21'}});++ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-21T09:00');+ });++ it('can clear an optimistic datetime created from an empty value', () => {+ stubPointer(true);+ const onChange = vi.fn();+ const changeAction = vi.fn(async () => new Promise<void>(() => {}));+ render(+ <DateTimeInput+ label="Meeting"+ onChange={onChange}+ changeAction={changeAction}+ />,+ );++ fireEvent.change(getNativeDateInput(), {target: {value: '2026-03-21'}});+ expect(onChange).toHaveBeenCalledTimes(1);+ expect(getNativeTimeInput()).not.toBeDisabled();++ fireEvent.change(getNativeTimeInput(), {target: {value: ''}});++ expect(onChange).toHaveBeenLastCalledWith(undefined);+ expect(changeAction).toHaveBeenLastCalledWith(undefined);+ });++ it('retains the preset-time combobox when timeOptionInterval is set', () => {+ stubPointer(true);+ render(+ <DateTimeInput+ label="Meeting"+ timeOptionInterval={60}+ onChange={() => {}}+ />,+ );++ expect(getNativeDateInput()).toBeInTheDocument();+ expect(document.querySelector('input[type="time"]')).toBeNull();+ expect(screen.getByLabelText('Meeting time')).toHaveAttribute(+ 'role',+ 'combobox',+ );+ });++ it('clamps the preserved time at a datetime boundary', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-16T08:00' as ISODateTimeString}+ min={'2026-03-15T09:00' as ISODateTimeString}+ onChange={onChange}+ />,+ );++ fireEvent.change(getNativeDateInput(), {target: {value: '2026-03-15'}});++ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-15T09:00');+ });++ it('forwards date and boundary-time constraints to the native controls', () => {+ stubPointer(true);+ 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}+ onChange={() => {}}+ />,+ );++ expect(getNativeDateInput()).toHaveAttribute('min', '2026-03-15');+ expect(getNativeDateInput()).toHaveAttribute('max', '2026-03-15');+ expect(getNativeTimeInput()).toHaveAttribute('min', '09:00');+ expect(getNativeTimeInput()).toHaveAttribute('max', '17:00');+ expect(getNativeTimeInput()).toHaveAttribute('step', '60');+ });++ it('retains the Astryx time field when seconds are requested', () => {+ stubPointer(true);+ render(+ <DateTimeInput+ label="Timestamp"+ value={'2026-03-15T14:30:45' as ISODateTimeString}+ hourFormat="24h"+ hasSeconds+ onChange={() => {}}+ />,+ );++ expect(getNativeDateInput()).toBeInTheDocument();+ expect(document.querySelector('input[type="time"]')).toBeNull();+ expect(screen.getByLabelText('Timestamp time')).toHaveValue('14:30:45');+ });++ it('retains the Astryx time field for a custom timeIncrement', () => {+ stubPointer(true);+ render(+ <DateTimeInput label="Meeting" timeIncrement={15} onChange={() => {}} />,+ );++ expect(getNativeDateInput()).toBeInTheDocument();+ expect(document.querySelector('input[type="time"]')).toBeNull();+ expect(screen.getByLabelText('Meeting time')).toHaveAttribute(+ 'type',+ 'text',+ );+ });++ it('refuses a custom date constraint and announces the rejection', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ dateConstraints={[() => false]}+ onChange={onChange}+ />,+ );++ fireEvent.change(getNativeDateInput(), {target: {value: '2026-03-15'}});++ expect(onChange).not.toHaveBeenCalled();+ expect(screen.getByText('Invalid date')).toBeInTheDocument();+ expect(getNativeDateInput()).toHaveAttribute('aria-invalid', 'true');+ });++ it('refuses an out-of-range native time and announces the rejection', () => {+ stubPointer(true);+ const onChange = vi.fn();+ 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}+ onChange={onChange}+ />,+ );++ fireEvent.change(getNativeTimeInput(), {target: {value: '08:00'}});++ expect(onChange).not.toHaveBeenCalled();+ expect(screen.getByText('Invalid time')).toBeInTheDocument();+ expect(getNativeTimeInput()).toHaveAttribute('aria-invalid', 'true');+ });++ it('announces the same rejected date again after the picker closes', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ dateConstraints={[() => false]}+ onChange={onChange}+ />,+ );+ const dateInput = getNativeDateInput();++ fireEvent.focus(dateInput);+ fireEvent.change(dateInput, {target: {value: '2026-03-15'}});+ fireEvent.blur(dateInput);+ expect(screen.queryByText('Invalid date')).not.toBeInTheDocument();++ fireEvent.focus(dateInput);+ fireEvent.change(dateInput, {target: {value: '2026-03-15'}});++ expect(onChange).not.toHaveBeenCalled();+ expect(screen.getByText('Invalid date')).toBeInTheDocument();+ });++ it('observes native date and time events that bypass React change handling', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ />,+ );++ const dateInput = getNativeDateInput();+ act(() => {+ dateInput.value = '2026-03-21';+ dateInput.dispatchEvent(new Event('input', {bubbles: true}));+ });+ expect(onChange).toHaveBeenLastCalledWith('2026-03-21T14:30');++ onChange.mockClear();+ const timeInput = getNativeTimeInput();+ act(() => {+ timeInput.value = '15:45';+ timeInput.dispatchEvent(new Event('input', {bubbles: true}));+ });+ expect(onChange).toHaveBeenLastCalledWith('2026-03-15T15:45');+ });++ it('does not overwrite externally changed values when native pickers blur', () => {+ stubPointer(true);+ const onChange = vi.fn();+ const renderInput = (value: ISODateTimeString) => (+ <DateTimeInput label="Meeting" value={value} onChange={onChange} />+ );+ const {rerender} = render(+ renderInput('2026-03-15T14:30' as ISODateTimeString),+ );+ const dateInput = getNativeDateInput();+ const timeInput = getNativeTimeInput();+ fireEvent.focus(dateInput);+ fireEvent.focus(timeInput);++ rerender(renderInput('2026-03-21T16:45' as ISODateTimeString));+ expect(dateInput).toHaveValue('2026-03-15');+ expect(timeInput).toHaveValue('14:30');++ fireEvent.blur(dateInput);+ fireEvent.blur(timeInput);++ expect(onChange).not.toHaveBeenCalled();+ expect(dateInput).toHaveValue('2026-03-21');+ expect(timeInput).toHaveValue('16:45');+ });++ it('opens the native time picker from the clock button', () => {+ stubPointer(true);+ render(<DateTimeInput label="Meeting" onChange={() => {}} />);+ const timeInput = getNativeTimeInput();+ const showPicker = vi.fn();+ (timeInput as HTMLInputElement & {showPicker: () => void}).showPicker =+ showPicker;++ fireEvent.click(screen.getByRole('button', {name: 'Open Meeting time'}));++ expect(timeInput).toHaveFocus();+ expect(showPicker).toHaveBeenCalledTimes(1);+ });++ it('clears without refocusing and reopening either native picker', () => {+ stubPointer(true);+ const onChange = vi.fn();+ render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ hasClear+ onChange={onChange}+ />,+ );++ fireEvent.click(screen.getByRole('button', {name: 'Clear Meeting'}));++ expect(onChange).toHaveBeenCalledExactlyOnceWith(undefined);+ expect(getNativeDateInput()).not.toHaveFocus();+ expect(getNativeTimeInput()).not.toHaveFocus();+ });++ it('empties the whole datetime when either native control is reset', () => {+ stubPointer(true);+ const onChange = vi.fn();+ const {rerender} = render(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ />,+ );++ fireEvent.change(getNativeDateInput(), {target: {value: ''}});+ expect(onChange).toHaveBeenLastCalledWith(undefined);++ onChange.mockClear();+ rerender(+ <DateTimeInput+ label="Meeting"+ value={'2026-03-15T14:30' as ISODateTimeString}+ onChange={onChange}+ />,+ );+ fireEvent.change(getNativeTimeInput(), {target: {value: ''}});+ expect(onChange).toHaveBeenLastCalledWith(undefined);+ });++ it('forwards the public ref to the native date input', () => {+ stubPointer(true);+ const ref = vi.fn();+ render(<DateTimeInput ref={ref} label="Meeting" onChange={() => {}} />);++ expect(ref).toHaveBeenCalledWith(getNativeDateInput());+ });+});diff --git a/packages/core/src/DateTimeInput/NativeTimeSegment.tsx b/packages/core/src/DateTimeInput/NativeTimeSegment.tsxnew file mode 100644index 0000000000..59431fa762--- /dev/null+++ b/packages/core/src/DateTimeInput/NativeTimeSegment.tsx@@ -0,0 +1,323 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file NativeTimeSegment.tsx+ * @input Uses React, native picker segment styles, and shared time utilities+ * @output Exports NativeTimeSegment — the OS-picker time half of DateTimeInput+ * @position Internal DateTimeInput surface selected by `nativePicker`+ *+ * Hands time picking to the platform through `<input type="time">`. The input+ * is deliberately uncontrolled and observed through native event listeners,+ * matching NativeDateSegment's iOS-safe value ownership: external values only+ * reconcile while the picker is unfocused, and native edits do not depend on+ * React's synthetic change event.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/core/src/DateTimeInput/DateTimeInput.tsx (surface selection)+ * - /packages/core/src/DateTimeInput/NativePickerSegments.test.tsx (native surface tests)+ * - /packages/core/src/DateTimeInput/DateTimeInput.doc.mjs (prop docs)+ */++import {useCallback, useEffect, useRef, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {hasEditableDateSegments} from '../DateInput/nativeDateSegments';+import type {InputStatusType} from '../Field';+import {useMediaQuery} from '../hooks/useMediaQuery';+import {useMergedRefs} from '../hooks/useMergedRefs';+import {Icon} from '../Icon';+import {useTranslator} from '../i18n';+import {VisuallyHidden} from '../VisuallyHidden';+import {+ focusOutlineStyles,+ formatDisplayTime12h,+ formatDisplayTime24h,+ formatISOTime,+ isTimeInRange,+ parseISOTime,+ themeProps,+ type ISOTimeString,+} from '../utils';+import type {DateTimeInputHourFormat} from './DateTimeInput';+import {nativePickerSegmentStyles as styles} from './nativePickerSegmentStyles';++const FRACTIONAL_SECONDS = /\.\d+$/;++function normalizeNativeTime(+ value: string | undefined,+): ISOTimeString | undefined {+ if (!value) {+ return undefined;+ }+ const withoutFraction = value.replace(+ FRACTIONAL_SECONDS,+ '',+ ) as ISOTimeString;+ const parsed = parseISOTime(withoutFraction);+ return parsed ? formatISOTime(parsed, false) : undefined;+}++export type NativeTimeSegmentProps = {+ id: string;+ inputRef: React.Ref<HTMLInputElement>;+ value?: ISOTimeString;+ onChange: (value: ISOTimeString | undefined) => void;+ placeholder: string;+ label: string;+ min?: ISOTimeString;+ max?: ISOTimeString;+ hourFormat: DateTimeInputHourFormat;+ isEffectivelyDisabled: boolean;+ hasDisabledMessage: boolean;+ isEffectivelyRequired: boolean;+ isBusy: boolean;+ statusType?: InputStatusType;+ ariaDescribedBy?: string;+};++/** The native time half rendered inside DateTimeInput's time wrapper. */+export function NativeTimeSegment({+ id,+ inputRef,+ value,+ onChange,+ placeholder,+ label,+ min,+ max,+ hourFormat,+ isEffectivelyDisabled,+ hasDisabledMessage,+ isEffectivelyRequired,+ isBusy,+ statusType,+ ariaDescribedBy,+}: NativeTimeSegmentProps) {+ const t = useTranslator();+ const isTouchPointer = useMediaQuery('(pointer: coarse)');+ const internalInputRef = useRef<HTMLInputElement | null>(null);+ const mergedInputRef = useMergedRefs(inputRef, internalInputRef);++ const [rejectedValue, setRejectedValue] = useState<string | null>(null);+ const [isFocused, setIsFocused] = useState(false);+ const [isSegmentEditable, setIsSegmentEditable] = useState(false);+ const valueAtFocusRef = useRef<string | null>(null);+ const lastCommitRef = useRef<string | null>(null);++ const prevValueRef = useRef(value);+ if (value !== prevValueRef.current) {+ prevValueRef.current = value;+ // Preserve the accepted DOM value while the OS wheel is open so an+ // optimistic rollback cannot replay that edit when the field blurs.+ if (!isFocused) {+ lastCommitRef.current = null;+ }+ if (rejectedValue !== null) {+ setRejectedValue(null);+ }+ }++ const nativeValue = normalizeNativeTime(value) ?? '';+ const isInputValid = rejectedValue === null;+ const formatDisplayTime =+ hourFormat === '12h' ? formatDisplayTime12h : formatDisplayTime24h;+ const overlayText = nativeValue+ ? formatDisplayTime(nativeValue, false)+ : placeholder;+ const showsOverlay = !!overlayText && !(isFocused && isSegmentEditable);++ const commitValue = useCallback(+ (newValue: string) => {+ if (isEffectivelyDisabled || lastCommitRef.current === newValue) {+ return;+ }++ if (!newValue) {+ lastCommitRef.current = newValue;+ setRejectedValue(null);+ if (value !== undefined) {+ onChange(undefined);+ }+ return;+ }++ const normalized = normalizeNativeTime(newValue);+ if (!normalized) {+ return;+ }+ if (!isTimeInRange(normalized, min, max)) {+ setRejectedValue(newValue);+ return;+ }++ setRejectedValue(null);+ lastCommitRef.current = newValue;+ if (normalized !== value) {+ onChange(normalized);+ }+ },+ [isEffectivelyDisabled, max, min, onChange, value],+ );++ const handleChange = useCallback(+ (event: React.ChangeEvent<HTMLInputElement>) => {+ commitValue(event.target.value);+ },+ [commitValue],+ );++ // React's synthetic change system does not reliably observe iOS picker edits.+ const commitRef = useRef(commitValue);+ useEffect(() => {+ commitRef.current = commitValue;+ });+ useEffect(() => {+ const input = internalInputRef.current;+ if (!input) {+ return;+ }+ const handleNative = () => commitRef.current(input.value);+ input.addEventListener('input', handleNative);+ input.addEventListener('change', handleNative);+ return () => {+ input.removeEventListener('input', handleNative);+ input.removeEventListener('change', handleNative);+ };+ }, []);++ // React touches defaultValue after mount when the prop changes. Capture it+ // once, then reconcile through the unfocused-only effect below.+ const initialValueRef = useRef<string | null>(null);+ if (initialValueRef.current === null) {+ initialValueRef.current = nativeValue;+ }++ useEffect(() => {+ if (isFocused) {+ return;+ }+ const input = internalInputRef.current;+ if (input && input.value !== nativeValue) {+ input.value = nativeValue;+ }+ }, [isFocused, nativeValue]);++ const handleFocus = useCallback(() => {+ valueAtFocusRef.current = nativeValue;+ // The engine probe classifies whether WebKit/Blink exposes editable native+ // segments. Date and time controls share that engine-level behavior.+ setIsSegmentEditable(hasEditableDateSegments(isTouchPointer));+ setIsFocused(true);+ }, [isTouchPointer, nativeValue]);++ const handleBlur = useCallback(() => {+ const domValue = internalInputRef.current?.value;+ const valueChangedWhileFocused =+ valueAtFocusRef.current !== null &&+ valueAtFocusRef.current !== nativeValue;+ const wasRejected = rejectedValue !== null;+ valueAtFocusRef.current = null;+ setIsFocused(false);+ setRejectedValue(null);+ if (+ !valueChangedWhileFocused &&+ !wasRejected &&+ domValue !== undefined &&+ domValue !== nativeValue+ ) {+ commitValue(domValue);+ }+ lastCommitRef.current = null;+ }, [commitValue, nativeValue, rejectedValue]);++ const openPicker = useCallback(() => {+ if (isEffectivelyDisabled) {+ return;+ }+ const input = internalInputRef.current;+ if (!input) {+ return;+ }+ input.focus();+ if (typeof input.showPicker === 'function') {+ try {+ input.showPicker();+ } catch {+ // Focus raises the iOS picker and is the fallback when showPicker needs+ // user activation or is unavailable.+ }+ }+ }, [isEffectivelyDisabled]);++ return (+ <>+ <button+ type="button"+ onClick={openPicker}+ disabled={isEffectivelyDisabled}+ aria-label={t('@astryx.dateTimeInput.openTimePicker', {label})}+ 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>+ <span {...stylex.props(styles.slot)}>+ <input+ ref={mergedInputRef}+ id={id}+ type="time"+ // UNCONTROLLED on purpose; see initialValueRef and the sync effect.+ defaultValue={initialValueRef.current ?? ''}+ onChange={handleChange}+ onFocus={handleFocus}+ onBlur={handleBlur}+ min={min}+ max={max}+ step={60}+ disabled={isEffectivelyDisabled && !hasDisabledMessage}+ aria-disabled={hasDisabledMessage ? 'true' : undefined}+ readOnly={hasDisabledMessage || undefined}+ aria-label={label}+ aria-describedby={ariaDescribedBy}+ aria-required={isEffectivelyRequired ? 'true' : undefined}+ aria-invalid={+ statusType === 'error' || !isInputValid ? 'true' : undefined+ }+ aria-busy={isBusy || undefined}+ {...stylex.props(+ styles.input,+ showsOverlay && styles.inputTextHidden,+ isEffectivelyDisabled && styles.inputDisabled,+ !isInputValid && styles.inputInvalid,+ )}+ />+ {showsOverlay && (+ <span+ aria-hidden="true"+ {...stylex.props(+ styles.overlay,+ nativeValue ? styles.overlayValue : styles.overlayPlaceholder,+ isEffectivelyDisabled && styles.inputDisabled,+ !isInputValid && !!nativeValue && styles.inputInvalid,+ )}>+ {overlayText}+ </span>+ )}+ </span>+ <VisuallyHidden as="div" role="alert" aria-live="assertive">+ {!isInputValid ? t('@astryx.timeInput.invalidTime') : ''}+ </VisuallyHidden>+ </>+ );+}++NativeTimeSegment.displayName = 'NativeTimeSegment';diff --git a/packages/core/src/DateTimeInput/index.ts b/packages/core/src/DateTimeInput/index.tsindex 2f14f0f83c..514235a431 100644--- a/packages/core/src/DateTimeInput/index.ts+++ b/packages/core/src/DateTimeInput/index.ts@@ -14,6 +14,7 @@ export type {DateTimeInputProps,DateTimeInputSize,DateTimeInputHourFormat,+ DateTimeInputNativePicker,DateTimeInputTimeIncrement,DateTimeInputTimeOptionInterval,DateTimeInputStatus,diff --git a/packages/core/src/DateTimeInput/nativePickerSegmentStyles.ts b/packages/core/src/DateTimeInput/nativePickerSegmentStyles.tsnew file mode 100644index 0000000000..4f4719ca2f--- /dev/null+++ b/packages/core/src/DateTimeInput/nativePickerSegmentStyles.ts@@ -0,0 +1,120 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file nativePickerSegmentStyles.ts+ * @input Uses StyleX and Astryx typography, color, and radius tokens+ * @output Exports styles shared by DateTimeInput's native date and time controls+ * @position Internal styling shared by NativeDateSegment and NativeTimeSegment+ */++import * as stylex from '@stylexjs/stylex';+import {+ colorVars,+ radiusVars,+ typeScaleVars,+ typographyVars,+} from '../theme/tokens.stylex';++export const nativePickerSegmentStyles = 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'],+ // Below 16px iOS zooms the page when the field takes focus.+ 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',+ // Native date/time controls size from their internal edit fields. Pin the+ // box to one text line so both segments stay aligned.+ height: stylex.firstThatWorks(+ '1lh',+ `calc(max(1rem, ${typeScaleVars['--text-body-size']}) * ${typeScaleVars['--text-body-leading']})`,+ ),+ WebkitAppearance: 'none',+ appearance: 'none',+ // DateTimeInput renders its own calendar/clock affordances.+ '::-webkit-calendar-picker-indicator': {+ display: 'none',+ },+ '::-webkit-date-and-time-value': {+ textAlign: 'start',+ marginBlock: 0,+ marginInline: 0,+ paddingBlock: 0,+ paddingInline: 0,+ lineHeight: 'inherit',+ minHeight: 0,+ },+ '::-webkit-datetime-edit': {+ paddingBlock: 0,+ paddingInline: 0,+ lineHeight: 'inherit',+ },+ },+ inputDisabled: {+ cursor: 'default',+ },+ inputInvalid: {+ color: colorVars['--color-text-secondary'],+ },+ inputTextHidden: {+ color: 'transparent',+ WebkitTextFillColor: 'transparent',+ },+ slot: {+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ flex: 1,+ minInlineSize: 0,+ },+ overlay: {+ position: 'absolute',+ insetInlineStart: 0,+ insetInlineEnd: 0,+ insetBlock: 0,+ display: 'block',+ fontSize: {+ default: typeScaleVars['--text-body-size'],+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,+ },+ lineHeight: typeScaleVars['--text-body-leading'],+ pointerEvents: 'none',+ overflow: 'hidden',+ whiteSpace: 'nowrap',+ textOverflow: 'ellipsis',+ },+ overlayValue: {+ color: colorVars['--color-text-primary'],+ },+ overlayPlaceholder: {+ color: colorVars['--color-text-secondary'],+ },+});