Skip to content

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

TypeScript

feat(DateInput): the platform's own date picker on touch, with `nativePicker` (#5261)

Xinzi Zhou66abf7bfe1c1
diff --git a/.changeset/date-input-native-picker-option.md b/.changeset/date-input-native-picker-option.md
new file mode 100644
index 0000000000..d8e85cf071
--- /dev/null
+++ b/.changeset/date-input-native-picker-option.md
@@ -0,0 +1,27 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DateInput: the platform's own date picker on touch, with
+`nativePicker` to choose otherwise
+
+A touch device now gets the browser/OS picker — the iOS wheel, the Android
+calendar dialog — drawn by the platform, with its own hit areas, momentum
+scrolling, locale and accessibility settings. `nativePicker` picks the
+surface: `'touch'` (the default) uses it on a coarse pointer, `'always'`
+wherever the browser supports `<input type="date">`, and `'never'` keeps
+Astryx's own pickers everywhere — the bottom-sheet picker on a finger, the
+calendar popover on a mouse.
+
+Reach for `'never'` on a field that needs what a native picker cannot
+express: `weekStartsOn`, `numberOfMonths`, or `dateConstraints`.
+
+`format` and `placeholder` still apply in native mode — DateInput paints the
+closed field's text itself, over the control, so a date reads the same on a
+phone as on a desktop. `min` and `max` are forwarded, but a native picker may
+not *show* them: on iOS they are constraint-validation flags rather than
+clamps, so an out-of-range date can be selected, and it is refused on commit
+and announced rather than greyed out in the picker. Mouse-driven devices are
+unaffected.
+
+@imdreamrunner
diff --git a/packages/cli/assets/templates/blocks/components/DateInput/DateInputClearable.tsx b/packages/cli/assets/templates/blocks/components/DateInput/DateInputClearable.tsx
index 164581dba0..f9a32ebac2 100644
--- a/packages/cli/assets/templates/blocks/components/DateInput/DateInputClearable.tsx
+++ b/packages/cli/assets/templates/blocks/components/DateInput/DateInputClearable.tsx
@@ -16,7 +16,11 @@ export default function DateInputClearable() {
);
return (
- <Stack direction="vertical" gap={4} width="100%" style={{maxWidth: 400}}>
+ <Stack
+ direction="vertical"
+ gap={4}
+ width="100%"
+ style={{minWidth: 240, maxWidth: 400}}>
<Text type="supporting" color="secondary">
{value ? `Selected: ${value}` : 'No date selected'}
</Text>
diff --git a/packages/cli/assets/templates/blocks/components/DateInput/DateInputDateRange.tsx b/packages/cli/assets/templates/blocks/components/DateInput/DateInputDateRange.tsx
index 01055d83c8..14199aa63e 100644
--- a/packages/cli/assets/templates/blocks/components/DateInput/DateInputDateRange.tsx
+++ b/packages/cli/assets/templates/blocks/components/DateInput/DateInputDateRange.tsx
@@ -27,7 +27,11 @@ export default function DateInputDateRange() {
const [value, setValue] = useState<DateString | undefined>(undefined);
return (
- <Stack direction="vertical" gap={4} width="100%" style={{maxWidth: 400}}>
+ <Stack
+ direction="vertical"
+ gap={4}
+ width="100%"
+ style={{minWidth: 240, maxWidth: 400}}>
<Text type="supporting" color="secondary">
{value ? `Booked: ${value}` : 'Pick a date in the available range'}
</Text>
@@ -37,6 +41,7 @@ export default function DateInputDateRange() {
max={max}
description={description}
placeholder="Select a booking date"
+ nativePicker="never"
value={value}
onChange={setValue}
/>
diff --git a/packages/cli/assets/templates/blocks/components/DateInput/DateInputFormats.tsx b/packages/cli/assets/templates/blocks/components/DateInput/DateInputFormats.tsx
index ab870ddb6f..c2e3c711a2 100644
--- a/packages/cli/assets/templates/blocks/components/DateInput/DateInputFormats.tsx
+++ b/packages/cli/assets/templates/blocks/components/DateInput/DateInputFormats.tsx
@@ -16,7 +16,11 @@ export default function DateInputFormats() {
);
return (
- <Stack direction="vertical" gap={4} width="100%" style={{maxWidth: 400}}>
+ <Stack
+ direction="vertical"
+ gap={4}
+ width="100%"
+ style={{minWidth: 240, maxWidth: 400}}>
<Text type="supporting" color="secondary">
The same committed date, displayed with different formats.
</Text>
diff --git a/packages/cli/assets/templates/blocks/components/DateInput/DateInputShowcase.tsx b/packages/cli/assets/templates/blocks/components/DateInput/DateInputShowcase.tsx
index 473e7fcc89..94d9e8f664 100644
--- a/packages/cli/assets/templates/blocks/components/DateInput/DateInputShowcase.tsx
+++ b/packages/cli/assets/templates/blocks/components/DateInput/DateInputShowcase.tsx
@@ -13,7 +13,10 @@ export default function DateInputShowcase() {
const [date, setDate] = useState<DateString | undefined>(undefined);
return (
- <Stack direction="vertical" width="100%" style={{maxWidth: 400}}>
+ <Stack
+ direction="vertical"
+ width="100%"
+ style={{minWidth: 240, maxWidth: 400}}>
<DateInput
label="Start date"
placeholder="Select a date"
diff --git a/packages/cli/assets/templates/blocks/components/DateInput/DateInputWithDescription.tsx b/packages/cli/assets/templates/blocks/components/DateInput/DateInputWithDescription.tsx
index a1121b4d0e..0185023529 100644
--- a/packages/cli/assets/templates/blocks/components/DateInput/DateInputWithDescription.tsx
+++ b/packages/cli/assets/templates/blocks/components/DateInput/DateInputWithDescription.tsx
@@ -14,7 +14,11 @@ export default function DateInputWithDescription() {
const [value, setValue] = useState<DateString | undefined>(undefined);
return (
- <Stack direction="vertical" gap={4} width="100%" style={{maxWidth: 400}}>
+ <Stack
+ direction="vertical"
+ gap={4}
+ width="100%"
+ style={{minWidth: 240, maxWidth: 400}}>
<Text type="supporting" color="secondary">
Helper text explains what the field expects
</Text>
diff --git a/packages/cli/assets/templates/blocks/components/DateInput/DateInputWithValidation.tsx b/packages/cli/assets/templates/blocks/components/DateInput/DateInputWithValidation.tsx
index ccd0190cfb..f819bd71f3 100644
--- a/packages/cli/assets/templates/blocks/components/DateInput/DateInputWithValidation.tsx
+++ b/packages/cli/assets/templates/blocks/components/DateInput/DateInputWithValidation.tsx
@@ -21,7 +21,11 @@ export default function DateInputWithValidation() {
);
return (
- <Stack direction="vertical" gap={4} width="100%" style={{maxWidth: 400}}>
+ <Stack
+ direction="vertical"
+ gap={4}
+ width="100%"
+ style={{minWidth: 240, maxWidth: 400}}>
<DateInput
label="Event date"
value={errorVal}
diff --git a/packages/core/src/DateInput/DateInput.doc.mjs b/packages/core/src/DateInput/DateInput.doc.mjs
index 19c31eb8de..fe4475fe0a 100644
--- a/packages/core/src/DateInput/DateInput.doc.mjs
+++ b/packages/core/src/DateInput/DateInput.doc.mjs
@@ -156,6 +156,13 @@ export const docs = {
"How the committed date value is displayed. Named values are reused from Timestamp's format vocabulary: 'date' shows 'Mar 21, 2026', 'date_long' shows 'March 21, 2026', 'date_weekday' shows 'Wed, Mar 21, 2026', 'system_date' shows '2026-03-21'. A function receives the ISO value and returns a custom string. Applies only to the committed value, never to text being typed.",
default: "'date_long'",
},
+ {
+ name: 'nativePicker',
+ type: "'touch' | 'always' | 'never'",
+ description:
+ "Which surface draws the date picker. 'touch' (the default) hands a touch device to the browser/OS \u2014 the field becomes an input type=date and the platform draws the picker (the iOS wheel, the Android calendar dialog); 'always' does that wherever the browser supports input type=date; 'never' keeps Astryx's own pickers everywhere (the bottom-sheet picker on a finger, the calendar popover on a mouse). Use 'never' for a field that needs weekStartsOn, numberOfMonths or dateConstraints, none of which a native picker can express. format and placeholder still apply in native mode; min and max are forwarded, but a native picker may not show them (on iOS an out-of-range date can be selected and is refused on commit rather than greyed out).",
+ default: "'touch'",
+ },
{
name: 'width',
type: 'SizeValue',
@@ -437,6 +444,13 @@ export const docsZh = {
"已选日期的显示格式。命名值复用 Timestamp 的格式词汇:'date' 显示 'Mar 21, 2026','date_long' 显示 'March 21, 2026','date_weekday' 显示 'Wed, Mar 21, 2026','system_date' 显示 '2026-03-21'。函数接收 ISO 值并返回自定义字符串。仅作用于已提交的值,不影响正在输入的文本。",
default: "'date_long'",
},
+ {
+ name: 'nativePicker',
+ type: "'touch' | 'always' | 'never'",
+ description:
+ "由哪个界面绘制日期选择器。'touch'(默认)在触摸设备上交给浏览器/操作系统:字段变为 input type=date,由平台绘制选择器(iOS 滚轮、Android 日历对话框);'always' 在所有支持 input type=date 的浏览器上都这样做;'never' 始终使用 Astryx 自带的选择器(触摸设备用底部弹出选择器,鼠标设备用日历弹出层)。需要 weekStartsOn、numberOfMonths 或 dateConstraints 的字段应使用 'never',原生选择器无法表达这些。原生模式下 format 和 placeholder 仍然生效;min 和 max 会传递给原生控件,但原生选择器可能不会显示这些限制(在 iOS 上仍可选中超出范围的日期,会在提交时被拒绝,而不是变灰)。",
+ default: "'touch'",
+ },
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -537,6 +551,8 @@ export const docsDense = {
weekStartsOn: 'first day of week in calendar (0=Sunday, or name e.g. "mon")',
format:
"committed-value display: 'date_long' (default, March 21, 2026), 'date' (Mar 21, 2026), 'date_weekday' (Wed, Mar 21, 2026), 'system_date' (2026-03-21), or (iso)=>string; reuses Timestamp vocabulary. Committed value only, not while typing.",
+ nativePicker:
+ "which surface draws the picker: 'touch' (default) = browser/OS on a coarse pointer, 'always', 'never' = Astryx's own everywhere. use 'never' for weekStartsOn/numberOfMonths/dateConstraints. format+placeholder still apply; min/max forwarded but not necessarily shown by the OS picker \u2014 refused on commit instead.",
xstyle: 'StyleX styles for layout; must be stylex.create() value',
},
};
diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsx
index 57d8d83d78..363654e6d1 100644
--- a/packages/core/src/DateInput/DateInput.tsx
+++ b/packages/core/src/DateInput/DateInput.tsx
@@ -62,6 +62,7 @@ import {useInputStatusIcon} from '../hooks/useInputStatusIcon';
import {useMediaQuery} from '../hooks/useMediaQuery';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {usePopover} from '../Popover';
+import {NativeDateField} from './NativeDateField';
import {TouchDateField} from './TouchDateField';
import {useTooltip} from '../Tooltip';
import {getInputARIA, isImeKeyEvent, parseDateInput} from '../utils';
@@ -150,6 +151,17 @@ export type DateInputSize = keyof typeof sizeStyles;
* types stay in compile-time lockstep: renaming or removing one of these
* members from `TimestampFormat` breaks this type at build time.
*/
+/**
+ * When DateInput hands date picking to the browser/OS instead of its own
+ * surfaces.
+ *
+ * - `'touch'`: native on touch devices (coarse pointer), Astryx's calendar
+ * popover on mouse-driven ones
+ * - `'always'`: native wherever the browser supports `<input type="date">`
+ * - `'never'`: Astryx's own pickers everywhere
+ */
+export type DateInputNativePicker = 'touch' | 'always' | 'never';
+
export type DateInputFormat = Extract<
TimestampFormat,
'date' | 'date_long' | 'date_weekday' | 'system_date'
@@ -361,6 +373,40 @@ export interface DateInputProps extends Omit<
* ```
*/
format?: DateInputFormat | ((value: ISODateString) => string);
+
+ /**
+ * When date picking is handed to the browser/OS instead of Astryx's own
+ * surfaces: the field becomes an `<input type="date">` and the platform
+ * draws the picker — the iOS wheel, the Android calendar dialog — with the
+ * OS's own hit areas, momentum scrolling, locale and accessibility
+ * settings.
+ *
+ * - `'touch'` (default): native on touch devices (coarse pointer), the text
+ * field and calendar popover on mouse-driven ones
+ * - `'always'`: native wherever the browser supports `<input type="date">`
+ * - `'never'`: Astryx's own pickers everywhere — the touch picker on a
+ * finger, the calendar popover on a mouse
+ *
+ * `format` and `placeholder` still apply in native mode: DateInput paints
+ * the closed field's text itself, over the control. `numberOfMonths` and
+ * `weekStartsOn` do not — they describe a calendar grid the native picker
+ * does not have — so a field that needs either should pass `'never'`.
+ *
+ * `min` and `max` are forwarded, but note that a native picker may not
+ * *show* them: on iOS they are constraint-validation flags rather than
+ * clamps, so an out-of-range date can be selected and is refused on commit
+ * (announced to assistive technology) rather than being greyed out in the
+ * picker. `dateConstraints` is enforced the same way, on commit, and is
+ * reason enough to prefer `'never'` on a field that uses it.
+ *
+ * @default 'touch'
+ * @example
+ * ```
+ * // Astryx's own touch picker instead of the platform's
+ * <DateInput label="Event date" value={date} onChange={setDate} nativePicker="never" />
+ * ```
+ */
+ nativePicker?: DateInputNativePicker;
}
/**
@@ -887,7 +933,13 @@ PointerDateField.displayName = 'PointerDateField';
*/
export function DateInput(props: DateInputProps) {
const isTouch = useMediaQuery(TOUCH_POINTER_QUERY);
+ const nativePicker = props.nativePicker ?? 'touch';
+ // The platform's picker, where the consumer asked for it — see the
+ // `nativePicker` prop for what that trades away.
+ if (nativePicker === 'always' || (nativePicker === 'touch' && isTouch)) {
+ return <NativeDateField {...props} />;
+ }
return isTouch ? (
<TouchDateField {...props} />
) : (
diff --git a/packages/core/src/DateInput/DateInputTouch.test.tsx b/packages/core/src/DateInput/DateInputTouch.test.tsx
index e2bf4cdf75..b5a9a74c43 100644
--- a/packages/core/src/DateInput/DateInputTouch.test.tsx
+++ b/packages/core/src/DateInput/DateInputTouch.test.tsx
@@ -219,6 +219,11 @@ function Controlled({
return (
<DateInput
label="Event date"
+ // This suite is about Astryx's own touch surface, which is now opt-out:
+ // `nativePicker` defaults to 'touch', so a coarse pointer gets the
+ // platform's picker unless a field says otherwise. Tests that assert on
+ // the surface selection itself pass their own value over this.
+ nativePicker="never"
{...DEFAULT_RANGE}
{...props}
value={value}
@@ -276,6 +281,16 @@ function weekdayRow(): HTMLElement {
// ---------------------------------------------------------------------------
describe('DateInput — surface selection', () => {
+ it('hands a touch device to the platform picker by default', () => {
+ // `nativePicker` defaults to 'touch': the OS draws the picker unless a
+ // field opts out. Everything else in this file passes 'never', so this is
+ // the one place the default itself is asserted.
+ stubMedia({pointer: 'coarse', width: 393});
+ render(<DateInput label="Event date" onChange={() => {}} />);
+ const input = document.querySelector('input');
+ expect(input).toHaveAttribute('type', 'date');
+ });
+
it('switches on the pointer alone, so a tablet gets the picker too', () => {
// `pointer` is the PRIMARY device, which is what makes it the whole test:
// a touchscreen laptop reports `fine` (its trackpad) and keeps the
@@ -320,7 +335,7 @@ describe('DateInput — surface selection', () => {
setViewport('desktop');
const onChange = vi.fn();
render(
- <DateInput label="Event date" onChange={onChange} min={undefined} />,
+ <DateInput nativePicker="never" label="Event date" onChange={onChange} min={undefined} />,
);
fireEvent.change(field(), {target: {value: '2026-03-25'}});
expect(onChange).toHaveBeenCalledWith('2026-03-25');
@@ -360,12 +375,12 @@ describe('DateInput — surface selection', () => {
describe('DateInput — field parity', () => {
it('shows a placeholder until a date is chosen, then the formatted value', () => {
const {rerender} = render(
- <DateInput label="Ship date" onChange={() => {}} />,
+ <DateInput nativePicker="never" label="Ship date" onChange={() => {}} />,
);
expect(field()).toHaveValue('');
expect(field()).toHaveAttribute('placeholder', 'Select a date');
rerender(
- <DateInput label="Ship date" value="2026-03-21" onChange={() => {}} />,
+ <DateInput nativePicker="never" label="Ship date" value="2026-03-21" onChange={() => {}} />,
);
expect(field()).toHaveValue('March 21, 2026');
});
@@ -373,6 +388,7 @@ describe('DateInput — field parity', () => {
it('honors a named format', () => {
render(
<DateInput
+ nativePicker="never"
label="Ship date"
value="2026-03-21"
format="system_date"
@@ -385,6 +401,7 @@ describe('DateInput — field parity', () => {
it('honors a function format', () => {
render(
<DateInput
+ nativePicker="never"
label="Ship date"
value="2026-03-21"
format={iso => `ISO:${iso}`}
@@ -397,6 +414,7 @@ describe('DateInput — field parity', () => {
it('honors a custom placeholder', () => {
render(
<DateInput
+ nativePicker="never"
label="Ship date"
placeholder="Pick a day"
onChange={() => {}}
@@ -409,6 +427,7 @@ describe('DateInput — field parity', () => {
const onChange = vi.fn();
render(
<DateInput
+ nativePicker="never"
label="Ship date"
value="2026-03-21"
hasClear
@@ -432,6 +451,7 @@ describe('DateInput — field parity', () => {
try {
render(
<DateInput
+ nativePicker="never"
label="Ship date"
value="2026-03-21"
hasClear
@@ -457,7 +477,7 @@ describe('DateInput — field parity', () => {
it('does not open the picker until the field is tapped', () => {
withLayout(() => {
- render(<DateInput label="Ship date" onChange={() => {}} />);
+ render(<DateInput nativePicker="never" label="Ship date" onChange={() => {}} />);
expect(field()).toHaveAttribute('aria-expanded', 'false');
expect(screen.queryByRole('grid')).not.toBeInTheDocument();
fireEvent.click(field());
@@ -475,7 +495,7 @@ describe('DateInput — field parity', () => {
});
it('is not openable while disabled', () => {
- render(<DateInput label="Ship date" isDisabled onChange={() => {}} />);
+ render(<DateInput nativePicker="never" label="Ship date" isDisabled onChange={() => {}} />);
expect(field()).toBeDisabled();
fireEvent.click(field());
expect(screen.queryByRole('grid')).not.toBeInTheDocument();
@@ -484,6 +504,7 @@ describe('DateInput — field parity', () => {
it('stays focusable and explains itself when disabled with a reason', () => {
render(
<DateInput
+ nativePicker="never"
label="Ship date"
isDisabled
disabledMessage="You need the Editor role"
@@ -500,6 +521,7 @@ describe('DateInput — field parity', () => {
it('renders label, description and status through Field', () => {
render(
<DateInput
+ nativePicker="never"
label="Ship date"
description="When it leaves the warehouse"
status={{type: 'error', message: 'Pick a date'}}
@@ -516,12 +538,12 @@ describe('DateInput — field parity', () => {
});
it('marks required for assistive technology', () => {
- render(<DateInput label="Ship date" isRequired onChange={() => {}} />);
+ render(<DateInput nativePicker="never" label="Ship date" isRequired onChange={() => {}} />);
expect(field()).toHaveAttribute('aria-required', 'true');
});
it('associates the label natively, so the field is named without ARIA', () => {
- render(<DateInput label="Ship date" onChange={() => {}} />);
+ render(<DateInput nativePicker="never" label="Ship date" onChange={() => {}} />);
expect(screen.getByLabelText('Ship date')).toBe(field());
});
@@ -536,6 +558,7 @@ describe('DateInput — field parity', () => {
withLayout(() => {
render(
<DateInput
+ nativePicker="never"
label="Ship date"
value="2026-03-10"
min="2026-03-01"
@@ -558,7 +581,7 @@ describe('DateInput — field parity', () => {
it('drops the Field wrapper inside an InputGroup', () => {
render(
<InputGroup label="Range">
- <DateInput label="Start" onChange={() => {}} />
+ <DateInput nativePicker="never" label="Start" onChange={() => {}} />
</InputGroup>,
);
// Named by the group label plus its own, the way core's inputs are.
@@ -643,7 +666,7 @@ describe('DateInput — calendar surface', () => {
it('Save closes even with no date chosen, committing nothing', () => {
const onChange = vi.fn();
withLayout(() => {
- render(<DateInput label="Ship date" onChange={onChange} />);
+ render(<DateInput nativePicker="never" label="Ship date" onChange={onChange} />);
fireEvent.click(field());
fireEvent.click(screen.getByRole('button', {name: 'Save'}));
});
diff --git a/packages/core/src/DateInput/NativeDateField.test.tsx b/packages/core/src/DateInput/NativeDateField.test.tsx
new file mode 100644
index 0000000000..67f03d96fa
--- /dev/null
+++ b/packages/core/src/DateInput/NativeDateField.test.tsx
@@ -0,0 +1,565 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file NativeDateField.test.tsx
+ * @input Uses vitest, @testing-library/react, DateInput
+ * @output Unit tests for the OS-picker surface (`nativePicker`)
+ * @position Testing; validates NativeDateField.tsx
+ *
+ * Every test renders through `DateInput` with a pointer stubbed, so the
+ * surface selection in DateInput.tsx is exercised too. `nativePicker`
+ * defaults to `'touch'`, so a coarse pointer alone gets the native control.
+ *
+ * The iOS behaviours these pin — the picker detaching from the field on a
+ * programmatic write, React's synthetic change not firing for the picker's
+ * edits, `text-overflow` being inert on a flex box — were all measured on a
+ * real device and none reproduce in jsdom. Where a test asserts a CSS rule
+ * rather than a behaviour, that is why.
+ *
+ * SYNC: When NativeDateField.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {DateInput} from './DateInput';
+import {InternationalizationProvider} from '../i18n';
+
+const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;
+
+/**
+ * Astryx's touch picker mounts a month scroller that observes its own size;
+ * jsdom ships no ResizeObserver. Only the `nativePicker="never"` test reaches
+ * it, but stubbing it for the file keeps that test honest about which surface
+ * it got.
+ */
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+/** Point `(pointer: coarse)` at a touch or mouse device. */
+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 getInput(): HTMLInputElement {
+ const input = document.querySelector('input');
+ if (!input) {
+ throw new Error('DateInput rendered no input element');
+ }
+ return input;
+}
+
+/** The CSS rules that apply to an element, for the paint-level assertions. */
+function rulesFor(el: Element): string {
+ const classes = new Set(el.className.split(/\s+/).filter(Boolean));
+ return Array.from(document.styleSheets)
+ .flatMap(sheet => {
+ try {
+ return Array.from(sheet.cssRules);
+ } catch {
+ return [];
+ }
+ })
+ .map(rule => rule.cssText)
+ .filter(text => [...classes].some(cls => text.includes(`.${cls}`)))
+ .join(' ');
+}
+
+beforeEach(() => {
+ vi.stubGlobal('ResizeObserver', MockResizeObserver);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('DateInput nativePicker', () => {
+ // ===========================================================================
+ // Which surface renders
+ // ===========================================================================
+
+ it('renders the native control on touch by default', () => {
+ stubPointer(true);
+ render(<DateInput label="Date" onChange={() => {}} />);
+
+ expect(getInput()).toHaveAttribute('type', 'date');
+ });
+
+ it('keeps the calendar popover on a mouse-driven device', () => {
+ stubPointer(false);
+ render(<DateInput label="Date" onChange={() => {}} />);
+
+ const input = getInput();
+ expect(input).toHaveAttribute('type', 'text');
+ expect(input).toHaveAttribute('role', 'combobox');
+ });
+
+ it('falls back to Astryx\u2019s touch picker when told never', () => {
+ stubPointer(true);
+ render(<DateInput label="Date" nativePicker="never" onChange={() => {}} />);
+
+ const input = getInput();
+ expect(input).toHaveAttribute('type', 'text');
+ expect(input).toHaveAttribute('role', 'combobox');
+ });
+
+ it('uses the native control on a mouse device when told always', () => {
+ stubPointer(false);
+ render(
+ <DateInput label="Date" nativePicker="always" onChange={() => {}} />,
+ );
+
+ expect(getInput()).toHaveAttribute('type', 'date');
+ });
+
+ it('drops the popup ARIA the other surfaces carry', () => {
+ // There is no in-page popup to describe: the OS draws the picker.
+ stubPointer(true);
+ render(<DateInput label="Date" onChange={() => {}} />);
+
+ const input = getInput();
+ expect(input).not.toHaveAttribute('role', 'combobox');
+ expect(input).not.toHaveAttribute('aria-expanded');
+ expect(input).not.toHaveAttribute('aria-haspopup');
+ });
+
+ // ===========================================================================
+ // Value round-trip
+ // ===========================================================================
+
+ it('keeps the control\u2019s own value ISO', () => {
+ stubPointer(true);
+ render(
+ <DateInput
+ label="Date"
+ value="2026-01-25"
+ format="date_long"
+ onChange={() => {}}
+ />,
+ );
+
+ // ISO is the only form the control accepts, and what the picker reads and
+ // writes; `format` rides on the overlay instead.
+ expect(getInput()).toHaveValue('2026-01-25');
+ expect(screen.getByText('January 25, 2026')).toBeInTheDocument();
+ });
+
+ it('fires onChange with the ISO date the control reports', () => {
+ stubPointer(true);
+ const onChange = vi.fn();
+ render(<DateInput label="Date" onChange={onChange} />);
+
+ fireEvent.change(getInput(), {target: {value: '2026-03-21'}});
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-21');
+ });
+
+ it('fires onChange with undefined when the control is emptied', () => {
+ stubPointer(true);
+ const onChange = vi.fn();
+ render(
+ <DateInput label="Date" value="2026-03-21" onChange={onChange} />,
+ );
+
+ fireEvent.change(getInput(), {target: {value: ''}});
+
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ });
+
+ it('commits an edit React\u2019s synthetic change does not see', () => {
+ // The iOS failure, reproduced: the picker edits the field and a native
+ // `input` event fires, but React's synthetic `onChange` never runs — so
+ // React re-renders and writes its stale value back over the picker's.
+ // Assigning `.value` first updates React's internal value tracker, which
+ // is what makes React skip the synthetic event; the native listener still
+ // sees the real one.
+ stubPointer(true);
+ const onChange = vi.fn();
+ render(
+ <DateInput label="Date" value="2026-03-21" onChange={onChange} />,
+ );
+
+ const input = getInput();
+ input.value = '2026-03-09';
+ input.dispatchEvent(new Event('input', {bubbles: true}));
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-09');
+ });
+
+ it('fires one change when both commit paths see the same edit', () => {
+ stubPointer(true);
+ const onChange = vi.fn();
+ render(
+ <DateInput label="Date" value="2026-03-21" onChange={onChange} />,
+ );
+
+ fireEvent.change(getInput(), {target: {value: '2026-03-09'}});
+
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-09');
+ });
+
+ it('does not write to the control while it has focus', () => {
+ // The iOS bug this guards: while the picker sheet is open, ANY
+ // programmatic write to the field detaches the sheet from it, and the
+ // user's pick silently stops reaching the input.
+ stubPointer(true);
+ const {rerender} = render(
+ <DateInput label="Date" value="2026-03-21" onChange={() => {}} />,
+ );
+ const input = getInput();
+
+ fireEvent.focus(input);
+ rerender(
+ <DateInput label="Date" value="2026-12-25" onChange={() => {}} />,
+ );
+
+ expect(input).toHaveValue('2026-03-21');
+ });
+
+ it('applies an external value once the control loses focus', () => {
+ stubPointer(true);
+ const {rerender} = render(
+ <DateInput label="Date" value="2026-03-21" onChange={() => {}} />,
+ );
+ const input = getInput();
+
+ fireEvent.focus(input);
+ rerender(
+ <DateInput label="Date" value="2026-12-25" onChange={() => {}} />,
+ );
+ fireEvent.blur(input);
+
+ expect(input).toHaveValue('2026-12-25');
+ });
+
+ // ===========================================================================
+ // Constraints
+ // ===========================================================================
+
+ it('forwards min and max to the native control', () => {
+ stubPointer(true);
+ render(
+ <DateInput
+ label="Date"
+ min="2026-01-01"
+ max="2026-12-31"
+ onChange={() => {}}
+ />,
+ );
+
+ const input = getInput();
+ expect(input).toHaveAttribute('min', '2026-01-01');
+ expect(input).toHaveAttribute('max', '2026-12-31');
+ });
+
+ it('refuses an out-of-range date and announces it', () => {
+ // iOS does not enforce min/max in its picker — it lets the user land on
+ // any date — so the refusal has to happen here.
+ stubPointer(true);
+ const onChange = vi.fn();
+ render(
+ <DateInput
+ label="Date"
+ min="2026-03-10"
+ max="2026-03-20"
+ value="2026-03-15"
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.change(getInput(), {target: {value: '2026-03-25'}});
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(screen.getByRole('alert')).toHaveTextContent('Invalid date');
+ expect(getInput()).toHaveAttribute('aria-invalid', 'true');
+ });
+
+ it('refuses a date dateConstraints rejects', () => {
+ stubPointer(true);
+ const onChange = vi.fn();
+ render(
+ <DateInput
+ label="Date"
+ // 2026-03-22 is a Sunday.
+ dateConstraints={[date => date.getDay() !== 0]}
+ value="2026-03-23"
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.change(getInput(), {target: {value: '2026-03-22'}});
+
+ expect(onChange).not.toHaveBeenCalled();
+ expect(screen.getByRole('alert')).toHaveTextContent('Invalid date');
+ });
+
+ it('drops the rejection once the field reverts', () => {
+ // The refused date is reverted the moment focus leaves, so the field is
+ // showing a valid date again. Marking that date invalid would be a lie
+ // about data the user never chose.
+ stubPointer(true);
+ render(
+ <DateInput
+ label="Date"
+ dateConstraints={[date => date.getDay() !== 0]}
+ value="2026-03-23"
+ onChange={() => {}}
+ />,
+ );
+
+ const input = getInput();
+ fireEvent.focus(input);
+ fireEvent.change(input, {target: {value: '2026-03-22'}});
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+
+ fireEvent.blur(input);
+
+ expect(input).toHaveValue('2026-03-23');
+ expect(input).not.toHaveAttribute('aria-invalid');
+ expect(screen.getByRole('alert')).toHaveTextContent('');
+ });
+
+ // ===========================================================================
+ // The text overlay: format, placeholder, paint
+ // ===========================================================================
+
+ it('honours every named format', () => {
+ stubPointer(true);
+ const {rerender} = render(
+ <DateInput
+ label="Date"
+ value="2026-01-25"
+ format="date"
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByText('Jan 25, 2026')).toBeInTheDocument();
+
+ rerender(
+ <DateInput
+ label="Date"
+ value="2026-01-25"
+ format="date_weekday"
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByText('Sun, Jan 25, 2026')).toBeInTheDocument();
+ });
+
+ it('honours a function format', () => {
+ stubPointer(true);
+ render(
+ <DateInput
+ label="Date"
+ value="2026-01-25"
+ format={iso => `ships ${iso}`}
+ onChange={() => {}}
+ />,
+ );
+
+ expect(screen.getByText('ships 2026-01-25')).toBeInTheDocument();
+ });
+
+ it('formats in the provider locale', () => {
+ stubPointer(true);
+ render(
+ <InternationalizationProvider locale="de-DE">
+ <DateInput label="Date" value="2026-03-21" onChange={() => {}} />
+ </InternationalizationProvider>,
+ );
+
+ expect(screen.getByText('21. März 2026')).toBeInTheDocument();
+ expect(getInput()).toHaveValue('2026-03-21');
+ });
+
+ it('keeps painting the value while the picker is open', () => {
+ // The OS picker has no segments to reveal, so `format` holds throughout.
+ stubPointer(true);
+ render(
+ <DateInput label="Date" value="2026-01-25" onChange={() => {}} />,
+ );
+
+ fireEvent.focus(getInput());
+
+ expect(screen.getByText('January 25, 2026')).toBeInTheDocument();
+ });
+
+ it('shows the placeholder when empty, and drops it when filled', () => {
+ stubPointer(true);
+ const {rerender} = render(
+ <DateInput label="Date" onChange={() => {}} />,
+ );
+ expect(screen.getByText('Select a date')).toBeInTheDocument();
+
+ rerender(
+ <DateInput label="Date" value="2026-01-25" onChange={() => {}} />,
+ );
+
+ expect(screen.queryByText('Select a date')).toBeNull();
+ });
+
+ it('keeps the overlay out of the accessibility tree', () => {
+ // The input still holds the value and carries the label, so announcing
+ // the overlay too would double-speak.
+ stubPointer(true);
+ render(
+ <DateInput label="Date" value="2026-01-25" onChange={() => {}} />,
+ );
+
+ expect(screen.getByText('January 25, 2026')).toHaveAttribute(
+ 'aria-hidden',
+ 'true',
+ );
+ });
+
+ it('hides the engine\u2019s own text under the overlay', () => {
+ stubPointer(true);
+ render(
+ <DateInput label="Date" value="2026-01-25" onChange={() => {}} />,
+ );
+
+ const rules = rulesFor(getInput());
+ // One transparent colour covers Chromium's `::-webkit-datetime-edit` and
+ // Firefox's plain text; `-webkit-text-fill-color` is what wins in WebKit.
+ expect(rules).toContain('color: transparent');
+ expect(rules).toContain('-webkit-text-fill-color: transparent');
+ });
+
+ it('bounds the overlay so a long date cannot paint past it', () => {
+ stubPointer(true);
+ render(
+ <DateInput
+ label="Date"
+ value="2026-09-30"
+ hasClear
+ onChange={() => {}}
+ />,
+ );
+
+ const rules = rulesFor(screen.getByText('September 30, 2026'));
+ // Without the end inset the overlay is shrink-to-fit and a long date runs
+ // over the clear button — measured 24px across it on an iPhone.
+ expect(rules).toContain('inset-inline-end: 0');
+ // `text-overflow` only applies to a BLOCK container: on a flex one a
+ // too-long date hard-clips mid-glyph instead (measured identical to
+ // `text-overflow: clip` in WebKit and Chromium). Centring then comes from
+ // the line box, so the overlay must carry the input's own leading.
+ expect(rules).toContain('display: block');
+ expect(rules).toContain('text-overflow: ellipsis');
+ expect(rules).toContain('line-height: var(--text-body-leading)');
+ });
+
+ // ===========================================================================
+ // Toggle, clear, disabled
+ // ===========================================================================
+
+ it('asks the browser for its picker from the toggle button', () => {
+ stubPointer(true);
+ render(<DateInput label="Date" onChange={() => {}} />);
+
+ const input = getInput();
+ const showPicker = vi.fn();
+ // jsdom implements no picker; attach one so the call is observable.
+ (input as HTMLInputElement & {showPicker: () => void}).showPicker =
+ showPicker;
+
+ fireEvent.click(screen.getByLabelText('Open calendar'));
+
+ expect(showPicker).toHaveBeenCalledTimes(1);
+ expect(input).toHaveFocus();
+ });
+
+ it('survives a browser that refuses showPicker', () => {
+ // Chrome throws NotAllowedError without transient user activation, and
+ // iOS implements no showPicker for type=date at all. Focus is the
+ // fallback, and on iOS it is the whole mechanism.
+ stubPointer(true);
+ render(<DateInput label="Date" onChange={() => {}} />);
+
+ const input = getInput();
+ (input as HTMLInputElement & {showPicker: () => void}).showPicker = () => {
+ throw new DOMException('not allowed', 'NotAllowedError');
+ };
+
+ expect(() =>
+ fireEvent.click(screen.getByLabelText('Open calendar')),
+ ).not.toThrow();
+ expect(input).toHaveFocus();
+ });
+
+ it('clears the value without taking focus back', () => {
+ // Focusing a date control is what raises the OS picker, so reclaiming
+ // focus would pop the wheel the clear tap just dismissed.
+ stubPointer(true);
+ const onChange = vi.fn();
+ render(
+ <DateInput
+ label="Date"
+ value="2026-03-21"
+ hasClear
+ onChange={onChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByLabelText('Clear Date'));
+
+ expect(onChange).toHaveBeenCalledWith(undefined);
+ expect(getInput()).not.toHaveFocus();
+ });
+
+ it('disables the control and its toggle when isDisabled', () => {
+ stubPointer(true);
+ render(<DateInput label="Date" isDisabled onChange={() => {}} />);
+
+ expect(getInput()).toBeDisabled();
+ expect(screen.getByLabelText('Open calendar')).toBeDisabled();
+ });
+
+ it('ignores a change while disabled', () => {
+ stubPointer(true);
+ const onChange = vi.fn();
+ render(
+ <DateInput
+ label="Date"
+ isDisabled
+ disabledMessage="Ask an editor"
+ onChange={onChange}
+ />,
+ );
+
+ // With a disabledMessage the field stays focusable via aria-disabled, so
+ // the mutation guard is what has to hold.
+ fireEvent.change(getInput(), {target: {value: '2026-03-21'}});
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('keeps the field labelled, required-marked, and ref-forwarded', () => {
+ stubPointer(true);
+ const ref = vi.fn();
+ render(
+ <DateInput ref={ref} label="Event date" isRequired onChange={() => {}} />,
+ );
+
+ const input = screen.getByLabelText(/Event date/);
+ expect(input).toHaveAttribute('type', 'date');
+ expect(input).toHaveAttribute('aria-required', 'true');
+ expect(ref).toHaveBeenCalledWith(expect.any(HTMLInputElement));
+ });
+});
diff --git a/packages/core/src/DateInput/NativeDateField.tsx b/packages/core/src/DateInput/NativeDateField.tsx
new file mode 100644
index 0000000000..8a8094c6a9
--- /dev/null
+++ b/packages/core/src/DateInput/NativeDateField.tsx
@@ -0,0 +1,623 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file NativeDateField.tsx
+ * @input Uses React, Field, Icon, InputClearButton, Spinner, useCalendarConstraints
+ * @output Exports NativeDateField — the OS-picker touch surface
+ * @position One of DateInput's three surfaces. `DateInput` picks the pointer
+ * field on a mouse and, on touch, either `TouchDateField` (the default) or
+ * this one when the consumer opts in with `nativePicker`.
+ *
+ * Hands date picking to the platform: a real `<input type="date">`, whose
+ * picker the OS draws — the iOS wheel, the Android calendar dialog. The field
+ * itself still looks like every other Astryx input, and DateInput paints its
+ * text so `format` and `placeholder` keep applying.
+ *
+ * Everything unusual in here was measured on a real iOS device; the comments
+ * say which behaviour forced which decision, because none of them are
+ * reproducible in a desktop browser.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/DateInput/DateInput.tsx (the `nativePicker` prop)
+ * - /packages/core/src/DateInput/DateInput.doc.mjs (prop table)
+ * - /packages/core/src/DateInput/DateInputNative.test.tsx (tests)
+ */
+
+import {useCallback, useEffect, useId, useRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {useCalendarConstraints} from '../Calendar';
+import type {DateInputProps} from './DateInput';
+import {
+ Field,
+ InputClearButton,
+ inputStatusBorderStyles,
+ inputStatusFocusWithinStyles,
+ inputStatusHoverShadowStyles,
+ inputWrapperStyles,
+} from '../Field';
+import {useInputStatusIcon, useMergedRefs} from '../hooks';
+import {useResolvedRequired} from '../hooks/useResolvedRequired';
+import {Icon} from '../Icon';
+import {useLocale, useTranslator} from '../i18n';
+import {useInputGroup} from '../InputGroup';
+import {groupStyles} from '../InputGroup/groupStyles';
+import {stableClassName} from '../naming';
+import {useSize} from '../SizeContext';
+import {Spinner} from '../Spinner';
+import {
+ colorVars,
+ radiusVars,
+ sizeVars,
+ typeScaleVars,
+ typographyVars,
+} from '../theme/tokens.stylex';
+import {useTooltip} from '../Tooltip';
+import {VisuallyHidden} from '../VisuallyHidden';
+import {
+ focusOutlineStyles,
+ formatSharedDate,
+ getInputARIA,
+ mergeProps,
+ parseDateInput,
+ plainDateFromISO,
+ plainDateToISO,
+ themeProps,
+ type ISODateString,
+} from '../utils';
+
+const styles = stylex.create({
+ wrapper: {
+ gap: 8,
+ },
+ 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',
+ // A date control's intrinsic height comes from its inner edit fields, not
+ // from `line-height`, so it renders ~2px taller than a text input and its
+ // value sits off the shared baseline inside the same flex row. One line
+ // box is exactly what the text field occupies.
+ height: stylex.firstThatWorks(
+ '1lh',
+ `calc(max(1rem, ${typeScaleVars['--text-body-size']}) * ${typeScaleVars['--text-body-leading']})`,
+ ),
+ // iOS gives date controls their own button-like chrome, with inner
+ // spacing and a centred value that no reset of ours can reach.
+ WebkitAppearance: 'none',
+ appearance: 'none',
+ // Chromium paints a second calendar glyph inside the field; this surface
+ // already ships a toggle button, so drop the duplicate.
+ '::-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'],
+ },
+ // Hides whatever the engine paints inside the control so this field's own
+ // text can take that space. WebKit renders the value into a single
+ // `::-webkit-date-and-time-value` run which the UA stylesheet gives no
+ // colour of its own (the iOS UA colour sits on the INPUT), so it inherits
+ // this; Chromium's `::-webkit-datetime-edit` fields inherit it too.
+ // `-webkit-text-fill-color` is what actually wins inside a WebKit date
+ // control.
+ inputTextHidden: {
+ color: 'transparent',
+ WebkitTextFillColor: 'transparent',
+ },
+ // Positioning context for the overlay, standing in for the input's own box
+ // in the field's flex row.
+ slot: {
+ position: 'relative',
+ display: 'flex',
+ alignItems: 'center',
+ flex: 1,
+ minWidth: 0,
+ },
+ // This field's own text, laid over the control. Decorative: the input still
+ // holds the value and keeps its label, description, and status wiring, so
+ // announcing this too would just double-speak.
+ overlay: {
+ position: 'absolute',
+ insetInlineStart: 0,
+ // Both insets, so the overlay is bounded by the slot rather than
+ // shrink-to-fit. Without the end inset a long formatted date paints past
+ // the slot and over whatever follows it in the field — measured running
+ // 24px across the clear button.
+ insetInlineEnd: 0,
+ insetBlock: 0,
+ // A BLOCK box, not a flex one: `text-overflow` only applies to a block
+ // container, so on a flex container a too-long date hard-clips mid-glyph
+ // instead of ellipsising (measured identical to `text-overflow: clip` in
+ // both WebKit and Chromium). Centring then comes from the line box, so
+ // the overlay carries the same font size and leading as the input it
+ // covers — one line of that leading fills its height exactly, which puts
+ // the glyphs on the input's own baseline.
+ display: 'block',
+ fontSize: {
+ default: typeScaleVars['--text-body-size'],
+ '@media (pointer: coarse)': `max(1rem, ${typeScaleVars['--text-body-size']})`,
+ },
+ lineHeight: typeScaleVars['--text-body-leading'],
+ // A tap has to reach the control underneath — that is what raises the
+ // picker.
+ pointerEvents: 'none',
+ overflow: 'hidden',
+ whiteSpace: 'nowrap',
+ textOverflow: 'ellipsis',
+ },
+ overlayValue: {
+ color: colorVars['--color-text-primary'],
+ },
+ overlayPlaceholder: {
+ color: colorVars['--color-text-secondary'],
+ },
+});
+
+const sizeStyles = stylex.create({
+ sm: {height: sizeVars['--size-element-sm'], minWidth: 180},
+ md: {height: sizeVars['--size-element-md'], minWidth: 180},
+ lg: {height: sizeVars['--size-element-lg'], minWidth: 180},
+});
+
+const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+/**
+ * The OS-picker surface. Takes `DateInput`'s props verbatim; see
+ * {@link DateInput} for when it is chosen over the other two.
+ */
+export function NativeDateField({
+ label,
+ isLabelHidden = false,
+ description,
+ isOptional = false,
+ isRequired = false,
+ isDisabled = false,
+ disabledMessage,
+ value,
+ onChange,
+ isLoading = false,
+ min,
+ max,
+ dateConstraints,
+ placeholder: placeholderFromProps,
+ size: sizeProp,
+ status,
+ statusVariant = 'attached',
+ labelTooltip,
+ hasClear = false,
+ // The OS draws the picker, so neither reaches it: both describe a calendar
+ // grid it does not have. Accepted (the prop types are shared) and ignored.
+ numberOfMonths: _numberOfMonths,
+ weekStartsOn: _weekStartsOn,
+ format = 'date_long',
+ width,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...rest
+}: DateInputProps) {
+ const t = useTranslator();
+ const locale = useLocale();
+ const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
+ const placeholder =
+ placeholderFromProps ?? t('@astryx.dateInput.placeholder');
+ const size = useSize(sizeProp, 'md');
+
+ const id = useId();
+ const inputLabelID = useId();
+ const descriptionID = useId();
+ const statusMessageID = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const mergedInputRef = useMergedRefs(ref, inputRef);
+ const inputGroup = useInputGroup();
+
+ const isEffectivelyDisabled = isDisabled || isLoading;
+
+ // Disabled-reason tooltip, same contract as the other two surfaces: a
+ // disabled control swallows pointer events, so the listeners attach to the
+ // wrapper and the input stays focusable via aria-disabled.
+ const showsDisabledMessage = isDisabled && !!disabledMessage;
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ focusTrigger: 'always',
+ isEnabled: showsDisabledMessage,
+ });
+
+ const {isDateDisabled} = useCalendarConstraints({min, max, dateConstraints});
+
+ const {statusIcon, describedBy: statusTooltipDescribedBy} =
+ useInputStatusIcon({
+ status,
+ statusVariant,
+ isInGroup: !!inputGroup,
+ });
+
+ const {ariaLabelledBy, ariaDescribedBy} = getInputARIA(
+ inputLabelID,
+ [
+ description ? descriptionID : null,
+ statusVariant !== 'tooltip' && status?.message ? statusMessageID : null,
+ statusTooltipDescribedBy,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
+ ],
+ inputGroup,
+ );
+
+ // A date the picker produced that `dateConstraints` refuses, held so the
+ // refusal can be announced instead of looking like a dead tap.
+ const [rejectedValue, setRejectedValue] = useState<string | null>(null);
+ // Whether the control has focus — which, on a touch device, means its
+ // picker is open.
+ const [isFocused, setIsFocused] = useState(false);
+ // The raw value the control last reported and we acted on, so the same edit
+ // arriving through both commit paths only fires one change.
+ const lastCommitRef = useRef<string | null>(null);
+
+ const prevValueRef = useRef(value);
+ if (value !== prevValueRef.current) {
+ prevValueRef.current = value;
+ lastCommitRef.current = null;
+ if (rejectedValue !== null) {
+ setRejectedValue(null);
+ }
+ }
+
+ // The control's own value is always ISO — the only form it accepts, and
+ // what the picker reads and writes. `format` rides on the overlay instead.
+ const nativeValue = value && ISO_DATE.test(value) ? value : '';
+ const isInputValid = rejectedValue === null;
+
+ const formatValue = useCallback(
+ (iso: ISODateString): string =>
+ typeof format === 'function'
+ ? format(iso)
+ : formatSharedDate(plainDateFromISO(iso), format, locale),
+ [format, locale],
+ );
+
+ // This field paints the closed control's text itself, which is what keeps
+ // `format` and `placeholder` applying: the OS picker has no segments to
+ // edit, so our text holds even while the picker is open, and tracks it live.
+ const overlayText = nativeValue ? formatValue(nativeValue) : placeholder;
+ const showsOverlay = !!overlayText;
+
+ const commitValue = useCallback(
+ (newValue: string) => {
+ if (isEffectivelyDisabled) {
+ return;
+ }
+ // The same edit can arrive twice — React's synthetic change and the
+ // native listener below both report it — so act on a raw value once.
+ if (lastCommitRef.current === newValue) {
+ return;
+ }
+ lastCommitRef.current = newValue;
+
+ if (!newValue) {
+ setRejectedValue(null);
+ if (value !== undefined) {
+ onChange?.(undefined);
+ }
+ return;
+ }
+
+ const parsed = parseDateInput(newValue, locale);
+ if (!parsed) {
+ return;
+ }
+ if (isDateDisabled(parsed)) {
+ // iOS does not enforce min/max in its picker — those attributes are
+ // constraint-validation flags, not clamps, and the sheet lets the
+ // user land on any date. Refuse it here and let the sync effect snap
+ // the control back; the live region below announces the refusal.
+ setRejectedValue(newValue);
+ return;
+ }
+
+ setRejectedValue(null);
+ const parsedISO = plainDateToISO(parsed);
+ if (parsedISO !== value) {
+ onChange?.(parsedISO);
+ }
+ },
+ [value, onChange, isDateDisabled, isEffectivelyDisabled, locale],
+ );
+
+ const handleChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ commitValue(e.target.value);
+ },
+ [commitValue],
+ );
+
+ // React's synthetic change system does not reliably observe the iOS
+ // picker's edits. Measured on an iPhone: picking a date fired a native
+ // `input` event carrying the new date while React's `onChange` never ran —
+ // so React re-rendered and wrote its own stale value straight back over the
+ // picker's, and the user's pick (and their Reset) silently reverted. A
+ // native listener reads what the control actually holds, whatever React's
+ // synthetic layer made of it.
+ const commitRef = useRef(commitValue);
+ useEffect(() => {
+ commitRef.current = commitValue;
+ });
+ useEffect(() => {
+ const input = inputRef.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);
+ };
+ }, []);
+
+ // The value the control mounts with. Deliberately captured once: React
+ // writes to the element whenever a `value` OR `defaultValue` prop changes,
+ // and on iOS ANY write while the picker sheet is open detaches the sheet
+ // from the field — the wheel and Reset keep moving the sheet's own
+ // highlight, but nothing they do reaches the input and no event fires, so
+ // the user's pick appears to do nothing. Holding this constant means React
+ // touches the element exactly once, at mount; the effect below owns every
+ // later update and only writes while the field is unfocused.
+ const initialValueRef = useRef<string | null>(null);
+ if (initialValueRef.current === null) {
+ initialValueRef.current = nativeValue;
+ }
+
+ // Push an externally-changed value in — but never while the control has
+ // focus, for the reason above. Blur flips `isFocused`, so this doubles as
+ // the reconcile once the picker closes. (Self-heals a stale
+ // `initialValueRef` too, on the commit right after a remount.)
+ useEffect(() => {
+ if (isFocused) {
+ return;
+ }
+ const input = inputRef.current;
+ if (input && input.value !== nativeValue) {
+ input.value = nativeValue;
+ }
+ }, [isFocused, nativeValue]);
+
+ const handleBlur = useCallback(() => {
+ const domValue = inputRef.current?.value;
+ setIsFocused(false);
+ // A refused date is reverted by the sync effect the moment focus leaves,
+ // so the field is once again showing a date that IS valid. Keeping the
+ // rejection past that point would mark good data invalid, with no way
+ // back except changing the field again. The live region announced the
+ // refusal while it happened; that is the feedback.
+ setRejectedValue(null);
+ if (domValue !== undefined && domValue !== nativeValue) {
+ commitValue(domValue);
+ }
+ }, [commitValue, nativeValue]);
+
+ // Focusing a date control is what raises the OS picker, so the usual
+ // focus-restore after a clear would pop the picker the tap just dismissed —
+ // and on iOS that reads as the clear having done nothing.
+ const handleClear = useCallback(() => {
+ onChange?.(undefined);
+ }, [onChange]);
+
+ const openPicker = useCallback(() => {
+ if (isEffectivelyDisabled) {
+ return;
+ }
+ const input = inputRef.current;
+ if (!input) {
+ return;
+ }
+ // Focus first: on touch browsers focusing the control is itself what
+ // raises the picker, and iOS implements no `showPicker()` for type=date
+ // (WebKit bug 261703), so focus is the whole mechanism there.
+ input.focus();
+ if (typeof input.showPicker === 'function') {
+ try {
+ input.showPicker();
+ } catch {
+ // showPicker throws without transient user activation and inside a
+ // cross-origin iframe. The focus above is the fallback.
+ }
+ }
+ }, [isEffectivelyDisabled]);
+
+ const inputWrapper = (
+ <div
+ ref={el => {
+ disabledMessageTooltip.ref(el);
+ }}
+ {...rest}
+ {...mergeProps(
+ themeProps('date-input', {
+ size,
+ status: status?.type ?? null,
+ disabled: isDisabled ? 'disabled' : null,
+ }),
+ stylex.props(
+ inputWrapperStyles.base,
+ sizeStyles[size],
+ styles.wrapper,
+ isEffectivelyDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status &&
+ !isEffectivelyDisabled &&
+ inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ inputGroup && groupStyles.inGroup,
+ xstyle,
+ ),
+ className,
+ style,
+ )}>
+ {inputGroup && <VisuallyHidden id={inputLabelID}>{label}</VisuallyHidden>}
+ <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-input-toggle-icon', {state: 'collapsed'})}
+ />
+ </button>
+ <span {...stylex.props(styles.slot)}>
+ <input
+ ref={mergedInputRef}
+ id={id}
+ type="date"
+ // UNCONTROLLED on purpose, with a value React never rewrites after
+ // mount — see `initialValueRef` and the sync effect above.
+ defaultValue={initialValueRef.current ?? ''}
+ onChange={handleChange}
+ onFocus={() => setIsFocused(true)}
+ onBlur={handleBlur}
+ min={min}
+ max={max}
+ disabled={isEffectivelyDisabled && !showsDisabledMessage}
+ aria-disabled={showsDisabledMessage ? 'true' : undefined}
+ readOnly={showsDisabledMessage || undefined}
+ aria-labelledby={ariaLabelledBy}
+ aria-describedby={ariaDescribedBy}
+ aria-required={isEffectivelyRequired ? 'true' : undefined}
+ aria-invalid={
+ status?.type === 'error' || !isInputValid ? 'true' : undefined
+ }
+ aria-busy={isLoading || 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>
+ {/*
+ Live region announcing a refused date. The value snaps back on its
+ own, so without this a screen-reader user would get no feedback that
+ their pick was rejected (WCAG 3.3.1).
+ */}
+ <VisuallyHidden as="div" role="alert" aria-live="assertive">
+ {!isInputValid ? t('@astryx.dateInput.invalidDate') : ''}
+ </VisuallyHidden>
+ {hasClear && value !== undefined && !isEffectivelyDisabled && (
+ <InputClearButton
+ label={t('@astryx.dateInput.clear', {label})}
+ onClick={handleClear}
+ iconClassName={stableClassName('date-input-clear-icon')}
+ />
+ )}
+ {isLoading && <Spinner size="sm" />}
+ {statusIcon}
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
+ </div>
+ );
+
+ if (inputGroup) {
+ return inputWrapper;
+ }
+
+ return (
+ <Field
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ inputID={id}
+ descriptionID={description ? descriptionID : undefined}
+ isOptional={isOptional}
+ isRequired={isRequired}
+ isDisabled={isDisabled}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageID : undefined,
+ }
+ : undefined
+ }
+ statusVariant={statusVariant}
+ labelTooltip={labelTooltip}
+ width={width}>
+ {inputWrapper}
+ </Field>
+ );
+}
+
+NativeDateField.displayName = 'NativeDateField';
diff --git a/packages/core/src/DateInput/index.ts b/packages/core/src/DateInput/index.ts
index eed5271fd2..8144a3e54d 100644
--- a/packages/core/src/DateInput/index.ts
+++ b/packages/core/src/DateInput/index.ts
@@ -14,6 +14,7 @@ export type {
DateInputProps,
DateInputSize,
DateInputFormat,
+ DateInputNativePicker,
DateInputStatus,
DateInputStatusType,
} from './DateInput';