Skip to content

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

TypeScript

feat(DateInput, DateTimeInput, DateRangeInput): type, pick and show dates in the active calendar (#9643, #9842)

nynexman4464189a730ce4e7
diff --git a/.changeset/calendar-bottom-sheet.md b/.changeset/calendar-bottom-sheet.md
new file mode 100644
index 0000000000..a5f6e1c2f5
--- /dev/null
+++ b/.changeset/calendar-bottom-sheet.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DateInput, DateTimeInput: the bottom sheet shows the calendar. With a `calendar` such as `'persian'`, `'hebrew'`, or `'japanese'`, the bottom sheet shows months of the calendar, with its month names and the locale's digits, in panes of one fixed height, and its closed field writes the date in the calendar. Its month wheel lists the months of the selected calendar year, including leap months such as Adar I and Adar II, and a year change keeps the month or moves to its common counterpart (Adar I becomes Adar). Year labels carry the era, such as `令和8`, and a year in which the era changes is labeled with the era of the shown month, as on iOS: 2019 reads `平成31` in January and `令和元` in July, and the month heading follows the same date, so January 3, 1989 reads `昭和64年1月`. A provider locale with a `-u-ca-` keyword keeps the Gregorian sheet; set `calendar` to choose a calendar. Values stay Gregorian ISO dates.
+
+@nynexman4464
diff --git a/.changeset/calendar-inputs-guide.md b/.changeset/calendar-inputs-guide.md
new file mode 100644
index 0000000000..0fc9b1c202
--- /dev/null
+++ b/.changeset/calendar-inputs-guide.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] The calendars guide says `Calendar`, `DateInput`, `DateRangeInput`, and `DateTimeInput` show the Gregorian calendar unless the application chooses another one.
+
+@nynexman4464
diff --git a/.changeset/calendar-native-fallback.md b/.changeset/calendar-native-fallback.md
new file mode 100644
index 0000000000..4d24366425
--- /dev/null
+++ b/.changeset/calendar-native-fallback.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DateInput, DateTimeInput: never show the native date control in a calendar it cannot show. With a `calendar` other than `gregory` or `iso8601`, such as `'persian'` or `'hebrew'`, `adaptive-native` (the default), the deprecated `nativePicker` values, and `presentation="native"` use the calendar popover on a mouse and the bottom sheet on a touch screen, because the native date control shows only Gregorian dates. An explicit `presentation="native"` also warns in development. A provider locale with a `-u-ca-` keyword keeps Gregorian dates and the native control; set `calendar` to choose a calendar. Values stay Gregorian ISO dates. Without `Temporal`, calendars other than `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese` show Gregorian dates and the native control as before.
+
+@nynexman4464
diff --git a/.changeset/calendar-presentations.md b/.changeset/calendar-presentations.md
new file mode 100644
index 0000000000..ad27bd8158
--- /dev/null
+++ b/.changeset/calendar-presentations.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DateRangeInput: show the range in the calendar. DateRangeInput takes a `calendar` prop, such as `'persian'` or `'hebrew'`, defaulting to the `InternationalizationProvider` calendar (a provider locale with a `-u-ca-` keyword keeps Gregorian dates; set `calendar` to choose one), and writes its trigger text and shows its popover calendar in it. Values stay Gregorian ISO dates. Without `Temporal`, calendars other than `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese` show Gregorian dates.
+
+@nynexman4464
diff --git a/.changeset/calendar-systems-core.md b/.changeset/calendar-systems-core.md
index 0c128d4f38..1c6071f20c 100644
--- a/.changeset/calendar-systems-core.md
+++ b/.changeset/calendar-systems-core.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[feat] Calendar shows dates in other calendar systems. `Calendar` takes a `calendar` prop (`CalendarSystem`), such as `'persian'`, `'hebrew'`, `'islamic-umalqura'`, or `'buddhist'`, and otherwise shows the `InternationalizationProvider` calendar. A provider locale with a `-u-ca-` keyword, such as `en-u-ca-buddhist`, keeps Gregorian dates; set `calendar` to choose one. Values do not change: `value`, `min`, `max`, `focusDate`, and every callback stay Gregorian ISO dates. `DateInput`, `DateRangeInput`, and `DateTimeInput`, including their popover calendars, keep showing Gregorian dates. In the selected calendar, the grid shows that calendar's months, including leap months such as Adar I and Adar II and the five- or six-day thirteenth month of the Ethiopic and Coptic calendars. Its heading, day names, and announcements use the calendar; Previous, Next, PageUp, and PageDown move one calendar month; and Shift+PageUp and Shift+PageDown move one calendar year to the same month. Day numbers use the locale's digits, and week numbers stay ISO 8601. The Gregorian-aligned calendars (`gregory`, `iso8601`, `buddhist`, `roc`, `japanese`) work everywhere. The others need `Temporal`; where the runtime lacks it, such as Safari or Node.js 24, load a polyfill like `temporal-polyfill/full/global` on the server and in the browser, or those calendars show Gregorian dates and warn once in development. A server-rendered app loads `Temporal` on the server too, since a server without it renders Gregorian markup.
+[feat] Calendar shows dates in other calendar systems. `Calendar` takes a `calendar` prop (`CalendarSystem`), such as `'persian'`, `'hebrew'`, `'islamic-umalqura'`, or `'buddhist'`, and otherwise shows the `InternationalizationProvider` calendar. A provider locale with a `-u-ca-` keyword, such as `en-u-ca-buddhist`, keeps Gregorian dates; set `calendar` to choose one. Values do not change: `value`, `min`, `max`, `focusDate`, and every callback stay Gregorian ISO dates. `DateInput`, `DateTimeInput`, and `DateRangeInput` show dates in the same calendar. In the selected calendar, the grid shows that calendar's months, including leap months such as Adar I and Adar II and the five- or six-day thirteenth month of the Ethiopic and Coptic calendars. Its heading, day names, and announcements use the calendar; Previous, Next, PageUp, and PageDown move one calendar month; and Shift+PageUp and Shift+PageDown move one calendar year to the same month. Day numbers use the locale's digits, and week numbers stay ISO 8601. The Gregorian-aligned calendars (`gregory`, `iso8601`, `buddhist`, `roc`, `japanese`) work everywhere. The others need `Temporal`; where the runtime lacks it, such as Safari or Node.js 24, load a polyfill like `temporal-polyfill/full/global` on the server and in the browser, or those calendars show Gregorian dates and warn once in development. A server-rendered app loads `Temporal` on the server too, since a server without it renders Gregorian markup.
@nynexman4464
diff --git a/.changeset/calendar-systems-formatters.md b/.changeset/calendar-systems-formatters.md
index fabe047532..8459e513c7 100644
--- a/.changeset/calendar-systems-formatters.md
+++ b/.changeset/calendar-systems-formatters.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[feat] Built-in date formats follow the calendar of the `InternationalizationProvider`. With `calendar="persian"`, Timestamp's `date`, `date_long`, `date_weekday`, and `date_time` formats, the full date in its hover card and accessible name, and PowerSearch date values are written in that calendar, the same one `Calendar` shows. A provider locale with a `-u-ca-` keyword keeps Gregorian dates; set `calendar` to choose one. `date_time` keeps its time of day. The editor a PowerSearch date value opens still shows Gregorian dates. `time`, the relative formats, `system_*`, and `unix_seconds` do not change, and without a provider calendar every output stays the same. `formatSharedDate` from `@astryxdesign/core/utils` and `formatFilterValue` from `@astryxdesign/core/PowerSearch/utils` take an optional trailing `calendar` argument that defaults to `'gregory'`. Each of these dates names the month and day that `Calendar` shows for the same day, as does `plainDateFormat` with a `calendar` option other than `'gregory'`. A calendar that needs `Temporal` shows Gregorian dates where the runtime lacks it, as the date components do.
+[feat] Built-in date formats follow the calendar of the `InternationalizationProvider`. With `calendar="persian"`, Timestamp's `date`, `date_long`, `date_weekday`, and `date_time` formats, the full date in its hover card and accessible name, and PowerSearch date values are written in that calendar, the same one `Calendar` shows. A provider locale with a `-u-ca-` keyword keeps Gregorian dates; set `calendar` to choose one. `date_time` keeps its time of day. `time`, the relative formats, `system_*`, and `unix_seconds` do not change, and without a provider calendar every output stays the same. `formatSharedDate` from `@astryxdesign/core/utils` and `formatFilterValue` from `@astryxdesign/core/PowerSearch/utils` take an optional trailing `calendar` argument that defaults to `'gregory'`. Each of these dates names the month and day that `Calendar` shows for the same day, as does `plainDateFormat` with a `calendar` option other than `'gregory'`. A calendar that needs `Temporal` shows Gregorian dates where the runtime lacks it, as the date components do.
@nynexman4464
diff --git a/.changeset/calendar-typed-entry.md b/.changeset/calendar-typed-entry.md
new file mode 100644
index 0000000000..8595ef6bbf
--- /dev/null
+++ b/.changeset/calendar-typed-entry.md
@@ -0,0 +1,14 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] DateInput, DateTimeInput: type dates in other calendar systems. Both take a `calendar` prop, such as `'persian'`, `'hebrew'`, `'japanese'`, or `'buddhist'`, and otherwise use the `InternationalizationProvider` calendar. A provider locale with a `-u-ca-` keyword keeps Gregorian dates; set `calendar` to choose one. `value`, `onChange`, `min`, and `max` stay Gregorian ISO dates. People type a date the way the locale writes it in that calendar, in any decimal digits, such as `۱۴۰۵/۸/۱۱`, `1 Adar 5784`, or `令和元年5月1日`; the committed text, the popover calendar, and the `date`, `date_long`, and `date_weekday` formats use the calendar, and `system_date` stays the ISO date. Years are years of the calendar, so a Buddhist field reads `2026` as Buddhist year 2026: set `min` and `max` on Buddhist and Minguo calendar fields to catch a Gregorian year typed by mistake. A date the calendar does not have, such as 30 Esfand in a common Persian year, is named and never adjusted. An empty focused field without a `placeholder` shows an example date that the field accepts, and its description names the calendar when it differs from the `InternationalizationProvider` calendar. Calendars other than `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese` need `Temporal`, native or a polyfill you load; without it the field shows Gregorian dates.
+
+Typing changes for Gregorian fields too:
+
+- `onChange` fires while typing only once the date is complete, and once for each date, so partial input such as `12/0` or `12/01/202` no longer reports wrong dates. A two-digit year, such as `12/01/90`, or a date without a year commits on Enter or blur, and is read in the locale's field order. A one-digit or three-digit year, such as `1/5/2` or `12/01/202`, is not a date: Enter or blur keeps it and shows it as invalid. `parseDateInput` still reads, on Enter or blur, text the field cannot otherwise read and a date the locale's field order does not have, such as `13/5/2026` in `en-US`.
+- A typed date outside `min`, `max`, or `dateConstraints` stays in the field with an error that names the allowed range, or says the date is not available when only a `dateConstraints` rule rejects it, instead of reverting on blur; the error shows even when you set `status`. Unreadable text, a date that does not exist, and an out-of-range date each announce their own message, once.
+
+Fixes #8958.
+
+@nynexman4464
diff --git a/.changeset/date-fields-keep-typed-text-while-disabled.md b/.changeset/date-fields-keep-typed-text-while-disabled.md
new file mode 100644
index 0000000000..2eb8f07ce3
--- /dev/null
+++ b/.changeset/date-fields-keep-typed-text-while-disabled.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] DateInput and DateTimeInput keep typed text that has not reported a date, without an error, while disabled or busy, and commit it on the next Enter or blur once editable. A new value still replaces it. Typed text whose date `onChange` already reported gives way to the field's value once the field is editable again, on the next Enter or blur if the field has focus.
+
+@nynexman4464
diff --git a/.changeset/typed-entry-shared-hook.md b/.changeset/typed-entry-shared-hook.md
new file mode 100644
index 0000000000..f957385b50
--- /dev/null
+++ b/.changeset/typed-entry-shared-hook.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: DateInput and DateTimeInput keep their typed-entry state, rejection status, and commits in one shared hook instead of two copies. Typing, committing, and rejection messages are unchanged. Not exported from the package entry point.
+
+@nynexman4464
diff --git a/apps/storybook/stories/DateInput.stories.tsx b/apps/storybook/stories/DateInput.stories.tsx
index 2a535ab047..005ba5edd5 100644
--- a/apps/storybook/stories/DateInput.stories.tsx
+++ b/apps/storybook/stories/DateInput.stories.tsx
@@ -3,14 +3,17 @@
import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import {expect, userEvent, waitFor, within} from 'storybook/test';
-import {DateInput} from '@astryxdesign/core/DateInput';
+import {DateInput, type DateInputProps} from '@astryxdesign/core/DateInput';
import {FormLayout} from '@astryxdesign/core/FormLayout';
import {Text} from '@astryxdesign/core/Text';
-import {InternationalizationProvider} from '@astryxdesign/core/i18n';
import {InputGroup, InputGroupText} from '@astryxdesign/core/InputGroup';
import type {ISODateString} from '@astryxdesign/core/Calendar';
import {Layout, LayoutContent} from '@astryxdesign/core/Layout';
import {Theme, defineTheme} from '@astryxdesign/core/theme';
+import {
+ type CalendarSystem,
+ InternationalizationProvider,
+} from '@astryxdesign/core/i18n';
const meta: Meta<typeof DateInput> = {
title: 'Core/DateInput',
@@ -252,6 +255,207 @@ export const Formats: Story = {
},
};
+const CALENDAR_FIELDS: ReadonlyArray<{
+ locale: string;
+ calendar: CalendarSystem;
+ label: string;
+ dir: 'ltr' | 'rtl';
+ min?: ISODateString;
+ max?: ISODateString;
+}> = [
+ {locale: 'fa-IR', calendar: 'persian', label: 'تاریخ شروع', dir: 'rtl'},
+ {locale: 'he', calendar: 'hebrew', label: 'תאריך התחלה', dir: 'rtl'},
+ {locale: 'ja-JP', calendar: 'japanese', label: '開始日', dir: 'ltr'},
+ {
+ locale: 'th-TH',
+ calendar: 'buddhist',
+ label: 'วันที่เริ่มต้น',
+ dir: 'ltr',
+ min: '2020-01-01' as ISODateString,
+ max: '2030-12-31' as ISODateString,
+ },
+ {
+ locale: 'en',
+ calendar: 'hebrew',
+ label: 'Start date (Hebrew calendar)',
+ dir: 'ltr',
+ },
+];
+
+function CalendarField({
+ locale,
+ calendar,
+ label,
+ dir,
+ min,
+ max,
+}: (typeof CALENDAR_FIELDS)[number]) {
+ const [value, setValue] = useState<ISODateString | undefined>(
+ '2026-11-02' as ISODateString,
+ );
+ return (
+ <InternationalizationProvider locale={locale}>
+ <div
+ dir={dir}
+ lang={locale}
+ data-calendar-field={`${locale}-${calendar}`}
+ style={{display: 'flex', flexDirection: 'column', gap: 4}}>
+ <DateInput
+ label={label}
+ calendar={calendar}
+ value={value}
+ onChange={setValue}
+ min={min}
+ max={max}
+ width={320}
+ />
+ <Text type="supporting" color="secondary">
+ <code data-value>{`value: ${value ?? '—'}`}</code>
+ </Text>
+ </div>
+ </InternationalizationProvider>
+ );
+}
+
+/**
+ * `calendar` sets the calendar the field reads and writes typed dates in.
+ * `value` and `onChange` stay Gregorian ISO dates. Type in the locale's
+ * digits or Latin digits; the field reports a date only when it is complete,
+ * and names a date the calendar does not have. The Buddhist field sets `min`
+ * and `max`, so a Gregorian year typed by mistake is caught. Calendars other
+ * than Gregorian, Buddhist, Minguo, and Japanese need `Temporal`.
+ */
+export const CalendarSystems: Story = {
+ render: () => (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>
+ {CALENDAR_FIELDS.map(field => (
+ <CalendarField key={`${field.locale}-${field.calendar}`} {...field} />
+ ))}
+ </div>
+ ),
+};
+
+const PRESENTATION_FIELDS: ReadonlyArray<{
+ id: string;
+ locale: string;
+ calendar: CalendarSystem;
+ label: string;
+ dir: 'ltr' | 'rtl';
+ value: ISODateString;
+ min?: ISODateString;
+ max?: ISODateString;
+ presentation?: DateInputProps['presentation'];
+}> = [
+ {
+ id: 'fa-persian',
+ locale: 'fa-IR',
+ calendar: 'persian',
+ label: 'تاریخ شروع',
+ dir: 'rtl',
+ value: '2026-11-02' as ISODateString,
+ },
+ {
+ id: 'en-persian-native',
+ locale: 'en',
+ calendar: 'persian',
+ label: 'Start date (Persian, presentation="native")',
+ dir: 'ltr',
+ value: '2026-11-02' as ISODateString,
+ presentation: 'native',
+ },
+ {
+ id: 'en-hebrew-leap',
+ locale: 'en',
+ calendar: 'hebrew',
+ label: 'Start date (Hebrew, a leap year)',
+ dir: 'ltr',
+ value: '2024-02-15' as ISODateString,
+ min: '2020-01-01' as ISODateString,
+ max: '2030-12-31' as ISODateString,
+ },
+ {
+ id: 'ja-japanese',
+ locale: 'ja-JP',
+ calendar: 'japanese',
+ label: '開始日',
+ dir: 'ltr',
+ value: '2026-11-02' as ISODateString,
+ min: '2015-01-01' as ISODateString,
+ max: '2030-12-31' as ISODateString,
+ },
+ {
+ id: 'en-ethiopic-pagume',
+ locale: 'en',
+ calendar: 'ethiopic',
+ label: 'Start date (Ethiopic, the thirteenth month)',
+ dir: 'ltr',
+ value: '2026-09-08' as ISODateString,
+ },
+ {
+ id: 'en-gregory',
+ locale: 'en',
+ calendar: 'gregory',
+ label: 'Start date (Gregorian)',
+ dir: 'ltr',
+ value: '2026-11-02' as ISODateString,
+ },
+];
+
+function PresentationField({
+ id,
+ locale,
+ calendar,
+ label,
+ dir,
+ value: initialValue,
+ min,
+ max,
+ presentation,
+}: (typeof PRESENTATION_FIELDS)[number]) {
+ const [value, setValue] = useState<ISODateString | undefined>(initialValue);
+ return (
+ <InternationalizationProvider locale={locale}>
+ <div
+ dir={dir}
+ lang={locale}
+ data-calendar-field={id}
+ style={{display: 'flex', flexDirection: 'column', gap: 4}}>
+ <DateInput
+ label={label}
+ calendar={calendar}
+ value={value}
+ onChange={setValue}
+ min={min}
+ max={max}
+ presentation={presentation}
+ width={320}
+ />
+ <Text type="supporting" color="secondary">
+ <code data-value>{`value: ${value ?? '—'}`}</code>
+ </Text>
+ </div>
+ </InternationalizationProvider>
+ );
+}
+
+/**
+ * In a calendar other than Gregorian, the field never shows the native date
+ * control, which is Gregorian: the default and `presentation="native"` open
+ * the calendar popover on a mouse and the bottom sheet on a touch screen. The
+ * bottom sheet shows months of the calendar, its month wheel lists the months
+ * of the calendar year, including leap months, and its year wheel names the
+ * era. Values stay Gregorian ISO dates.
+ */
+export const CalendarSystemPresentations: Story = {
+ render: () => (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>
+ {PRESENTATION_FIELDS.map(field => (
+ <PresentationField key={field.id} {...field} />
+ ))}
+ </div>
+ ),
+};
+
export const NativePickerModes: Story = {
name: 'Native picker modes',
render: () => {
diff --git a/apps/storybook/stories/DateRangeInput.stories.tsx b/apps/storybook/stories/DateRangeInput.stories.tsx
index af598649ee..e8462cd9d0 100644
--- a/apps/storybook/stories/DateRangeInput.stories.tsx
+++ b/apps/storybook/stories/DateRangeInput.stories.tsx
@@ -8,6 +8,10 @@ import {Text} from '@astryxdesign/core/Text';
import type {DateRange} from '@astryxdesign/core/DateRangeInput';
import type {ISODateString} from '@astryxdesign/core/Calendar';
import {Theme, defineTheme} from '@astryxdesign/core/theme';
+import {
+ type CalendarSystem,
+ InternationalizationProvider,
+} from '@astryxdesign/core/i18n';
function daysAgo(n: number): ISODateString {
const d = new Date();
@@ -536,3 +540,90 @@ export const StylingParts: Story = {
</div>
),
};
+
+const RANGE_CALENDAR_FIELDS: ReadonlyArray<{
+ id: string;
+ locale: string;
+ calendar: CalendarSystem;
+ label: string;
+ dir: 'ltr' | 'rtl';
+}> = [
+ {
+ id: 'en-persian',
+ locale: 'en',
+ calendar: 'persian',
+ label: 'Stay',
+ dir: 'ltr',
+ },
+ {
+ id: 'fa-persian',
+ locale: 'fa-IR',
+ calendar: 'persian',
+ label: 'اقامت',
+ dir: 'rtl',
+ },
+ {
+ id: 'he-hebrew',
+ locale: 'he',
+ calendar: 'hebrew',
+ label: 'שהייה',
+ dir: 'rtl',
+ },
+ {
+ id: 'th-buddhist',
+ locale: 'th-TH',
+ calendar: 'buddhist',
+ label: 'การเข้าพัก',
+ dir: 'ltr',
+ },
+];
+
+function RangeCalendarField({
+ id,
+ locale,
+ calendar,
+ label,
+ dir,
+}: (typeof RANGE_CALENDAR_FIELDS)[number]) {
+ const [value, setValue] = useState<DateRange | null>({
+ start: '2026-10-30' as ISODateString,
+ end: '2026-11-02' as ISODateString,
+ });
+ return (
+ <InternationalizationProvider locale={locale}>
+ <div
+ dir={dir}
+ lang={locale}
+ data-calendar-field={id}
+ style={{display: 'flex', flexDirection: 'column', gap: 4}}>
+ <DateRangeInput
+ label={label}
+ calendar={calendar}
+ value={value}
+ onChange={setValue}
+ width={360}
+ />
+ <Text type="supporting" color="secondary">
+ <code data-value>
+ {`value: ${value == null ? '—' : `${value.start} – ${value.end}`}`}
+ </code>
+ </Text>
+ </div>
+ </InternationalizationProvider>
+ );
+}
+
+/**
+ * `calendar` sets the calendar the trigger text and the popover calendar
+ * show. The range stays Gregorian ISO dates. Calendars other than Gregorian,
+ * Buddhist, Minguo, and Japanese need `Temporal`.
+ */
+export const CalendarSystems: Story = {
+ render: () => (
+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>
+ {RANGE_CALENDAR_FIELDS.map(field => (
+ <RangeCalendarField key={field.id} {...field} />
+ ))}
+ </div>
+ ),
+};
diff --git a/apps/storybook/stories/DateTimeInput.stories.tsx b/apps/storybook/stories/DateTimeInput.stories.tsx
index 1de513a81d..d423612922 100644
--- a/apps/storybook/stories/DateTimeInput.stories.tsx
+++ b/apps/storybook/stories/DateTimeInput.stories.tsx
@@ -8,6 +8,7 @@ import {FormLayout} from '@astryxdesign/core/FormLayout';
import {Text} from '@astryxdesign/core/Text';
import type {ISODateTimeString} from '@astryxdesign/core/DateTimeInput';
import {Theme, defineTheme} from '@astryxdesign/core/theme';
+import {InternationalizationProvider} from '@astryxdesign/core/i18n';
const meta: Meta<typeof DateTimeInput> = {
title: 'Core/DateTimeInput',
@@ -717,3 +718,31 @@ export const StylingParts: Story = {
</div>
),
};
+
+function PersianDateTimeField() {
+ const [value, setValue] = useState<ISODateTimeString | undefined>(
+ '2026-11-02T09:30' as ISODateTimeString,
+ );
+ return (
+ <InternationalizationProvider locale="en" calendar="persian">
+ <div
+ data-calendar-field="en-persian"
+ style={{display: 'flex', flexDirection: 'column', gap: 4}}>
+ <DateTimeInput label="Appointment" value={value} onChange={setValue} />
+ <Text type="supporting" color="secondary">
+ <code data-value>{`value: ${value ?? '—'}`}</code>
+ </Text>
+ </div>
+ </InternationalizationProvider>
+ );
+}
+
+/**
+ * In a calendar other than Gregorian, DateTimeInput never shows native date
+ * and time controls: it opens the popovers on a mouse and the bottom sheet on
+ * a touch screen, whose Date panel shows months of the calendar. The value
+ * stays a Gregorian ISO date-time.
+ */
+export const CalendarSystems: Story = {
+ render: () => <PersianDateTimeField />,
+};
diff --git a/docs/architecture/internationalization.md b/docs/architecture/internationalization.md
index e4442ecf45..83efcd9a1f 100644
--- a/docs/architecture/internationalization.md
+++ b/docs/architecture/internationalization.md
@@ -279,7 +279,7 @@ for all 30 shipped locales plus `pseudo`.
`Calendar` shows the calendar that it resolves from its own `calendar` prop
or the provider's `calendar` prop, and otherwise the Gregorian calendar
(`spec:AST-111` FR2). `DateInput`, `DateRangeInput`, and `DateTimeInput`
- show Gregorian dates. Locale changes language, numbering, and field order; a
+ do the same. Locale changes language, numbering, and field order; a
locale never selects the calendar, neither by its default calendar nor by a
`-u-ca-` keyword. `PlainDate` values, constraints, and machine formats stay
Gregorian ISO in every calendar. The runtime's `Temporal` owns the arithmetic
diff --git a/docs/specs/AST-043-input-presentation/spec.md b/docs/specs/AST-043-input-presentation/spec.md
index 4f8bf4d05d..621a170459 100644
--- a/docs/specs/AST-043-input-presentation/spec.md
+++ b/docs/specs/AST-043-input-presentation/spec.md
@@ -79,12 +79,18 @@ adaptive-native`; only `TimeInput` accepts all six.
Coarse uses the inputs' existing pointer test, no width condition. Forced
values (`popover` on coarse, `bottom-sheet` where not reached today, and
`text-input` on `TimeInput`) MUST render the named surface, never silently
- substitute another.
+ substitute another. In a calendar other than `gregory` or `iso8601`,
+ `DateInput` and `DateTimeInput` resolve `native` and `adaptive-native` to
+ Astryx desktop on a fine pointer and Astryx sheet on a coarse pointer (FR2,
+ `spec:AST-111` FR15).
- **FR2 — Fallback split for native.** Explicit `presentation="native"` MUST
always show the native surface, with no eligibility fallbacks — a state the
native control cannot express (seconds, non-default step/increment, preset
time options, no usable native control) is the caller's explicit choice.
+ The one exception is the calendar: with a calendar other than `gregory` or
+ `iso8601`, explicit `native` uses the Astryx surface and warns in development
+ (`spec:AST-111` FR15).
`presentation="adaptive-native"` — including the default and
`nativePicker="touch"` — MUST keep the released fallbacks: in those same
states it falls back to the component's Astryx surface (per-segment for
@@ -105,7 +111,8 @@ adaptive-native`; only `TimeInput` accepts all six.
| `always` | `native` (legacy, FR2) | `native` (legacy, FR2) |
| `never` | `adaptive-bottom-sheet` | `text-input` |
- `always` maps to the `native` surface on every pointer but retains the
+ `always` maps to the `native` surface on every pointer, except in a calendar
+ other than `gregory` or `iso8601` (FR2), but retains the
released eligibility fallbacks (FR2): `hasSeconds`, non-default
step/increment, preset time options, or no usable native control keep the
Astryx surface, exactly as released. It is therefore not identical to
@@ -142,12 +149,12 @@ adaptive-native`; only `TimeInput` accepts all six.
## Verification
-| Contract | Verification | Representative states | Mutation or failure expectation |
-| -------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
-| FR1 | Unit tests per input + real-browser check | Per-component values × fine/coarse, incl. forced + `TimeInput` sheet; `text-input` type-rejected outside `TimeInput` | Wrong/substituted surface fails |
-| FR2 | Unit tests, native requested | Seconds, step≠default, presets, no usable native: explicit `native` stays native; `adaptive-native` and deprecated `always` fall back | Any fallback under explicit `native`, or none under `adaptive-native`/`always`, fails |
-| FR3–FR4 | Unit tests: default, deprecated, dual-prop | Omitted; `touch`/`always`/`never` per component; both props, any order | Mapping drift (incl. `TimeInput:never→sheet`) or `nativePicker` winning fails |
-| FR5 | Doc/type consistency tests | All 3 components, en + zh | Documented-but-untyped value/default fails |
+| Contract | Verification | Representative states | Mutation or failure expectation |
+| -------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
+| FR1 | Unit tests per input + real-browser check | Per-component values × fine/coarse, incl. forced + `TimeInput` sheet; `text-input` type-rejected outside `TimeInput` | Wrong/substituted surface fails |
+| FR2 | Unit tests, native requested | Seconds, step≠default, presets, no usable native: explicit `native` stays native; `adaptive-native` and deprecated `always` fall back | Any eligibility fallback under explicit `native`, or none under `adaptive-native`/`always`, fails |
+| FR3–FR4 | Unit tests: default, deprecated, dual-prop | Omitted; `touch`/`always`/`never` per component; both props, any order | Mapping drift (incl. `TimeInput:never→sheet`) or `nativePicker` winning fails |
+| FR5 | Doc/type consistency tests | All 3 components, en + zh | Documented-but-untyped value/default fails |
## Decision log
diff --git a/docs/specs/components/Calendar/Calendar.spec.md b/docs/specs/components/Calendar/Calendar.spec.md
index 2c8e2d31d2..1d34c1fdad 100644
--- a/docs/specs/components/Calendar/Calendar.spec.md
+++ b/docs/specs/components/Calendar/Calendar.spec.md
@@ -246,6 +246,9 @@ button.
- `spec:AST-111` owns calendar selection, the supported calendars, Gregorian
ISO values, and the `Temporal` boundary; FR8–FR10 and AR1 project its FR4,
FR6–FR8, and AR1 onto the grid.
+- `component:DateInput`, `component:DateRangeInput`, and
+ `component:DateTimeInput` pass their popover Calendar the calendar their field
+ text uses (`component:DateInput` FR20, `component:DateRangeInput` FR6).
### `spec:AST-013` FR12 exception — calendars that need `Temporal`
diff --git a/docs/specs/components/DateInput/DateInput.spec.md b/docs/specs/components/DateInput/DateInput.spec.md
index 196897858c..efc66de127 100644
--- a/docs/specs/components/DateInput/DateInput.spec.md
+++ b/docs/specs/components/DateInput/DateInput.spec.md
@@ -15,6 +15,13 @@ verified_by:
packages/core/src/DateInput/MonthScrollerSettle.test.tsx,
packages/core/src/DateInput/DateInput.test.tsx,
packages/core/src/DateInput/DateInput.fr10.test.tsx,
+ packages/core/src/DateInput/DateInput.calendar.test.tsx,
+ packages/core/src/DateInput/DateInput.calendarPresentation.test.tsx,
+ packages/core/src/DateInput/DateInputTouch.calendar.test.tsx,
+ packages/core/src/DateInput/DateInput.noTemporal.test.tsx,
+ packages/core/src/utils/calendarSystem.test.ts,
+ packages/core/src/utils/calendarDateParser.test.ts,
+ packages/core/src/utils/calendarDateParser.roundtrip.test.ts,
packages/core/src/DateInput/DateInputTouch.test.tsx,
packages/core/src/DateInput/NativeDateField.test.tsx,
packages/core/src/DateInput/PickerWheel.test.tsx,
@@ -40,14 +47,18 @@ architecture:
contributing: []
system_specs:
[
+ spec:AST-013/FR12,
spec:AST-020/FR15,
spec:AST-043,
spec:AST-085,
+ spec:AST-085/FR1,
+ spec:AST-085/FR2,
spec:AST-086,
spec:AST-094/FR5,
spec:AST-094/FR10,
spec:AST-094/FR43,
spec:AST-102,
+ spec:AST-111,
]
---
@@ -55,15 +66,15 @@ system_specs:
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| Public contract | None. API shape and defaults are as shipped; every surface follows the input-field `changeAction`, disabled, and busy contracts. |
-| Behavior | `presentation` selects the picker surface; an omitted value is `adaptive-native`; `presentation` wins over deprecated `nativePicker`; every committed path emits the same controlled ISO-date value and action feedback. |
-| End-user impact | People type or pick one date using a surface suited to the primary pointer. Disabled and busy fields stay focusable; a busy field keeps its ordinary paint with a Spinner while new commits are blocked. |
-| Builder impact | None. `changeAction` runs after `onChange` with optimistic busy feedback on every surface. |
-| Compatibility/readiness | No API or default change. Under a finger, the sheet wheels' markup changes (one strip of flat rows, faded by a layer inside the column). Under every presentation, keys step through the values in time order (FR17). Caller handlers while disabled, fixed field height, the English-only typed parser, a clear control that drops focus, and month paging in the touch calendar are listed under Current-state impact. |
-| Review checks | Reject a surface-mapping change, lost constraint, callback-order change, unlabeled field, native `disabled`, disabled paint on a busy-only field, unreachable disabled reason, changed close behavior, or a theming target placed on the wrong owner. |
-| Governing rules | `spec:AST-043/FR1–FR5`; `spec:AST-085/FR1–FR6`; `spec:AST-086/FR3, FR4, FR6, FR8`; `family:input-fields/FR1–FR6, FR8–FR11`; `family:overlay-dismissal/FR1–FR7`, including its recorded BottomSheet adoption gap; `spec:AST-020/FR15`; `spec:AST-102/FR4`; the four architecture records linked above. |
+| Area | Contract |
+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `calendar` selects the calendar system the field shows on every surface (`spec:AST-111` FR2); every other API shape and default is as shipped, and every surface follows the input-field `changeAction`, disabled, and busy contracts. |
+| Behavior | `presentation` selects the picker surface; an omitted value is `adaptive-native`; `presentation` wins over deprecated `nativePicker`; every committed path emits the same controlled ISO-date value and action feedback. The pointer field reads and writes typed dates in the resolved calendar and reports a typed date only when it is complete (FR20). With a calendar other than `gregory` or `iso8601`, a presentation that would show the native control shows the popover on a fine pointer and the bottom sheet on a coarse pointer, and the bottom sheet shows months of the calendar (FR21). |
+| End-user impact | People type or pick one date using a surface suited to the primary pointer, in the calendar the application chooses. Disabled and busy fields stay focusable; a busy field keeps its ordinary paint with a Spinner while new commits are blocked. |
+| Builder impact | Optional: set `calendar` on the field or its provider, and `min` and `max` on Buddhist and Minguo calendar fields. `changeAction` runs after `onChange` with optimistic busy feedback on every surface. |
+| Compatibility/readiness | `calendar` is additive and the default stays Gregorian. Typed Gregorian entry fires `onChange` only for complete input and keeps an out-of-range date with its error; `parseDateInput` handles only unreadable text and dates the locale's order lacks, and a two-digit year reads within the 80 years before and 19 after the current year, 1946–2045 in 2026 (FR20). Calendars that need `Temporal` fall back to Gregorian where it is missing (the `spec:AST-013` FR12 exception). Under a finger, the sheet wheels' markup changes (one strip of flat rows, faded by a layer inside the column). Under every presentation, keys step through the values in time order (FR17). Caller handlers while disabled, fixed field height, a clear control that drops focus, and month paging in the touch calendar are listed under Current-state impact. |
+| Review checks | Reject a surface-mapping change, lost constraint, callback-order change, unlabeled field, native `disabled`, disabled paint on a busy-only field, unreachable disabled reason, changed close behavior, a theming target placed on the wrong owner, a typed date reported before it is complete, an adjusted typed date, or two rejection kinds that share a message. |
+| Governing rules | `spec:AST-043/FR1–FR5`; `spec:AST-085/FR1–FR6`; `spec:AST-086/FR3, FR4, FR6, FR8`; `spec:AST-111` FR2, FR3, FR9–FR16, AR2, AR3; `spec:AST-013` FR12; `family:input-fields/FR1–FR6, FR8–FR11`; `family:overlay-dismissal/FR1–FR7`, including its recorded BottomSheet adoption gap; `spec:AST-020/FR15`; `spec:AST-102/FR4`; the four architecture records linked above. |
This table is a review projection; the body below is authoritative.
@@ -76,9 +87,17 @@ browser/OS date picker selected by the public presentation contract.
## Compatibility and migration
- Released default preserved: `yes`
-- Compatibility class: no public prop, default, or export change; under a
- finger the sheet wheels' markup changes, and under every presentation keys
- step through the values in time order (FR17)
+- Compatibility class: additive `calendar` prop with a Gregorian default; under
+ a finger the sheet wheels' markup changes, and under every presentation keys
+ step through the values in time order (FR17). Typed Gregorian entry fires
+ `onChange` only for complete input, a nonbreaking fix that restores FR1's
+ next-ISO-date contract; its rejection messages are additive; on Enter or blur,
+ `parseDateInput` still reads text the field cannot otherwise read and a date
+ the locale's field order lacks, and a one- or three-digit year is not a date
+ (FR20). A non-Gregorian calendar replaces the native control with the Astryx
+ surface for the pointer, and an explicit `native` warns in development (FR21).
+ A provider locale with a `-u-ca-` keyword keeps Gregorian dates
+ (`spec:AST-111` DEC-2); set `calendar` to choose one.
- Controlled/uncontrolled behavior: unchanged; DateInput remains controlled by
`value`, with `undefined` representing no selected date
- Migration decision: `spec:AST-043/DEC-1` and `spec:AST-043/DEC-2` own the
@@ -128,41 +147,44 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
-| ----------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ----------------- | ----------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------- |
-| selected date | `undefined` or `YYYY-MM-DD` ISO date | Controlled committed calendar date | Every surface | `undefined` | `component:DateInput` | stable | Types reject other values; unparseable typed text is announced and reverts on commit |
-| presentation | `popover`, `bottom-sheet`, `native`, `adaptive-bottom-sheet`, `adaptive-native` | Surface that collects the date | Every pointer; adaptive values resolve by primary pointer | `adaptive-native` | `spec:AST-043` | stable | Types reject other values; DateInput has no text-only presentation |
-| legacy native selection | `touch`, `always`, `never` | Deprecated mapping to the released picker behavior | Used only when `presentation` is absent | `touch` behavior | `spec:AST-043` | deprecated, retained | `presentation` wins when both props are present |
-| committed display | `date`, `date_long`, `date_weekday`, `system_date`, or formatter function | Display shape for the committed ISO date | Closed field on every surface; never rewrites in-progress typed text | `date_long` | `component:DateInput` | stable | Function output is displayed; unparsable output cannot be re-committed as typed text |
-| selectable range | optional `min`, `max`, and date-constraint predicates | Dates that may commit | Every surface; native surfaces validate on commit when the OS cannot disable them | unbounded | `component:DateInput` with `component:Calendar` | stable | A rejected date does not replace the controlled value and is announced where applicable |
-| calendar configuration | one or two popover months; week start Sunday through Saturday | Calendar-grid layout | Week start applies to popover and bottom-sheet surfaces; month count applies only to the popover; neither is expressible by native pickers | one month, Sunday | `component:DateInput` with `component:Calendar` | stable | Types close the value set |
-| field state | enabled, disabled, disabled with reason, busy, optional, required, status | Shared field semantics and supporting presentation | Every surface, with surface-specific control mechanics | enabled, not busy | `family:input-fields` | stable | Conflicting optional/required resolution follows the shared Field owner |
-| clear affordance | absent or present while a committed value exists | Emits `undefined` and preserves the field interaction path | Every surface when `hasClear` and a value are present; hidden while disabled or busy | absent | `component:DateInput` with `component:Field` | stable | No control renders when there is no value |
-| field shell | standalone Field or admitted InputGroup child | Ownership of label, status, and outer geometry | Pointer surface supports both; other surfaces preserve the same public field semantics | standalone | `family:input-fields` | stable | InputGroup context selects grouped adaptation |
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ----------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| selected date | `undefined` or `YYYY-MM-DD` ISO date | Controlled committed calendar date | Every surface | `undefined` | `component:DateInput` | stable | Types reject other values; unreadable typed text is announced and reverts on commit; a typed date the calendar does not have, or one out of range, is announced, shown, and kept for correction |
+| presentation | `popover`, `bottom-sheet`, `native`, `adaptive-bottom-sheet`, `adaptive-native` | Surface that collects the date | Every pointer; adaptive values resolve by primary pointer | `adaptive-native` | `spec:AST-043` | stable | Types reject other values; DateInput has no text-only presentation |
+| legacy native selection | `touch`, `always`, `never` | Deprecated mapping to the released picker behavior | Used only when `presentation` is absent | `touch` behavior | `spec:AST-043` | deprecated, retained | `presentation` wins when both props are present |
+| committed display | `date`, `date_long`, `date_weekday`, `system_date`, or formatter function | Display shape for the committed ISO date | Closed field on every surface; never rewrites in-progress typed text; named formats other than `system_date` write the date in the resolved calendar | `date_long` | `component:DateInput` | stable | Function output is displayed; unreadable output cannot be re-committed as typed text |
+| calendar | a `CalendarSystem` (`spec:AST-111` FR1) | The calendar system the field shows dates in | Every surface; a calendar other than `gregory` or `iso8601` replaces the native surface (FR21) | the provider's resolved calendar, else `gregory` (`spec:AST-111` FR2) | `spec:AST-111` | stable | Resolves to `gregory` and warns once in development; a calendar that needs `Temporal` falls back to `gregory` where `Temporal` is missing |
+| selectable range | optional `min`, `max`, and date-constraint predicates | Dates that may commit | Every surface; native surfaces validate on commit when the OS cannot disable them | unbounded | `component:DateInput` with `component:Calendar` | stable | A rejected date does not replace the controlled value and is announced where applicable |
+| calendar configuration | one or two popover months; week start Sunday through Saturday | Calendar-grid layout | Week start applies to popover and bottom-sheet surfaces; month count applies only to the popover; neither is expressible by native pickers | one month, Sunday | `component:DateInput` with `component:Calendar` | stable | Types close the value set |
+| field state | enabled, disabled, disabled with reason, busy, optional, required, status | Shared field semantics and supporting presentation | Every surface, with surface-specific control mechanics | enabled, not busy | `family:input-fields` | stable | Conflicting optional/required resolution follows the shared Field owner |
+| clear affordance | absent or present while a committed value exists | Emits `undefined` and preserves the field interaction path | Every surface when `hasClear` and a value are present; hidden while disabled or busy | absent | `component:DateInput` with `component:Field` | stable | No control renders when there is no value |
+| field shell | standalone Field or admitted InputGroup child | Ownership of label, status, and outer geometry | Pointer surface supports both; other surfaces preserve the same public field semantics | standalone | `family:input-fields` | stable | InputGroup context selects grouped adaptation |
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
-| FR1 | DateInput MUST present the controlled ISO `value` and emit `onChange` with the next ISO date or `undefined` without maintaining a competing committed value. | Current source, docs, and focused tests |
-| FR2 | The five `presentation` values MUST resolve to the fine/coarse surfaces in `spec:AST-043/FR1`; omitting both presentation props MUST preserve `adaptive-native`. | `spec:AST-043/FR1–FR3`; Presentation tests |
-| FR3 | Explicit `presentation` MUST outrank deprecated `nativePicker`; the legacy values MUST retain their mappings and development-only warning from `spec:AST-043/FR3–FR4`. | Current source, docs, and Presentation tests |
-| FR4 | Adaptive resolution MUST use the primary pointer rather than viewport width or any-pointer availability, so tablets receive a touch surface and touchscreen laptops retain the typable field. | Current source, consumer docs, and surface-selection tests |
-| FR5 | Text, Calendar, bottom-sheet, and native commit paths MUST enforce `min`, `max`, and `dateConstraints`; a rejected value MUST NOT replace the controlled value. | Current source and all four focused suites |
-| FR6 | Named committed formats MUST follow the InternationalizationProvider locale and shared Timestamp vocabulary; formatting MUST NOT rewrite in-progress typed text. Typed text MUST parse in the provider locale (`architecture:internationalization` INV1a, INV8); in a day-first locale, numeric text outside the locale-ordered forms is not a date, so no fixed month-first reading applies. The touch sheet's month heading and each month pane's name are stand-alone month labels: they start with a capital where CLDR's stand-alone context transform titlecases the month, as `component:Calendar` FR1 states for Calendar's. Implementation gap: the typed parser accepts only English month names and ASCII digits, using the locale only to order day and month. In a month-first locale, numeric text outside the locale-ordered forms (such as `1/5/25`) still falls back to the browser's month-first reading, and a four-digit year written first (`2026/01/12`) parses in every locale. | `architecture:internationalization`; current source, docs, locale tests; `spec:AST-043/FR5` |
-| FR7 | Every value-change path MUST call `onChange` before `changeAction`, present the proposed value optimistically, and expose one busy state while the Action is pending. | `family:input-fields/FR6`; current source and focused tests |
-| FR8 | The pointer field MUST open its Calendar from the input, calendar toggle, ArrowDown, or Alt+ArrowDown; Popover dismissal and focus return MUST remain owned by the shared Popover path. The open pointer Calendar stays open for a press on the field's input, clear button or label, or in the Calendar, and closes for a press elsewhere (`architecture:layer-runtime`) or for focus moving from anywhere in the field (its input, clear button or calendar toggle) to anything outside the field and the Calendar (`family:overlay-dismissal` AV4). | Current source, Popover composition, keyboard/focus tests |
-| FR9 | A pointer-surface Calendar selection MUST commit and close its Popover; a bottom-sheet Calendar selection MUST remain editable in the open sheet until Save closes the surface. | Current source and pointer/touch tests |
-| FR10 | Standalone mode MUST compose Field; admitted InputGroup mode MUST remove competing Field chrome while preserving name, description, value, keyboard, focus, and editing semantics. The field has no root styling props; `control*` reaches the control box on every surface, and `container*` reaches the Field box where one renders (in a horizontal-labels FormLayout none renders and `container*` warns; inside an InputGroup it is dropped) (`family:input-fields` FR10). The field height is the shared element size for its size and MUST grow with a set text size (`spec:AST-102` FR4). Implementation gap: the height is fixed. | `family:input-fields` FR3, FR10; `spec:AST-102` FR4; current source and tests |
-| FR11 | Clear MUST emit `undefined` through the ordinary change pipeline. The pointer and bottom-sheet surfaces restore field focus using their shipped timing; the native surface MUST NOT reclaim focus because doing so reopens the OS picker. Implementation gap: when the field becomes disabled or busy while its clear control holds focus, the control unmounts and focus falls to the document body; `spec:AST-085/FR4` requires focus to stay or move to a destination this record names. | Current source and focused clear tests; `spec:AST-085/FR4` |
-| FR12 | No surface renders native `disabled`. A disabled field MUST stay focusable with `aria-disabled`, block typing, picking, clearing, and opening, describe its disabled reason when one is given, and take disabled paint. While busy (`isLoading` or a pending Action) the pointer and bottom-sheet surfaces expose `aria-disabled` and `aria-busy`, stay focusable, and block new commits; the native surface does the same for `isLoading`, and during a pending Action stays editable so the OS picker remains attached but rejects additional commits until the Action settles. A busy field that is not disabled keeps its ordinary paint and Spinner, shows no hover ring while commits are blocked, and keeps its keyboard focus ring. Caller handlers other than focus and blur MUST NOT run while the field is disabled (`spec:AST-085` FR2). Implementation gap: only a caller `onClick` is skipped while disabled; caller key, paste, and pointer handlers (such as `onKeyDown`, `onKeyUp`, `onPaste`, and `onPointerDown`) still run on every surface, the native field included. | `spec:AST-085/FR1–FR6`; `family:input-fields/FR4–FR6`; `family:buttons/FR4`; current source and focused tests |
-| FR13 | A bottom-sheet picker wheel that comes to rest on a disabled row (outside `min`/`max`) MUST continue to the nearest enabled row, a tie going toward the committed row, and select it there. A wheel resting on its committed row MUST NOT select or commit, even when that row is outside the bounds, so opening a bounded sheet never changes an untouched value: a committed value outside the bounds stays, and an empty field stays empty. This holds for every wheel in the DateInput, TimeInput, and DateTimeInput sheets. | DEC-1; UIDatePicker on the iOS 26.2 simulator; current source |
-| FR14 | A shown bottom-sheet picker wheel whose value changes from outside, as when a bound clamps the time after another wheel turned, MUST turn onto the new row rather than jump to it, on the theme's move duration and easing tokens, as a tap on a row does (`spec:AST-094` FR45). The internal motion role `picker.tapSpin.durationMs`, UIKit's measured 300 ms, stays as the measured reference. Under a finger, a tapped row commits its value when its turn ends; a keyboard or assistive-technology activation commits at once. Implementation gap: under a finger, the turn and a tapped row's turn still play `picker.tapSpin.durationMs` on `timing.curves.move`; under a mouse, the turn plays the browser's smooth scroll. | UIDatePicker on the iOS 26.2 simulator; current source |
-| FR15 | Wherever the sheet shows, a sheet wheel's pan takes a trackpad's two-finger scroll, as `spec:AST-094` FR43 allows a record to grant: the rows follow the fingers, coast on at the lift with the fingers' last speed, the coast starting from that speed (`spec:AST-094` FR45), and rest on a row by FR13. A mouse-wheel notch turns the wheel one row, as an arrow key does, with no coast. A ctrl-scroll stays the page's zoom (`spec:AST-094` FR43). Implementation gap: a trackpad drives the wheel only under a coarse primary pointer. | `spec:AST-094` FR43; current source |
-| FR16 | Enter in the pointer field's text input commits typed text that has not been committed and is then held back, so a form never submits the value from before the commit. With no typed text pending, Enter is not prevented, so a form submits as it does from any text field, except on a disabled or busy field, where Enter does nothing (`spec:AST-085` FR2). |
-| FR17 | In a sheet wheel, Arrow, Page, Home and End move through the wheel's enabled values in time order, skipping disabled ones, and stop at the first or last enabled value; a key with no enabled value in its direction commits nothing, under every presentation. On a 12-hour hour wheel, time order follows the full time (12 PM comes before 1 PM), not the column's row order. | Owner decision (cixzhang, 2026-11-02); current source |
-| FR18 | Under a finger, while a wheel coasts, snaps or turns, no row carries the selection band's accent mark; the mark returns on the row that comes to rest, as UIPickerView does (`spec:AST-094` FR3). | Owner decision (cixzhang, 2026-11-02); UIDatePicker on the iOS 26.2 simulator; current source |
-| FR19 | The bottom-sheet calendar's weekday row MUST show the weekday names `component:Calendar` DD1 sets for the provider locale, in the order of the panes' day columns (`weekStartsOn`), so both pickers label a locale's columns alike. |
+| ID | Invariant | Basis |
+| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
+| FR1 | DateInput MUST present the controlled ISO `value` and emit `onChange` with the next ISO date or `undefined` without maintaining a competing committed value. | Current source, docs, and focused tests |
+| FR2 | The five `presentation` values MUST resolve to the fine/coarse surfaces in `spec:AST-043/FR1`, except as FR21 states for a calendar; omitting both presentation props MUST preserve `adaptive-native`. | `spec:AST-043/FR1–FR3`; Presentation tests |
+| FR3 | Explicit `presentation` MUST outrank deprecated `nativePicker`; the legacy values MUST retain their mappings and development-only warning from `spec:AST-043/FR3–FR4`. | Current source, docs, and Presentation tests |
+| FR4 | Adaptive resolution MUST use the primary pointer rather than viewport width or any-pointer availability, so tablets receive a touch surface and touchscreen laptops retain the typable field. | Current source, consumer docs, and surface-selection tests |
+| FR5 | Text, Calendar, bottom-sheet, and native commit paths MUST enforce `min`, `max`, and `dateConstraints`; a rejected value MUST NOT replace the controlled value. | Current source and all four focused suites |
+| FR6 | Named committed formats MUST follow the InternationalizationProvider locale, the resolved calendar (FR20), and the shared Timestamp vocabulary; formatting MUST NOT rewrite in-progress typed text. Typed text MUST parse in the provider locale (`architecture:internationalization` INV1a, INV8); in a day-first locale, numeric text outside the locale-ordered forms is not a date, so no fixed month-first reading applies. The touch sheet's month heading and each month pane's name are stand-alone month labels: they start with a capital where CLDR's stand-alone context transform titlecases the month, as `component:Calendar` FR1 states for Calendar's. Implementation gap: a four-digit year written first (`2026/01/12`) parses in every locale. | `architecture:internationalization`; current source, docs, locale tests; `spec:AST-043/FR5` |
+| FR7 | Every value-change path MUST call `onChange` before `changeAction`, present the proposed value optimistically, and expose one busy state while the Action is pending. | `family:input-fields/FR6`; current source and focused tests |
+| FR8 | The pointer field MUST open its Calendar from the input, calendar toggle, ArrowDown, or Alt+ArrowDown; Popover dismissal and focus return MUST remain owned by the shared Popover path. The open pointer Calendar stays open for a press on the field's input, clear button or label, or in the Calendar, and closes for a press elsewhere (`architecture:layer-runtime`) or for focus moving from anywhere in the field (its input, clear button or calendar toggle) to anything outside the field and the Calendar (`family:overlay-dismissal` AV4). | Current source, Popover composition, keyboard/focus tests |
+| FR9 | A pointer-surface Calendar selection MUST commit and close its Popover; a bottom-sheet Calendar selection MUST remain editable in the open sheet until Save closes the surface. | Current source and pointer/touch tests |
+| FR10 | Standalone mode MUST compose Field; admitted InputGroup mode MUST remove competing Field chrome while preserving name, description, value, keyboard, focus, and editing semantics. The field has no root styling props; `control*` reaches the control box on every surface, and `container*` reaches the Field box where one renders (in a horizontal-labels FormLayout none renders and `container*` warns; inside an InputGroup it is dropped) (`family:input-fields` FR10). The field height is the shared element size for its size and MUST grow with a set text size (`spec:AST-102` FR4). Implementation gap: the height is fixed. | `family:input-fields` FR3, FR10; `spec:AST-102` FR4; current source and tests |
+| FR11 | Clear MUST emit `undefined` through the ordinary change pipeline. The pointer and bottom-sheet surfaces restore field focus using their shipped timing; the native surface MUST NOT reclaim focus because doing so reopens the OS picker. Implementation gap: when the field becomes disabled or busy while its clear control holds focus, the control unmounts and focus falls to the document body; `spec:AST-085/FR4` requires focus to stay or move to a destination this record names. | Current source and focused clear tests; `spec:AST-085/FR4` |
+| FR12 | No surface renders native `disabled`. A disabled field MUST stay focusable with `aria-disabled`, block typing, picking, clearing, and opening, describe its disabled reason when one is given, and take disabled paint. While busy (`isLoading` or a pending Action) the pointer and bottom-sheet surfaces expose `aria-disabled` and `aria-busy`, stay focusable, and block new commits; the native surface does the same for `isLoading`, and during a pending Action stays editable so the OS picker remains attached but rejects additional commits until the Action settles. A busy field that is not disabled keeps its ordinary paint and Spinner, shows no hover ring while commits are blocked, and keeps its keyboard focus ring. While disabled or busy, the field ignores Enter and blur and shows no typed rejection. Typed text whose date typing has not reported stays, and the next Enter or blur once the field is editable commits or rejects it; a new `value` replaces it. Text whose date typing already reported through `onChange` gives way to the field's value once the field is editable again, whether or not the change took it; a focused field keeps the text until the next Enter or blur. Caller handlers other than focus and blur MUST NOT run while the field is disabled (`spec:AST-085` FR2). Implementation gap: only a caller `onClick` is skipped while disabled; caller key, paste, and pointer handlers (such as `onKeyDown`, `onKeyUp`, `onPaste`, and `onPointerDown`) still run on every surface, the native field included. | `spec:AST-085/FR1–FR6`; `family:input-fields/FR4–FR6`; `family:buttons/FR4`; current source and focused tests |
+| FR13 | A bottom-sheet picker wheel that comes to rest on a disabled row (outside `min`/`max`) MUST continue to the nearest enabled row, a tie going toward the committed row, and select it there. A wheel resting on its committed row MUST NOT select or commit, even when that row is outside the bounds, so opening a bounded sheet never changes an untouched value: a committed value outside the bounds stays, and an empty field stays empty. This holds for every wheel in the DateInput, TimeInput, and DateTimeInput sheets. | DEC-1; UIDatePicker on the iOS 26.2 simulator; current source |
+| FR14 | A shown bottom-sheet picker wheel whose value changes from outside, as when a bound clamps the time after another wheel turned, MUST turn onto the new row rather than jump to it, on the theme's move duration and easing tokens, as a tap on a row does (`spec:AST-094` FR45). The internal motion role `picker.tapSpin.durationMs`, UIKit's measured 300 ms, stays as the measured reference. Under a finger, a tapped row commits its value when its turn ends; a keyboard or assistive-technology activation commits at once. Implementation gap: under a finger, the turn and a tapped row's turn still play `picker.tapSpin.durationMs` on `timing.curves.move`; under a mouse, the turn plays the browser's smooth scroll. | UIDatePicker on the iOS 26.2 simulator; current source |
+| FR15 | Wherever the sheet shows, a sheet wheel's pan takes a trackpad's two-finger scroll, as `spec:AST-094` FR43 allows a record to grant: the rows follow the fingers, coast on at the lift with the fingers' last speed, the coast starting from that speed (`spec:AST-094` FR45), and rest on a row by FR13. A mouse-wheel notch turns the wheel one row, as an arrow key does, with no coast. A ctrl-scroll stays the page's zoom (`spec:AST-094` FR43). Implementation gap: a trackpad drives the wheel only under a coarse primary pointer. | `spec:AST-094` FR43; current source |
+| FR16 | Enter in the pointer field's text input commits typed text that has not been committed and is then held back, so a form never submits the value from before the commit. With no typed text pending, Enter is not prevented, so a form submits as it does from any text field, except on a disabled or busy field, where Enter does nothing (`spec:AST-085` FR2). |
+| FR17 | In a sheet wheel, Arrow, Page, Home and End move through the wheel's enabled values in time order, skipping disabled ones, and stop at the first or last enabled value; a key with no enabled value in its direction commits nothing, under every presentation. On a 12-hour hour wheel, time order follows the full time (12 PM comes before 1 PM), not the column's row order. | Owner decision (cixzhang, 2026-11-02); current source |
+| FR18 | Under a finger, while a wheel coasts, snaps or turns, no row carries the selection band's accent mark; the mark returns on the row that comes to rest, as UIPickerView does (`spec:AST-094` FR3). | Owner decision (cixzhang, 2026-11-02); UIDatePicker on the iOS 26.2 simulator; current source |
+| FR19 | The bottom-sheet calendar's weekday row MUST show the weekday names `component:Calendar` DD1 sets for the provider locale, in the order of the panes' day columns (`weekStartsOn`), so both pickers label a locale's columns alike. |
+| FR20 | The pointer field reads and writes typed dates in the resolved calendar (`spec:AST-111` FR2), and its Calendar shows that calendar. It reads the dates `Intl.DateTimeFormat` writes for the locale and calendar, in any Unicode decimal digits and with month and era names of the locale and English; in the Gregorian calendar, text that matches none of these forms, or that these forms read as a date the calendar does not have, still commits on Enter or blur when `parseDateInput` reads it, so `13/5/2026` in `en-US` commits as 13 May 2026 (`spec:AST-111` FR9). A typed year is a year of the calendar (`spec:AST-111` FR10). It rejects a date the calendar does not have and never adjusts it; a typed date outside `min`, `max`, or `dateConstraints` shows and announces an out-of-range error that writes the bounds in the calendar, and Enter or blur keeps both kinds of rejected text so the person can correct it, while unreadable text reverts (`spec:AST-111` FR11). While a person types, `onChange` fires only for complete input, at most once for each distinct value in one typing session, and a one-digit day stays open until another digit, Enter, or blur, so a day the month lacks is never reported as another date; a two-digit year and input without a year commit on Enter or blur, in every calendar system, and a year of one or three digits is not a date: like other text the field cannot finish, Enter or blur keeps it and shows the unreadable message as the field status (`spec:AST-111` FR12, AR3). Each rejection is announced once: a shown status announces itself, and the field's alert carries only a rejection that no status shows. `date`, `date_long`, and `date_weekday` write the committed text in the calendar and read back as the same date; `system_date` stays Gregorian ISO and the field reads ISO input with it (`spec:AST-111` FR13). Text from a custom `format` function that the field cannot read back cannot be re-committed after an edit (`spec:AST-111` FR14). Values stay Gregorian ISO dates (`spec:AST-111` FR3). | `spec:AST-111` FR3, FR9–FR14; current source; parser, round-trip, and calendar typed-entry tests |
+| FR21 | With a calendar other than `gregory` or `iso8601`, every presentation that would show the native control — `adaptive-native`, the default, deprecated `touch` and `always`, and an explicit `native` — shows the popover on a fine pointer and the bottom sheet on a coarse pointer, because the native control is Gregorian (`spec:AST-111` FR15). An explicit `native` also warns once in development. The bottom sheet shows months of the calendar: each scroller pane lays out one calendar month with calendar labels and day names and the locale's digits, as `component:Calendar` shows it, and every pane keeps the six-row height, including the five- or six-day thirteenth month of the Coptic and Ethiopic calendars. The month wheel lists the months of the selected calendar year, leap months by name; a year change keeps the month when the new year has it and otherwise moves to its common counterpart (Adar I becomes Adar); year labels carry the era where the calendar has one, such as `令和8`, and a year whose first and last days fall in different eras keeps one row, labeled with the era year of the date the wheels show: that year, the selected month, and the day the picker keeps, clamped to the month, else the month's first day. So 2019 reads `平成31` with January selected and `令和元` with July, and the row's text and accessible name change as the month wheel turns, while its size stays the same. The month and year heading takes its era from the same date when the shown month spans an era change, so January 1989 reads `昭和64年1月` for a kept day of 3; every other heading names the era of the month's middle day. A pane's grid name always takes the era of its month's middle day, so that pane reads `平成元年1月`. The closed sheet field writes the committed text in the calendar (`spec:AST-111` FR16). Values stay Gregorian ISO dates (`spec:AST-111` FR3). | `spec:AST-111` FR3, FR15, FR16; current source; calendar presentation, touch calendar, and no-`Temporal` tests |
### Allowed variation
@@ -185,7 +207,8 @@ Consumer migration instructions belong in consumer docs and release notes.
| empty rest | Labelled field shows the placeholder and calendar affordance without a committed value. | Label, placeholder, size, width |
| committed rest | Field displays the controlled value in the selected committed format. | Format and locale |
| typing | Raw typed text remains visible until commit or reversion. | Parseable text form and locale |
-| invalid typed text | Field reflects invalid state, announces the error, and preserves the prior committed value. | Invalid text |
+| calendar | Every surface shows the resolved calendar, and the native control gives way to the popover or bottom sheet outside `gregory` and `iso8601`; values stay Gregorian ISO. | Calendar, locale, digits |
+| invalid typed text | Field reflects invalid state, announces the error, and preserves the prior committed value. A date the calendar does not have, or one out of range, also shows its message and stays in the field after Enter or blur. | Rejection kind |
| constrained date | Unreachable dates cannot commit on any surface. | Bound or predicate source |
| popover open | Input reflects expanded dialog state and the Calendar is reachable by pointer and keyboard. | Month count and week start |
| bottom sheet open | Touch calendar remains open across date corrections until Save. | Visible month and wheel state |
@@ -199,13 +222,17 @@ Consumer migration instructions belong in consumer docs and release notes.
### Transformation and precedence order
- **ORD1 — Surface.** Resolve explicit `presentation`; otherwise map deprecated
- `nativePicker`; otherwise use `adaptive-native`; then resolve adaptive values from
- the primary pointer.
+ `nativePicker`; otherwise use `adaptive-native`; with a calendar other than
+ `gregory` or `iso8601`, use `adaptive-bottom-sheet` in place of `native` and
+ `adaptive-native` (FR21); then resolve adaptive values from the primary
+ pointer.
- **ORD2 — Display.** While editing, display pending typed text; otherwise format the
- controlled or optimistic ISO value with the selected format and provider locale.
+ controlled or optimistic ISO value with the selected format, provider locale, and
+ resolved calendar.
- **ORD3 — Commit.** Parse or receive the proposed date, reject it when constrained,
call `onChange`, then start `changeAction` with the same proposed value and busy
- presentation.
+ presentation. Typed text proposes a date while typing only when it is complete,
+ and on Enter or blur otherwise (FR20).
- **ORD4 — Clear.** Emit `undefined` through ORD3, then apply the selected surface's
shipped focus policy: pointer and bottom-sheet fields reclaim focus, while the native
field does not reopen the OS picker.
@@ -233,7 +260,10 @@ Consumer migration instructions belong in consumer docs and release notes.
composition, and focus is not reclaimed from an intentional destination.
- **AR3 — Validation.** Invalid typed or native selections are exposed without color
alone; rejected typed input uses an assertive alert and native rejection remains
- described to assistive technology.
+ described to assistive technology. Unreadable text, a date the calendar does not
+ have, and an out-of-range date each announce a different catalog message
+ (`spec:AST-111` AR3); the last two also show it as the field's error status,
+ in place of a caller `status` while the rejected text stays.
- **AR4 — Disabled and busy focus.** A disabled or busy field remains focusable and
exposes its state on the focused control (`spec:AST-085/FR1, FR5`); a disabled
reason, when given, describes the field's focusable controls while all value
@@ -258,6 +288,16 @@ Consumer migration instructions belong in consumer docs and release notes.
by a year, as in the APG date picker dialog. Implementation gap: PageUp and
PageDown do not page by a month, and Shift+PageUp and Shift+PageDown do not
move by a year.
+- **AR9 — The field names its calendar** (`spec:AST-111` AR2). The pointer
+ field's accessible description names the calendar only when the field's
+ resolved calendar differs from the provider's resolved calendar, else
+ `gregory`; `gregory` and `iso8601` count as one calendar. Both are compared after the Gregorian fallback for a runtime
+ without `Temporal`, so a calendar that falls back compares as `gregory`. With a
+ calendar other than `gregory` or `iso8601` and no caller `placeholder`, the
+ empty focused field shows an example date in the calendar's numeric pattern as
+ its placeholder; a caller `placeholder` shows in every state and replaces the
+ hint. The example date is today when the field accepts it, else the nearest
+ date it accepts.
## Design relationships
@@ -320,33 +360,64 @@ clear-glyph target of its own.
- `architecture:interaction-modality` owns input-modality principles; DateInput uses
the primary pointer to choose an interaction surface rather than a width breakpoint.
- `architecture:public-component-api` owns the package/export and public-prop boundary.
+- `spec:AST-111` owns calendar selection, the supported calendars, Gregorian ISO
+ values, the `Temporal` boundary, typed entry, and presentations in a
+ calendar; FR20, FR21, AR3, and AR9 project its FR3, FR9–FR16, AR2, and AR3. `component:Calendar` owns the
+ popover grid in the calendar.
+
+### `spec:AST-013` FR12 exception — calendars that need `Temporal`
+
+- **Capability:** typed entry, committed text, and the bottom sheet in
+ calendars other than `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese`,
+ which need the runtime's `Temporal`.
+- **Reduction:** where `Temporal` is missing, as in Safari on macOS and iOS,
+ the field reads, writes, and shows Gregorian dates, its presentations resolve
+ as they do for `gregory`, and it warns once in development, naming a polyfill
+ (`spec:AST-111` FR5). An application that loads a
+ `Temporal` polyfill gets the full calendar. When a server and a browser use
+ `chinese` or `dangi` implementations that disagree on a month start, React
+ renders the differing text again on the client (`spec:AST-111` FR19).
+- **Preserved obligations:** `spec:AST-013` FR7 and FR8, and FR9 outside that
+ `chinese` and `dangi` case. The Gregorian field keeps every interaction,
+ label, and announcement, and Buddhist, Minguo, and Japanese entry and bottom
+ sheets work without `Temporal`.
+- **Evidence:** real Chromium and Firefox typing in Persian, Hebrew, Japanese,
+ and Buddhist fields with native `Temporal`, with `Temporal` removed and a
+ polyfill loaded, and with `Temporal` removed and no polyfill; the Persian
+ bottom sheet, the Hebrew wheels in a leap year, and the Japanese era wheel in
+ real Chromium, Firefox, and WebKit in the same three modes.
+- **Owner:** `nynexman4464`.
+- **Review condition:** Safari ships `Temporal`.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
-| FR1, ORD2 | `DateInput.test.tsx` "displays formatted date when value is provided", "calls onChange on blur when input is valid", "calls onChange with undefined when input is cleared and blurred", "clears pending input when value changes externally"; `NativeDateField.test.tsx` "keeps the control's own value ISO", "fires onChange with the ISO date the control reports" | Typed, cleared, external value; native | A committed value kept beside `value`, a non-ISO change, or pending text that survives an external change fails. | `audit:DateInput/behavior` |
-| FR2, FR3, FR4, ORD1 | `Presentation.test.tsx` cases; `DateInputTouch.test.tsx` surface-selection cases; `NativeDateField.test.tsx` nativePicker cases | Each presentation on fine and coarse pointers; deprecated mappings; tablet and touchscreen laptop | A wrong surface, a lost deprecated mapping, `nativePicker` winning, or width-based resolution fails. Evidence gap: no test asserts the development warning. | `audit:DateInput/behavior` |
-| FR5 | `DateInput.test.tsx` min, max, and dateConstraints typed cases; `DateInputTouch.test.tsx` "disables days outside min/max and refuses to commit them", "honors custom date constraints"; `NativeDateField.test.tsx` "refuses an out-of-range date and announces it", "refuses a date dateConstraints rejects" | Typed, sheet, native; bounds and predicates | A constrained date that commits on any surface fails. Evidence gap: no test asserts constraints on a popover Calendar pick. | `audit:DateInput/behavior` |
-| FR6 | `DateInput.test.tsx` format cases, including "updates when the InternationalizationProvider locale changes (#5074)" and "does not apply format to in-progress typed input" and "typing a day-first date in en-GB never reports a month-first date"; `dateParser.test.ts` "in a day-first locale, never reads numeric text month-first outside the locale-ordered forms"; `NativeDateField.test.tsx` format and locale cases; `DateInputTouch.test.tsx` "updates the field and open picker when the provider locale changes" | Named and function formats; locale change | A format that ignores the locale or rewrites typed text fails. Evidence gap: no test types a localized month name or non-ASCII digits (the FR6 gap). | `audit:DateInput/i18n` |
-| FR7, ORD3 | `DateInput.test.tsx` "runs changeAction after onChange for a typed date"; `NativeDateField.test.tsx` "runs changeAction after onChange and exposes the pending state"; `DateInputTouch.test.tsx` "runs changeAction and shows a busy state"; `BusyOwnerAnnouncement.test.tsx` DateInput cases; `DateInputTouch.test.tsx` "announces a busy start from a pick inside the open sheet, not behind it (spec:AST-086 FR8, Platform support)" | Typed, native, sheet | An Action before `onChange`, a missing busy state, or a missing busy announcement fails. | `audit:DateInput/behavior` |
-| FR8, AR2 | `DateInput.test.tsx` "opens the calendar popover on ArrowDown (keyboard, forms-13)", "opens the calendar popover on Alt+ArrowDown (keyboard, forms-13)", "input has aria-expanded attribute", "combobox input has aria-haspopup=\"dialog\" attribute", "moves focus into the calendar on each open from the toggle"; `DateInputTouch.test.tsx` "opens from the keyboard, APG combobox style"; `DateInput.test.tsx` "press inside and outside the open calendar" cases | Pointer and touch fields | A missing open path, combobox state, or focus move fails. Evidence gap: no test asserts Escape outside IME composition on the popover. | `audit:DateInput/accessibility` |
-| FR9 | `DateInputTouch.test.tsx` "commits the tapped day and LEAVES the sheet open", "lets a second tap correct the first, still without closing", "Save closes the sheet without touching the value" | Sheet picks and Save | A sheet that closes on a pick or a Save that changes the value fails. Evidence gap: no test asserts that a popover Calendar pick closes the popover. | `audit:DateInput/behavior` |
-| FR10 | `DateInput.fr10.test.tsx` styling and per-surface cases ("has no root styling props and has the container* and control* parts", "rejects root xstyle, className, and style at compile time", "keeps control* on the control box in a horizontal-labels FormLayout") and handler-composition cases; `DateInput.test.tsx` InputGroup cases; `DateInputTouch.test.tsx` "drops the Field wrapper inside an InputGroup" | Standalone, grouped, horizontal labels; every surface | A root styling prop, `control*` off the control box, or Field chrome inside a group fails. Evidence gap: no test asserts the field height or its growth with text size (the FR10 gap). | `audit:DateInput/layout` |
-| FR11, ORD4 | `DateInput.test.tsx` hasClear cases; `DateInputTouch.test.tsx` "clears from the field", "returns focus to the field without letting the page scroll"; `NativeDateField.test.tsx` "clears the value without taking focus back", "runs clear through changeAction after onChange" | Pointer, sheet, native clear | A clear that does not emit `undefined`, a native clear that takes focus, or a clear shown while disabled fails. Evidence gap: no test covers the clear control unmounting under focus (the FR11 gap). | `audit:DateInput/behavior` |
-| FR12, AR4 | `DateInput.test.tsx` disabled, loading, and disabledMessage cases (including "does not call a caller onClick while disabled (AST-085 FR2)" and "links the reason tooltip from the calendar button too (AST-085 FR5)"); `DateInputTouch.test.tsx` open-sheet disablement and disabled cases; `NativeDateField.test.tsx` "keeps a disabled control focusable and its toggle inert (AST-085 FR1, FR2)", "does not call a caller onClick while disabled (AST-085 FR2)"; `DateInput.test.tsx` disabled theme-state cases | Disabled with and without a reason; loading; open picker becoming disabled | Native `disabled`, a change or open while disabled, a caller `onClick` while disabled, a reason not linked from each focusable control, or a missing `aria-busy` fails. Evidence gap: no test asserts that caller key, paste, or pointer handlers are skipped while disabled (the FR12 gap) or the busy-only paint. | `audit:DateInput/accessibility` |
-| AR1, AR3, AR5 | `DateInput.test.tsx` label, required, description, status, and invalid-input cases ("announces an alert message when typed input is invalid", "resolves the invalid-date announcement from the i18n catalog"); `NativeDateField.test.tsx` "keeps the overlay out of the accessibility tree", "keeps the field labelled, required-marked, and ref-forwarded"; `DateInputTouch.test.tsx` "associates the label natively, so the field is named without ARIA" | Every surface | A missing label, required, description, status, or invalid announcement, or an exposed native overlay, fails. | `audit:DateInput/accessibility` |
-| AR6, AR8, PR1 | `DateInputTouch.test.tsx` calendar-surface cases ("mounts a window of months around the visible one, not the whole century", "leaves exactly one day per month tab-reachable", "gives a spilled date no tab stop in the pane that borrows it", "moves keyboard focus by date, across the month boundary", "follows the reading direction under RTL: ArrowLeft moves to the next day", "moves a week at a time with the vertical arrows", "labels the columns with three-letter weekday names", "marks the selection and today") and wheel cases ("is a single tab stop driven by the arrow keys", "shows exactly one footer action, and only the visible one is reachable") | Touch calendar and wheels; RTL | A second Tab stop per month, a wrong arrow move, reversed RTL arrows, an unbounded month window, or more than one reachable footer action fails. Evidence gap: no test asserts Home, End, PageUp, PageDown, Shift+PageUp, Shift+PageDown (the AR8 gap), or Enter and Space on a day. | `audit:DateInput/accessibility` |
-| AR7 | `apps/storybook/rtl-audit/targets.json` DateInput entry; `DateInputTouch.test.tsx` RTL scroll-offset cases | RTL | A changed audit target or RTL offset fails. | `audit:DateInput/rtl` |
-| PR2 | `MonthScrollerSettle.test.tsx` cases; `DateInputTouch.test.tsx` "a rest position between two months" cases | Settle and re-snap | A scroller that never settles or corrects mid-gesture fails. Evidence gap: no test asserts listener, frame, and observer cleanup on unmount, drags a month pager, or counts the visible-month reports per half-month (the PR2 gap). | `audit:DateInput/behavior` |
-| FR13 | `Wheel.test.tsx`, the wheel every sheet renders: "stopping below the minimum travels on to the minimum and commits it there", "stopping past the maximum travels back to the maximum", "a stop on another disabled row still travels to the bounds", "opening on a value outside the bounds parks on it without travelling or committing", "a drag that comes back to rest on a committed value outside the bounds stays there and commits nothing", "never commits a disabled row, even with nowhere valid to go", and `nearestEnabledIndex` "breaks a tie toward the committed row"; `PickerWheel.test.tsx`, the wheel under a finger: "turns on to the minimum after resting below it, and commits that", "opening on a value outside the bounds commits nothing", "rests back on a committed value outside the bounds and commits nothing"; `WheelRest.a11y.chromium.spec.ts` in the TimeInput sheet: "a wheel dragged below the minimum comes to rest on the minimum", "a wheel dragged onto a row inside the bounds commits that row"; `DateInputTouch.test.tsx` "bounds the year wheel to the reachable range" (rows outside the bounds are disabled). | Below the minimum, above the maximum, on another disabled row; opened on a value outside the bounds and rested back on it after a drag; DateInput, TimeInput, and DateTimeInput sheets | A wheel that returns to its committed row, skips the nearest enabled row, breaks a tie away from the committed row, or commits on opening or on a rest back on its committed row fails. | `audit:DateInput/behavior` |
-| FR14 | `Wheel.test.tsx` "turns onto a value set while it is shown, as a bound clamping the time after another wheel turned"; `WheelRest.a11y.chromium.spec.ts` in the TimeInput sheet: "a meridiem change past the maximum turns the hour wheel onto it, frame by frame"; `PickerWheel.test.tsx`, the wheel under a finger: "turns the wheel onto its row, as a bound clamping the time", "turns on from where the wheel is drawn when the value changes again during that turn", "plays a tapped row’s turn on the tap spin’s motion role", "turns onto a tapped row and commits it on arrival", "commits each arrow key at once, stepping from the row it is heading to", "commits a clicked row at once and never a disabled one". | A bound clamping the value of a shown wheel after another wheel turned, in DateInput, TimeInput, and DateTimeInput sheets; a tapped row, an arrow key and a row click | A wheel that jumps to the new row fails, and so does a tap that commits at the lift, or a key or click that waits for a turn. | `audit:DateInput/behavior` |
-| FR15 | `WheelPinchZoom.a11y.chromium.spec.ts` "a pinch over an open picker wheel zooms the page and changes no value"; `DateInputTouch.test.tsx` "leaves a two-finger pinch to the page over the wheels". `PickerWheel.test.tsx` "follows a trackpad’s fingers, coasts on at their lift and rests on a row, as a finger’s flick does", "rests on the nearest row after a slow trackpad drag that stops, without coasting", "turns one row for a mouse wheel’s notch, as an arrow key does, with no coast", "turns three rows for three notches, one each", "leaves a ctrl-wheel, a trackpad pinch, to the page"; `Wheel.interaction.browser.spec.ts` "one mouse-wheel notch turns the touch column one row, as an arrow key does; three turn it three" (Chromium) and the trackpad flick and slow stopped drag (WebKit, whose driver sends a trackpad's deltas). | A trackpad scroll and its lift; a slow stopped trackpad drag; one and three mouse-wheel notches; a ctrl-scroll over an open wheel | A trackpad scroll that does not follow, a lift that stops dead or coasts at the browser's rate, a notch that turns more or less than one row or coasts, or a ctrl-scroll that turns the wheel fails. | `audit:DateInput/behavior` |
-| FR16 | `DateInput.test.tsx` "Enter submits the form when nothing is typed, and commits typed text without submitting" "Enter on a disabled field does not submit the form" and "Enter on a busy field does not submit the form" | Nothing typed; typed text; disabled; busy (`isLoading`) | An Enter that is prevented with nothing typed, or that submits before typed text commits, fails. | — |
-| FR17 | `TimeInput/Presentation.test.tsx`: "at a 12:00–17:00 bound, ArrowDown from 5 PM commits nothing and ArrowDown from 12 PM commits 1 PM, under a finger", "… under a mouse". `Wheel.test.tsx`, the column under a mouse, and `PickerWheel.test.tsx`, the wheel under a finger: "at a 12:00–17:00 bound, moves a key to the next enabled row and stops at the last one", "at a 12:00–17:00 bound on a 12-hour hour wheel, steps in time order: nothing after 5 PM, and 1 PM after 12 PM", "moves a key from a row outside the bounds onto the first enabled row in its direction". | At a 12:00–17:00 bound, ArrowDown from 5 PM commits nothing and ArrowDown from 12 PM commits 1 PM, under a finger and a mouse | A key that commits a disabled value, leaves time order, or strands 12 PM fails. | `audit:DateInput/behavior` |
-| FR18 | `PickerWheel.test.tsx` "marks no row while a fling coasts, then the row it rests on", "marks no row while the wheel snaps or turns, then the row it rests on". | A fling's coast, a slow release's snap and a key's turn, each to its rest | A row that carries the band's accent mark while the wheel moves, or a rest with no marked row, fails. | `audit:DateInput/behavior` |
-| FR19 | `DateInputTouch.test.tsx` "labels the columns with three-letter weekday names", "labels the columns in %s with the same names as the Calendar header" for `fr-FR`, `pt-PT`, `pl-PL`, and `id-ID`, "rotates the weekday header with weekStartsOn" | English; a locale within Calendar DD1's four-character limit; locales above it; a locale with no shipped weekday data; `weekStartsOn` rotation | A weekday row that differs from the Calendar header names for the same locale, or that does not rotate with `weekStartsOn`, fails. | — |
-| Theming anatomy | `DateInput.test.tsx` clear-icon and calendar-toggle icon theme-target cases; `themingTargets.test.ts`; `scripts/check-knowledge.mjs` | Toggle, clear glyph, disabled root | A missing or moved target, or a stale anatomy mapping, fails. | `audit:DateInput/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
+| FR1, ORD2 | `DateInput.test.tsx` "displays formatted date when value is provided", "calls onChange on blur when input is valid", "calls onChange with undefined when input is cleared and blurred", "clears pending input when value changes externally"; `NativeDateField.test.tsx` "keeps the control's own value ISO", "fires onChange with the ISO date the control reports" | Typed, cleared, external value; native | A committed value kept beside `value`, a non-ISO change, or pending text that survives an external change fails. | `audit:DateInput/behavior` |
+| FR2, FR3, FR4, ORD1 | `Presentation.test.tsx` cases; `DateInputTouch.test.tsx` surface-selection cases; `NativeDateField.test.tsx` nativePicker cases | Each presentation on fine and coarse pointers; deprecated mappings; tablet and touchscreen laptop | A wrong surface, a lost deprecated mapping, `nativePicker` winning, or width-based resolution fails. Evidence gap: no test asserts the development warning. | `audit:DateInput/behavior` |
+| FR5 | `DateInput.test.tsx` min, max, and dateConstraints typed cases; `DateInputTouch.test.tsx` "disables days outside min/max and refuses to commit them", "honors custom date constraints"; `NativeDateField.test.tsx` "refuses an out-of-range date and announces it", "refuses a date dateConstraints rejects" | Typed, sheet, native; bounds and predicates | A constrained date that commits on any surface fails. Evidence gap: no test asserts constraints on a popover Calendar pick. | `audit:DateInput/behavior` |
+| FR6 | `DateInput.test.tsx` format cases, including "updates when the InternationalizationProvider locale changes (#5074)" and "does not apply format to in-progress typed input" and "typing a day-first date in en-GB never reports a month-first date"; `dateParser.test.ts` "in a day-first locale, never reads numeric text month-first outside the locale-ordered forms"; `NativeDateField.test.tsx` format and locale cases; `DateInputTouch.test.tsx` "updates the field and open picker when the provider locale changes"; `calendarDateParser.test.ts` "reads month and era names of the locale and English, in every width", "reads any Unicode decimal digits, in mixed scripts" | Named and function formats; locale change; localized month names and digits | A format that ignores the locale or rewrites typed text, or a localized committed value that cannot be retyped, fails. | `audit:DateInput/i18n` |
+| FR7, ORD3 | `DateInput.test.tsx` "runs changeAction after onChange for a typed date"; `NativeDateField.test.tsx` "runs changeAction after onChange and exposes the pending state"; `DateInputTouch.test.tsx` "runs changeAction and shows a busy state"; `BusyOwnerAnnouncement.test.tsx` DateInput cases; `DateInputTouch.test.tsx` "announces a busy start from a pick inside the open sheet, not behind it (spec:AST-086 FR8, Platform support)" | Typed, native, sheet | An Action before `onChange`, a missing busy state, or a missing busy announcement fails. | `audit:DateInput/behavior` |
+| FR8, AR2 | `DateInput.test.tsx` "opens the calendar popover on ArrowDown (keyboard, forms-13)", "opens the calendar popover on Alt+ArrowDown (keyboard, forms-13)", "input has aria-expanded attribute", "combobox input has aria-haspopup=\"dialog\" attribute", "moves focus into the calendar on each open from the toggle"; `DateInputTouch.test.tsx` "opens from the keyboard, APG combobox style"; `DateInput.test.tsx` "press inside and outside the open calendar" cases | Pointer and touch fields | A missing open path, combobox state, or focus move fails. Evidence gap: no test asserts Escape outside IME composition on the popover. | `audit:DateInput/accessibility` |
+| FR9 | `DateInputTouch.test.tsx` "commits the tapped day and LEAVES the sheet open", "lets a second tap correct the first, still without closing", "Save closes the sheet without touching the value" | Sheet picks and Save | A sheet that closes on a pick or a Save that changes the value fails. Evidence gap: no test asserts that a popover Calendar pick closes the popover. | `audit:DateInput/behavior` |
+| FR10 | `DateInput.fr10.test.tsx` styling and per-surface cases ("has no root styling props and has the container* and control* parts", "rejects root xstyle, className, and style at compile time", "keeps control* on the control box in a horizontal-labels FormLayout") and handler-composition cases; `DateInput.test.tsx` InputGroup cases; `DateInputTouch.test.tsx` "drops the Field wrapper inside an InputGroup" | Standalone, grouped, horizontal labels; every surface | A root styling prop, `control*` off the control box, or Field chrome inside a group fails. Evidence gap: no test asserts the field height or its growth with text size (the FR10 gap). | `audit:DateInput/layout` |
+| FR11, ORD4 | `DateInput.test.tsx` hasClear cases; `DateInputTouch.test.tsx` "clears from the field", "returns focus to the field without letting the page scroll"; `NativeDateField.test.tsx` "clears the value without taking focus back", "runs clear through changeAction after onChange" | Pointer, sheet, native clear | A clear that does not emit `undefined`, a native clear that takes focus, or a clear shown while disabled fails. Evidence gap: no test covers the clear control unmounting under focus (the FR11 gap). | `audit:DateInput/behavior` |
+| FR12, AR4 | `DateInput.test.tsx` disabled, loading, and disabledMessage cases (including "does not call a caller onClick while disabled (AST-085 FR2)" and "links the reason tooltip from the calendar button too (AST-085 FR5)"); `DateInputTouch.test.tsx` open-sheet disablement and disabled cases; `NativeDateField.test.tsx` "keeps a disabled control focusable and its toggle inert (AST-085 FR1, FR2)", "does not call a caller onClick while disabled (AST-085 FR2)"; `DateInput.test.tsx` disabled theme-state cases | Disabled with and without a reason; loading; open picker becoming disabled | Native `disabled`, a change or open while disabled, a caller `onClick` while disabled, a reason not linked from each focusable control, or a missing `aria-busy` fails. Evidence gap: no test asserts that caller key, paste, or pointer handlers are skipped while disabled (the FR12 gap) or the busy-only paint. | `audit:DateInput/accessibility` |
+| FR12 | `DateInput.test.tsx` "typed text while the field is disabled or busy" cases and "keeps a cleared draft without committing it when the field becomes disabled (AST-085 FR2)" | `isLoading`, `isDisabled`, and a `changeAction` save that takes or fails; unfinished, valid, reported, and cleared text; shown rejection; new `value` | A commit, `onChange`, reset, or rejection while disabled or busy, a rejection that does not return once editable, typed text that outlives a new `value`, or reported text that outlives the lock fails. | `audit:DateInput/behavior` |
+| AR1, AR3, AR5 | `DateInput.test.tsx` label, required, description, status, and invalid-input cases ("announces an alert message when typed input is invalid", "resolves the invalid-date announcement from the i18n catalog"); `NativeDateField.test.tsx` "keeps the overlay out of the accessibility tree", "keeps the field labelled, required-marked, and ref-forwarded"; `DateInputTouch.test.tsx` "associates the label natively, so the field is named without ARIA" | Every surface | A missing label, required, description, status, or invalid announcement, or an exposed native overlay, fails. | `audit:DateInput/accessibility` |
+| AR6, AR8, PR1 | `DateInputTouch.test.tsx` calendar-surface cases ("mounts a window of months around the visible one, not the whole century", "leaves exactly one day per month tab-reachable", "gives a spilled date no tab stop in the pane that borrows it", "moves keyboard focus by date, across the month boundary", "follows the reading direction under RTL: ArrowLeft moves to the next day", "moves a week at a time with the vertical arrows", "labels the columns with three-letter weekday names", "marks the selection and today") and wheel cases ("is a single tab stop driven by the arrow keys", "shows exactly one footer action, and only the visible one is reachable") | Touch calendar and wheels; RTL | A second Tab stop per month, a wrong arrow move, reversed RTL arrows, an unbounded month window, or more than one reachable footer action fails. Evidence gap: no test asserts Home, End, PageUp, PageDown, Shift+PageUp, Shift+PageDown (the AR8 gap), or Enter and Space on a day. | `audit:DateInput/accessibility` |
+| AR7 | `apps/storybook/rtl-audit/targets.json` DateInput entry; `DateInputTouch.test.tsx` RTL scroll-offset cases | RTL | A changed audit target or RTL offset fails. | `audit:DateInput/rtl` |
+| PR2 | `MonthScrollerSettle.test.tsx` cases; `DateInputTouch.test.tsx` "a rest position between two months" cases | Settle and re-snap | A scroller that never settles or corrects mid-gesture fails. Evidence gap: no test asserts listener, frame, and observer cleanup on unmount, drags a month pager, or counts the visible-month reports per half-month (the PR2 gap). | `audit:DateInput/behavior` |
+| FR13 | `Wheel.test.tsx`, the wheel every sheet renders: "stopping below the minimum travels on to the minimum and commits it there", "stopping past the maximum travels back to the maximum", "a stop on another disabled row still travels to the bounds", "opening on a value outside the bounds parks on it without travelling or committing", "a drag that comes back to rest on a committed value outside the bounds stays there and commits nothing", "never commits a disabled row, even with nowhere valid to go", and `nearestEnabledIndex` "breaks a tie toward the committed row"; `PickerWheel.test.tsx`, the wheel under a finger: "turns on to the minimum after resting below it, and commits that", "opening on a value outside the bounds commits nothing", "rests back on a committed value outside the bounds and commits nothing"; `WheelRest.a11y.chromium.spec.ts` in the TimeInput sheet: "a wheel dragged below the minimum comes to rest on the minimum", "a wheel dragged onto a row inside the bounds commits that row"; `DateInputTouch.test.tsx` "bounds the year wheel to the reachable range" (rows outside the bounds are disabled). | Below the minimum, above the maximum, on another disabled row; opened on a value outside the bounds and rested back on it after a drag; DateInput, TimeInput, and DateTimeInput sheets | A wheel that returns to its committed row, skips the nearest enabled row, breaks a tie away from the committed row, or commits on opening or on a rest back on its committed row fails. | `audit:DateInput/behavior` |
+| FR14 | `Wheel.test.tsx` "turns onto a value set while it is shown, as a bound clamping the time after another wheel turned"; `WheelRest.a11y.chromium.spec.ts` in the TimeInput sheet: "a meridiem change past the maximum turns the hour wheel onto it, frame by frame"; `PickerWheel.test.tsx`, the wheel under a finger: "turns the wheel onto its row, as a bound clamping the time", "turns on from where the wheel is drawn when the value changes again during that turn", "plays a tapped row’s turn on the tap spin’s motion role", "turns onto a tapped row and commits it on arrival", "commits each arrow key at once, stepping from the row it is heading to", "commits a clicked row at once and never a disabled one". | A bound clamping the value of a shown wheel after another wheel turned, in DateInput, TimeInput, and DateTimeInput sheets; a tapped row, an arrow key and a row click | A wheel that jumps to the new row fails, and so does a tap that commits at the lift, or a key or click that waits for a turn. | `audit:DateInput/behavior` |
+| FR15 | `WheelPinchZoom.a11y.chromium.spec.ts` "a pinch over an open picker wheel zooms the page and changes no value"; `DateInputTouch.test.tsx` "leaves a two-finger pinch to the page over the wheels". `PickerWheel.test.tsx` "follows a trackpad’s fingers, coasts on at their lift and rests on a row, as a finger’s flick does", "rests on the nearest row after a slow trackpad drag that stops, without coasting", "turns one row for a mouse wheel’s notch, as an arrow key does, with no coast", "turns three rows for three notches, one each", "leaves a ctrl-wheel, a trackpad pinch, to the page"; `Wheel.interaction.browser.spec.ts` "one mouse-wheel notch turns the touch column one row, as an arrow key does; three turn it three" (Chromium) and the trackpad flick and slow stopped drag (WebKit, whose driver sends a trackpad's deltas). | A trackpad scroll and its lift; a slow stopped trackpad drag; one and three mouse-wheel notches; a ctrl-scroll over an open wheel | A trackpad scroll that does not follow, a lift that stops dead or coasts at the browser's rate, a notch that turns more or less than one row or coasts, or a ctrl-scroll that turns the wheel fails. | `audit:DateInput/behavior` |
+| FR16 | `DateInput.test.tsx` "Enter submits the form when nothing is typed, and commits typed text without submitting" "Enter on a disabled field does not submit the form" and "Enter on a busy field does not submit the form" | Nothing typed; typed text; disabled; busy (`isLoading`) | An Enter that is prevented with nothing typed, or that submits before typed text commits, fails. | — |
+| FR17 | `TimeInput/Presentation.test.tsx`: "at a 12:00–17:00 bound, ArrowDown from 5 PM commits nothing and ArrowDown from 12 PM commits 1 PM, under a finger", "… under a mouse". `Wheel.test.tsx`, the column under a mouse, and `PickerWheel.test.tsx`, the wheel under a finger: "at a 12:00–17:00 bound, moves a key to the next enabled row and stops at the last one", "at a 12:00–17:00 bound on a 12-hour hour wheel, steps in time order: nothing after 5 PM, and 1 PM after 12 PM", "moves a key from a row outside the bounds onto the first enabled row in its direction". | At a 12:00–17:00 bound, ArrowDown from 5 PM commits nothing and ArrowDown from 12 PM commits 1 PM, under a finger and a mouse | A key that commits a disabled value, leaves time order, or strands 12 PM fails. | `audit:DateInput/behavior` |
+| FR18 | `PickerWheel.test.tsx` "marks no row while a fling coasts, then the row it rests on", "marks no row while the wheel snaps or turns, then the row it rests on". | A fling's coast, a slow release's snap and a key's turn, each to its rest | A row that carries the band's accent mark while the wheel moves, or a rest with no marked row, fails. | `audit:DateInput/behavior` |
+| FR19 | `DateInputTouch.test.tsx` "labels the columns with three-letter weekday names", "labels the columns in %s with the same names as the Calendar header" for `fr-FR`, `pt-PT`, `pl-PL`, and `id-ID`, "rotates the weekday header with weekStartsOn" | English; a locale within Calendar DD1's four-character limit; locales above it; a locale with no shipped weekday data; `weekStartsOn` rotation | A weekday row that differs from the Calendar header names for the same locale, or that does not rotate with `weekStartsOn`, fails. | — |
+| FR20, AR3, AR9 | `calendarDateParser.test.ts` reading, year, rejection-kind, completeness, committed-text, and calendar-name cases; `calendarDateParser.roundtrip.test.ts` committed text and format hint of every calendar in its native locale, English, and Swedish, sampled from 1900 through 2100; `DateInput.calendar.test.tsx` ("reports one Persian date typed in Persian digits, only when complete", "reads a plain Adar in a Hebrew leap year as Adar II", "reads Japanese era dates and rejects a year outside its era", "rejects a date the calendar does not have and keeps it on blur", "shows an out-of-range error with the bounds in the calendar", "announces a different message for each kind of rejection", "fires once for a day-first date typed one key at a time", "commits Gregorian text that only parseDateInput reads, on blur only", "commits a day-first date that does not exist month-first, on blur only", "commits a month-first date that does not exist day-first, on blur", "never falls back to a month-first reading in a day-first locale", "keeps a one-digit year on %s and announces it as invalid", "reports no date while %s %s text grows to a day the month lacks", "reports a retyped date again after the caller keeps its value", "still rejects a Gregorian date that does not exist in either order", "never reads a date that does not exist in another calendar with parseDateInput", "shows a format hint in the empty focused field", "shows a caller placeholder instead of the format hint", "uses max when max is before today", "uses min when min is after today", "uses the nearest weekday when today is a disabled Saturday", "names the calendar in the description", "names no calendar when the field uses the provider calendar", "names the Gregorian calendar inside a Persian provider", "names no calendar for an iso8601 field in a Gregorian provider", "names the Persian calendar without a provider calendar"); real Chromium and Firefox typing with native `Temporal`, a polyfill, and no `Temporal` | Persian digits, Hebrew leap year, Japanese era change, Buddhist bounds, partial input, Gregorian day-first typing, a one-digit Gregorian year, no `Temporal` | A typed date reported before it is complete, an adjusted date, a failed round trip, Gregorian text that FR20 says commits failing to commit on blur, a one-digit year that commits or reverts silently, a rejection announced twice, a shared rejection message, a missing hint, a hint that replaces a caller placeholder, a hint example the field rejects, a calendar description that is missing or that repeats the provider's calendar, or a non-ISO value fails. Evidence gap: no WebKit run; no server render and hydrate test. | `audit:DateInput/behavior` |
+| FR21 | `DateInput.calendarPresentation.test.tsx` (every presentation and deprecated `nativePicker` value in Gregorian and Persian on fine and coarse pointers; "warns once when an explicit native cannot show the calendar"); `DateInputTouch.calendar.test.tsx` ("lays out a Persian month with its days, labels and locale digits", "shows Adar I and Adar II as separate months in a Hebrew leap year", "keeps six rows for the Ethiopic thirteenth month", "lists 13 months in a Hebrew leap year and 12 in a common year", "labels Japanese years with their era", and the month-model round trips); `calendarSystem.test.ts` `formatCalendarYearLabel` and `calendarYearSpansEras` cases (2019 in January and May, 1989 on January 3 and 22, 1926, 1912, and 2020); `DateInputTouch.calendar.test.tsx` "names the era of the shown month for a year with an era change" and the split-month heading cases (January 3, 1989; December 26, 1926); `calendarSystem.test.ts` `formatCalendarMonthLabel` kept-day cases; `DateInput.noTemporal.test.tsx`; real Chromium, Firefox, and WebKit bottom sheets and popovers with native `Temporal`, a polyfill, and no `Temporal` | Persian, Hebrew leap and common years, Ethiopic thirteenth month, Japanese eras, no `Temporal` | A native date control for a non-Gregorian calendar, a wheel with 12 months for a 13-month year, a pane of another height, a lost leap month, a missing era, a year with an era change labeled with an era other than that of the shown date, or a non-ISO value fails | `audit:DateInput/behavior` |
+| Theming anatomy | `DateInput.test.tsx` clear-icon and calendar-toggle icon theme-target cases; `themingTargets.test.ts`; `scripts/check-knowledge.mjs` | Toggle, clear glyph, disabled root | A missing or moved target, or a stale anatomy mapping, fails. | `audit:DateInput/theming` |
## Current-state impact
@@ -355,9 +426,6 @@ clear-glyph target of its own.
against `spec:AST-085` FR2.
- **Fixed field height (FR10).** The field holds the shared element height
instead of growing with a set text size, against `spec:AST-102` FR4.
-- **English-only typed parser (FR6).** Typed dates parse only English month
- names and ASCII digits, so a localized committed value cannot be retyped as
- shown, against `architecture:internationalization` INV1a and INV8.
- **Clear control under focus (FR11).** A clear control that unmounts while
focused drops focus to the page, against `spec:AST-085` FR4.
- **Selection tick haptics.** Under a finger each row that reaches the band
diff --git a/docs/specs/components/DateRangeInput/DateRangeInput.spec.md b/docs/specs/components/DateRangeInput/DateRangeInput.spec.md
index e132c4dc9f..b8729eeb1b 100644
--- a/docs/specs/components/DateRangeInput/DateRangeInput.spec.md
+++ b/docs/specs/components/DateRangeInput/DateRangeInput.spec.md
@@ -13,6 +13,8 @@ review_triggers: [theming]
verified_by:
[
packages/core/src/DateRangeInput/DateRangeInput.test.tsx,
+ packages/core/src/DateRangeInput/DateRangeInput.calendar.test.tsx,
+ packages/core/src/Calendar/Calendar.calendarSystems.test.tsx,
packages/core/src/theme/themingTargets.test.ts,
packages/core/src/DateRangeInput/__tests__/DateRangeInputReflow.interaction.browser.spec.ts,
scripts/check-knowledge.mjs,
@@ -22,7 +24,7 @@ families: [family:input-fields, family:overlay-dismissal]
design_specs: []
architecture: [architecture:component-theming-surface]
contributing: []
-system_specs: [spec:AST-020]
+system_specs: [spec:AST-013/FR12, spec:AST-020, spec:AST-111]
---
# DateRangeInput component contract
@@ -32,10 +34,16 @@ system_specs: [spec:AST-020]
DateRangeInput presents one controlled date range through a labeled field surface.
Its trigger opens a Calendar-backed Popover and may include a list of quick-select
presets beside that calendar, or above it when the two do not fit side by side.
+The trigger text and the calendar show the application's calendar system, and
+the range stays Gregorian ISO dates.
## Compatibility and migration
- Released default preserved: `yes`; canonical DateRangeInput behavior is unchanged
+- The `calendar` prop is additive; it defaults to the provider's calendar, else
+ `gregory`, so a field without a provider calendar keeps its Gregorian text. A
+ provider locale with a `-u-ca-` keyword keeps Gregorian dates (`spec:AST-111`
+ DEC-2); set `calendar` to choose one
- 0.7.0 removes the `date-range-input-clear-icon` alias; the shared clear glyph
remains available through `input-clear-icon`
- The preset constraint correction remains unchanged
@@ -68,18 +76,23 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
-No public prop or value domain is added. This contract records the existing
-preset-list anatomy and its additive theming surface.
+| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid-value behavior |
+| -------- | --------------------------------------- | ------------------------------------------------------------------ | -------------------- | --------------------------------------------------------------------- | -------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
+| calendar | a `CalendarSystem` (`spec:AST-111` FR1) | The calendar system the trigger text and the popover Calendar show | Trigger and Calendar | the provider's resolved calendar, else `gregory` (`spec:AST-111` FR2) | `spec:AST-111` | stable | Resolves to `gregory` and warns once in development; a calendar that needs `Temporal` falls back to `gregory` where `Temporal` is missing |
+
+This contract also records the existing preset-list anatomy and its additive
+theming surface.
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Review state |
-| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | -------------------------- |
-| FR1 | DateRangeInput MUST present the controlled `value` and emit range changes without maintaining a competing selected range. | Current source, docs, and focused tests | Verified current behavior |
-| FR2 | When presets are present, each preset remains an independent button in one labeled group; the applied preset reflects current state and a preset whose endpoint violates `min`, `max`, or `dateConstraints`, or whose range violates `minRangeSpan` or `maxRangeSpan`, reflects disabled state. | Current source, accessibility comments, and focused tests | Verified current behavior |
-| FR3 | The preset group and each preset button expose stable theme targets; selected and disabled are states of the preset-button target rather than separate targets. | `architecture:component-theming-surface`; #5417 demand | Approved additive contract |
-| FR4 | Adding theme targets MUST NOT change the Popover, Calendar, button, focus, or selection semantics those elements already own. | Composition boundary and compatibility goal | Approved additive contract |
-| FR5 | When the preset group and a one-month calendar do not fit side by side in the layer, the preset group stacks above the calendar, and every month grid and the month navigation stay inside the layer (`spec:AST-020` FR1, WCAG 2.2 SC 1.4.10). Visual order matches DOM order. When they fit, the presets stay beside the calendar. When the content is taller than the layer's viewport cap, it scrolls inside the layer. | `spec:AST-020` FR1; 390 px, 390 × 664 px and 440 px reflow checks | Verified current behavior |
+| ID | Candidate invariant | Basis | Review state |
+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -------------------------- |
+| FR1 | DateRangeInput MUST present the controlled `value` and emit range changes without maintaining a competing selected range. | Current source, docs, and focused tests | Verified current behavior |
+| FR2 | When presets are present, each preset remains an independent button in one labeled group; the applied preset reflects current state and a preset whose endpoint violates `min`, `max`, or `dateConstraints`, or whose range violates `minRangeSpan` or `maxRangeSpan`, reflects disabled state. | Current source, accessibility comments, and focused tests | Verified current behavior |
+| FR3 | The preset group and each preset button expose stable theme targets; selected and disabled are states of the preset-button target rather than separate targets. | `architecture:component-theming-surface`; consumer demand for preset theming | Approved additive contract |
+| FR4 | Adding theme targets MUST NOT change the Popover, Calendar, button, focus, or selection semantics those elements already own. | Composition boundary and compatibility goal | Approved additive contract |
+| FR5 | When the preset group and a one-month calendar do not fit side by side in the layer, the preset group stacks above the calendar, and every month grid and the month navigation stay inside the layer (`spec:AST-020` FR1, WCAG 2.2 SC 1.4.10). Visual order matches DOM order. When they fit, the presets stay beside the calendar. When the content is taller than the layer's viewport cap, it scrolls inside the layer. | `spec:AST-020` FR1; 390 px, 390 × 664 px and 440 px reflow checks | Verified current behavior |
+| FR6 | The trigger text, its accessible name, and the popover Calendar show the resolved calendar (`spec:AST-111` FR2, FR17): the trigger writes each end of the range in the calendar, with the year when either end falls outside the current calendar year, and the Calendar lays out calendar months. The field has no typed entry. `value`, `onChange`, `min`, `max`, presets, and span bounds stay Gregorian ISO dates (`spec:AST-111` FR3). | `spec:AST-111` FR3, FR17; current source and calendar tests | Verified current behavior |
### Allowed variation
@@ -92,12 +105,13 @@ preset-list anatomy and its additive theming surface.
### Representative states
-| State | Required invariant | Allowed variation |
-| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
-| No presets | No preset group or preset-button target renders. | Calendar configuration |
-| Presets, no match | Every button carries the preset target with no selected state. | Preset count and labels |
-| Applied preset | The matching button carries `aria-current="true"` and the target's selected state. | Selected range |
-| Disabled preset | A preset that violates an endpoint date constraint or a range-span constraint is disabled per `spec:AST-085` and carries the target's disabled state. | Constraint source |
+| State | Required invariant | Allowed variation |
+| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
+| Calendar | The trigger text and the Calendar show the resolved calendar; values stay Gregorian ISO. | Calendar, locale, digits |
+| No presets | No preset group or preset-button target renders. | Calendar configuration |
+| Presets, no match | Every button carries the preset target with no selected state. | Preset count and labels |
+| Applied preset | The matching button carries `aria-current="true"` and the target's selected state. | Selected range |
+| Disabled preset | A preset that violates an endpoint date constraint or a range-span constraint is disabled per `spec:AST-085` and carries the target's disabled state. | Constraint source |
### Transformation and precedence order
@@ -174,15 +188,40 @@ fill measures 3.88:1 on the popover surface, under 4.5:1.
- `family:overlay-dismissal` owns the Popover dismissal stack.
- `architecture:component-theming-surface` owns target admission, state
reflection, and anatomy mapping.
+- `spec:AST-111` owns calendar selection, Gregorian ISO values, and the
+ `Temporal` boundary; FR6 projects its FR3 and FR17. `component:Calendar` owns
+ the popover grid in the calendar.
+
+### `spec:AST-013` FR12 exception — calendars that need `Temporal`
+
+- **Capability:** trigger text and the popover Calendar in calendars other than
+ `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese`, which need the
+ runtime's `Temporal`.
+- **Reduction:** where `Temporal` is missing, as in Safari on macOS and iOS,
+ the field shows Gregorian dates and warns once in development, naming a
+ polyfill (`spec:AST-111` FR5). An application that loads a `Temporal`
+ polyfill gets the full calendar. When a server and a browser use `chinese` or
+ `dangi` implementations that disagree on a month start, React renders the
+ differing text again on the client (`spec:AST-111` FR19).
+- **Preserved obligations:** `spec:AST-013` FR7 and FR8, and FR9 outside that
+ `chinese` and `dangi` case. The Gregorian field keeps every interaction,
+ label, and announcement, and Buddhist, Minguo, and Japanese text works without
+ `Temporal`.
+- **Evidence:** real Chromium and Firefox with native `Temporal`, and real
+ Chromium, Firefox, and WebKit with `Temporal` removed, with and without a
+ polyfill, showing the Persian trigger text.
+- **Owner:** `nynexman4464`.
+- **Review condition:** Safari ships `Temporal`.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------ |
-| FR1, FR2, AR1–AR3 | `DateRangeInput.test.tsx`; disabled-preset focusability (AR3) pending conformance | no match, applied preset, endpoint-invalid preset, span-invalid preset | Semantics or state attributes disappear | `audit:DateRangeInput/presets` |
-| FR3, FR4 | `DateRangeInput.test.tsx`, `themingTargets.test.ts`, generated probe theme | group target, selected button, disabled button | Target class/state is missing, undocumented, or placed on the wrong element | `audit:DateRangeInput/theming` |
-| FR5 | `DateRangeInputReflow.interaction.browser.spec.ts` | 390 px page with presets and two months; desktop page | The calendar or its navigation crosses the layer edge, or the presets leave the calendar's side at desktop width | `audit:DateRangeInput/reflow` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | all documented anatomy | Target ownership or anatomy names drift | `audit:DateRangeInput/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------- |
+| FR1, FR2, AR1–AR3 | `DateRangeInput.test.tsx`; disabled-preset focusability (AR3) pending conformance | no match, applied preset, endpoint-invalid preset, span-invalid preset | Semantics or state attributes disappear | `audit:DateRangeInput/presets` |
+| FR3, FR4 | `DateRangeInput.test.tsx`, `themingTargets.test.ts`, generated probe theme | group target, selected button, disabled button | Target class/state is missing, undocumented, or placed on the wrong element | `audit:DateRangeInput/theming` |
+| FR5 | `DateRangeInputReflow.interaction.browser.spec.ts` | 390 px page with presets and two months; desktop page | The calendar or its navigation crosses the layer edge, or the presets leave the calendar's side at desktop width | `audit:DateRangeInput/reflow` |
+| FR6 | `DateRangeInput.calendar.test.tsx` ("writes the trigger text and its accessible name in the Persian calendar", "shows the year when the range leaves the current calendar year", "opens a Persian popover calendar and reports Gregorian ISO dates", and the cases without `Temporal`); `Calendar.calendarSystems.test.tsx` "DateRangeInput opens its popover calendar in the calendar"; real Chromium, Firefox, and WebKit trigger text | Persian, Buddhist, a range across a calendar year, no `Temporal` | Trigger text or Calendar in another calendar, or a non-ISO value, fails | `audit:DateRangeInput/behavior` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | all documented anatomy | Target ownership or anatomy names drift | `audit:DateRangeInput/theming` |
## Decision log
diff --git a/docs/specs/components/DateTimeInput/DateTimeInput.spec.md b/docs/specs/components/DateTimeInput/DateTimeInput.spec.md
index 21a2bdfc82..9b6f5175bb 100644
--- a/docs/specs/components/DateTimeInput/DateTimeInput.spec.md
+++ b/docs/specs/components/DateTimeInput/DateTimeInput.spec.md
@@ -17,6 +17,10 @@ verified_by:
packages/core/src/DateTimeInput/NativePickerSegments.test.tsx,
packages/core/src/DateTimeInput/Presentation.test.tsx,
packages/core/src/DateTimeInput/DateTimeInput.fr10.test.tsx,
+ packages/core/src/DateTimeInput/DateTimeInput.calendar.test.tsx,
+ packages/core/src/DateInput/DateInput.calendarPresentation.test.tsx,
+ packages/core/src/DateInput/DateInputTouch.calendar.test.tsx,
+ packages/core/src/DateInput/DateInput.noTemporal.test.tsx,
packages/core/src/__tests__/BusyOwnerAnnouncement.test.tsx,
packages/core/src/theme/themingTargets.test.ts,
scripts/check-knowledge.mjs,
@@ -31,22 +35,30 @@ architecture:
architecture:public-component-api,
]
contributing: []
-system_specs: [spec:AST-043, spec:AST-085, spec:AST-086, spec:AST-102]
+system_specs:
+ [
+ spec:AST-013/FR12,
+ spec:AST-043,
+ spec:AST-085,
+ spec:AST-086,
+ spec:AST-102,
+ spec:AST-111,
+ ]
---
# DateTimeInput component contract
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | One controlled ISO date-time value presented through coordinated date and time segments; `presentation` selects Astryx, native, or adaptive picker surfaces. |
-| Behavior | Date and time changes emit one combined value; clear emits `undefined`; controlled empty state remains empty in every rendered picker. |
-| End-user impact | People selecting a date and time see one value reflected consistently in the closed field and the active picker, including after clearing. |
-| Builder impact | A caller that relied on the `12h` hour-format default under a 24-hour locale passes `hourFormat="12h"` to keep twelve-hour time text. A per-user 12/24-hour preference goes on the provider locale as a `-u-hc-` extension (`en-US-u-hc-h23`). |
-| Compatibility/readiness | The `hourFormat` default is the provider locale's hour cycle (`12h` for `en`/`en-US` and with no provider); every other released default, API, and DOM shape holds. The presentation matrix and deprecated `nativePicker` mapping follow `spec:AST-043`. Fixed segment height, typed-time prefix commits, busy paint, and caller handlers while disabled are listed under Current-state impact. |
-| Review checks | Reject competing picker selection, date/time output that is not one valid combined value, presentation precedence drift, lost per-segment fallback, or broken segment accessibility. |
-| Governing rules | `spec:AST-043`, `family:input-fields`, `family:overlay-dismissal`, `spec:AST-085`, `spec:AST-086` FR8, and objective platform accessibility standards. |
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Public contract | One controlled ISO date-time value presented through coordinated date and time segments; `presentation` selects Astryx, native, or adaptive picker surfaces. `calendar` selects the calendar system the date segment shows on every surface (`spec:AST-111` FR2). |
+| Behavior | Date and time changes emit one combined value; clear emits `undefined`; controlled empty state remains empty in every rendered picker. The pointer date segment reads and writes typed dates in the resolved calendar and reports a typed date only when it is complete (FR11). With a calendar other than `gregory` or `iso8601`, a presentation that would show native controls shows the popovers on a fine pointer and the bottom sheet on a coarse pointer, and the bottom sheet shows months of the calendar (FR12). |
+| End-user impact | People selecting a date and time see one value reflected consistently in the closed field and the active picker, including after clearing. |
+| Builder impact | A caller that relied on the `12h` hour-format default under a 24-hour locale passes `hourFormat="12h"` to keep twelve-hour time text. A per-user 12/24-hour preference goes on the provider locale as a `-u-hc-` extension (`en-US-u-hc-h23`). |
+| Compatibility/readiness | The `hourFormat` default is the provider locale's hour cycle (`12h` for `en`/`en-US` and with no provider); every other released default, API, and DOM shape holds. The presentation matrix and deprecated `nativePicker` mapping follow `spec:AST-043`. Fixed segment height, typed-time prefix commits, busy paint, and caller handlers while disabled are listed under Current-state impact. `calendar` is additive with a Gregorian default; typed Gregorian dates follow FR11, and calendars that need `Temporal` fall back to Gregorian where it is missing (the `spec:AST-013` FR12 exception). |
+| Review checks | Reject competing picker selection, date/time output that is not one valid combined value, presentation precedence drift, lost per-segment fallback, or broken segment accessibility. |
+| Governing rules | `spec:AST-043`, `family:input-fields`, `family:overlay-dismissal`, `spec:AST-085`, `spec:AST-086` FR8, `spec:AST-111` FR2, FR3, FR9–FR16, AR2, AR3, `spec:AST-013` FR12, and objective platform accessibility standards. |
This table is a review projection; the body below is authoritative.
@@ -62,8 +74,13 @@ or pointer-adaptive combinations of those surfaces.
- Released default preserved: `yes`, except `hourFormat`, which follows the
provider locale's hour cycle (`12h` for `en` and `en-US`, the released
default with no provider) and shares TimeInput's locale time text
-- Compatibility class: default change for non-English-US locales; existing
- types, callbacks, roles, and exports remain stable
+- Compatibility class: default change for non-English-US locales; additive
+ `calendar` prop with a Gregorian default; typed Gregorian dates fire
+ `onChange` only for complete input (FR11); a non-Gregorian calendar replaces
+ native controls with the Astryx surfaces for the pointer, and an explicit
+ `native` warns in development (FR12); existing types, callbacks, roles, and
+ exports remain stable. A provider locale with a `-u-ca-` keyword keeps
+ Gregorian dates (`spec:AST-111` DEC-2); set `calendar` to choose one.
- Controlled/uncontrolled behavior: DateTimeInput remains controlled; `undefined`
represents no committed date-time value
- Migration decision: none; picker presentation and deprecated `nativePicker`
@@ -99,28 +116,32 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
-| ----------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------- | ----------------- | ------------------------- | ---------- | ---------------------------------------------- |
-| Committed date-time | valid ISO local date-time string or `undefined` | The one controlled value reflected by both segments and active picker. | Every presentation. | `undefined` | `component:DateTimeInput` | Stable | Rejected edits revert without emitting change. |
-| Picker presentation | `popover`, `bottom-sheet`, `native`, `adaptive-bottom-sheet`, `adaptive-native` | Selects which surface collects date and time. | Every render; pointer adaptation applies only to adaptive values. | `adaptive-native` | `spec:AST-043` | Stable | Type-rejected. |
-| Legacy picker selection | `touch`, `always`, `never` | Deprecated compatibility input mapped by `spec:AST-043`; presentation wins. | When `presentation` is omitted. | `touch` | `spec:AST-043` | Deprecated | Type-rejected. |
-| Time precision | minute-only or seconds | Controls value precision and whether native time can represent it. | Every presentation; native fallback follows `spec:AST-043`. | minute-only | `component:DateTimeInput` | Stable | Type-rejected. |
-| Preset-time cadence | omitted, `5`, `10`, `15`, `30`, or `60` minutes | Adds a fine-pointer time listbox without restricting typed entry. | Astryx pointer time field only. | omitted | `component:DateTimeInput` | Stable | Type-rejected. |
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ----------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | ------------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------- |
+| Committed date-time | valid ISO local date-time string or `undefined` | The one controlled value reflected by both segments and active picker. | Every presentation. | `undefined` | `component:DateTimeInput` | Stable | Unreadable text reverts; a date the calendar lacks, out of range, or incomplete stays for correction; neither emits change. |
+| Picker presentation | `popover`, `bottom-sheet`, `native`, `adaptive-bottom-sheet`, `adaptive-native` | Selects which surface collects date and time. | Every render; pointer adaptation applies only to adaptive values. | `adaptive-native` | `spec:AST-043` | Stable | Type-rejected. |
+| Legacy picker selection | `touch`, `always`, `never` | Deprecated compatibility input mapped by `spec:AST-043`; presentation wins. | When `presentation` is omitted. | `touch` | `spec:AST-043` | Deprecated | Type-rejected. |
+| Time precision | minute-only or seconds | Controls value precision and whether native time can represent it. | Every presentation; native fallback follows `spec:AST-043`. | minute-only | `component:DateTimeInput` | Stable | Type-rejected. |
+| Preset-time cadence | omitted, `5`, `10`, `15`, `30`, or `60` minutes | Adds a fine-pointer time listbox without restricting typed entry. | Astryx pointer time field only. | omitted | `component:DateTimeInput` | Stable | Type-rejected. |
+| Calendar | a `CalendarSystem` (`spec:AST-111` FR1) | The calendar system the date segment shows dates in. | Every surface; a calendar other than `gregory` or `iso8601` replaces native controls (FR12). | the provider's resolved calendar, else `gregory` (`spec:AST-111` FR2) | `spec:AST-111` | stable | Resolves to `gregory` and warns once in development; a calendar that needs `Temporal` falls back to `gregory` where it is missing. |
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
-| FR1 | DateTimeInput MUST reflect one controlled date-time value across its visible segments and active picker, and MUST NOT reveal a competing selected date after the parent accepts a clear. | Public docs, controlled component seam, current source, focused tests |
-| FR2 | Every committed date or time change MUST emit one valid combined ISO date-time value; clearing MUST emit `undefined`; changing time while no date is committed MUST emit nothing. | Public types, docs, current source, focused tests |
-| FR3 | `presentation`, deprecated `nativePicker`, precedence, pointer adaptation, forced surfaces, and per-segment native fallbacks MUST follow `spec:AST-043` FR1–FR4. The touch date sheet's month heading and month-pane names follow `component:DateInput` FR6, and its weekday row follows `component:DateInput` FR19. | `spec:AST-043` |
-| FR4 | When `changeAction` is present, every value-change path MUST call `onChange` first, show the proposed controlled value optimistically, and contribute to one busy state until the controlled value accepts or replaces it. | `family:input-fields/FR6` |
-| FR5 | The two pointer segments share one row while each retains its intrinsic basis; when the container is narrower, flex wrapping moves them into separate full-width rows. Each segment is the shared element height for its size, as a minimum that grows with a set text size under `spec:AST-102` FR4. Implementation gap: the height is fixed at that size. | Public docs, current source, focused layout tests; `spec:AST-102` FR4 |
-| FR6 | Date-time bounds and date constraints MUST prevent invalid commits. Native controls MAY receive platform hints, but JavaScript validation remains the final commit boundary; calendar-only options MAY be unavailable on native surfaces. | Public docs, current source, focused presentation tests |
-| FR7 | A preset-time listbox MUST remain optional, preserve typed entry, expose one selected option independently from keyboard highlight, and limit offered values to the selected date's effective minimum and maximum. Time text and typed times MUST follow the active locale's digits, separator, and day-period words (`architecture:internationalization` INV1a, INV8). The hour format is `hourFormat` when set, else the provider locale's hour cycle; time text, preset options, and the stepped-time announcement come from the shared time formatter, and typed times parse the locale's digits, separators, and day-period words as well as English. Implementation gap: the typed time field commits as soon as a prefix parses. While open, the listbox stays open for a press on the time field or in the listbox and closes for a press elsewhere (`architecture:layer-runtime`). | Public docs, current source, focused interaction tests; `architecture:internationalization` INV1a, INV8 |
-| FR8 | Base props and `ref` MUST reach the date segment's input; a caller `aria-describedby` joins the component's own descriptions, and a caller DOM handler runs after the field's own handler. `container*` reaches the Field box and `control*` the segment row; root `xstyle`, `className`, and `style` are not accepted. | `family:input-fields` FR10; `DateTimeInput.fr10.test.tsx` |
-| FR9 | A disabled field MUST keep both segments focusable with `aria-disabled` and no native `disabled`, block every value-changing path, keep the calendar button's tab stop, and paint the keyboard focus ring. Explicit `isLoading` makes every surface inert the same way; a pending `changeAction` does so only on the popover surface, and the bottom sheet and any field with a native date segment keep accepting edits. The busy start is announced once. Implementation gap: a caller `onKeyDown` and other DOM handlers on the date segment still run while disabled (`spec:AST-085` FR2). Implementation gap: a busy field that is not disabled takes the disabled paint (half opacity), on every surface while `isLoading` and on the popover while a `changeAction` is pending, against `spec:AST-085` FR6. | `spec:AST-085` FR1, FR2, FR6; `spec:AST-086` FR8; current source and tests |
-| FR10 | Enter in the date segment's text input commits typed text that has not been committed and is then held back, so a form never submits the value from before the commit. With no typed text pending, Enter is not prevented, so a form submits as it does from any text field, except on a disabled or busy field, where Enter does nothing (`spec:AST-085` FR2). |
+| ID | Invariant | Basis |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
+| FR1 | DateTimeInput MUST reflect one controlled date-time value across its visible segments and active picker, and MUST NOT reveal a competing selected date after the parent accepts a clear. | Public docs, controlled component seam, current source, focused tests |
+| FR2 | Every committed date or time change MUST emit one valid combined ISO date-time value; clearing MUST emit `undefined`; changing time while no date is committed MUST emit nothing. | Public types, docs, current source, focused tests |
+| FR3 | `presentation`, deprecated `nativePicker`, precedence, pointer adaptation, forced surfaces, and per-segment native fallbacks MUST follow `spec:AST-043` FR1–FR4, except that a calendar other than `gregory` or `iso8601` replaces native surfaces as FR12 states. The touch date sheet's month heading and month-pane names follow `component:DateInput` FR6, and its weekday row follows `component:DateInput` FR19. | `spec:AST-043` |
+| FR4 | When `changeAction` is present, every value-change path MUST call `onChange` first, show the proposed controlled value optimistically, and contribute to one busy state until the controlled value accepts or replaces it. | `family:input-fields/FR6` |
+| FR5 | The two pointer segments share one row while each retains its intrinsic basis; when the container is narrower, flex wrapping moves them into separate full-width rows. Each segment is the shared element height for its size, as a minimum that grows with a set text size under `spec:AST-102` FR4. Implementation gap: the height is fixed at that size. | Public docs, current source, focused layout tests; `spec:AST-102` FR4 |
+| FR6 | Date-time bounds and date constraints MUST prevent invalid commits. Native controls MAY receive platform hints, but JavaScript validation remains the final commit boundary; calendar-only options MAY be unavailable on native surfaces. | Public docs, current source, focused presentation tests |
+| FR7 | A preset-time listbox MUST remain optional, preserve typed entry, expose one selected option independently from keyboard highlight, and limit offered values to the selected date's effective minimum and maximum. Time text and typed times MUST follow the active locale's digits, separator, and day-period words (`architecture:internationalization` INV1a, INV8). The hour format is `hourFormat` when set, else the provider locale's hour cycle; time text, preset options, and the stepped-time announcement come from the shared time formatter, and typed times parse the locale's digits, separators, and day-period words as well as English. Implementation gap: the typed time field commits as soon as a prefix parses. While open, the listbox stays open for a press on the time field or in the listbox and closes for a press elsewhere (`architecture:layer-runtime`). | Public docs, current source, focused interaction tests; `architecture:internationalization` INV1a, INV8 |
+| FR8 | Base props and `ref` MUST reach the date segment's input; a caller `aria-describedby` joins the component's own descriptions, and a caller DOM handler runs after the field's own handler. `container*` reaches the Field box and `control*` the segment row; root `xstyle`, `className`, and `style` are not accepted. | `family:input-fields` FR10; `DateTimeInput.fr10.test.tsx` |
+| FR9 | A disabled field MUST keep both segments focusable with `aria-disabled` and no native `disabled`, block every value-changing path, keep the calendar button's tab stop, and paint the keyboard focus ring. Explicit `isLoading` makes every surface inert the same way; a pending `changeAction` does so only on the popover surface, and the bottom sheet and any field with a native date segment keep accepting edits. The busy start is announced once. Implementation gap: a caller `onKeyDown` and other DOM handlers on the date segment still run while disabled (`spec:AST-085` FR2). Implementation gap: a busy field that is not disabled takes the disabled paint (half opacity), on every surface while `isLoading` and on the popover while a `changeAction` is pending, against `spec:AST-085` FR6. | `spec:AST-085` FR1, FR2, FR6; `spec:AST-086` FR8; current source and tests |
+| FR10 | Enter in the date segment's text input commits typed text that has not been committed and is then held back, so a form never submits the value from before the commit. With no typed text pending, Enter is not prevented, so a form submits as it does from any text field, except on a disabled or busy field, where Enter does nothing (`spec:AST-085` FR2). |
+| FR11 | The pointer date segment follows `component:DateInput` FR20 for typed entry in the resolved calendar: it reads the dates `Intl.DateTimeFormat` writes for the locale and calendar, and in the Gregorian calendar, on Enter or blur, text it cannot otherwise read and a date the locale's field order lacks, such as `13/5/2026` in `en-US`, when `parseDateInput` reads it, with a one- or three-digit year not a date, reads years of the calendar, rejects a date the calendar does not have without adjusting it, shows and announces an out-of-range error with the bounds in the calendar, fires `onChange` while typing only for complete input and at most once for each distinct date in one typing session, shows and announces each rejection once as DateInput does, and writes the committed date as `date_long` in the calendar (`spec:AST-111` FR9–FR13). Its Calendar shows the same calendar, and the combined value stays a Gregorian ISO date-time (`spec:AST-111` FR3). | `spec:AST-111` FR3, FR9–FR13; current source; calendar typed-entry tests |
+| FR12 | With a calendar other than `gregory` or `iso8601`, every presentation that would show native controls — `adaptive-native`, the default, deprecated `touch` and `always`, and an explicit `native` — shows the Astryx popovers on a fine pointer and the bottom sheet on a coarse pointer, for the date and the time alike, because the native date control is Gregorian (`spec:AST-111` FR15). An explicit `native` also warns once in development. The bottom sheet's Date panel follows `component:DateInput` FR21: calendar months in six-row panes, the month wheel of the selected calendar year with leap months, the common counterpart on a year change, and year labels with their era; its date segment writes the date as `date_long` in the calendar (`spec:AST-111` FR16). The combined value stays a Gregorian ISO date-time (`spec:AST-111` FR3). | `spec:AST-111` FR3, FR15, FR16; current source; calendar presentation and touch calendar tests |
+| FR13 | While disabled or busy, the date segment keeps or drops typed text as `component:DateInput` FR12 states, judging it on the next Enter or blur once editable. | `spec:AST-085` FR2; current source and tests |
### Allowed variation
@@ -140,12 +161,15 @@ Consumer migration instructions belong in consumer docs and release notes.
| Cleared after picker change | Closed field is empty and reopening the picker reveals no selected date or retained committed time. | Picker focus date may remain navigational. |
| Busy | Proposed value remains visible; both editable segments expose busy. With explicit `isLoading`, mutation paths are unavailable on every surface; with a pending `changeAction`, only on the popover surface. | Explicit loading or pending action source. |
| Focusable disabled | Both segments stay focusable with `aria-disabled` while every value-changing path stays blocked. | Disabled-reason text. |
+| Calendar | Every surface shows the resolved calendar, and native controls give way to the popovers or bottom sheet outside `gregory` and `iso8601`; the value stays Gregorian ISO. | Calendar, locale, digits |
### Transformation and precedence order
- **ORD1 — Picker selection.** Resolve `presentation` before deprecated
- `nativePicker`, apply pointer adaptation, then apply only the per-segment native
- fallbacks permitted by `spec:AST-043`.
+ `nativePicker`; with a calendar other than `gregory` or `iso8601`, use
+ `adaptive-bottom-sheet` in place of `native` and `adaptive-native` (FR12);
+ apply pointer adaptation, then apply only the per-segment native fallbacks
+ permitted by `spec:AST-043`.
- **ORD2 — Value mutation.** Validate the proposed segment value, combine it with
its committed counterpart, call `onChange`, present the optimistic combined
value, then run `changeAction` in a transition.
@@ -172,6 +196,19 @@ durable constraints and their verification target.
- **AR4 — Required, invalid, busy, and disabled.** Both editable segments expose
applicable required, invalid, busy, and disabled states; a focusable disabled
reason never re-enables mutation.
+- **AR5 — Typed-date rejections and the calendar.** Unreadable text, a date the
+ calendar does not have, and an out-of-range date each announce a different
+ catalog message from the date segment, and the last two also show it as the
+ field's error status, in place of a caller `status` while the rejected text
+ stays (`spec:AST-111` AR3).
+ The pointer date segment's description names the calendar only when its
+ resolved calendar differs from the provider's resolved calendar, else
+ `gregory`, with `gregory` and `iso8601` as one calendar, both compared after the Gregorian fallback for a runtime without
+ `Temporal`. With a calendar other than `gregory` or `iso8601` and no caller
+ `placeholder`, the empty focused segment shows an example date in the
+ calendar's numeric pattern; a caller `placeholder` shows in every state and
+ replaces the hint. The example date is today when the field accepts it, else
+ the nearest date it accepts (`spec:AST-111` AR2).
## Design relationships
@@ -231,19 +268,51 @@ leading clock glyph uses `date-time-input-clock-icon`.
reflection, and anatomy mapping.
- `spec:AST-043` owns picker-presentation values, defaults, precedence,
compatibility mapping, forced surfaces, and native fallback rules.
+- `spec:AST-111` owns calendar selection, Gregorian ISO values, the `Temporal`
+ boundary, typed entry, and presentations in a calendar; FR11, FR12, and AR5
+ project its FR3, FR9–FR13, FR15, FR16, AR2, and AR3 through
+ `component:DateInput` FR20 and FR21.
+
+### `spec:AST-013` FR12 exception — calendars that need `Temporal`
+
+- **Capability:** typed date entry, committed date text, and the bottom sheet's
+ Date panel in calendars other than `gregory`, `iso8601`, `buddhist`, `roc`,
+ and `japanese`, which need the runtime's `Temporal`.
+- **Reduction:** where `Temporal` is missing, as in Safari on macOS and iOS,
+ the date segment reads, writes, and shows Gregorian dates, its presentations
+ resolve as they do for `gregory`, and it warns once in development, naming a
+ polyfill (`spec:AST-111` FR5). An application that
+ loads a `Temporal` polyfill gets the full calendar. When a server and a
+ browser use `chinese` or `dangi` implementations that disagree on a month
+ start, React renders the differing text again on the client
+ (`spec:AST-111` FR19).
+- **Preserved obligations:** `spec:AST-013` FR7 and FR8, and FR9 outside that
+ `chinese` and `dangi` case. The Gregorian date and time segments keep every
+ interaction, label, and announcement, and Buddhist, Minguo, and Japanese entry
+ works without `Temporal`.
+- **Evidence:** real Chromium and Firefox typing in calendar fields with native
+ `Temporal`, with `Temporal` removed and a polyfill loaded, and with
+ `Temporal` removed and no polyfill, through the shared DateInput field; the
+ shared bottom sheet in real Chromium, Firefox, and WebKit in the same three
+ modes.
+- **Owner:** `nynexman4464`.
+- **Review condition:** Safari ships `Temporal`.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
-| FR1–FR2 | `DateTimeInput.test.tsx` | empty, calendar selection, typed date/time, clear | A stale Calendar selection, partial output, or invalid mutation makes a public-state test fail. | `audit:DateTimeInput/behavior` |
-| FR3, FR6 | `Presentation.test.tsx`, `NativePickerSegments.test.tsx`, `DateTimeInputTouch.test.tsx` (including "labels the date sheet columns in %s with the Calendar header names" for `en-US`, `pt-PT`, and `id-ID`) | forced, adaptive, legacy, native fallback, constrained commit | A substituted surface, precedence drift, or invalid commit makes a presentation test fail. | `audit:DateTimeInput/surfaces` |
-| FR4, FR9, AR4 | `DateTimeInput.test.tsx`, `DateTimeInputTouch.test.tsx`; `BusyOwnerAnnouncement.test.tsx` DateTimeInput case | pending, loading, disabled reason | Mutation during busy/disabled state or stale optimistic output makes a state test fail. Evidence gap: no test asserts that caller handlers still run while disabled. | `audit:DateTimeInput/state` |
-| FR5 | `DateTimeInput.test.tsx` | intrinsic row, narrow-container wrap classes | Removing the intrinsic basis or wrap styles makes the class-level layout assertions fail; rendered geometry remains review evidence. Evidence gap: no test asserts segment heights or text growth. | `audit:DateTimeInput/layout` |
-| FR7, AR1–AR3 | `DateTimeInput.test.tsx`, `DateTimeInputTouch.test.tsx`; `DateTimeInput.test.tsx` "keeps the time list open on a press in the time input, closes it on a press elsewhere" | popovers, time options, keyboard/focus | Wrong role, name, state, keyboard behavior, or focus behavior makes a focused interaction test fail. A provider-locale test asserts the closed time text follows the locale's hour cycle and day period; the shared formatter's tests cover parsing. | `audit:DateTimeInput/interaction` |
-| FR8 | `DateTimeInput.fr10.test.tsx` | each surface; caller id, describedby, onClick, onKeyDown | A base prop off the date input, a dropped caller description, or styling on the wrong part fails. | `audit:DateTimeInput/api` |
-| FR10 | `DateTimeInput.test.tsx` "Enter in the date segment submits the form when nothing is typed, and commits typed text without submitting" "Enter on a disabled field does not submit the form" and "Enter on a busy field does not submit the form" | Nothing typed; typed text; disabled; busy (`isLoading`) | An Enter that is prevented with nothing typed, or that submits before typed text commits, fails. | — |
-| Theming anatomy map | `scripts/check-knowledge.mjs`, `themingTargets.test.ts` | root, segments, icons, listbox, options | Missing, undocumented, or wrongly placed targets fail knowledge or target checks. | `audit:DateTimeInput/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
+| FR1–FR2 | `DateTimeInput.test.tsx` | empty, calendar selection, typed date/time, clear | A stale Calendar selection, partial output, or invalid mutation makes a public-state test fail. | `audit:DateTimeInput/behavior` |
+| FR3, FR6 | `Presentation.test.tsx`, `NativePickerSegments.test.tsx`, `DateTimeInputTouch.test.tsx` (including "labels the date sheet columns in %s with the Calendar header names" for `en-US`, `pt-PT`, and `id-ID`) | forced, adaptive, legacy, native fallback, constrained commit | A substituted surface, precedence drift, or invalid commit makes a presentation test fail. | `audit:DateTimeInput/surfaces` |
+| FR4, FR9, AR4 | `DateTimeInput.test.tsx`, `DateTimeInputTouch.test.tsx`; `BusyOwnerAnnouncement.test.tsx` DateTimeInput case | pending, loading, disabled reason | Mutation during busy/disabled state or stale optimistic output makes a state test fail. Evidence gap: no test asserts that caller handlers still run while disabled. | `audit:DateTimeInput/state` |
+| FR5 | `DateTimeInput.test.tsx` | intrinsic row, narrow-container wrap classes | Removing the intrinsic basis or wrap styles makes the class-level layout assertions fail; rendered geometry remains review evidence. Evidence gap: no test asserts segment heights or text growth. | `audit:DateTimeInput/layout` |
+| FR7, AR1–AR3 | `DateTimeInput.test.tsx`, `DateTimeInputTouch.test.tsx`; `DateTimeInput.test.tsx` "keeps the time list open on a press in the time input, closes it on a press elsewhere" | popovers, time options, keyboard/focus | Wrong role, name, state, keyboard behavior, or focus behavior makes a focused interaction test fail. A provider-locale test asserts the closed time text follows the locale's hour cycle and day period; the shared formatter's tests cover parsing. | `audit:DateTimeInput/interaction` |
+| FR8 | `DateTimeInput.fr10.test.tsx` | each surface; caller id, describedby, onClick, onKeyDown | A base prop off the date input, a dropped caller description, or styling on the wrong part fails. | `audit:DateTimeInput/api` |
+| FR10 | `DateTimeInput.test.tsx` "Enter in the date segment submits the form when nothing is typed, and commits typed text without submitting" "Enter on a disabled field does not submit the form" and "Enter on a busy field does not submit the form" | Nothing typed; typed text; disabled; busy (`isLoading`) | An Enter that is prevented with nothing typed, or that submits before typed text commits, fails. | — |
+| FR11, AR5 | `DateTimeInput.calendar.test.tsx` ("reports one Persian date typed in Persian digits, only when complete", "writes the committed date in the calendar", "rejects a date the calendar does not have and names the calendar", "shows an out-of-range error with the bounds in the calendar", "names the calendar and shows the hint when focused and empty", "shows a caller placeholder instead of the format hint", "names no calendar when the field uses the provider calendar", "names the Gregorian calendar inside a Persian provider", "commits Gregorian text that only parseDateInput reads on blur", "commits a day-first date that does not exist month-first, on blur only", "fires once for a day-first Gregorian date typed one key at a time"); the parser and round-trip suites under `component:DateInput` FR20 | Persian digits, Hebrew leap year, Japanese era bound, Gregorian day-first typing | A typed date reported before it is complete, an adjusted date, a shared rejection message, a hint that replaces a caller placeholder, a calendar description that is missing or that repeats the provider's calendar, or a non-ISO value fails. Evidence gap: no real-browser run drives the DateTimeInput date segment itself. | `audit:DateTimeInput/behavior` |
+| FR12 | `DateInput.calendarPresentation.test.tsx` DateTimeInput cases (every presentation and deprecated `nativePicker` value in Gregorian and Persian on fine and coarse pointers; "warns once when an explicit native cannot show the calendar"; "writes the sheet date segment in %s %s with its era" for `en` and `fa-IR` Persian and `th-TH` Buddhist); `DateInputTouch.calendar.test.tsx` "shows Persian months and the date in the calendar"; `DateInput.noTemporal.test.tsx` "shows a Persian DateTimeInput as Gregorian native controls" | Persian on fine and coarse pointers, explicit `native`, no `Temporal` | A native date or time control for a non-Gregorian calendar, a missing warning for an explicit `native`, or a Date panel in another calendar, fails | `audit:DateTimeInput/surfaces` |
+| FR13 | `DateTimeInput.test.tsx` "typed text while the field is disabled or busy" cases | Loading, disabled, and saves; unfinished, valid, reported, rejected, new `value` | A commit, `onChange`, reset, or rejection while disabled or busy, a rejection that does not return once editable, typed text that outlives a new `value`, or reported text that outlives the lock fails. | `audit:DateTimeInput/state` |
+| Theming anatomy map | `scripts/check-knowledge.mjs`, `themingTargets.test.ts` | root, segments, icons, listbox, options | Missing, undocumented, or wrongly placed targets fail knowledge or target checks. | `audit:DateTimeInput/theming` |
## Current-state impact
diff --git a/docs/specs/components/PowerSearch/PowerSearch.spec.md b/docs/specs/components/PowerSearch/PowerSearch.spec.md
index 2fd68ee52b..64db1861ca 100644
--- a/docs/specs/components/PowerSearch/PowerSearch.spec.md
+++ b/docs/specs/components/PowerSearch/PowerSearch.spec.md
@@ -89,11 +89,7 @@ present-tense implementation gap note.
- Controlled/uncontrolled behavior: unchanged.
- Calendar: date values follow the provider's calendar. A provider locale with a
`-u-ca-` keyword keeps Gregorian dates (`spec:AST-111` DEC-2); set the
- provider's `calendar` to choose one. Implementation gap: a date value's
- editor is a `DateInput`, or a `DateRangeInput` for a `date_range` value, and
- shows the calendar that input resolves, which is Gregorian; under a provider
- calendar such as `persian`, a date token and its editor name one day in two
- calendars.
+ provider's `calendar` to choose one.
- Migration decisions: `component:PowerSearch/DEC-1`,
`component:PowerSearch/DEC-2`, and, for the `adaptive` default,
`presentation="popover"` (below).
diff --git a/docs/specs/components/i18n/InternationalizationProvider.spec.md b/docs/specs/components/i18n/InternationalizationProvider.spec.md
index 2d0e105ea5..16d48a7519 100644
--- a/docs/specs/components/i18n/InternationalizationProvider.spec.md
+++ b/docs/specs/components/i18n/InternationalizationProvider.spec.md
@@ -95,25 +95,25 @@ Consumer migration instructions belong in consumer docs and release notes.
| Messages | locale → `Catalog` or `RuntimeCatalog` | Adds translated or application-supplied catalogs, as rich `{defaultMessage, description?}` entries or as a generated key-to-string map, without replacing shipped English | Every locale | `{}` | `component:InternationalizationProvider` | stable | Missing entries fall back through the active locale's parent chain, then to shipped English; a supplied `en` catalog is read only when that chain includes `en`; mixed shapes within one call are accepted |
| Overrides | locale → sparse key/string map | Rewords individual Astryx strings before catalog lookup | Every locale | none | `component:InternationalizationProvider` | stable | `null` does not become visible content; unresolved keys continue through fallback |
| Direction | `ltr` or `rtl` | Exposes the provider's semantic direction default | Every provider subtree | derived from locale; `ltr` without provider | `component:InternationalizationProvider` | stable | Invalid values are rejected by the type contract |
-| Calendar | a `CalendarSystem` (`spec:AST-111` FR1) | The calendar system that `Calendar` in the subtree shows; values stay Gregorian ISO dates | Every provider subtree | `gregory` | `spec:AST-111` | stable | An identifier outside `CalendarSystem` resolves to `gregory` and warns once in development; a `-u-ca-` keyword in `locale` does not select the calendar |
+| Calendar | a `CalendarSystem` (`spec:AST-111` FR1) | The calendar system that `Calendar`, `DateInput`, `DateRangeInput`, and `DateTimeInput` in the subtree show; values stay Gregorian ISO dates | Every provider subtree | `gregory` | `spec:AST-111` | stable | An identifier outside `CalendarSystem` resolves to `gregory` and warns once in development; a `-u-ca-` keyword in `locale` does not select the calendar |
Consumer prop syntax and examples remain in
`InternationalizationProvider.doc.mjs` and `astryx docs internationalization`.
## Behavioral and layout contract
-| ID | Candidate invariant | Basis | Draft review state |
-| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------ |
-| FR1 | The provider MUST resolve Astryx strings through exact-locale overrides, parent-locale overrides, exact/parent supplied catalogs, then shipped English. | Current resolver and focused tests | settled |
-| FR2 | A missing translated key MUST fall back silently; a key absent from every applicable source, including shipped English, MUST warn once in development and render the key visibly. | Released resolver and tests | settled |
-| FR3 | Re-rendering with changed locale, messages, overrides, or direction MUST update the context value and translator used by descendants. | Released provider and rerender tests | settled |
-| FR4 | The provider MUST NOT select, persist, or mutate application locale state. | Released API ownership | settled |
-| FR5 | The provider MUST NOT set DOM `lang` or `dir`. Its direction value and the application's DOM direction are separate inputs the application keeps aligned. | `architecture:internationalization/INV12` | settled |
-| FR6 | Without a provider, the public context and hooks MUST expose locale `en`, direction `ltr`, an empty supplied-catalog map, and a translator backed by shipped English. | Released context and tests | settled |
-| FR7 | The provider MUST preserve a string-returning translator suitable for visible and assistive attributes. | Released catalog/runtime contract | settled |
-| FR8 | A nested provider MUST replace locale, messages, overrides, direction, and calendar with values derived solely from the child provider's own props rather than merge parent context. | Released provider and nested-provider tests | settled |
-| FR10 | The provider MUST resolve its calendar from its `calendar` prop, else `gregory`, and expose it on the context as `calendar`. A locale MUST NOT select the calendar, by its default calendar or by a `-u-ca-` keyword: `fa-IR` and `th-TH-u-ca-buddhist` alone resolve to `gregory`. The calendar is independent of language, numbering, and direction. `Calendar` follows the resolved calendar, and its own `calendar` prop takes precedence over the provider's; `DateInput`, `DateRangeInput`, and `DateTimeInput` show Gregorian dates. | `spec:AST-111` FR1, FR2 | settled |
-| FR9 | The provider MUST accept a `RuntimeCatalog` string map or a rich `Catalog` per locale, resolve both to the same strings, and expose `messages` on the context in the rich `MessagesByLocale` shape regardless of input. | `architecture:internationalization/INV15`; provider and resolver runtime-catalog tests | settled |
+| ID | Candidate invariant | Basis | Draft review state |
+| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ------------------ |
+| FR1 | The provider MUST resolve Astryx strings through exact-locale overrides, parent-locale overrides, exact/parent supplied catalogs, then shipped English. | Current resolver and focused tests | settled |
+| FR2 | A missing translated key MUST fall back silently; a key absent from every applicable source, including shipped English, MUST warn once in development and render the key visibly. | Released resolver and tests | settled |
+| FR3 | Re-rendering with changed locale, messages, overrides, or direction MUST update the context value and translator used by descendants. | Released provider and rerender tests | settled |
+| FR4 | The provider MUST NOT select, persist, or mutate application locale state. | Released API ownership | settled |
+| FR5 | The provider MUST NOT set DOM `lang` or `dir`. Its direction value and the application's DOM direction are separate inputs the application keeps aligned. | `architecture:internationalization/INV12` | settled |
+| FR6 | Without a provider, the public context and hooks MUST expose locale `en`, direction `ltr`, an empty supplied-catalog map, and a translator backed by shipped English. | Released context and tests | settled |
+| FR7 | The provider MUST preserve a string-returning translator suitable for visible and assistive attributes. | Released catalog/runtime contract | settled |
+| FR8 | A nested provider MUST replace locale, messages, overrides, direction, and calendar with values derived solely from the child provider's own props rather than merge parent context. | Released provider and nested-provider tests | settled |
+| FR10 | The provider MUST resolve its calendar from its `calendar` prop, else `gregory`, and expose it on the context as `calendar`. A locale MUST NOT select the calendar, by its default calendar or by a `-u-ca-` keyword: `fa-IR` and `th-TH-u-ca-buddhist` alone resolve to `gregory`. The calendar is independent of language, numbering, and direction. `Calendar`, `DateInput`, `DateRangeInput`, and `DateTimeInput` follow the resolved calendar, and a component's own `calendar` prop takes precedence over the provider's. | `spec:AST-111` FR1, FR2 | settled |
+| FR9 | The provider MUST accept a `RuntimeCatalog` string map or a rich `Catalog` per locale, resolve both to the same strings, and expose `messages` on the context in the rich `MessagesByLocale` shape regardless of input. | `architecture:internationalization/INV15`; provider and resolver runtime-catalog tests | settled |
### Allowed variation
diff --git a/packages/cli/assets/docs/tree/calendars.doc.mjs b/packages/cli/assets/docs/tree/calendars.doc.mjs
index 87f1b7cb35..503f821826 100644
--- a/packages/cli/assets/docs/tree/calendars.doc.mjs
+++ b/packages/cli/assets/docs/tree/calendars.doc.mjs
@@ -40,7 +40,7 @@ export const docs = {
blocks: [
{
type: 'prose',
- text: '`Calendar` shows the Gregorian calendar unless the application chooses another one; DateInput, DateRangeInput, and DateTimeInput stay Gregorian. Values never change with the calendar: they stay Gregorian ISO dates. {@link generic:i18n-calendars} has the short version.',
+ text: '`Calendar`, DateInput, DateRangeInput, and DateTimeInput show the Gregorian calendar unless the application chooses another one. Values never change with the calendar: they stay Gregorian ISO dates. {@link generic:i18n-calendars} has the short version.',
},
],
};
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index 48b68b1448..dfebb42905 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -865,6 +865,7 @@ component ContextMenuSubMenu(props: DropdownMenuSubMenuProps)
prop xstyle?: StyleXStyles
inherits AriaAttributes, DOMAttributes, HTMLAttributes
component DateInput(props: DateInputProps)
+ prop calendar?: CalendarSystem = the InternationalizationProvider's calendar, else `'gregory'`
prop changeAction?: (value: ISODateString | undefined) => void | Promise<void>
prop containerClassName?: string
prop containerStyle?: CSSProperties
@@ -900,6 +901,7 @@ component DateInput(props: DateInputProps)
prop width?: SizeValue
inherits AriaAttributes, DOMAttributes, HTMLAttributes
component DateRangeInput(props: DateRangeInputProps)
+ prop calendar?: CalendarSystem = the InternationalizationProvider's calendar, else `'gregory'`
prop changeAction?: (value: DateRange | null) => void | Promise<void>
prop containerClassName?: string
prop containerStyle?: CSSProperties
@@ -935,6 +937,7 @@ component DateRangeInput(props: DateRangeInputProps)
prop width?: SizeValue
inherits AriaAttributes, DOMAttributes, HTMLAttributes
component DateTimeInput(props: DateTimeInputProps)
+ prop calendar?: CalendarSystem = the InternationalizationProvider's calendar, else `'gregory'`
prop changeAction?: (value: ISODateTimeString | undefined) => void | Promise<void>
prop containerClassName?: string
prop containerStyle?: CSSProperties
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index a43e611e5a..512a2f307f 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1121,7 +1121,23 @@
},
"@astryx.dateInput.invalidDate": {
"defaultMessage": "Invalid date",
- "description": "Screen-reader-only live-region alert in DateInput / DateTimeInput when the typed date cannot be parsed. The field silently reverts on blur, so this is the only rejection feedback a screen-reader user gets."
+ "description": "Screen-reader-only live-region alert in DateInput / DateTimeInput when the typed text cannot be read as a date. Text the field cannot finish, such as a one-digit year, stays on Enter or blur and shows this message as the field status."
+ },
+ "@astryx.dateInput.nonexistentDate": {
+ "defaultMessage": "This date does not exist in the {calendar}",
+ "description": "Error in DateInput / DateTimeInput, shown below the field and announced, when the typed date is readable but the calendar does not have it, such as 30 Esfand in a common Persian year or February 30. {calendar} is the calendar's localized name from the platform, such as \"Persian Calendar\" or \"Gregorian Calendar\"."
+ },
+ "@astryx.dateInput.outOfRangeDate": {
+ "defaultMessage": "{bounds, select, both {Enter a date from {min} to {max}} min {Enter a date on or after {min}} max {Enter a date on or before {max}} other {This date is not available}}",
+ "description": "Error in DateInput / DateTimeInput, shown below the field and announced, when the typed date is outside the allowed range. {min} and {max} are the bounds, written as dates in the field's calendar. `bounds` is `both`, `min`, or `max` for a date outside those bounds, and `other` for a date that a custom rule rejects."
+ },
+ "@astryx.dateInput.formatHint": {
+ "defaultMessage": "e.g., {example}",
+ "description": "Placeholder hint in a DateInput / DateTimeInput date field that uses a calendar other than the Gregorian calendar, shown when the field is focused and empty. {example} is today's date, or the nearest date the field accepts, written in that calendar's numeric pattern, such as ۱۴۰۵/۸/۱۱."
+ },
+ "@astryx.dateInput.calendarDescription": {
+ "defaultMessage": "Dates use the {calendar}",
+ "description": "Screen-reader-only description of a DateInput / DateTimeInput date field whose calendar differs from the app's calendar, such as a Persian field in a Gregorian app or a Gregorian field in a Persian app. {calendar} is the calendar's localized name from the platform, such as \"Persian Calendar\" or \"Gregorian Calendar\"."
},
"@astryx.dateInput.resetPicking": {
"defaultMessage": "Reset",
diff --git a/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx b/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx
index 266d781e16..3dd7277465 100644
--- a/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx
+++ b/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx
@@ -10,6 +10,7 @@
*/
import 'temporal-polyfill/full/global';
+import type {ReactElement} from 'react';
import {afterEach, describe, expect, it, vi} from 'vitest';
import {render, screen, waitFor, within} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
@@ -291,12 +292,38 @@ describe('Calendar year paging in the Gregorian calendar', () => {
});
describe('date inputs under a provider calendar', () => {
- // Their field text is Gregorian, so their popover calendars stay Gregorian.
+ async function openGridLabel(field: ReactElement): Promise<string> {
+ const user = userEvent.setup();
+ render(
+ <InternationalizationProvider locale="en" calendar="persian">
+ {field}
+ </InternationalizationProvider>,
+ );
+ await user.click(screen.getByRole('button', {name: 'Open calendar'}));
+ // The popover is not shown in jsdom, so the grid is read from the DOM.
+ const grid = await waitFor(() => {
+ const element = document.querySelector('[role="grid"]');
+ expect(element).not.toBeNull();
+ return element as HTMLElement;
+ });
+ return grid.getAttribute('aria-label') ?? '';
+ }
+
+ // Their field text is in the calendar, so their popover calendars are too.
it.each([
[
'DateInput',
<DateInput key="d" label="Date" value="2026-10-30" onChange={() => {}} />,
],
+ [
+ 'DateRangeInput',
+ <DateRangeInput
+ key="dr"
+ label="Dates"
+ value={{start: '2026-10-30', end: '2026-11-02'}}
+ onChange={() => {}}
+ />,
+ ],
[
'DateTimeInput',
<DateTimeInput
@@ -306,30 +333,7 @@ describe('date inputs under a provider calendar', () => {
onChange={() => {}}
/>,
],
- [
- 'DateRangeInput',
- <DateRangeInput
- key="r"
- label="Dates"
- value={{start: '2026-10-30', end: '2026-11-02'}}
- onChange={() => {}}
- />,
- ],
- ])('%s keeps a Gregorian popover calendar', async (_name, field) => {
- const user = userEvent.setup();
- render(
- <InternationalizationProvider locale="en" calendar="persian">
- {field}
- </InternationalizationProvider>,
- );
- await user.click(screen.getByRole('button', {name: 'Open calendar'}));
- // The popover is not shown in jsdom, so the grid is read from the DOM.
- const grid = await waitFor(() => {
- const element = document.querySelector('[role="grid"]');
- expect(element).not.toBeNull();
- return element as HTMLElement;
- });
- expect(grid.getAttribute('aria-label')).toContain('2026');
- expect(grid.getAttribute('aria-label')).not.toContain('1405');
+ ])('%s opens its popover calendar in the calendar', async (_name, field) => {
+ expect(await openGridLabel(field)).toContain('1405');
});
});
diff --git a/packages/core/src/DateInput/DateInput.calendar.test.tsx b/packages/core/src/DateInput/DateInput.calendar.test.tsx
new file mode 100644
index 0000000000..f1ac486bb4
--- /dev/null
+++ b/packages/core/src/DateInput/DateInput.calendar.test.tsx
@@ -0,0 +1,460 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DateInput.calendar.test.tsx
+ * @input Uses vitest, Testing Library, temporal-polyfill, DateInput
+ * @output Typed entry in calendar systems: partial input, digits, Adar,
+ * Japanese eras, rejected dates, bounds, onChange counts, hint, description
+ * @position Testing; validates DateInput typed entry with a calendar
+ */
+
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+import {fireEvent, render, screen, within} from '@testing-library/react';
+import {Temporal as TemporalPolyfill} from 'temporal-polyfill/full';
+import {DateInput, type DateInputProps} from './DateInput';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import {formatCalendarDateHint} from '../utils/calendarDateParser';
+import type {ISODateString} from '../utils/dateTypes';
+import {plainDateFromISO} from '../utils/plainDate';
+
+const host = globalThis as {Temporal?: unknown};
+const hadTemporal = host.Temporal != null;
+beforeAll(() => {
+ host.Temporal ??= TemporalPolyfill;
+});
+afterAll(() => {
+ if (!hadTemporal) {
+ delete host.Temporal;
+ }
+});
+
+function renderField(locale: string, props: Partial<DateInputProps> = {}) {
+ const onChange = vi.fn();
+ const result = render(
+ <InternationalizationProvider locale={locale}>
+ <DateInput label="Date" onChange={onChange} {...props} />
+ </InternationalizationProvider>,
+ );
+ const input = screen.getByRole('combobox');
+ return {...result, input, onChange};
+}
+
+// A shown status describes the input and announces itself; the alert stays
+// empty, so nothing is spoken twice.
+function expectShown(input: HTMLElement, box: HTMLElement, text: string) {
+ expect(input).toHaveAccessibleDescription(expect.stringContaining(text));
+ expect(within(box).getByRole('alert')).toHaveTextContent('');
+}
+
+/** Types text one character at a time, as a person does. */
+function typeSlowly(input: HTMLElement, text: string) {
+ let typed = '';
+ for (const ch of text) {
+ typed += ch;
+ fireEvent.change(input, {target: {value: typed}});
+ }
+}
+
+describe('DateInput typed entry with a calendar', () => {
+ it('reports one Persian date typed in Persian digits, only when complete', () => {
+ const {input, onChange} = renderField('fa-IR', {calendar: 'persian'});
+ typeSlowly(input, '۱۴۰۵/۸/۱۱');
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('2026-11-02');
+ });
+
+ it('takes the calendar from the provider', () => {
+ const onChange = vi.fn();
+ render(
+ <InternationalizationProvider locale="fa-IR" calendar="persian">
+ <DateInput label="Date" onChange={onChange} />
+ </InternationalizationProvider>,
+ );
+ typeSlowly(screen.getByRole('combobox'), '1405/8/11');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-11-02');
+ });
+
+ it('writes the committed value in the calendar and keeps ISO values', () => {
+ renderField('en', {calendar: 'persian', value: '2026-11-02'});
+ expect(screen.getByRole('combobox')).toHaveValue('Aban 11, 1405 AP');
+ });
+
+ it('keeps system_date ISO and reads ISO input with it', () => {
+ const {input, onChange} = renderField('fa-IR', {
+ calendar: 'persian',
+ format: 'system_date',
+ value: '2026-11-02',
+ });
+ expect(input).toHaveValue('2026-11-02');
+ fireEvent.change(input, {target: {value: '2026-11-03'}});
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-11-03');
+ });
+
+ it('reads a plain Adar in a Hebrew leap year as Adar II', () => {
+ const {input, onChange} = renderField('en', {calendar: 'hebrew'});
+ fireEvent.change(input, {target: {value: '1 Adar 5784'}});
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2024-03-11');
+ });
+
+ it('reads Japanese era dates and rejects a year outside its era', () => {
+ const {input, onChange, container} = renderField('en', {
+ calendar: 'japanese',
+ });
+ fireEvent.change(input, {target: {value: 'May 1, 1 Reiwa'}});
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2019-05-01');
+
+ fireEvent.change(input, {target: {value: 'May 1, 31 Heisei'}});
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expectShown(
+ input,
+ container,
+ 'This date does not exist in the Japanese Calendar',
+ );
+ });
+
+ it('rejects a date the calendar does not have and keeps it on blur', () => {
+ const {input, onChange, container} = renderField('en', {
+ calendar: 'persian',
+ value: '2026-11-02',
+ status: {type: 'warning', message: 'Check the date'},
+ });
+ fireEvent.change(input, {target: {value: '12/30/1404 AP'}});
+ expectShown(
+ input,
+ container,
+ 'This date does not exist in the Persian Calendar',
+ );
+ fireEvent.blur(input);
+ expect(input).toHaveValue('12/30/1404 AP');
+ expectShown(
+ input,
+ container,
+ 'This date does not exist in the Persian Calendar',
+ );
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('shows an out-of-range error with the bounds in the calendar', () => {
+ const {input, onChange, container} = renderField('en', {
+ calendar: 'buddhist',
+ min: '2026-01-01',
+ max: '2026-12-31',
+ });
+ // A Gregorian year typed into a Buddhist field is Buddhist year 2026.
+ fireEvent.change(input, {target: {value: '11/2/2026'}});
+ expect(onChange).not.toHaveBeenCalled();
+ expectShown(
+ input,
+ container,
+ 'Enter a date from January 1, 2569 BE to December 31, 2569 BE',
+ );
+ fireEvent.change(input, {target: {value: '11/2/2569'}});
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-11-02');
+ });
+
+ it('announces a different message for each kind of rejection', () => {
+ const {input, container} = renderField('en', {
+ calendar: 'persian',
+ max: '2026-12-31',
+ });
+ fireEvent.change(input, {target: {value: 'abc'}});
+ expect(within(container).getByRole('alert')).toHaveTextContent(
+ 'Invalid date',
+ );
+ fireEvent.change(input, {target: {value: '12/30/1404 AP'}});
+ expectShown(input, container, 'does not exist in the Persian Calendar');
+ fireEvent.change(input, {target: {value: '1/1/1406 AP'}});
+ expectShown(input, container, 'on or before Dey 10, 1405 AP');
+ });
+
+ it('reports nothing for partial input and stays silent while it grows', () => {
+ const {input, onChange, container} = renderField('fa-IR', {
+ calendar: 'persian',
+ });
+ for (const text of [
+ '۱',
+ '۱۴۰۵',
+ '۱۴۰۵/',
+ '۱۴۰۵/۸',
+ '۱۴۰۵/۸/',
+ '۱۴۰۵/۸/۱',
+ ]) {
+ fireEvent.change(input, {target: {value: text}});
+ expect(input).not.toHaveAttribute('aria-invalid');
+ expect(within(container).getByRole('alert')).toHaveTextContent('');
+ }
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('commits a partial-looking date on blur', () => {
+ const {input, onChange} = renderField('fa-IR', {calendar: 'persian'});
+ fireEvent.change(input, {target: {value: '۱۴۰۵/۸/۱'}});
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-10-23');
+ });
+
+ it('shows a format hint in the empty focused field', () => {
+ const {input} = renderField('en', {calendar: 'persian'});
+ expect(input).toHaveAttribute('placeholder', 'Select a date');
+ fireEvent.focus(input);
+ expect(input.getAttribute('placeholder')).toMatch(
+ /^e\.g\., \d+\/\d+\/\d+ AP$/,
+ );
+ fireEvent.blur(input);
+ expect(input).toHaveAttribute('placeholder', 'Select a date');
+ });
+
+ describe('format hint example date', () => {
+ // 2026-11-07 is a Saturday.
+ beforeEach(() => {
+ vi.useFakeTimers({toFake: ['Date']});
+ vi.setSystemTime(new Date(2026, 10, 7, 12));
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ function hintFor(props: Partial<DateInputProps>) {
+ const {input} = renderField('en', {calendar: 'persian', ...props});
+ fireEvent.focus(input);
+ return input.getAttribute('placeholder');
+ }
+ const hintOf = (iso: ISODateString) =>
+ `e.g., ${formatCalendarDateHint(plainDateFromISO(iso), 'en', 'persian')}`;
+
+ it('uses max when max is before today', () => {
+ expect(hintFor({max: '2026-03-15'})).toBe(hintOf('2026-03-15'));
+ });
+
+ it('uses min when min is after today', () => {
+ expect(hintFor({min: '2027-02-01'})).toBe(hintOf('2027-02-01'));
+ });
+
+ it('uses the nearest weekday when today is a disabled Saturday', () => {
+ expect(
+ hintFor({
+ dateConstraints: [date => date.getDay() !== 0 && date.getDay() !== 6],
+ }),
+ ).toBe(hintOf('2026-11-06'));
+ });
+ });
+
+ it('shows a caller placeholder instead of the format hint', () => {
+ const {input} = renderField('en', {
+ calendar: 'persian',
+ placeholder: 'Pick a day',
+ });
+ fireEvent.focus(input);
+ expect(input).toHaveValue('');
+ expect(input).toHaveAttribute('placeholder', 'Pick a day');
+ });
+
+ it('opens its calendar in the same calendar', () => {
+ const {input} = renderField('en', {
+ calendar: 'persian',
+ value: '2026-11-02',
+ });
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ expect(document.querySelector('[role="grid"]')).toHaveAccessibleName(
+ 'Aban 1405 AP',
+ );
+ });
+
+ it('names the calendar in the description', () => {
+ const {input} = renderField('en', {calendar: 'hebrew'});
+ expect(input).toHaveAccessibleDescription('Dates use the Hebrew Calendar');
+ });
+
+ it('names no calendar when the field uses the provider calendar', () => {
+ render(
+ <InternationalizationProvider locale="fa-IR" calendar="persian">
+ <DateInput label="Date" onChange={vi.fn()} />
+ </InternationalizationProvider>,
+ );
+ const input = screen.getByRole('combobox');
+ expect(input).not.toHaveAttribute('aria-describedby');
+ fireEvent.focus(input);
+ expect(input.getAttribute('placeholder')).toMatch(/^e\.g\./);
+ });
+
+ it('names the Gregorian calendar inside a Persian provider', () => {
+ render(
+ <InternationalizationProvider locale="en" calendar="persian">
+ <DateInput label="Date" calendar="gregory" onChange={vi.fn()} />
+ </InternationalizationProvider>,
+ );
+ const input = screen.getByRole('combobox');
+ expect(input).toHaveAccessibleDescription(
+ 'Dates use the Gregorian Calendar',
+ );
+ fireEvent.focus(input);
+ expect(input).toHaveAttribute('placeholder', 'Select a date');
+ });
+
+ it('names no calendar for an iso8601 field in a Gregorian provider', () => {
+ const {input} = renderField('en', {calendar: 'iso8601'});
+ expect(input).not.toHaveAttribute('aria-describedby');
+ });
+
+ it('names the Persian calendar without a provider calendar', () => {
+ const {input} = renderField('en', {calendar: 'persian'});
+ expect(input).toHaveAccessibleDescription('Dates use the Persian Calendar');
+ });
+
+ it('keeps the Gregorian field free of a hint and a calendar description', () => {
+ const {input} = renderField('en');
+ fireEvent.focus(input);
+ expect(input).toHaveAttribute('placeholder', 'Select a date');
+ expect(input).not.toHaveAttribute('aria-describedby');
+ });
+});
+
+describe('DateInput onChange while typing a Gregorian date', () => {
+ it('fires once for a day-first date typed one key at a time', () => {
+ const {input, onChange} = renderField('en-GB');
+ typeSlowly(input, '12/01/2026');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-01-12');
+ });
+
+ it('commits a two-digit year in the locale order on blur', () => {
+ const {input, onChange} = renderField('en-GB');
+ typeSlowly(input, '12/01/90');
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('1990-01-12');
+ });
+
+ it('commits Gregorian text that only parseDateInput reads, on blur only', () => {
+ const {input, onChange, container} = renderField('en-US');
+ fireEvent.change(input, {target: {value: '2026-01-25 10:00'}});
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input).not.toHaveAttribute('aria-invalid');
+ expect(within(container).getByRole('alert')).toHaveTextContent('');
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-01-25');
+ });
+
+ it('commits a day-first date that parseDateInput reads, on Enter only', () => {
+ const {input, onChange} = renderField('en-US');
+ fireEvent.change(input, {target: {value: '25/1/2026'}});
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.keyDown(input, {key: 'Enter'});
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-01-25');
+ });
+
+ it('commits a day-first date that does not exist month-first, on blur only', () => {
+ const {input, onChange} = renderField('en-US');
+ typeSlowly(input, '13/5/2026');
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-05-13');
+ });
+
+ it('commits a month-first date that does not exist day-first, on blur', () => {
+ const {input, onChange} = renderField('en-GB');
+ fireEvent.change(input, {target: {value: '5/13/2026'}});
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-05-13');
+ });
+
+ it('never falls back to a month-first reading in a day-first locale', () => {
+ const {input, onChange} = renderField('en-GB');
+ fireEvent.change(input, {target: {value: '12/01/2026 10:00'}});
+ fireEvent.blur(input);
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input).toHaveValue('');
+ });
+
+ it.each(['blur', 'Enter'])(
+ 'keeps a one-digit year on %s and announces it as invalid',
+ commit => {
+ const {input, onChange, container} = renderField('en-US');
+ typeSlowly(input, '1/5/2');
+ const alert = within(container).getByRole('alert');
+ expect(alert).toHaveTextContent('');
+ if (commit === 'blur') {
+ fireEvent.blur(input);
+ } else {
+ fireEvent.keyDown(input, {key: 'Enter'});
+ }
+ expect(input).toHaveValue('1/5/2');
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expectShown(input, container, 'Invalid date');
+ expect(onChange).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ ['en-GB', '31/02/2026'],
+ ['en-US', '2/30/2026'],
+ ])(
+ 'still rejects a Gregorian date that does not exist in either order (%s %s)',
+ (locale, text) => {
+ const {input, onChange, container} = renderField(locale);
+ fireEvent.change(input, {target: {value: text}});
+ fireEvent.blur(input);
+ expect(input).toHaveValue(text);
+ expectShown(
+ input,
+ container,
+ 'This date does not exist in the Gregorian Calendar',
+ );
+ expect(onChange).not.toHaveBeenCalled();
+ },
+ );
+
+ it('never reads a date that does not exist in another calendar with parseDateInput', () => {
+ const {input, onChange, container} = renderField('en', {
+ calendar: 'persian',
+ });
+ fireEvent.change(input, {target: {value: '13/5/1405 AP'}});
+ fireEvent.blur(input);
+ expect(input).toHaveValue('13/5/1405 AP');
+ expectShown(
+ input,
+ container,
+ 'This date does not exist in the Persian Calendar',
+ );
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['fa-IR', 'persian', '1404/12/30'],
+ ['sv-SE', 'gregory', '2026-02-30'],
+ ] as const)(
+ 'reports no date while %s %s text grows to a day the month lacks',
+ (locale, calendar, text) => {
+ const {input, onChange} = renderField(locale, {calendar});
+ typeSlowly(input, text);
+ expect(onChange).not.toHaveBeenCalled();
+ },
+ );
+
+ it('reports a retyped date again after the caller keeps its value', () => {
+ const {input, onChange} = renderField('en-US', {value: '2026-01-01'});
+ for (let round = 1; round <= 2; round += 1) {
+ typeSlowly(input, '11/2/2026');
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledTimes(round);
+ }
+ });
+
+ it('does not fire again on blur for a date it already reported', () => {
+ const {input, onChange} = renderField('en-US');
+ fireEvent.change(input, {target: {value: '11/2/2026'}});
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-11-02');
+ });
+});
diff --git a/packages/core/src/DateInput/DateInput.calendarPresentation.test.tsx b/packages/core/src/DateInput/DateInput.calendarPresentation.test.tsx
new file mode 100644
index 0000000000..5abe673021
--- /dev/null
+++ b/packages/core/src/DateInput/DateInput.calendarPresentation.test.tsx
@@ -0,0 +1,340 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DateInput.calendarPresentation.test.tsx
+ * @input Uses vitest, Testing Library, temporal-polyfill, DateInput,
+ * DateTimeInput
+ * @output Surface choice in a calendar: every presentation and pointer, in
+ * Gregorian and Persian, and the warning for an explicit `native`
+ * @position Testing; validates that the native date control never shows a
+ * calendar it cannot show
+ */
+
+import {afterAll, afterEach, beforeAll, beforeEach} from 'vitest';
+import {describe, expect, it, vi} from 'vitest';
+import {render} from '@testing-library/react';
+import {Temporal as TemporalPolyfill} from 'temporal-polyfill/full';
+import {DateInput, type DateInputProps} from './DateInput';
+import {
+ DateTimeInput,
+ type ISODateTimeString,
+} from '../DateTimeInput/DateTimeInput';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import {resetDateSegmentProbe} from './nativeDateSegments';
+import {__resetDevWarnings} from '../utils/devWarning';
+import type {CalendarSystem} from '../utils/calendarSystem';
+
+const host = globalThis as {Temporal?: unknown};
+const hadTemporal = host.Temporal != null;
+beforeAll(() => {
+ host.Temporal ??= TemporalPolyfill;
+});
+afterAll(() => {
+ if (!hadTemporal) {
+ delete host.Temporal;
+ }
+});
+
+const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+function stubPointer(pointer: Pointer): void {
+ const isCoarse = pointer === 'coarse';
+ 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,
+ }));
+ vi.stubGlobal('ResizeObserver', MockResizeObserver);
+}
+
+beforeEach(() => {
+ __resetDevWarnings();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ resetDateSegmentProbe();
+});
+
+type Pointer = 'fine' | 'coarse';
+type Surface = 'native' | 'sheet' | 'popover';
+type PresentationProps = Pick<DateInputProps, 'presentation' | 'nativePicker'>;
+
+/** The surface on screen, read from the date control the field renders. */
+function surfaceShown(): Surface {
+ if (document.querySelector('input[type="date"]') != null) {
+ return 'native';
+ }
+ const input = document.querySelector<HTMLInputElement>('input');
+ return input?.getAttribute('inputmode') === 'none' ? 'sheet' : 'popover';
+}
+
+// [props, Gregorian fine, Gregorian coarse, Persian fine, Persian coarse]
+const MATRIX: ReadonlyArray<
+ [string, PresentationProps, Surface, Surface, Surface, Surface]
+> = [
+ ['default', {}, 'popover', 'native', 'popover', 'sheet'],
+ [
+ 'adaptive-native',
+ {presentation: 'adaptive-native'},
+ 'popover',
+ 'native',
+ 'popover',
+ 'sheet',
+ ],
+ ['native', {presentation: 'native'}, 'native', 'native', 'popover', 'sheet'],
+ [
+ 'popover',
+ {presentation: 'popover'},
+ 'popover',
+ 'popover',
+ 'popover',
+ 'popover',
+ ],
+ [
+ 'bottom-sheet',
+ {presentation: 'bottom-sheet'},
+ 'sheet',
+ 'sheet',
+ 'sheet',
+ 'sheet',
+ ],
+ [
+ 'adaptive-bottom-sheet',
+ {presentation: 'adaptive-bottom-sheet'},
+ 'popover',
+ 'sheet',
+ 'popover',
+ 'sheet',
+ ],
+ [
+ 'nativePicker="touch"',
+ {nativePicker: 'touch'},
+ 'popover',
+ 'native',
+ 'popover',
+ 'sheet',
+ ],
+ [
+ 'nativePicker="always"',
+ {nativePicker: 'always'},
+ 'native',
+ 'native',
+ 'popover',
+ 'sheet',
+ ],
+ [
+ 'nativePicker="never"',
+ {nativePicker: 'never'},
+ 'popover',
+ 'sheet',
+ 'popover',
+ 'sheet',
+ ],
+];
+
+const CASES = MATRIX.flatMap(
+ ([name, props, gregoryFine, gregoryCoarse, persianFine, persianCoarse]) =>
+ [
+ ['gregory', 'fine', gregoryFine],
+ ['gregory', 'coarse', gregoryCoarse],
+ ['persian', 'fine', persianFine],
+ ['persian', 'coarse', persianCoarse],
+ ].map(
+ ([calendar, pointer, surface]) =>
+ [name, calendar, pointer, surface, props] as [
+ string,
+ CalendarSystem,
+ Pointer,
+ Surface,
+ PresentationProps,
+ ],
+ ),
+);
+
+describe('DateInput surface in a calendar', () => {
+ it.each(CASES)(
+ '%s in %s on a %s pointer shows the %s',
+ (_name, calendar, pointer, surface, props) => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ stubPointer(pointer);
+ render(
+ <DateInput
+ label="Date"
+ calendar={calendar}
+ value="2026-11-02"
+ onChange={() => {}}
+ {...props}
+ />,
+ );
+ expect(surfaceShown()).toBe(surface);
+ },
+ );
+
+ it('takes the calendar from the provider', () => {
+ stubPointer('coarse');
+ render(
+ <InternationalizationProvider locale="en" calendar="persian">
+ <DateInput label="Date" value="2026-11-02" onChange={() => {}} />
+ </InternationalizationProvider>,
+ );
+ expect(surfaceShown()).toBe('sheet');
+ expect(document.querySelector('input')).toHaveValue('Aban 11, 1405 AP');
+ });
+
+ it('writes the sheet field text in the calendar', () => {
+ stubPointer('coarse');
+ render(
+ <DateInput
+ label="Date"
+ calendar="persian"
+ value="2026-11-02"
+ onChange={() => {}}
+ />,
+ );
+ expect(document.querySelector('input')).toHaveValue('Aban 11, 1405 AP');
+ });
+
+ it('warns once when an explicit native cannot show the calendar', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ stubPointer('coarse');
+ const field = (
+ <DateInput
+ label="Date"
+ calendar="persian"
+ presentation="native"
+ onChange={() => {}}
+ />
+ );
+ const first = render(field);
+ first.unmount();
+ render(field);
+ const messages = warn.mock.calls
+ .map(([message]) => String(message))
+ .filter(message => message.includes('presentation="native"'));
+ expect(messages).toHaveLength(1);
+ expect(messages[0]).toContain('"persian"');
+ });
+
+ it.each([
+ ['the default', {}],
+ ['nativePicker="always"', {nativePicker: 'always'}],
+ ['an explicit native in Gregorian', {presentation: 'native'}],
+ ] as const)('does not warn for %s', (_name, props) => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ stubPointer('coarse');
+ render(
+ <DateInput
+ label="Date"
+ calendar={'presentation' in props ? 'gregory' : 'persian'}
+ onChange={() => {}}
+ {...props}
+ />,
+ );
+ expect(
+ warn.mock.calls.filter(([message]) =>
+ String(message).includes('presentation="native"'),
+ ),
+ ).toHaveLength(0);
+ });
+});
+
+describe('DateTimeInput surface in a calendar', () => {
+ /** The date surface on screen; the time segment follows the same policy. */
+ function dateTimeSurfaceShown(): Surface {
+ if (document.querySelector('input[type="date"]') != null) {
+ return 'native';
+ }
+ return document.querySelector('input[inputmode="none"]') != null
+ ? 'sheet'
+ : 'popover';
+ }
+
+ it.each(CASES)(
+ '%s in %s on a %s pointer shows the %s',
+ (_name, calendar, pointer, surface, props) => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ stubPointer(pointer);
+ render(
+ <DateTimeInput
+ label="When"
+ calendar={calendar}
+ value={'2026-11-02T09:00' as ISODateTimeString}
+ onChange={() => {}}
+ {...props}
+ />,
+ );
+ expect(dateTimeSurfaceShown()).toBe(surface);
+ if (surface !== 'native') {
+ expect(document.querySelector('input[type="time"]')).toBeNull();
+ }
+ },
+ );
+
+ it('warns once when an explicit native cannot show the calendar', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ stubPointer('fine');
+ render(
+ <>
+ <DateTimeInput
+ label="Start"
+ calendar="hebrew"
+ presentation="native"
+ onChange={() => {}}
+ />
+ <DateTimeInput
+ label="End"
+ calendar="hebrew"
+ presentation="native"
+ onChange={() => {}}
+ />
+ </>,
+ );
+ const messages = warn.mock.calls
+ .map(([message]) => String(message))
+ .filter(message => message.includes('presentation="native"'));
+ expect(messages).toHaveLength(1);
+ expect(messages[0]).toContain('DateTimeInput');
+ });
+
+ it.each([
+ ['en', 'persian', 'Aban 11, 1405 AP'],
+ ['fa-IR', 'persian', '۱۱ آبان ۱۴۰۵ ه‍.ش.'],
+ ['th-TH', 'buddhist', '2 พฤศจิกายน พ.ศ. 2569'],
+ ] as const)(
+ 'writes the sheet date segment in %s %s with its era',
+ (locale, calendar, text) => {
+ stubPointer('coarse');
+ render(
+ <InternationalizationProvider locale={locale}>
+ <DateTimeInput
+ label="When"
+ calendar={calendar}
+ presentation="adaptive-bottom-sheet"
+ value={'2026-11-02T09:00' as ISODateTimeString}
+ onChange={() => {}}
+ />
+ </InternationalizationProvider>,
+ );
+ expect(document.querySelector('input[inputmode="none"]')).toHaveValue(
+ text,
+ );
+ },
+ );
+});
diff --git a/packages/core/src/DateInput/DateInput.doc.mjs b/packages/core/src/DateInput/DateInput.doc.mjs
index 27fa65ef6b..65a2bf9fd2 100644
--- a/packages/core/src/DateInput/DateInput.doc.mjs
+++ b/packages/core/src/DateInput/DateInput.doc.mjs
@@ -101,7 +101,8 @@ export const docs = {
{
name: 'placeholder',
type: 'string',
- description: 'Placeholder text shown in the text input.',
+ description:
+ 'Placeholder text shown in the text input. A caller placeholder replaces the calendar format hint.',
default: "'Select a date'",
},
{
@@ -154,21 +155,28 @@ export const docs = {
name: 'format',
type: "'date' | 'date_long' | 'date_weekday' | 'system_date' | ((value: ISODateString) => string)",
description:
- "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.",
+ "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'. 'date', 'date_long', and 'date_weekday' write the date in the field's calendar; 'system_date' stays the Gregorian ISO date. A function receives the ISO value and returns a custom string; the field cannot re-commit text it cannot read back. Applies only to the committed value, never to text being typed.",
default: "'date_long'",
},
+ {
+ name: 'calendar',
+ type: "'gregory' | 'iso8601' | 'buddhist' | 'roc' | 'japanese' | 'persian' | 'indian' | 'hebrew' | 'chinese' | 'dangi' | 'coptic' | 'ethiopic' | 'ethioaa' | 'islamic-civil' | 'islamic-tbla' | 'islamic-umalqura'",
+ description:
+ 'The calendar the text field reads and writes dates in, and the calendar its popover and bottom sheet show. value, onChange, min, and max stay Gregorian ISO dates. People type a date the way the locale writes it in this calendar, in any decimal digits; the field reports a date only once it is complete, and names a date the calendar does not have. Years are years of this calendar: a Buddhist field reads 2026 as Buddhist year 2026, so set min and max on Buddhist and Minguo calendar fields to catch a Gregorian year typed by mistake. Calendars other than gregory, iso8601, buddhist, roc, and japanese need Temporal, native or a polyfill the application loads; without it the field shows Gregorian dates. With a calendar other than gregory or iso8601, a presentation that would show the native date control shows the popover on a fine pointer and the bottom sheet on a coarse pointer, because the native control is Gregorian; the bottom sheet shows the months, leap months, and era years of the calendar. A year in which the era changes is labeled with the era of the shown month, such as 平成31 in January 2019 and 令和元 in July.',
+ default: "the InternationalizationProvider's calendar, else 'gregory'",
+ },
{
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'native' | 'adaptive-bottom-sheet' | 'adaptive-native'",
description:
- "Which surface draws the date picker. 'adaptive-native' (the default) uses Astryx's calendar popover on a fine pointer and the browser/OS picker (input type=date) on a coarse pointer, keeping Astryx fallbacks where a native control cannot express the value; 'native' always uses the browser/OS picker with no fallback; 'adaptive-bottom-sheet' uses the popover on a fine pointer and Astryx's bottom-sheet picker on a coarse pointer; 'popover' and 'bottom-sheet' force that Astryx surface on every pointer. Every value opens a picker; a typed-only field is TimeInput's alone. Use a non-native presentation for a field that needs weekStartsOn, numberOfMonths or dateConstraints, none of which a native picker can express.",
+ "Which surface draws the date picker. 'adaptive-native' (the default) uses Astryx's calendar popover on a fine pointer and the browser/OS picker (input type=date) on a coarse pointer, keeping Astryx fallbacks where a native control cannot express the value; 'native' always uses the browser/OS picker with no fallback; 'adaptive-bottom-sheet' uses the popover on a fine pointer and Astryx's bottom-sheet picker on a coarse pointer; 'popover' and 'bottom-sheet' force that Astryx surface on every pointer. Every value opens a picker; a typed-only field is TimeInput's alone. Use a non-native presentation for a field that needs weekStartsOn, numberOfMonths or dateConstraints, none of which a native picker can express. With a calendar other than gregory or iso8601, 'native' and 'adaptive-native' use the popover on a fine pointer and the bottom sheet on a coarse pointer, and an explicit 'native' warns in development.",
default: "'adaptive-native'",
},
{
name: 'nativePicker',
type: "'touch' | 'always' | 'never'",
description:
- "Deprecated: use presentation ('touch' = 'adaptive-native', 'always' = 'native', 'never' = 'adaptive-bottom-sheet'). Still works exactly as released; presentation wins when both are set.",
+ "Deprecated: use presentation ('touch' = 'adaptive-native', 'always' = 'native', 'never' = 'adaptive-bottom-sheet'). Still works exactly as released; presentation wins when both are set. With a calendar other than gregory or iso8601, 'touch' and 'always' use the popover on a fine pointer and the bottom sheet on a coarse pointer.",
default: "'touch'",
},
{
@@ -243,6 +251,11 @@ export const docs = {
description:
'Use min, max, and dateConstraints to restrict selectable dates to valid ranges.',
},
+ {
+ guidance: true,
+ description:
+ 'Set min and max on a Buddhist or Minguo calendar field, so a Gregorian year typed by mistake shows an error instead of a date centuries away.',
+ },
{
guidance: true,
description:
@@ -294,7 +307,7 @@ export const docs = {
name: 'Text input',
required: true,
description:
- 'A field where the user can type a date directly. Parses common formats like MM/DD/YYYY.',
+ "A field where the user can type a date directly, written the way the locale writes it in the field's calendar.",
},
{
name: 'Calendar icon',
@@ -346,6 +359,11 @@ export const docsZh = {
description:
'Use min, max, and dateConstraints to restrict selectable dates to valid ranges.',
},
+ {
+ guidance: true,
+ description:
+ 'Set min and max on a Buddhist or Minguo calendar field, so a Gregorian year typed by mistake shows an error instead of a date centuries away.',
+ },
{
guidance: true,
description:
@@ -462,7 +480,8 @@ export const docsZh = {
{
name: 'placeholder',
type: 'string',
- description: '文本输入框中显示的占位符文本。',
+ description:
+ '文本输入框中显示的占位符文本。调用方提供的占位符会替代日历格式提示。',
default: "'Select a date'",
},
{
@@ -511,21 +530,28 @@ export const docsZh = {
name: 'format',
type: "'date' | 'date_long' | 'date_weekday' | 'system_date' | ((value: ISODateString) => string)",
description:
- "已选日期的显示格式。命名值复用 Timestamp 的格式词汇:'date' 显示 'Mar 21, 2026','date_long' 显示 'March 21, 2026','date_weekday' 显示 'Wed, Mar 21, 2026','system_date' 显示 '2026-03-21'。函数接收 ISO 值并返回自定义字符串。仅作用于已提交的值,不影响正在输入的文本。",
+ "已选日期的显示格式。命名值复用 Timestamp 的格式词汇:'date' 显示 'Mar 21, 2026','date_long' 显示 'March 21, 2026','date_weekday' 显示 'Wed, Mar 21, 2026','system_date' 显示 '2026-03-21'。'date'、'date_long' 与 'date_weekday' 按字段的历法书写日期;'system_date' 始终为公历 ISO 日期。函数接收 ISO 值并返回自定义字符串;字段无法读回的文本在编辑后不能重新提交。仅作用于已提交的值,不影响正在输入的文本。",
default: "'date_long'",
},
+ {
+ name: 'calendar',
+ type: "'gregory' | 'iso8601' | 'buddhist' | 'roc' | 'japanese' | 'persian' | 'indian' | 'hebrew' | 'chinese' | 'dangi' | 'coptic' | 'ethiopic' | 'ethioaa' | 'islamic-civil' | 'islamic-tbla' | 'islamic-umalqura'",
+ description:
+ '文本字段读写日期所用的历法,也是其弹出日历和底部选择器显示的历法。value、onChange、min 和 max 始终为公历 ISO 日期。用户按当前语言区域在该历法中的写法输入日期,可使用任意十进制数字;只有输入完整时字段才会报告日期,并会指出该历法中不存在的日期。年份是该历法的年份:佛历字段把 2026 读作佛历 2026 年,因此请为佛历和民国纪年字段设置 min 和 max,以发现误输入的公历年份。gregory、iso8601、buddhist、roc 和 japanese 以外的历法需要 Temporal(原生或由应用加载的 polyfill);没有 Temporal 时字段显示公历日期。使用 gregory 或 iso8601 以外的历法时,原本显示原生日期控件的呈现会在精细指针上显示弹出层、在粗指针上显示底部选择器,因为原生控件只显示公历;底部选择器显示该历法的月份、闰月和带纪元的年份。年号更替的年份按所显示月份的年号标注,如 2019 年 1 月为“平成31”,7 月为“令和元”。',
+ default: "InternationalizationProvider 的历法,否则为 'gregory'",
+ },
{
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'native' | 'adaptive-bottom-sheet' | 'adaptive-native'",
description:
- "由哪个界面绘制日期选择器。'adaptive-native'(默认)在精细指针上使用 Astryx 日历弹出层、在粗指针上使用浏览器/操作系统选择器(input type=date),且原生控件无法表达值时保留 Astryx 回退;'native' 始终使用浏览器/操作系统选择器且不回退;'adaptive-bottom-sheet' 在精细指针上用弹出层、在粗指针上用 Astryx 底部选择器;'popover' 与 'bottom-sheet' 在任何指针上强制使用对应 Astryx 界面。每个值都会打开选择器;仅输入字段的呈现只属于 TimeInput。需要 weekStartsOn、numberOfMonths 或 dateConstraints 的字段应使用非原生呈现,原生选择器无法表达这些。",
+ "由哪个界面绘制日期选择器。'adaptive-native'(默认)在精细指针上使用 Astryx 日历弹出层、在粗指针上使用浏览器/操作系统选择器(input type=date),且原生控件无法表达值时保留 Astryx 回退;'native' 始终使用浏览器/操作系统选择器且不回退;'adaptive-bottom-sheet' 在精细指针上用弹出层、在粗指针上用 Astryx 底部选择器;'popover' 与 'bottom-sheet' 在任何指针上强制使用对应 Astryx 界面。每个值都会打开选择器;仅输入字段的呈现只属于 TimeInput。需要 weekStartsOn、numberOfMonths 或 dateConstraints 的字段应使用非原生呈现,原生选择器无法表达这些。使用 gregory 或 iso8601 以外的历法时,'native' 与 'adaptive-native' 在精细指针上使用弹出层、在粗指针上使用底部选择器,显式的 'native' 会在开发环境中发出警告。",
default: "'adaptive-native'",
},
{
name: 'nativePicker',
type: "'touch' | 'always' | 'never'",
description:
- "已弃用:请使用 presentation('touch'='adaptive-native'、'always'='native'、'never'='adaptive-bottom-sheet')。仍按已发布行为工作;同时设置时以 presentation 为准。",
+ "已弃用:请使用 presentation('touch'='adaptive-native'、'always'='native'、'never'='adaptive-bottom-sheet')。仍按已发布行为工作;同时设置时以 presentation 为准。使用 gregory 或 iso8601 以外的历法时,'touch' 与 'always' 在精细指针上使用弹出层、在粗指针上使用底部选择器。",
default: "'touch'",
},
{
@@ -601,6 +627,11 @@ export const docsDense = {
description:
'Use min, max, and dateConstraints to restrict selectable dates to valid ranges.',
},
+ {
+ guidance: true,
+ description:
+ 'Set min and max on a Buddhist or Minguo calendar field, so a Gregorian year typed by mistake shows an error instead of a date centuries away.',
+ },
{
guidance: true,
description:
@@ -671,11 +702,13 @@ 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.",
+ "committed-value display: 'date_long' (default, March 21, 2026), 'date' (Mar 21, 2026), 'date_weekday' (Wed, Mar 21, 2026), 'system_date' (2026-03-21, always Gregorian ISO), or (iso)=>string; reuses Timestamp vocabulary; named formats write the field's calendar. Committed value only, not while typing.",
+ calendar:
+ "calendar for typed + committed text, the popover, and the bottom sheet (months, leap months, era years; an era-change year follows the shown month, e.g. 平成31 in Jan 2019, 令和元 in Jul) (default: provider's, else 'gregory'); values stay Gregorian ISO; years are the calendar's, so set min/max on buddhist/roc fields; non-Gregorian-aligned calendars need Temporal (native or app-loaded polyfill), else Gregorian; non-gregory/iso8601 never shows the native control: popover fine / sheet coarse",
presentation:
- "which surface draws the picker: 'adaptive-native' (default) = Astryx popover on fine, browser/OS on coarse w/ Astryx fallbacks; 'native' = browser/OS always, no fallback; 'adaptive-bottom-sheet' = popover fine / Astryx sheet coarse; 'popover'/'bottom-sheet' force Astryx. every value opens a picker (no text-only value; that is TimeInput's). use non-native for weekStartsOn/numberOfMonths/dateConstraints.",
+ "which surface draws the picker: 'adaptive-native' (default) = Astryx popover on fine, browser/OS on coarse w/ Astryx fallbacks; 'native' = browser/OS always, no fallback; 'adaptive-bottom-sheet' = popover fine / Astryx sheet coarse; 'popover'/'bottom-sheet' force Astryx. every value opens a picker (no text-only value; that is TimeInput's). use non-native for weekStartsOn/numberOfMonths/dateConstraints. non-gregory/iso8601 calendar: native + adaptive-native become popover fine / sheet coarse; explicit 'native' warns in dev.",
nativePicker:
- "deprecated, use presentation: 'touch'='adaptive-native', 'always'='native', 'never'='adaptive-bottom-sheet'. still works as released; presentation wins if both set.",
+ "deprecated, use presentation: 'touch'='adaptive-native', 'always'='native', 'never'='adaptive-bottom-sheet'. still works as released, except that a calendar other than gregory or iso8601 never shows the native control; presentation wins if both set.",
containerXstyle:
'Field box (label+control+status); also containerClassName/containerStyle. no effect in InputGroup or horizontal-labels FormLayout',
containerClassName:
diff --git a/packages/core/src/DateInput/DateInput.noTemporal.test.tsx b/packages/core/src/DateInput/DateInput.noTemporal.test.tsx
new file mode 100644
index 0000000000..43def49adb
--- /dev/null
+++ b/packages/core/src/DateInput/DateInput.noTemporal.test.tsx
@@ -0,0 +1,213 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DateInput.noTemporal.test.tsx
+ * @input Uses vitest, Testing Library, DateInput, DateTimeInput; no Temporal
+ * @output Presentations without Temporal: a calendar that needs it falls back
+ * to Gregorian, with the native control and a warning, while Buddhist and
+ * Japanese still show their years in the bottom sheet
+ * @position Testing; validates the runtime without Temporal, such as Safari
+ */
+
+import {afterAll, afterEach, beforeAll, beforeEach} from 'vitest';
+import {describe, expect, it, vi, type MockInstance} from 'vitest';
+import {fireEvent, render, screen, within} from '@testing-library/react';
+import {DateInput, type DateInputProps} from './DateInput';
+import {
+ DateTimeInput,
+ type ISODateTimeString,
+} from '../DateTimeInput/DateTimeInput';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import {resetDateSegmentProbe} from './nativeDateSegments';
+import {__resetDevWarnings} from '../utils/devWarning';
+
+const host = globalThis as {Temporal?: unknown};
+const saved = host.Temporal;
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;
+
+function stubCoarsePointer(): void {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: /pointer:\s*coarse/.test(query)
+ ? true
+ : /pointer:\s*fine/.test(query)
+ ? false
+ : HOVER_CAPABLE.test(query),
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ }));
+}
+
+function withLayout<T>(fn: () => T): T {
+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', {
+ configurable: true,
+ get(this: HTMLElement) {
+ return this.dataset?.scroller === 'months' ? 360 : 0;
+ },
+ });
+ try {
+ return fn();
+ } finally {
+ delete (HTMLElement.prototype as {clientWidth?: unknown}).clientWidth;
+ }
+}
+
+beforeAll(() => {
+ delete host.Temporal;
+ Element.prototype.scrollTo = vi.fn();
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.open = true;
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.open = false;
+ });
+});
+
+afterAll(() => {
+ if (saved != null) {
+ host.Temporal = saved;
+ }
+});
+
+beforeEach(() => {
+ __resetDevWarnings();
+ vi.stubGlobal('ResizeObserver', MockResizeObserver);
+ stubCoarsePointer();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ resetDateSegmentProbe();
+});
+
+type WarnSpy = MockInstance<typeof console.warn>;
+
+function warnings(): WarnSpy {
+ return vi.spyOn(console, 'warn').mockImplementation(() => {});
+}
+
+function messages(warn: WarnSpy): string[] {
+ return warn.mock.calls.map(([message]) => String(message));
+}
+
+function renderField(locale: string, props: Partial<DateInputProps>) {
+ return withLayout(() =>
+ render(
+ <InternationalizationProvider locale={locale}>
+ <DateInput label="Date" onChange={() => {}} {...props} />
+ </InternationalizationProvider>,
+ ),
+ );
+}
+
+describe('presentations without Temporal', () => {
+ it('runs without Temporal', () => {
+ expect(host.Temporal).toBeUndefined();
+ });
+
+ it('shows a Persian field as a Gregorian native control and warns', () => {
+ const warn = warnings();
+ renderField('en', {calendar: 'persian', value: '2026-11-02'});
+ expect(document.querySelector('input[type="date"]')).not.toBeNull();
+ const all = messages(warn);
+ expect(all.some(m => m.includes('needs a Temporal'))).toBe(true);
+ expect(all.some(m => m.includes('presentation="native"'))).toBe(false);
+ });
+
+ it('keeps an explicit native native, because the calendar fell back', () => {
+ const warn = warnings();
+ renderField('en', {
+ calendar: 'persian',
+ presentation: 'native',
+ value: '2026-11-02',
+ });
+ expect(document.querySelector('input[type="date"]')).not.toBeNull();
+ expect(messages(warn).some(m => m.includes('presentation="native"'))).toBe(
+ false,
+ );
+ });
+
+ it('shows Gregorian months in a Persian bottom sheet', () => {
+ warnings();
+ renderField('en', {
+ calendar: 'persian',
+ presentation: 'bottom-sheet',
+ value: '2026-11-02',
+ min: '2026-10-01',
+ max: '2026-12-31',
+ });
+ withLayout(() => fireEvent.click(screen.getByRole('combobox')));
+ expect(screen.getByRole('combobox')).toHaveValue('November 2, 2026');
+ expect(
+ document.querySelector('[data-title="month-year"]'),
+ ).toHaveTextContent('November 2026');
+ });
+
+ it('shows Buddhist years in the bottom sheet a coarse pointer gets', () => {
+ const warn = warnings();
+ renderField('th-TH', {
+ calendar: 'buddhist',
+ value: '2026-11-02',
+ min: '2025-01-01',
+ max: '2026-12-31',
+ });
+ expect(document.querySelector('input[type="date"]')).toBeNull();
+ expect(screen.getByRole('combobox')).toHaveAttribute('inputmode', 'none');
+ expect(screen.getByRole<HTMLInputElement>('combobox').value).toContain(
+ '2569',
+ );
+ withLayout(() => fireEvent.click(screen.getByRole('combobox')));
+ expect(
+ document.querySelector('[data-title="month-year"]'),
+ ).toHaveTextContent('2569');
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('labels Japanese years with their era', () => {
+ const warn = warnings();
+ renderField('ja-JP', {
+ calendar: 'japanese',
+ value: '2026-11-02',
+ min: '2025-01-01',
+ max: '2026-12-31',
+ });
+ withLayout(() => fireEvent.click(screen.getByRole('combobox')));
+ withLayout(() =>
+ fireEvent.click(
+ document.querySelector<HTMLElement>('[data-title="month-year"]')!,
+ ),
+ );
+ const years = within(screen.getByRole('listbox', {name: 'Year'}))
+ .getAllByRole('option')
+ .map(option => option.textContent);
+ expect(years).toEqual(['令和7', '令和8']);
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('shows a Persian DateTimeInput as Gregorian native controls', () => {
+ warnings();
+ render(
+ <DateTimeInput
+ label="When"
+ calendar="persian"
+ value={'2026-11-02T09:00' as ISODateTimeString}
+ onChange={() => {}}
+ />,
+ );
+ expect(document.querySelector('input[type="date"]')).not.toBeNull();
+ });
+});
diff --git a/packages/core/src/DateInput/DateInput.test.tsx b/packages/core/src/DateInput/DateInput.test.tsx
index bb6a245577..ae31438d5b 100644
--- a/packages/core/src/DateInput/DateInput.test.tsx
+++ b/packages/core/src/DateInput/DateInput.test.tsx
@@ -337,7 +337,7 @@ describe('DateInput', () => {
expect(onChange).toHaveBeenCalledWith('2026-06-15');
});
- it('reverts on blur when typed date violates constraints', () => {
+ it('keeps a typed date that violates constraints and shows the bounds on blur', () => {
const onChange = vi.fn();
render(
<DateInput
@@ -353,8 +353,12 @@ describe('DateInput', () => {
fireEvent.change(input, {target: {value: '04/15/2026'}});
fireEvent.blur(input);
- // Should revert to previous value
- expect(screen.getByDisplayValue('March 10, 2026')).toBeInTheDocument();
+ // The text stays so the person can correct it; the value does not change.
+ expect(input).toHaveValue('04/15/2026');
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expect(input).toHaveAccessibleDescription(
+ 'Enter a date from March 1, 2026 to March 31, 2026',
+ );
expect(onChange).not.toHaveBeenCalled();
});
@@ -838,6 +842,249 @@ describe('DateInput', () => {
);
});
+ describe('typed text while the field is disabled or busy', () => {
+ const locks = ['isLoading', 'isDisabled'] as const;
+ type Lock = (typeof locks)[number];
+
+ function renderField(value: ISODateString) {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const props = {label: 'Date', value, onChange} satisfies DateInputProps;
+ const {rerender} = render(<DateInput {...props} />);
+ const setProps = (lock?: Lock, next?: {value: ISODateString}) =>
+ rerender(
+ <DateInput
+ {...props}
+ isLoading={lock === 'isLoading'}
+ isDisabled={lock === 'isDisabled'}
+ {...next}
+ />,
+ );
+ return {user, onChange, input: screen.getByRole('combobox'), setProps};
+ }
+
+ function expectNoRejection(input: HTMLElement) {
+ expect(input).not.toHaveAttribute('aria-invalid');
+ expect(screen.queryByText('Invalid date')).not.toBeInTheDocument();
+ }
+
+ it.each(locks)(
+ 'ignores Enter and blur while %s, then rejects the text once editable',
+ async lock => {
+ const {user, onChange, input, setProps} = renderField('2026-03-15');
+ await user.clear(input);
+ await user.type(input, '3/15/2');
+
+ setProps(lock);
+ await user.keyboard('{Enter}');
+ await user.tab();
+ expect(input).toHaveValue('3/15/2');
+ expect(onChange).not.toHaveBeenCalled();
+ expectNoRejection(input);
+
+ setProps();
+ act(() => input.focus());
+ await user.tab();
+ expect(input).toHaveValue('3/15/2');
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expect(screen.getByText('Invalid date')).toBeInTheDocument();
+ },
+ );
+
+ it.each(locks)(
+ 'hides a shown rejection while %s and shows it again once editable',
+ async lock => {
+ const {user, input, setProps} = renderField('2026-03-15');
+ await user.clear(input);
+ await user.type(input, '3/15/2');
+ await user.tab();
+ expect(screen.getByText('Invalid date')).toBeInTheDocument();
+
+ setProps(lock);
+ expect(input).toHaveValue('3/15/2');
+ expectNoRejection(input);
+
+ setProps();
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expect(screen.getByText('Invalid date')).toBeInTheDocument();
+ },
+ );
+
+ it.each(locks)(
+ 'commits a date typed before %s only once editable',
+ async lock => {
+ const {user, onChange, input, setProps} = renderField('2026-01-12');
+ await user.clear(input);
+ // A two-digit year commits only on Enter or blur.
+ await user.type(input, '3/15/26');
+
+ setProps(lock);
+ await user.tab();
+ expect(input).toHaveValue('3/15/26');
+ expect(onChange).not.toHaveBeenCalled();
+
+ setProps();
+ act(() => input.focus());
+ await user.tab();
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('2026-03-15');
+ },
+ );
+
+ it.each(locks)(
+ 'replaces the text with a new value while %s',
+ async lock => {
+ const {user, onChange, input, setProps} = renderField('2026-03-15');
+ await user.clear(input);
+ await user.type(input, '3/15/2');
+
+ setProps(lock);
+ setProps(lock, {value: '2026-04-01'});
+ expect(input).toHaveValue('April 1, 2026');
+
+ setProps(undefined, {value: '2026-04-01'});
+ act(() => input.focus());
+ await user.tab();
+ expect(input).toHaveValue('April 1, 2026');
+ expect(onChange).not.toHaveBeenCalled();
+ expectNoRejection(input);
+ },
+ );
+
+ it.each(locks)(
+ 'shows the old value once a %s change that did not take a typed date ends',
+ async lock => {
+ const {user, onChange, input, setProps} = renderField('2026-01-12');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-15');
+
+ setProps(lock);
+ await user.tab();
+ expect(input).toHaveValue('3/15/2026');
+
+ setProps();
+ expect(input).toHaveValue('January 12, 2026');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+ expect(onChange).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it.each(
+ locks.flatMap(lock => [
+ [lock, 'blur'],
+ [lock, 'Enter'],
+ ]),
+ )(
+ 'keeps a reported date in the focused field when %s ends, until %s',
+ async (lock, commit) => {
+ const {user, onChange, input, setProps} = renderField('2026-01-12');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-15');
+
+ setProps(lock);
+ setProps();
+ expect(input).toHaveFocus();
+ expect(input).toHaveValue('3/15/2026');
+
+ if (commit === 'blur') {
+ await user.tab();
+ } else {
+ await user.keyboard('{Enter}');
+ }
+ expect(input).toHaveValue('January 12, 2026');
+ expect(onChange).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it.each(locks)(
+ 'shows the new value once a %s change that took a typed date ends',
+ async lock => {
+ const {user, input, setProps} = renderField('2026-01-12');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+
+ setProps(lock, {value: '2026-03-15'});
+ await user.tab();
+ expect(input).toHaveValue('3/15/2026');
+
+ setProps(undefined, {value: '2026-03-15'});
+ expect(input).toHaveValue('March 15, 2026');
+ },
+ );
+
+ it.each([
+ ['fails', false, 'January 12, 2026'],
+ ['succeeds', true, 'March 15, 2026'],
+ ])(
+ 'shows the resulting value after a changeAction save that %s',
+ async (_, takes, shown) => {
+ const user = userEvent.setup();
+ let settle = () => {};
+ function Field() {
+ const [value, setValue] = useState<ISODateString>('2026-01-12');
+ const save = async (next: ISODateString | undefined) =>
+ new Promise<void>(resolve => {
+ settle = () => {
+ if (takes && next) {
+ setValue(next);
+ }
+ resolve();
+ };
+ });
+ return (
+ <DateInput
+ label="Date"
+ value={value}
+ onChange={() => {}}
+ changeAction={save}
+ />
+ );
+ }
+ render(<Field />);
+ const input = screen.getByRole('combobox');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+ expect(input).toHaveAttribute('aria-busy', 'true');
+ await user.tab();
+
+ await act(async () => settle());
+ expect(input).toHaveValue(shown);
+ },
+ );
+
+ it('keeps a reported date in the focused field when a changeAction save fails', async () => {
+ const user = userEvent.setup();
+ let fail = () => {};
+ function Field() {
+ const [value] = useState<ISODateString>('2026-01-12');
+ const save = async () =>
+ new Promise<void>(resolve => {
+ fail = resolve;
+ });
+ return (
+ <DateInput
+ label="Date"
+ value={value}
+ onChange={() => {}}
+ changeAction={save}
+ />
+ );
+ }
+ render(<Field />);
+ const input = screen.getByRole('combobox');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+
+ await act(async () => fail());
+ expect(input).toHaveFocus();
+ expect(input).toHaveValue('3/15/2026');
+ });
+ });
+
// --- Enter key commits typed date ---
it('commits typed date and fires onChange on Enter key', () => {
@@ -845,8 +1092,9 @@ describe('DateInput', () => {
render(<DateInput label="Date" onChange={onChange} />);
const input = screen.getByRole('combobox');
- fireEvent.change(input, {target: {value: '03/15/2026'}});
- onChange.mockClear();
+ // A two-digit year commits only on Enter or blur.
+ fireEvent.change(input, {target: {value: '03/15/26'}});
+ expect(onChange).not.toHaveBeenCalled();
fireEvent.keyDown(input, {key: 'Enter'});
expect(onChange).toHaveBeenCalledWith('2026-03-15');
@@ -857,8 +1105,9 @@ describe('DateInput', () => {
render(<DateInput label="Date" onChange={onChange} />);
const input = screen.getByRole('combobox');
- fireEvent.change(input, {target: {value: '03/15/2026'}});
- onChange.mockClear();
+ // A two-digit year commits only on Enter or blur.
+ fireEvent.change(input, {target: {value: '03/15/26'}});
+ expect(onChange).not.toHaveBeenCalled();
// The composing keydown (isComposing / legacy keyCode 229) that commits an
// IME candidate fires before compositionend; it must not be read as
@@ -1225,7 +1474,7 @@ describe('DateInput', () => {
).toContain(tooltip.id);
});
- it('drops a draft instead of committing it when the field becomes disabled (AST-085 FR2)', async () => {
+ it('keeps a cleared draft without committing it when the field becomes disabled (AST-085 FR2)', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const {rerender} = render(
@@ -1246,6 +1495,7 @@ describe('DateInput', () => {
await user.keyboard('{Enter}');
await user.tab();
expect(onChange).not.toHaveBeenCalled();
+ expect(input).toHaveValue('');
});
it('links the reason tooltip from the input via aria-describedby', () => {
diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsx
index ef88660bbf..2cb7b742dd 100644
--- a/packages/core/src/DateInput/DateInput.tsx
+++ b/packages/core/src/DateInput/DateInput.tsx
@@ -4,7 +4,7 @@
/**
* @file DateInput.tsx
- * @input Uses React, useId, useState, useCallback, useRef, Field, Icon, Calendar, usePopover, InputGroupContext
+ * @input Uses React, useId, useCallback, useRef, useTypedDateField, Field, Icon, Calendar, usePopover, InputGroupContext
* @output Exports DateInput component, DateInputProps
* @position Core implementation; consumed by index.ts, tested by DateInput.test.tsx
*
@@ -19,7 +19,6 @@
import {
use,
useId,
- useState,
useCallback,
useRef,
useOptimistic,
@@ -71,19 +70,17 @@ import {
import {NativeDateField} from './NativeDateField';
import {TouchDateField} from './TouchDateField';
import {useTooltip} from '../Tooltip';
-import {getInputARIA, isImeKeyEvent, parseDateInput} from '../utils';
+import {getInputARIA, isImeKeyEvent} from '../utils';
import {chainEventHandlers} from '../utils/chainEventHandlers';
-import {
- plainDateFromISO,
- plainDateToISO,
- formatSharedDate,
-} from '../utils/plainDate';
+import type {CalendarSystem} from '../utils/calendarSystem';
+import {isRenderable} from '../utils/isRenderable';
+import {useTypedDateField} from './useTypedDate';
import type {TimestampFormat} from '../Timestamp';
import {
- effectivePickerPresentation,
resolvePickerPresentation,
type PickerPresentation,
} from '../utils/inputPresentation';
+import {useCalendarPresentation} from './useCalendarPresentation';
import {useDevWarning} from '../hooks/useDevWarning';
const styles = stylex.create({
@@ -204,7 +201,6 @@ import {
import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
-import {useLocale} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
import type {FieldStatusPlacement} from '../Field/fieldStatusPlacement';
@@ -318,7 +314,8 @@ export interface DateInputProps extends Omit<
dateConstraints?: ReadonlyArray<(date: Date) => boolean>;
/**
- * Placeholder text shown when no date is selected.
+ * Placeholder text shown when no date is selected. A caller placeholder
+ * replaces the calendar format hint.
* @default "Select a date"
*/
placeholder?: string;
@@ -391,9 +388,10 @@ export interface DateInputProps extends Omit<
* - `(value: ISODateString) => string`: fully custom display string
*
* Formatting applies only to the committed value — never to text the user is
- * actively typing. A custom function's output that `parseDateInput` cannot
- * read back can't be re-committed after an edit; external `value` changes
- * always recompute the display from the ISO value.
+ * actively typing. Named formats write the date in the field's `calendar`;
+ * `'system_date'` stays the Gregorian ISO date. A custom function's output
+ * that the field cannot read back can't be re-committed after an edit;
+ * external `value` changes always recompute the display from the ISO value.
*
* @default 'date_long'
* @example
@@ -409,6 +407,29 @@ export interface DateInputProps extends Omit<
*/
format?: DateInputFormat | ((value: ISODateString) => string);
+ /**
+ * The calendar the field shows dates in, such as `'persian'`, `'hebrew'`, or
+ * `'buddhist'`: the text field, its calendar popover, and the bottom sheet's
+ * months and wheels. `value`, `onChange`, `min`, and `max` stay Gregorian
+ * ISO dates in every calendar. People type a date the way the locale writes
+ * it in this calendar, and the committed text uses it.
+ * Years are years of this calendar, so a Buddhist field reads `2026` as
+ * Buddhist year 2026; set `min` and `max` to catch a year typed in the
+ * wrong calendar. Calendars other than `gregory`, `iso8601`, `buddhist`,
+ * `roc`, and `japanese` need `Temporal`, native or a polyfill the
+ * application loads; without it the field uses the Gregorian calendar.
+ * The native date control is Gregorian, so with a calendar other than
+ * `gregory` or `iso8601` every presentation that would show it uses the
+ * popover on a fine pointer and the bottom sheet on a coarse pointer.
+ *
+ * @default the InternationalizationProvider's calendar, else `'gregory'`
+ * @example
+ * ```
+ * <DateInput label="Start date" calendar="persian" value={date} onChange={setDate} />
+ * ```
+ */
+ calendar?: CalendarSystem;
+
/**
* 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
@@ -434,6 +455,9 @@ export interface DateInputProps extends Omit<
* picker. `dateConstraints` is enforced the same way, on commit, and is
* reason enough to prefer `'never'` on a field that uses it.
*
+ * In a calendar other than `gregory` or `iso8601`, `'touch'` and `'always'`
+ * use the calendar popover on a mouse and the touch picker on a finger.
+ *
* @default 'touch'
* @deprecated Use `presentation` (`spec:AST-043` FR3):
* `'touch'` → `'adaptive-native'`, `'always'` → `'native'`,
@@ -449,12 +473,15 @@ export interface DateInputProps extends Omit<
* - `'popover'`: Astryx's typed field + calendar popover on every pointer
* - `'bottom-sheet'`: Astryx's bottom-sheet calendar on every pointer
* - `'native'`: the browser/OS picker on every pointer, with no Astryx
- * fallback (FR2)
+ * fallback (FR2), except in a calendar other than `gregory` or
+ * `iso8601`, where it is `'adaptive-bottom-sheet'` and warns in
+ * development
* - `'adaptive-bottom-sheet'`: popover on a fine pointer, bottom sheet on
* a coarse pointer
* - `'adaptive-native'` (default): popover on a fine pointer, browser/OS
* picker on a coarse pointer, keeping the released Astryx fallbacks
- * where a native control cannot express the value (FR2)
+ * where a native control cannot express the value (FR2), and the bottom
+ * sheet in a calendar other than `gregory` or `iso8601`
*
* @default 'adaptive-native'
*/
@@ -523,6 +550,7 @@ function PointerDateField({
numberOfMonths = 1,
weekStartsOn,
format = 'date_long',
+ calendar,
width,
containerXstyle,
containerClassName,
@@ -544,11 +572,11 @@ function PointerDateField({
'aria-labelledby': ariaLabelledByProp,
onBlur: onBlurProp,
onClick: onClickProp,
+ onFocus: onFocusProp,
onKeyDown: onKeyDownProp,
...controlProps
} = rest;
const t = useComponentTranslator();
- const locale = useLocale();
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
const placeholder =
placeholderFromProps ?? t('@astryx.dateInput.placeholder');
@@ -559,9 +587,9 @@ function PointerDateField({
const inputLabelID = useId();
const descriptionID = useId();
const statusMessageID = useId();
+ const calendarDescriptionID = useId();
const inputRef = useRef<HTMLInputElement | null>(null);
const calendarRef = useRef<CalendarHandle | null>(null);
- const lastFiredValueRef = useRef<ISODateString | undefined>(undefined);
const inputGroup = useInputGroup();
const [, startTransition] = useTransition();
@@ -591,9 +619,70 @@ function PointerDateField({
// Constraint checking for text input validation (reuses calendar logic)
const {isDateDisabled} = useCalendarConstraints({min, max, dateConstraints});
+ const fireChange = useCallback(
+ (newValue: ISODateString | undefined) => {
+ if (isEffectivelyDisabled) {
+ return;
+ }
+ onChange?.(newValue);
+ if (changeAction) {
+ startTransition(async () => {
+ setOptimisticValue(newValue);
+ await changeAction(newValue);
+ });
+ }
+ },
+ [
+ isEffectivelyDisabled,
+ onChange,
+ changeAction,
+ startTransition,
+ setOptimisticValue,
+ ],
+ );
+
+ const clearTypedDate = useCallback(() => {
+ if (value !== undefined) {
+ fireChange(undefined);
+ }
+ }, [value, fireChange]);
+ const navigateToTypedDate = useCallback((date: ISODateString) => {
+ calendarRef.current?.navigateTo(date);
+ }, []);
+ const {
+ typedDate,
+ displayValue,
+ formatHint,
+ isPending,
+ isInvalid,
+ fieldStatus,
+ alertMessage,
+ handleChange: handleTypedChange,
+ commit: commitPendingInput,
+ handleFocus,
+ handleBlur,
+ reset: resetTypedInput,
+ } = useTypedDateField({
+ source: 'DateInput',
+ calendar,
+ format,
+ min,
+ max,
+ isDateDisabled,
+ value,
+ shownValue: optimisticValue,
+ onChange: fireChange,
+ onClear: clearTypedDate,
+ onTypedDate: navigateToTypedDate,
+ isDisabled: isEffectivelyDisabled,
+ status,
+ isStatusAnnounced: !inputGroup,
+ hasPlaceholder: placeholderFromProps != null,
+ });
+
const {statusIcon, describedBy: statusTooltipDescribedBy} =
useInputStatusIcon({
- status,
+ status: fieldStatus,
statusVariant,
isInGroup: !!inputGroup,
});
@@ -602,7 +691,10 @@ function PointerDateField({
inputLabelID,
[
description ? descriptionID : null,
- statusVariant !== 'tooltip' && status?.message ? statusMessageID : null,
+ typedDate.calendarDescription != null ? calendarDescriptionID : null,
+ statusVariant !== 'tooltip' && fieldStatus?.message
+ ? statusMessageID
+ : null,
// The tooltip variant renders no message box; describe the input by the
// tooltip's content instead so the status is still announced.
statusTooltipDescribedBy,
@@ -612,50 +704,6 @@ function PointerDateField({
inputGroup,
);
- // Pending input while user is typing (null = show formatted value)
- const [pendingInput, setPendingInput] = useState<string | null>(null);
-
- // Clear pending input when value changes externally (computed during render
- // via prev-value ref instead of useEffect to avoid an extra render cycle)
- const prevValueRef = useRef(value);
- if (value !== prevValueRef.current) {
- prevValueRef.current = value;
- if (value !== lastFiredValueRef.current) {
- lastFiredValueRef.current = undefined;
- if (pendingInput !== null) {
- setPendingInput(null);
- }
- }
- }
-
- // Format a committed ISO value for display. The default `date_long` renders
- // the long-month shape (byte-identical to the historical hardcoded
- // DATE_FORMAT_LONG rendering, so still non-breaking); a function is called
- // with the ISO value; every other named member reuses Timestamp's shared
- // date mapping. Applies ONLY to the committed value, never to in-progress
- // typed input.
- const formatCommittedValue = useCallback(
- (iso: ISODateString): string =>
- typeof format === 'function'
- ? format(iso)
- : formatSharedDate(plainDateFromISO(iso), format, locale),
- [format, locale],
- );
-
- // Display value: pending input if typing, otherwise formatted value
- const displayValue =
- pendingInput !== null
- ? pendingInput
- : optimisticValue && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
- ? formatCommittedValue(optimisticValue)
- : '';
-
- // Check if current input is valid (for styling purposes)
- const isInputValid =
- pendingInput === null || !pendingInput.trim()
- ? true
- : parseDateInput(pendingInput, locale) !== null;
-
const fieldElementRef = useRef<HTMLDivElement | null>(null);
// Set just before a close that focus already left the field for, so onHide
// does not pull focus back to the input.
@@ -717,29 +765,6 @@ function PointerDateField({
}
}, [isEffectivelyDisabled, popover]);
- // Unified change handler that fires both onChange and changeAction
- const fireChange = useCallback(
- (newValue: ISODateString | undefined) => {
- if (isEffectivelyDisabled) {
- return;
- }
- onChange?.(newValue);
- if (changeAction) {
- startTransition(async () => {
- setOptimisticValue(newValue);
- await changeAction(newValue);
- });
- }
- },
- [
- isEffectivelyDisabled,
- onChange,
- changeAction,
- startTransition,
- setOptimisticValue,
- ],
- );
-
// Handle clear button click
const handleClear = useCallback(
(e?: React.MouseEvent<HTMLButtonElement>) => {
@@ -766,81 +791,19 @@ function PointerDateField({
return;
}
fireChange(selectedDate);
- setPendingInput(null);
+ resetTypedInput();
popover.hide();
},
- [isDisabled, fireChange, popover],
+ [isDisabled, fireChange, resetTypedInput, popover],
);
- // Handle input text change - update immediately if valid and allowed
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
- // The input is never natively disabled (spec:AST-085 FR1), so guard
- // value mutation explicitly (readOnly also blocks typing).
- if (isEffectivelyDisabled) {
- return;
- }
- const newValue = e.target.value;
- setPendingInput(newValue);
-
- // If the input is valid and passes constraints, update immediately
- const parsed = parseDateInput(newValue, locale);
- if (
- parsed &&
- plainDateToISO(parsed) !== value &&
- !isDateDisabled(parsed)
- ) {
- const parsedISO = plainDateToISO(parsed);
- lastFiredValueRef.current = parsedISO;
- fireChange(parsedISO);
- // Navigate calendar to show the parsed date's month
- calendarRef.current?.navigateTo(parsedISO);
- }
+ handleTypedChange(e.target.value);
},
- [value, fireChange, isDateDisabled, isEffectivelyDisabled, locale],
+ [handleTypedChange],
);
- // Commit pending input (shared by blur and Enter key)
- const commitPendingInput = useCallback(() => {
- if (pendingInput === null) {
- return;
- }
- // Disabled or busy: keep the value, drop the draft (spec:AST-085 FR2).
- if (isEffectivelyDisabled) {
- setPendingInput(null);
- return;
- }
-
- if (!pendingInput.trim()) {
- if (value !== undefined) {
- fireChange(undefined);
- }
- setPendingInput(null);
- return;
- }
-
- const parsed = parseDateInput(pendingInput, locale);
- if (parsed && !isDateDisabled(parsed)) {
- const parsedISO = plainDateToISO(parsed);
- if (parsedISO !== value) {
- fireChange(parsedISO);
- }
- }
- setPendingInput(null);
- }, [
- pendingInput,
- isEffectivelyDisabled,
- value,
- fireChange,
- isDateDisabled,
- locale,
- ]);
-
- // Handle blur - validate, check constraints, and clear pending input.
- const handleBlur = useCallback(() => {
- commitPendingInput();
- }, [commitPendingInput]);
-
// A manual popover has no auto-popover exclusivity, so without this close
// the next field's calendar would open beside this one. Focus going nowhere
// (a window switch) leaves it open.
@@ -884,10 +847,7 @@ function PointerDateField({
if (!isEffectivelyDisabled) {
popover.show({skipAutoFocus: true});
}
- } else if (
- e.key === 'Enter' &&
- (pendingInput !== null || isEffectivelyDisabled)
- ) {
+ } else if (e.key === 'Enter' && (isPending || isEffectivelyDisabled)) {
// Typed text holds Enter back, or a form would submit the value from
// before the commit. A disabled or busy field must not submit its
// form either. Otherwise Enter keeps its default, as in any text field.
@@ -895,7 +855,7 @@ function PointerDateField({
commitPendingInput();
}
},
- [popover, commitPendingInput, isEffectivelyDisabled, pendingInput],
+ [popover, commitPendingInput, isEffectivelyDisabled, isPending],
);
const inputWrapper = (
@@ -913,7 +873,7 @@ function PointerDateField({
{...mergeProps(
themeProps('date-input', {
size,
- status: status?.type ?? null,
+ status: fieldStatus?.type ?? null,
disabled: isDisabled ? 'disabled' : null,
}),
stylex.props(
@@ -924,11 +884,11 @@ function PointerDateField({
// FR6, family:buttons FR4).
isDisabled && inputWrapperStyles.disabled,
isEffectivelyDisabled && inputDisabledFocusStyles.inputFocusRing,
- status && inputStatusBorderStyles[status.type],
- status &&
+ fieldStatus && inputStatusBorderStyles[fieldStatus.type],
+ fieldStatus &&
!isEffectivelyDisabled &&
- inputStatusHoverShadowStyles[status.type],
- status && inputStatusFocusWithinStyles[status.type],
+ inputStatusHoverShadowStyles[fieldStatus.type],
+ fieldStatus && inputStatusFocusWithinStyles[fieldStatus.type],
inputGroup && groupStyles.inGroup,
controlXstyle,
),
@@ -978,13 +938,14 @@ function PointerDateField({
value={displayValue}
onChange={handleInputChange}
onBlur={chainEventHandlers(handleBlur, onBlurProp)}
+ onFocus={chainEventHandlers(handleFocus, onFocusProp)}
onClick={
isEffectivelyDisabled
? undefined
: chainEventHandlers(handleInputClick, onClickProp)
}
onKeyDown={chainEventHandlers(handleInputKeyDown, onKeyDownProp)}
- placeholder={placeholder}
+ placeholder={formatHint ?? placeholder}
aria-disabled={isEffectivelyDisabled ? 'true' : undefined}
readOnly={isEffectivelyDisabled || undefined}
aria-labelledby={
@@ -995,7 +956,7 @@ function PointerDateField({
aria-describedby={ariaDescribedBy}
aria-required={isEffectivelyRequired ? 'true' : undefined}
aria-invalid={
- status?.type === 'error' || !isInputValid ? 'true' : undefined
+ fieldStatus?.type === 'error' || isInvalid ? 'true' : undefined
}
aria-busy={isBusy || undefined}
aria-expanded={popover.isOpen}
@@ -1006,17 +967,21 @@ function PointerDateField({
{...stylex.props(
styles.input,
isEffectivelyDisabled && styles.inputDisabled,
- !isInputValid && styles.inputInvalid,
+ isInvalid && styles.inputInvalid,
)}
/>
{/*
- Live region announcing invalid typed input to assistive technology.
- The value silently reverts on blur, so without this a screen-reader
- user would get no feedback that their entry was rejected (WCAG 3.3.1).
+ Announces a typed rejection that the field status does not announce.
+ The field status announces the rest.
*/}
<VisuallyHidden as="div" role="alert" aria-live="assertive">
- {!isInputValid ? t('@astryx.dateInput.invalidDate') : ''}
+ {alertMessage}
</VisuallyHidden>
+ {isRenderable(typedDate.calendarDescription) && (
+ <VisuallyHidden id={calendarDescriptionID}>
+ {typedDate.calendarDescription}
+ </VisuallyHidden>
+ )}
{hasClear && value !== undefined && !isEffectivelyDisabled && (
<InputClearButton
label={t('@astryx.dateInput.clear', {label})}
@@ -1030,9 +995,8 @@ function PointerDateField({
// calendar only while it is open; it opens on the current value.
!popover.isOpen ? null : (
<Calendar
- // The field text is Gregorian, so the popover calendar is too.
- calendar="gregory"
handleRef={calendarRef}
+ calendar={typedDate.calendar}
mode="single"
value={optimisticValue ?? null}
onChange={handleDateSelect}
@@ -1067,11 +1031,11 @@ function PointerDateField({
isRequired={isRequired}
isDisabled={isDisabled}
status={
- status
+ fieldStatus
? {
- type: status.type,
- message: status.message,
- messageID: status.message ? statusMessageID : undefined,
+ type: fieldStatus.type,
+ message: fieldStatus.message,
+ messageID: fieldStatus.message ? statusMessageID : undefined,
}
: undefined
}
@@ -1140,22 +1104,40 @@ export function DateInput(props: DateInputProps) {
'`nativePicker` is deprecated; use `presentation` instead (`touch` → `adaptive-native`, `always` → `native`, `never` → `adaptive-bottom-sheet`). `presentation` wins when both are set.',
props.nativePicker !== undefined,
);
- const surface = resolvePickerPresentation(
- effectivePickerPresentation(props.presentation, props.nativePicker),
- isTouch,
+ const {calendar, presentation} = useCalendarPresentation(
+ 'DateInput',
+ props.calendar,
+ props.presentation,
+ props.nativePicker,
);
+ const surface = resolvePickerPresentation(presentation, isTouch);
const {
presentation: _presentation,
nativePicker: _nativePicker,
+ calendar: _calendar,
...rest
} = props;
switch (surface) {
case 'native':
return <NativeDateField {...rest} isDisabled={isDisabled} />;
case 'sheet':
- return <TouchDateField {...rest} isDisabled={isDisabled} />;
+ return (
+ <TouchDateField
+ // Month indexes depend on the calendar. A new calendar remounts the sheet.
+ key={calendar}
+ {...rest}
+ calendar={calendar}
+ isDisabled={isDisabled}
+ />
+ );
case 'desktop':
- return <PointerDateField {...rest} isDisabled={isDisabled} />;
+ return (
+ <PointerDateField
+ {...rest}
+ calendar={calendar}
+ isDisabled={isDisabled}
+ />
+ );
}
}
diff --git a/packages/core/src/DateInput/DateInputTouch.calendar.test.tsx b/packages/core/src/DateInput/DateInputTouch.calendar.test.tsx
new file mode 100644
index 0000000000..6b77f5f525
--- /dev/null
+++ b/packages/core/src/DateInput/DateInputTouch.calendar.test.tsx
@@ -0,0 +1,476 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DateInputTouch.calendar.test.tsx
+ * @input Uses vitest, Testing Library, temporal-polyfill, DateInput,
+ * DateTimeInput, monthGeometry
+ * @output The bottom sheet in calendars: month panes, labels and digits, the
+ * month and year wheels, leap months, eras, and the month model
+ * @position Testing; validates the touch surfaces against the calendar
+ */
+
+import {afterAll, afterEach, beforeAll, beforeEach} from 'vitest';
+import {describe, expect, it, vi} from 'vitest';
+import {fireEvent, render, screen, within} from '@testing-library/react';
+import {Temporal as TemporalPolyfill} from 'temporal-polyfill/full';
+import {DateInput, type DateInputProps} from './DateInput';
+import {
+ DateTimeInput,
+ type ISODateTimeString,
+} from '../DateTimeInput/DateTimeInput';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import {createMonthModel} from './monthGeometry';
+import type {CalendarSystem} from '../utils/calendarSystem';
+import type {ISODateString} from '../utils/dateTypes';
+import {plainDateAddDays, plainDateFromISO} from '../utils/plainDate';
+
+const host = globalThis as {Temporal?: unknown};
+const hadTemporal = host.Temporal != null;
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+const SCROLLPORT_WIDTH = 360;
+const HOVER_CAPABLE = /\(\s*hover\s*:\s*hover\s*\)/;
+
+function stubCoarsePointer(): void {
+ vi.stubGlobal('matchMedia', (query: string) => ({
+ matches: /pointer:\s*coarse/.test(query)
+ ? true
+ : /pointer:\s*fine/.test(query)
+ ? false
+ : HOVER_CAPABLE.test(query),
+ media: query,
+ onchange: null,
+ addListener: () => {},
+ removeListener: () => {},
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ dispatchEvent: () => false,
+ }));
+}
+
+// jsdom lays nothing out, so the month scrollport reports its CSS width only
+// while a test renders and opens the sheet.
+function withLayout<T>(fn: () => T): T {
+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', {
+ configurable: true,
+ get(this: HTMLElement) {
+ return this.dataset?.scroller === 'months' ? SCROLLPORT_WIDTH : 0;
+ },
+ });
+ try {
+ return fn();
+ } finally {
+ delete (HTMLElement.prototype as {clientWidth?: unknown}).clientWidth;
+ }
+}
+
+beforeAll(() => {
+ host.Temporal ??= TemporalPolyfill;
+ Element.prototype.scrollTo = vi.fn();
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.open = true;
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.open = false;
+ });
+});
+
+afterAll(() => {
+ if (!hadTemporal) {
+ delete host.Temporal;
+ }
+});
+
+beforeEach(() => {
+ vi.stubGlobal('ResizeObserver', MockResizeObserver);
+ stubCoarsePointer();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+function openSheet(
+ locale: string,
+ props: Partial<DateInputProps> & {calendar: CalendarSystem},
+): void {
+ withLayout(() => {
+ render(
+ <InternationalizationProvider locale={locale}>
+ <DateInput
+ label="Date"
+ presentation="bottom-sheet"
+ onChange={() => {}}
+ {...props}
+ />
+ </InternationalizationProvider>,
+ );
+ fireEvent.click(screen.getByRole('combobox'));
+ });
+}
+
+const title = () =>
+ document.querySelector<HTMLElement>('[data-title="month-year"]')!;
+
+function pane(label: string): HTMLElement {
+ const grid = [
+ ...document.querySelectorAll<HTMLElement>('[role="grid"]'),
+ ].find(element => element.getAttribute('aria-label') === label);
+ if (grid == null) {
+ throw new Error(
+ `no pane for ${label} among ${[...document.querySelectorAll('[role="grid"]')].map(g => g.getAttribute('aria-label')).join(' | ')}`,
+ );
+ }
+ return grid;
+}
+
+/** The in-month day buttons of a pane, in order. */
+function monthDays(grid: HTMLElement): HTMLButtonElement[] {
+ return [
+ ...grid.querySelectorAll<HTMLButtonElement>(
+ 'button[data-date]:not([data-outside])',
+ ),
+ ];
+}
+
+function wheelOptions(name: 'Month' | 'Year'): HTMLElement[] {
+ return within(screen.getByRole('listbox', {name})).getAllByRole('option');
+}
+
+function openWheels(): void {
+ withLayout(() => fireEvent.click(title()));
+}
+
+describe('the bottom sheet in a calendar', () => {
+ it('lays out a Persian month with its days, labels and locale digits', () => {
+ openSheet('fa-IR', {
+ calendar: 'persian',
+ value: '2026-11-02',
+ min: '2026-09-01',
+ max: '2026-12-31',
+ });
+ const aban = pane('۱۴۰۵ آبان');
+ const days = monthDays(aban);
+ expect(days).toHaveLength(30);
+ expect(days[0]).toHaveAttribute('data-date', '2026-10-23');
+ expect(days[0]).toHaveTextContent('۱');
+ expect(days[29]).toHaveAttribute('data-date', '2026-11-21');
+ expect(days[10]).toHaveAccessibleName('۱۴۰۵ آبان ۱۱, دوشنبه');
+ // Six rows, whatever the month needs.
+ expect(aban.querySelectorAll('button[data-date]')).toHaveLength(42);
+ expect(title()).toHaveTextContent('۱۴۰۵ آبان');
+ });
+
+ it('selects the Gregorian ISO date of a Persian day', () => {
+ const onChange = vi.fn();
+ openSheet('en', {
+ calendar: 'persian',
+ value: '2026-11-02',
+ min: '2026-09-01',
+ max: '2026-12-31',
+ onChange,
+ });
+ fireEvent.click(monthDays(pane('Aban 1405 AP'))[0]);
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-10-23');
+ });
+
+ it('shows Adar I and Adar II as separate months in a Hebrew leap year', () => {
+ openSheet('en', {
+ calendar: 'hebrew',
+ value: '2024-02-15',
+ min: '2024-01-01',
+ max: '2024-04-30',
+ });
+ const adarI = pane('Adar I 5784');
+ expect(monthDays(adarI)).toHaveLength(30);
+ expect(monthDays(adarI)[0]).toHaveAttribute('data-date', '2024-02-10');
+ const adarII = pane('Adar II 5784');
+ expect(monthDays(adarII)).toHaveLength(29);
+ expect(monthDays(adarII)[0]).toHaveAttribute('data-date', '2024-03-11');
+ });
+
+ it('shows one Adar in a common Hebrew year', () => {
+ openSheet('en', {
+ calendar: 'hebrew',
+ value: '2025-03-10',
+ min: '2025-01-15',
+ max: '2025-04-30',
+ });
+ const adar = pane('Adar 5785');
+ expect(monthDays(adar)).toHaveLength(29);
+ expect(monthDays(adar)[0]).toHaveAttribute('data-date', '2025-03-01');
+ expect(
+ [...document.querySelectorAll('[role="grid"]')].map(grid =>
+ grid.getAttribute('aria-label'),
+ ),
+ ).not.toContain('Adar I 5785');
+ });
+
+ it.each([
+ ['a common year', '2026-09-08', 'Pagumen 2018 AM', 5, '2026-09-06'],
+ ['a leap year', '2027-09-08', 'Pagumen 2019 AM', 6, '2027-09-06'],
+ ])(
+ 'keeps six rows for the Ethiopic thirteenth month in %s',
+ (_name, value, label, length, first) => {
+ openSheet('en', {
+ calendar: 'ethiopic',
+ value: value as ISODateString,
+ min: `${value.slice(0, 4)}-08-01` as ISODateString,
+ max: `${value.slice(0, 4)}-10-31` as ISODateString,
+ });
+ const pagume = pane(label);
+ expect(monthDays(pagume)).toHaveLength(length);
+ expect(monthDays(pagume)[0]).toHaveAttribute('data-date', first);
+ expect(pagume.querySelectorAll('button[data-date]')).toHaveLength(42);
+ },
+ );
+
+ it('lists 13 months in a Hebrew leap year and 12 in a common year', () => {
+ openSheet('en', {
+ calendar: 'hebrew',
+ value: '2024-02-15',
+ min: '2023-09-01',
+ max: '2025-09-30',
+ });
+ openWheels();
+ const leap = wheelOptions('Month');
+ expect(leap).toHaveLength(13);
+ expect(leap.map(option => option.textContent)).toEqual(
+ expect.arrayContaining(['Adar I', 'Adar II']),
+ );
+ expect(leap[5]).toHaveTextContent('Adar I');
+ expect(leap[5]).toHaveAttribute('aria-selected', 'true');
+
+ // Adar I becomes Adar in a year without it.
+ fireEvent.click(
+ within(screen.getByRole('listbox', {name: 'Year'})).getByText('5785 AM'),
+ );
+ expect(title()).toHaveTextContent('Adar 5785');
+ const common = wheelOptions('Month');
+ expect(common).toHaveLength(12);
+ expect(common.map(option => option.textContent)).not.toContain('Adar I');
+ expect(common[5]).toHaveTextContent('Adar');
+ expect(common[5]).toHaveAttribute('aria-selected', 'true');
+ });
+
+ it('keeps the month on a year change when the new year has it', () => {
+ openSheet('en', {
+ calendar: 'hebrew',
+ value: '2024-04-15',
+ min: '2023-09-01',
+ max: '2025-09-30',
+ });
+ expect(title()).toHaveTextContent('Nisan 5784');
+ openWheels();
+ fireEvent.click(
+ within(screen.getByRole('listbox', {name: 'Year'})).getByText('5785 AM'),
+ );
+ expect(title()).toHaveTextContent('Nisan 5785');
+ });
+
+ it('labels Japanese years with their era', () => {
+ openSheet('ja-JP', {
+ calendar: 'japanese',
+ value: '2026-11-02',
+ min: '2018-01-01',
+ max: '2026-12-31',
+ });
+ expect(title()).toHaveTextContent('令和8年11月');
+ openWheels();
+ const years = wheelOptions('Year').map(option => option.textContent);
+ expect(years).toContain('令和8');
+ expect(years).toContain('平成30');
+ // November is in Reiwa, so the 2019 row names Reiwa.
+ expect(years).toContain('令和元');
+ expect(years).toContain('令和2');
+ expect(wheelOptions('Month')[10]).toHaveTextContent('11月');
+ });
+
+ it('names the era of the shown month for a year with an era change', () => {
+ openSheet('ja-JP', {
+ calendar: 'japanese',
+ value: '2019-01-22',
+ min: '2018-01-01',
+ max: '2020-12-31',
+ });
+ expect(title()).toHaveTextContent('平成31年1月');
+ openWheels();
+ const yearRow = (name: string) =>
+ within(screen.getByRole('listbox', {name: 'Year'})).getByRole('option', {
+ name,
+ });
+ expect(yearRow('平成31')).toHaveAttribute('aria-selected', 'true');
+ expect(yearRow('平成30')).toBeInTheDocument();
+ expect(yearRow('令和2')).toBeInTheDocument();
+
+ fireEvent.click(
+ within(screen.getByRole('listbox', {name: 'Month'})).getByText('7月'),
+ );
+ expect(title()).toHaveTextContent('令和元年7月');
+ expect(yearRow('令和元')).toHaveAttribute('aria-selected', 'true');
+ expect(
+ within(screen.getByRole('listbox', {name: 'Year'})).queryByRole(
+ 'option',
+ {name: '平成31'},
+ ),
+ ).toBeNull();
+ });
+
+ it('names the era of the kept day in the heading of a split month', () => {
+ openSheet('ja-JP', {
+ calendar: 'japanese',
+ value: '1989-01-03',
+ min: '1988-01-01',
+ max: '1990-12-31',
+ });
+ expect(title()).toHaveTextContent('昭和64年1月');
+ openWheels();
+ expect(
+ within(screen.getByRole('listbox', {name: 'Year'})).getByRole('option', {
+ name: '昭和64',
+ }),
+ ).toHaveAttribute('aria-selected', 'true');
+ expect(title()).toHaveTextContent('昭和64年1月');
+ });
+
+ it('names Shōwa in the heading for December 26, 1926', () => {
+ openSheet('ja-JP', {
+ calendar: 'japanese',
+ value: '1926-12-26',
+ min: '1926-01-01',
+ max: '1927-12-31',
+ });
+ expect(title()).toHaveTextContent('昭和元年12月');
+ });
+
+ it('labels Buddhist and Persian years in the calendar', () => {
+ openSheet('en', {
+ calendar: 'persian',
+ value: '2026-11-02',
+ min: '2025-01-01',
+ max: '2026-12-31',
+ });
+ openWheels();
+ expect(wheelOptions('Year').map(option => option.textContent)).toEqual([
+ '1403 AP',
+ '1404 AP',
+ '1405 AP',
+ ]);
+ });
+
+ it('keeps Gregorian wheels as they were', () => {
+ openSheet('en', {
+ calendar: 'gregory',
+ value: '2026-03-21',
+ min: '2025-01-01',
+ max: '2026-12-31',
+ });
+ openWheels();
+ expect(wheelOptions('Year').map(option => option.textContent)).toEqual([
+ '2025',
+ '2026',
+ ]);
+ expect(wheelOptions('Month')).toHaveLength(12);
+ });
+});
+
+describe('the DateTimeInput bottom sheet in a calendar', () => {
+ it('shows Persian months and the date in the calendar', () => {
+ withLayout(() => {
+ render(
+ <InternationalizationProvider locale="en">
+ <DateTimeInput
+ label="When"
+ calendar="persian"
+ presentation="bottom-sheet"
+ value={'2026-11-02T09:00' as ISODateTimeString}
+ min={'2026-09-01T00:00' as ISODateTimeString}
+ max={'2026-12-31T23:59' as ISODateTimeString}
+ onChange={() => {}}
+ />
+ </InternationalizationProvider>,
+ );
+ fireEvent.click(document.querySelector('input[inputmode="none"]')!);
+ });
+ expect(monthDays(pane('Aban 1405 AP'))[0]).toHaveAttribute(
+ 'data-date',
+ '2026-10-23',
+ );
+ });
+});
+
+describe('the DateTimeInput bottom sheet heading in a split month', () => {
+ it('names the era of the kept day', () => {
+ withLayout(() => {
+ render(
+ <InternationalizationProvider locale="ja-JP">
+ <DateTimeInput
+ label="日時"
+ calendar="japanese"
+ presentation="bottom-sheet"
+ value={'1989-01-03T09:00' as ISODateTimeString}
+ min={'1988-12-01T00:00' as ISODateTimeString}
+ max={'1989-02-28T23:59' as ISODateTimeString}
+ onChange={() => {}}
+ />
+ </InternationalizationProvider>,
+ );
+ fireEvent.click(document.querySelector('input[inputmode="none"]')!);
+ });
+ // The heading button names the shown month; the date segment also holds
+ // 昭和64年1月 as part of its full date, so read the button's text.
+ const heading = [
+ ...document.querySelectorAll<HTMLButtonElement>(
+ 'dialog[open] button[aria-expanded]',
+ ),
+ ].find(button => button.textContent === '昭和64年1月');
+ expect(heading).toBeDefined();
+ });
+});
+
+describe('the month model', () => {
+ it.each([
+ 'gregory',
+ 'japanese',
+ 'persian',
+ 'hebrew',
+ 'chinese',
+ 'ethiopic',
+ 'islamic-umalqura',
+ ] as const)('round-trips indexes and months in %s', calendar => {
+ const model = createMonthModel(calendar);
+ const start = model.indexOf(plainDateFromISO('2020-01-01'));
+ for (let index = start - 30; index <= start + 90; index++) {
+ const month = model.monthAt(index);
+ expect(model.indexOf(month.start)).toBe(index);
+ expect(model.indexOf(month.end)).toBe(index);
+ expect(model.monthAt(index + 1).start).toEqual(
+ plainDateAddDays(month.end, 1),
+ );
+ const {year, month: position} = model.yearMonthAt(index);
+ expect(model.indexOfYearMonth(year, position)).toBe(index);
+ }
+ });
+
+ it('counts the months of Hebrew years', () => {
+ const model = createMonthModel('hebrew');
+ expect(model.monthsInYear(5784)).toBe(13);
+ expect(model.monthsInYear(5785)).toBe(12);
+ });
+
+ it('moves a leap month to its common counterpart a year on', () => {
+ const model = createMonthModel('hebrew');
+ const adarI = model.indexOfYearMonth(5784, 6);
+ expect(model.yearMonthAt(model.shiftYears(adarI, 1))).toEqual({
+ year: 5785,
+ month: 6,
+ });
+ });
+});
diff --git a/packages/core/src/DateInput/MonthScroller.test.tsx b/packages/core/src/DateInput/MonthScroller.test.tsx
index 0eba41d572..0dbe52f8b4 100644
--- a/packages/core/src/DateInput/MonthScroller.test.tsx
+++ b/packages/core/src/DateInput/MonthScroller.test.tsx
@@ -8,6 +8,7 @@ import {
type FakeAnimation,
} from '../motion/__tests__/fakeWebAnimation';
import {MonthScroller, type MonthScrollerHandle} from './MonthScroller';
+import {createMonthModel} from './monthGeometry';
/**
* A touch screen with Reduced Motion on: the policy's combined query
@@ -71,6 +72,7 @@ describe('MonthScroller under Reduced Motion on a touch screen', () => {
const view = render(
<MonthScroller
handleRef={handleRef}
+ monthModel={createMonthModel('gregory')}
minMonthIndex={0}
maxMonthIndex={23}
initialMonthIndex={9}
diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsx
index 376804946d..29c6dac321 100644
--- a/packages/core/src/DateInput/MonthScroller.tsx
+++ b/packages/core/src/DateInput/MonthScroller.tsx
@@ -4,7 +4,8 @@
/**
* @file MonthScroller.tsx
- * @input Month bounds, selected value, constraints, week start
+ * @input A calendar's month model, month bounds, selected value, constraints,
+ * week start
* @output Exports MonthScroller and MonthScrollerHandle
* @position Internal component; consumed by TouchDateField.tsx
*
@@ -36,12 +37,14 @@ import {
useImperativeHandle,
useLayoutEffect,
useRef,
+ useMemo,
useState,
} from 'react';
import {flushSync} from 'react-dom';
import * as stylex from '@stylexjs/stylex';
-import {useCalendarDays} from '../Calendar';
-import {useDirection, useLocale} from '../i18n';
+import {useCalendarDays} from '../Calendar/hooks/useCalendarDays';
+import {useDirection} from '../i18n/useDirection';
+import {useLocale} from '../i18n/useLocale';
import {
colorVars,
radiusVars,
@@ -50,33 +53,32 @@ import {
durationVars,
borderVars,
} from '../theme/tokens.stylex';
-import {focusOutlineStyles} from '../utils';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import type {DayOfWeek, ISODateString, PlainDate} from '../utils/dateTypes';
import {
- plainDateFormatDayNumber,
- plainDateFormatStandaloneMonthYear,
-} from '../utils/plainDate';
-import {
- type DayOfWeek,
- type ISODateString,
- type PlainDate,
plainDateAddDays,
plainDateDayOfWeek,
- plainDateFormat,
+ plainDateFormatDayNumber,
plainDateIsEqual,
plainDateToISO,
DATE_FORMAT_WITH_WEEKDAY,
-} from '../utils';
+} from '../utils/plainDate';
import {
playReducedMotionDip,
reducedMotionFade,
type ReducedMotionDip,
} from '../motion/reducedMotion';
+import {
+ calendarYearMonthOf,
+ formatCalendarDate,
+ formatCalendarMonthLabel,
+ isInCalendarMonth,
+} from '../utils/calendarSystem';
import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';
import {useOwnScrollGesture} from './useOwnScrollGesture';
import {useScrollSettle} from './useScrollSettle';
import {
- fromMonthIndex,
- monthIndexOf,
+ type MonthModel,
paneWindow,
rowAtScrollOffset,
rowsIn,
@@ -286,6 +288,8 @@ export interface MonthScrollerHandle {
export interface MonthScrollerProps {
/** Imperative handle for programmatic navigation (Today, the wheels). */
handleRef?: React.RefObject<MonthScrollerHandle | null>;
+ /** The calendar's months, by index. */
+ monthModel: MonthModel;
/** First reachable month, as a month index. */
minMonthIndex: number;
/** Last reachable month, as a month index. */
@@ -311,6 +315,7 @@ export interface MonthScrollerProps {
*/
export function MonthScroller({
handleRef,
+ monthModel,
minMonthIndex,
maxMonthIndex,
initialMonthIndex,
@@ -763,17 +768,17 @@ export function MonthScroller({
const moveFocus = useCallback(
(from: PlainDate, deltaDays: number) => {
const next = plainDateAddDays(from, deltaDays);
- const nextIndex = monthIndexOf(next);
+ const nextIndex = monthModel.indexOf(next);
if (nextIndex < minMonthIndex || nextIndex > maxMonthIndex) {
return;
}
shouldRestoreFocusRef.current = true;
setFocusedDate(next);
- if (nextIndex !== monthIndexOf(from)) {
+ if (nextIndex !== monthModel.indexOf(from)) {
scrollToMonth(nextIndex, 'smooth');
}
},
- [minMonthIndex, maxMonthIndex, scrollToMonth],
+ [monthModel, minMonthIndex, maxMonthIndex, scrollToMonth],
);
const handleKeyDown = useCallback(
@@ -861,6 +866,7 @@ export function MonthScroller({
rowsIn(visibleRows).map(row => (
<MonthPane
key={row}
+ monthModel={monthModel}
monthIndex={minMonthIndex + row}
insetInlineStart={row * paneSize}
inlineSize={paneSize}
@@ -882,6 +888,7 @@ export function MonthScroller({
MonthScroller.displayName = 'MonthScroller';
interface MonthPaneProps {
+ monthModel: MonthModel;
monthIndex: number;
insetInlineStart: number;
inlineSize: number;
@@ -903,6 +910,7 @@ interface MonthPaneProps {
* so each day instead carries its weekday in its accessible name.
*/
function MonthPane({
+ monthModel,
monthIndex,
insetInlineStart,
inlineSize,
@@ -916,40 +924,33 @@ function MonthPane({
onDayFocus,
}: MonthPaneProps) {
const locale = useLocale();
- const {year, month} = fromMonthIndex(monthIndex);
+ const {calendar} = monthModel;
+ const month = useMemo(
+ () => monthModel.monthAt(monthIndex),
+ [monthModel, monthIndex],
+ );
const {weeks} = useCalendarDays({
- year,
- month,
+ ...calendarYearMonthOf(calendar, month),
+ calendar,
weekStartsOn,
// Always six rows: a variable grid would make pane heights differ, and
// with them every snap offset below this month.
hasVariableRowCount: false,
});
- const monthLabel = plainDateFormatStandaloneMonthYear(
- {year, month, day: 1},
- locale,
- );
+ const monthLabel = formatCalendarMonthLabel(calendar, month, locale);
// Exactly one day per pane is tab-reachable, so Tab moves through the
// picker rather than through 42 buttons: the focused day if the keyboard
// owns one, else the selection, else the first of the month.
const tabbableISO = (() => {
- if (
- focusedDate != null &&
- focusedDate.year === year &&
- focusedDate.month === month
- ) {
+ if (focusedDate != null && isInCalendarMonth(focusedDate, month)) {
return plainDateToISO(focusedDate);
}
- if (
- selectedDate != null &&
- selectedDate.year === year &&
- selectedDate.month === month
- ) {
+ if (selectedDate != null && isInCalendarMonth(selectedDate, month)) {
return plainDateToISO(selectedDate);
}
- return plainDateToISO({year, month, day: 1});
+ return plainDateToISO(month.start);
})();
return (
@@ -987,7 +988,8 @@ function MonthPane({
data-date={day.iso}
data-outside={day.isOutside ? '' : undefined}
tabIndex={day.iso === tabbableISO ? 0 : -1}
- aria-label={plainDateFormat(
+ aria-label={formatCalendarDate(
+ calendar,
day.date,
DATE_FORMAT_WITH_WEEKDAY,
locale,
diff --git a/packages/core/src/DateInput/MonthScrollerSettle.test.tsx b/packages/core/src/DateInput/MonthScrollerSettle.test.tsx
index 368bebedb2..3e55268020 100644
--- a/packages/core/src/DateInput/MonthScrollerSettle.test.tsx
+++ b/packages/core/src/DateInput/MonthScrollerSettle.test.tsx
@@ -5,6 +5,7 @@ import {createRef} from 'react';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {MonthScroller, type MonthScrollerHandle} from './MonthScroller';
import {SCROLL_QUIET_MS} from './useScrollSettle';
+import {createMonthModel} from './monthGeometry';
class FakeResizeObserver {
constructor(private callback: ResizeObserverCallback) {}
@@ -52,6 +53,7 @@ describe('MonthScroller settle', () => {
const handleRef = createRef<MonthScrollerHandle>();
const view = render(
<MonthScroller
+ monthModel={createMonthModel('gregory')}
handleRef={handleRef}
minMonthIndex={0}
maxMonthIndex={23}
diff --git a/packages/core/src/DateInput/MonthYearWheels.tsx b/packages/core/src/DateInput/MonthYearWheels.tsx
index abd8ba7fe6..4cef901b81 100644
--- a/packages/core/src/DateInput/MonthYearWheels.tsx
+++ b/packages/core/src/DateInput/MonthYearWheels.tsx
@@ -4,8 +4,10 @@
/**
* @file MonthYearWheels.tsx
- * @input A month index, the reachable month bounds, a change callback
- * @output Exports MonthYearWheels — the month + year wheel pair
+ * @input A calendar's month model, a month index, the reachable month bounds,
+ * a change callback
+ * @output Exports MonthYearWheels — the month wheel of a calendar year and the
+ * year wheel with era labels
* @position Internal component; consumed by TouchDateField.tsx
*
* The shortcut out of continuous scrolling. Scrolling is the right gesture for
@@ -24,12 +26,16 @@
import {useMemo} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {useLocale} from '../i18n';
-import {DATE_FORMAT_MONTH_ONLY, plainDateFormat} from '../utils';
+import {useLocale} from '../i18n/useLocale';
+import {
+ calendarYearSpansEras,
+ formatCalendarMonthName,
+ formatCalendarYearLabel,
+} from '../utils/calendarSystem';
import {spacingVars} from '../theme/tokens.stylex';
import {dateInputTouchGeometry} from './tokens.stylex';
import {Wheel, type WheelOption} from './Wheel';
-import {fromMonthIndex, toMonthIndex} from './monthGeometry';
+import {clampIndex, type MonthModel} from './monthGeometry';
const styles = stylex.create({
wheels: {
@@ -40,6 +46,8 @@ const styles = stylex.create({
});
export interface MonthYearWheelsProps {
+ /** The calendar's months, by index. */
+ monthModel: MonthModel;
/** The month the wheels currently show. */
monthIndex: number;
/** First reachable month. */
@@ -54,12 +62,19 @@ export interface MonthYearWheelsProps {
yearLabel: string;
/** False while the panel is hidden. */
isActive?: boolean;
+ /**
+ * The day of the month the picker keeps, such as the selected date's. A year
+ * that spans an era change is labeled with the era of this day in the
+ * selected month. The first day of the month applies when it is absent.
+ */
+ keptDay?: number;
}
/**
* Month and year wheels, bounded by the same range as the scroller.
*/
export function MonthYearWheels({
+ monthModel,
monthIndex,
minMonthIndex,
maxMonthIndex,
@@ -67,60 +82,63 @@ export function MonthYearWheels({
monthLabel,
yearLabel,
isActive = true,
+ keptDay = 1,
}: MonthYearWheelsProps) {
const locale = useLocale();
- const {year, month} = fromMonthIndex(monthIndex);
-
- // Day 15 of a fixed year: no timezone can push it into an adjacent month
- // the way day 1 or day 31 can.
- //
- // `plainDateFormat` rather than a raw `Intl.DateTimeFormat`, which the
- // shared lint rule forbids and which would duplicate the format vocabulary
- // besides. Recompute when the provider locale changes so the wheel labels
- // stay in sync with the field and calendar.
- const monthNames = useMemo(
- () =>
- Array.from({length: 12}, (_, index) =>
- plainDateFormat(
- {year: 2021, month: index + 1, day: 15},
- DATE_FORMAT_MONTH_ONLY,
- locale,
- ),
- ),
- [locale],
- );
+ const {calendar} = monthModel;
+ const {year, month} = monthModel.yearMonthAt(monthIndex);
// Months outside the range stay on the wheel rather than vanishing: a list
- // whose length changes with the year would jump under the finger.
+ // whose length changed with the range would jump under the finger. Only the
+ // calendar changes its length, for a year with a leap month.
const monthOptions: WheelOption[] = useMemo(
() =>
- monthNames.map((name, index) => {
- const candidate = toMonthIndex(year, index + 1);
+ Array.from({length: monthModel.monthsInYear(year)}, (_, index) => {
+ const candidate = monthModel.indexOfYearMonth(year, index + 1);
return {
value: index + 1,
- label: name,
+ label: formatCalendarMonthName(
+ calendar,
+ monthModel.monthAt(candidate),
+ locale,
+ ),
isDisabled: candidate < minMonthIndex || candidate > maxMonthIndex,
};
}),
- [monthNames, year, minMonthIndex, maxMonthIndex],
+ [monthModel, calendar, year, locale, minMonthIndex, maxMonthIndex],
);
- const yearOptions: WheelOption[] = useMemo(() => {
- const first = fromMonthIndex(minMonthIndex).year;
- const last = fromMonthIndex(maxMonthIndex).year;
- const options: WheelOption[] = [];
+ // Every listed year holds a reachable month: the list runs from the year of
+ // the first reachable month to the year of the last.
+ const years = useMemo(() => {
+ const first = monthModel.yearMonthAt(minMonthIndex).year;
+ const last = monthModel.yearMonthAt(maxMonthIndex).year;
+ const result: {value: number; label: string; spansEras: boolean}[] = [];
for (let candidate = first; candidate <= last; candidate++) {
- options.push({
+ result.push({
value: candidate,
- label: String(candidate),
- // A year is reachable when any of its months is.
- isDisabled:
- toMonthIndex(candidate, 12) < minMonthIndex ||
- toMonthIndex(candidate, 1) > maxMonthIndex,
+ label: formatCalendarYearLabel(calendar, candidate, locale),
+ spansEras: calendarYearSpansEras(calendar, candidate, locale),
});
}
- return options;
- }, [minMonthIndex, maxMonthIndex]);
+ return result;
+ }, [monthModel, calendar, locale, minMonthIndex, maxMonthIndex]);
+
+ // A year with an era change takes the era of the shown date, as iOS does.
+ // Its row text changes as the month turns. Each row keeps one fixed size.
+ const yearOptions: WheelOption[] = useMemo(
+ () =>
+ years.map(({value, label, spansEras}) => ({
+ value,
+ label: spansEras
+ ? formatCalendarYearLabel(calendar, value, locale, {
+ month,
+ day: keptDay,
+ })
+ : label,
+ })),
+ [years, calendar, locale, month, keptDay],
+ );
return (
<div {...stylex.props(styles.wheels)}>
@@ -129,7 +147,9 @@ export function MonthYearWheels({
options={monthOptions}
value={month}
isActive={isActive}
- onChange={nextMonth => onChange(toMonthIndex(year, nextMonth))}
+ onChange={nextMonth =>
+ onChange(monthModel.indexOfYearMonth(year, nextMonth))
+ }
/>
<Wheel
label={yearLabel}
@@ -137,10 +157,11 @@ export function MonthYearWheels({
value={year}
isActive={isActive}
onChange={nextYear => {
- // Jan 31 -> Feb has no equivalent here (months carry no day), but a
- // year change can still land outside the range; clamp to it.
- const candidate = toMonthIndex(nextYear, month);
- onChange(Math.min(Math.max(candidate, minMonthIndex), maxMonthIndex));
+ // The same month of the new year, or its common counterpart when
+ // the new year lacks a leap month (Adar I becomes Adar). A year
+ // change can still land outside the range; clamp to it.
+ const candidate = monthModel.shiftYears(monthIndex, nextYear - year);
+ onChange(clampIndex(candidate, minMonthIndex, maxMonthIndex));
}}
/>
</div>
diff --git a/packages/core/src/DateInput/TouchDateField.tsx b/packages/core/src/DateInput/TouchDateField.tsx
index 6ea4423dc5..5f90e8b227 100644
--- a/packages/core/src/DateInput/TouchDateField.tsx
+++ b/packages/core/src/DateInput/TouchDateField.tsx
@@ -4,7 +4,7 @@
/**
* @file TouchDateField.tsx
- * @input Uses React, Field, BottomSheet, Button, Icon, Calendar hooks, MonthScroller, MonthYearWheels
+ * @input Uses React, Field, BottomSheet, Button, Icon, Calendar hooks, the resolved calendar, MonthScroller, MonthYearWheels
* @output Exports TouchDateField — the touch surface behind DateInput
* @position Internal component; consumed by DateInput.tsx
*
@@ -105,12 +105,16 @@ import {
mergeProps,
rtlStyles,
themeProps,
- formatSharedDate,
plainDateFromISO,
plainDateToday,
type ISODateString,
} from '../utils';
-import {plainDateFormatStandaloneMonthYear} from '../utils/plainDate';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
+import {
+ calendarDayOfMonth,
+ formatCalendarMonthLabel,
+} from '../utils/calendarSystem';
+import {formatCalendarDateText} from '../utils/calendarDateParser';
import {chainEventHandlers} from '../utils/chainEventHandlers';
import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';
import {usePressFeedback} from '../hooks/usePressFeedback';
@@ -121,8 +125,7 @@ import {MonthYearWheels} from './MonthYearWheels';
import {
DEFAULT_MONTH_REACH,
clampIndex,
- fromMonthIndex,
- monthIndexOf,
+ createMonthModel,
} from './monthGeometry';
import {dateInputTouchSizes, dateInputTouchGeometry} from './tokens.stylex';
import {
@@ -581,6 +584,7 @@ export function TouchDateField({
numberOfMonths: _numberOfMonths,
weekStartsOn: weekStartsOnProp = 0,
format = 'date_long',
+ calendar: calendarProp,
width,
containerXstyle,
containerClassName,
@@ -612,6 +616,8 @@ export function TouchDateField({
placeholderFromProps ?? t('@astryx.dateInput.placeholder');
const size = useSize(sizeProp, 'md');
const weekStartsOn = normalizeDayOfWeek(weekStartsOnProp);
+ const calendar = useCalendarSystem(calendarProp, 'DateInput');
+ const monthModel = useMemo(() => createMonthModel(calendar), [calendar]);
const generatedID = useId();
const id = idProp ?? generatedID;
@@ -698,8 +704,10 @@ export function TouchDateField({
// century in each direction from wherever it opened. Anchored once, in a
// state initializer: recomputing it as the selection moves would shift every
// pane's scroll offset under the user mid-gesture.
+ // Indexes belong to the calendar, so DateInput remounts this surface when
+ // the calendar changes.
const [anchorMonthIndex] = useState(() =>
- monthIndexOf(
+ monthModel.indexOf(
value != null && /^\d{4}-\d{2}-\d{2}$/.test(value)
? plainDateFromISO(value)
: plainDateToday(),
@@ -707,36 +715,45 @@ export function TouchDateField({
);
const minMonthIndex =
min != null
- ? monthIndexOf(plainDateFromISO(min))
+ ? monthModel.indexOf(plainDateFromISO(min))
: anchorMonthIndex - DEFAULT_MONTH_REACH;
const maxMonthIndex =
max != null
- ? monthIndexOf(plainDateFromISO(max))
+ ? monthModel.indexOf(plainDateFromISO(max))
: anchorMonthIndex + DEFAULT_MONTH_REACH;
const [monthIndex, setMonthIndex] = useState(() =>
clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex),
);
- const {year, month} = fromMonthIndex(monthIndex);
-
const weekdayHeaders = useMemo(
() => getWeekdayHeaders(locale, weekStartsOn),
[locale, weekStartsOn],
);
- const monthYearLabel = plainDateFormatStandaloneMonthYear(
- {year, month, day: 1},
+ // The day the picker keeps: the selected date's day of its month. A month
+ // with an era change takes its heading era from this day.
+ const keptDay =
+ selectedDate == null ? 1 : calendarDayOfMonth(calendar, selectedDate);
+ const monthYearLabel = formatCalendarMonthLabel(
+ calendar,
+ monthModel.monthAt(monthIndex),
locale,
+ keptDay,
);
// Formats the committed value only. A function format is called with the ISO
- // value; a named one reuses Timestamp's shared date mapping, so the same
- // literal renders the same shape here and on the desktop control.
+ // value; a named one writes the date in the calendar exactly as the desktop
+ // control commits it.
const displayValue =
optimisticValue != null && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
? typeof format === 'function'
? format(optimisticValue)
- : formatSharedDate(plainDateFromISO(optimisticValue), format, locale)
+ : formatCalendarDateText(
+ plainDateFromISO(optimisticValue),
+ format,
+ locale,
+ calendar,
+ )
: '';
const fireChange = useCallback(
@@ -822,7 +839,7 @@ export function TouchDateField({
return;
}
fireChange(undefined);
- const currentMonth = monthIndexOf(today);
+ const currentMonth = monthModel.indexOf(today);
if (currentMonth < minMonthIndex || currentMonth > maxMonthIndex) {
return;
}
@@ -831,7 +848,15 @@ export function TouchDateField({
}
setMonthIndex(currentMonth);
scrollerHandleRef.current?.scrollToMonth(currentMonth, 'smooth');
- }, [isDisabled, fireChange, today, monthIndex, minMonthIndex, maxMonthIndex]);
+ }, [
+ isDisabled,
+ fireChange,
+ monthModel,
+ today,
+ monthIndex,
+ minMonthIndex,
+ maxMonthIndex,
+ ]);
// Selection commits on the tap and leaves the sheet up, so a mistake can be
// corrected in place and a nearby date reconsidered without reopening.
@@ -1104,6 +1129,7 @@ export function TouchDateField({
<MonthScroller
key={`${minMonthIndex}:${maxMonthIndex}`}
handleRef={scrollerHandleRef}
+ monthModel={monthModel}
minMonthIndex={minMonthIndex}
maxMonthIndex={maxMonthIndex}
initialMonthIndex={monthIndex}
@@ -1124,7 +1150,9 @@ export function TouchDateField({
!isWheelOpen && styles.panelOverlayHidden,
)}>
<MonthYearWheels
+ monthModel={monthModel}
monthIndex={monthIndex}
+ keptDay={keptDay}
minMonthIndex={minMonthIndex}
maxMonthIndex={maxMonthIndex}
onChange={handleWheelChange}
diff --git a/packages/core/src/DateInput/monthGeometry.ts b/packages/core/src/DateInput/monthGeometry.ts
index 62e5fa47d6..9138306b24 100644
--- a/packages/core/src/DateInput/monthGeometry.ts
+++ b/packages/core/src/DateInput/monthGeometry.ts
@@ -2,14 +2,16 @@
/**
* @file monthGeometry.ts
- * @input PlainDate values, scroll offsets, pane heights
- * @output Pure month-index arithmetic and the virtualized pane window
- * @position Internal helper; consumed by MonthScroller.tsx and DateInput.tsx
+ * @input PlainDate values, a calendar system, scroll offsets, pane heights
+ * @output Month-index arithmetic for a calendar and the virtualized pane window
+ * @position Internal helper; consumed by the touch date surfaces
*
- * A "month index" is a single integer that totally orders calendar months:
- * `year * 12 + (month - 1)`. The scroller is a list of equal-width panes, so
- * one integer converts freely between a month, a row in that list, and a
- * scroll offset — which is the whole trick behind continuous scrolling.
+ * A "month index" is a single integer that totally orders calendar months. In
+ * the Gregorian-aligned calendars it is `year * 12 + (month - 1)`; in the
+ * others it counts calendar months from a fixed month, because their years
+ * have 12 or 13 months. The scroller is a list of equal-width panes, so one
+ * integer converts freely between a month, a row in that list, and a scroll
+ * offset — which is the whole trick behind continuous scrolling.
*
* These are pure functions on purpose: the scroll math is the part most likely
* to be wrong, and it is testable without a layout engine.
@@ -17,7 +19,19 @@
* SYNC: When modified, update DateInputTouch.test.tsx.
*/
-import type {PlainDate} from '../utils';
+import type {PlainDate} from '../utils/dateTypes';
+import {
+ type CalendarMonth,
+ type CalendarSystem,
+ calendarAddMonths,
+ calendarMonthOf,
+ calendarMonthOfYear,
+ calendarMonthsBetween,
+ calendarMonthsInCalendarYear,
+ calendarShiftYears,
+ calendarYearMonthOf,
+ isGregorianAligned,
+} from '../utils/calendarSystem';
/** How many months are reachable in either direction when unbounded. */
export const DEFAULT_MONTH_REACH = 600;
@@ -116,3 +130,91 @@ export function rowsIn({start, end}: PaneWindow): number[] {
}
return rows;
}
+
+/**
+ * Month indexes for one calendar. Years and month positions are the ones
+ * `calendarMonthOfYear` counts.
+ */
+export interface MonthModel {
+ readonly calendar: CalendarSystem;
+ /** The index of the calendar month that contains a date. */
+ indexOf: (date: PlainDate) => number;
+ /** The calendar month at an index. */
+ monthAt: (index: number) => CalendarMonth;
+ /** The calendar year of an index and the month's position in it. */
+ yearMonthAt: (index: number) => {year: number; month: number};
+ /** The index of a month position in a calendar year. */
+ indexOfYearMonth: (year: number, month: number) => number;
+ /** The number of months in a calendar year. */
+ monthsInYear: (year: number) => number;
+ /**
+ * The index `years` calendar years from `index`, in the same month. A leap
+ * month that the target year does not have becomes its common counterpart.
+ */
+ shiftYears: (index: number, years: number) => number;
+}
+
+const GREGORIAN_MONTH_MODELS = new Map<CalendarSystem, MonthModel>();
+
+function gregorianMonthModel(calendar: CalendarSystem): MonthModel {
+ let model = GREGORIAN_MONTH_MODELS.get(calendar);
+ if (model == null) {
+ model = {
+ calendar,
+ indexOf: monthIndexOf,
+ monthAt: index => {
+ const {year, month} = fromMonthIndex(index);
+ return calendarMonthOfYear(calendar, year, month);
+ },
+ yearMonthAt: fromMonthIndex,
+ indexOfYearMonth: toMonthIndex,
+ monthsInYear: () => 12,
+ shiftYears: (index, years) => index + years * 12,
+ };
+ GREGORIAN_MONTH_MODELS.set(calendar, model);
+ }
+ return model;
+}
+
+// The month that holds EPOCH is index 0. Any fixed month works; a recent one
+// keeps the indexes of nearby months small.
+const EPOCH: PlainDate = {year: 2000, month: 1, day: 1};
+
+function temporalMonthModel(calendar: CalendarSystem): MonthModel {
+ const epoch = calendarMonthOf(calendar, EPOCH);
+ // Temporal arithmetic is slow next to a render. The panes and the wheels ask
+ // for the same months on every render.
+ const months = new Map<number, CalendarMonth>();
+ const monthAt = (index: number) => {
+ let month = months.get(index);
+ if (month == null) {
+ month = calendarAddMonths(calendar, epoch, index);
+ months.set(index, month);
+ }
+ return month;
+ };
+ const indexOf = (date: PlainDate) =>
+ calendarMonthsBetween(calendar, epoch, calendarMonthOf(calendar, date));
+ return {
+ calendar,
+ indexOf,
+ monthAt,
+ yearMonthAt: index => calendarYearMonthOf(calendar, monthAt(index)),
+ indexOfYearMonth: (year, month) =>
+ indexOf(calendarMonthOfYear(calendar, year, month).start),
+ monthsInYear: year => calendarMonthsInCalendarYear(calendar, year),
+ shiftYears: (index, years) =>
+ indexOf(calendarShiftYears(calendar, monthAt(index).start, years)),
+ };
+}
+
+/**
+ * The month model of a calendar. A calendar that needs Temporal must be
+ * available in this runtime; `useCalendarSystem` resolves one that is not to
+ * `gregory`.
+ */
+export function createMonthModel(calendar: CalendarSystem): MonthModel {
+ return isGregorianAligned(calendar)
+ ? gregorianMonthModel(calendar)
+ : temporalMonthModel(calendar);
+}
diff --git a/packages/core/src/DateInput/useCalendarPresentation.ts b/packages/core/src/DateInput/useCalendarPresentation.ts
new file mode 100644
index 0000000000..81f54bf504
--- /dev/null
+++ b/packages/core/src/DateInput/useCalendarPresentation.ts
@@ -0,0 +1,64 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useCalendarPresentation.ts
+ * @input A date component's `calendar`, `presentation`, and `nativePicker`
+ * @output The resolved calendar and the presentation policy it allows
+ * @position DateInput helper hook; used by DateInput and DateTimeInput to
+ * choose a surface. Warns once when an explicit `native` cannot apply.
+ */
+
+import {useEffect} from 'react';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
+import {
+ type CalendarSystem,
+ isGregorianCalendar,
+} from '../utils/calendarSystem';
+import {warnOnce} from '../utils/devWarning';
+import {
+ type LegacyNativePicker,
+ type PickerPresentation,
+ calendarPickerPresentation,
+ effectivePickerPresentation,
+} from '../utils/inputPresentation';
+
+export interface CalendarPresentation {
+ /** The calendar the component shows. */
+ calendar: CalendarSystem;
+ /** The presentation policy, with native surfaces replaced in a calendar the native control cannot show. */
+ presentation: PickerPresentation;
+}
+
+export function useCalendarPresentation(
+ source: string,
+ calendarProp: CalendarSystem | undefined,
+ presentation: PickerPresentation | undefined,
+ nativePicker: LegacyNativePicker | undefined,
+): CalendarPresentation {
+ const calendar = useCalendarSystem(calendarProp, source);
+ const isNativeCalendar = isGregorianCalendar(calendar);
+ const isNativeOverridden = presentation === 'native' && !isNativeCalendar;
+ // Synchronizes the development console. The key is the component and
+ // calendar, so a replay or a second field does not warn again.
+ useEffect(() => {
+ if (isNativeOverridden) {
+ warnOnce(
+ `presentation-native-calendar:${source}:${calendar}`,
+ source,
+ `presentation="native" shows the Astryx picker in the "${calendar}" ` +
+ 'calendar, because the native date control shows only Gregorian ' +
+ 'dates: the popover on a fine pointer and the bottom sheet on a ' +
+ 'coarse pointer.',
+ );
+ }
+ }, [isNativeOverridden, source, calendar]);
+ return {
+ calendar,
+ presentation: calendarPickerPresentation(
+ effectivePickerPresentation(presentation, nativePicker),
+ isNativeCalendar,
+ ),
+ };
+}
diff --git a/packages/core/src/DateInput/useTypedDate.ts b/packages/core/src/DateInput/useTypedDate.ts
new file mode 100644
index 0000000000..5c070bb59f
--- /dev/null
+++ b/packages/core/src/DateInput/useTypedDate.ts
@@ -0,0 +1,469 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useTypedDate.ts
+ * @input Provider locale and calendar, a field's format, bounds and constraints;
+ * calendarDateParser, and parseDateInput for other Gregorian text
+ * @output Typed-date reading, committed text, the format hint, the calendar
+ * description and rejection messages for a date text field, and the typed
+ * entry state that DateInput and DateTimeInput share
+ * @position DateInput helper hook; used by DateInput and DateTimeInput
+ */
+
+import {useCallback, useMemo, useRef, useState} from 'react';
+import type {InputStatus} from '../Field/types';
+import {useLocale} from '../i18n/useLocale';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
+import {
+ registerEnglishFallback,
+ useComponentTranslator,
+} from '../i18n/useComponentTranslator';
+import english from '../i18n/generated-english/DateInput/useTypedDate.generated';
+import {
+ type CalendarSystem,
+ isGregorianCalendar,
+} from '../utils/calendarSystem';
+import {
+ type CalendarDateParseResult,
+ calendarDisplayName,
+ formatCalendarDateText,
+ formatCalendarDateHint,
+ getCalendarDateLexicon,
+ parseCalendarDate,
+} from '../utils/calendarDateParser';
+import type {ISODateString, PlainDate} from '../utils/dateTypes';
+import {parseDateInput} from '../utils/dateParser';
+import {
+ type SharedDateFormat,
+ nearestAcceptedDate,
+ plainDateFromISO,
+ plainDateIsAfter,
+ plainDateIsBefore,
+ plainDateToISO,
+ plainDateToday,
+} from '../utils/plainDate';
+
+registerEnglishFallback(english);
+
+/** A rejected typed date, by the message it announces. */
+export type TypedDateError = 'unreadable' | 'nonexistent' | 'outOfRange';
+
+export interface UseTypedDateOptions {
+ /** The component that names itself in development warnings. */
+ source: string;
+ /** The field's own calendar; the provider's calendar applies otherwise. */
+ calendar?: CalendarSystem;
+ /** The committed display format. */
+ format: SharedDateFormat | ((value: ISODateString) => string);
+ min?: ISODateString;
+ max?: ISODateString;
+ isDateDisabled: (date: PlainDate) => boolean;
+}
+
+export interface TypedDate {
+ /** The resolved calendar, for the field's Calendar. */
+ calendar: CalendarSystem;
+ /** Builds the lexicon ahead of the first keystroke. */
+ prepare: () => void;
+ parse: (text: string) => CalendarDateParseResult;
+ formatCommitted: (value: ISODateString) => string;
+ /**
+ * An example date for an empty focused field, or null for Gregorian. The
+ * example is today when the field accepts it, else the nearest date it
+ * accepts.
+ */
+ getFormatHint: () => string | null;
+ /** Names the calendar, or null when it is the provider's calendar. */
+ calendarDescription: string | null;
+ /** The message for a rejected result. */
+ errorMessage: (result: CalendarDateParseResult) => string;
+}
+
+/** The rejection a result shows: errors of complete text, or of committed text. */
+export function typedDateError(
+ result: CalendarDateParseResult | null,
+ isCommitted: boolean,
+): TypedDateError | null {
+ if (result == null) {
+ return null;
+ }
+ if (
+ result.kind === 'unreadable' ||
+ (result.kind === 'incomplete' && isCommitted)
+ ) {
+ return 'unreadable';
+ }
+ if (
+ (result.kind === 'nonexistent' || result.kind === 'outOfRange') &&
+ (result.isComplete || isCommitted)
+ ) {
+ return result.kind;
+ }
+ return null;
+}
+
+/**
+ * Typed entry for a date text field in the active calendar. Values stay
+ * Gregorian; the calendar changes only what people type and read.
+ */
+export function useTypedDate({
+ source,
+ calendar: calendarProp,
+ format,
+ min,
+ max,
+ isDateDisabled,
+}: UseTypedDateOptions): TypedDate {
+ const t = useComponentTranslator();
+ const locale = useLocale();
+ const calendar = useCalendarSystem(calendarProp, source);
+ const providerCalendar = useCalendarSystem(undefined, source);
+ const isGregorian = isGregorianCalendar(calendar);
+
+ const prepare = useCallback(() => {
+ getCalendarDateLexicon(locale, calendar);
+ }, [locale, calendar]);
+
+ const parse = useCallback(
+ (text: string): CalendarDateParseResult => {
+ const result = parseCalendarDate(
+ text,
+ getCalendarDateLexicon(locale, calendar),
+ {isoIsGregorian: format === 'system_date', isDateDisabled},
+ );
+ if (
+ !isGregorian ||
+ (result.kind !== 'unreadable' && result.kind !== 'nonexistent')
+ ) {
+ return result;
+ }
+ // Gregorian text that only parseDateInput reads still commits, on Enter
+ // or blur only: it is never complete while the person types. This
+ // includes a day-first date in a month-first locale, which
+ // parseDateInput reads by swapping the order.
+ const date = parseDateInput(text, locale);
+ if (date == null) {
+ return result;
+ }
+ return isDateDisabled(date)
+ ? {kind: 'outOfRange', date, isComplete: false}
+ : {kind: 'value', date, isComplete: false};
+ },
+ [locale, calendar, format, isDateDisabled, isGregorian],
+ );
+
+ const formatCommitted = useCallback(
+ (value: ISODateString) =>
+ typeof format === 'function'
+ ? format(value)
+ : formatCalendarDateText(
+ plainDateFromISO(value),
+ format,
+ locale,
+ calendar,
+ ),
+ [format, locale, calendar],
+ );
+
+ const getFormatHint = useCallback(() => {
+ if (isGregorian) {
+ return null;
+ }
+ const example = nearestAcceptedDate(plainDateToday(), {
+ min: min != null ? plainDateFromISO(min) : null,
+ max: max != null ? plainDateFromISO(max) : null,
+ isDateDisabled,
+ });
+ return t('@astryx.dateInput.formatHint', {
+ example: formatCalendarDateHint(example, locale, calendar),
+ });
+ }, [isGregorian, t, locale, calendar, min, max, isDateDisabled]);
+
+ const calendarName = useMemo(
+ () => calendarDisplayName(calendar, locale),
+ [calendar, locale],
+ );
+
+ const errorMessage = useCallback(
+ (result: CalendarDateParseResult) => {
+ if (result.kind === 'nonexistent') {
+ return t('@astryx.dateInput.nonexistentDate', {calendar: calendarName});
+ }
+ if (result.kind === 'outOfRange') {
+ const boundFormat = typeof format === 'function' ? 'date_long' : format;
+ const writeBound = (bound: ISODateString) =>
+ formatCalendarDateText(
+ plainDateFromISO(bound),
+ boundFormat,
+ locale,
+ calendar,
+ );
+ const isBeforeMin =
+ min != null && plainDateIsBefore(result.date, plainDateFromISO(min));
+ const isAfterMax =
+ max != null && plainDateIsAfter(result.date, plainDateFromISO(max));
+ const bounds =
+ !isBeforeMin && !isAfterMax
+ ? 'none'
+ : min != null && max != null
+ ? 'both'
+ : min != null
+ ? 'min'
+ : 'max';
+ return t('@astryx.dateInput.outOfRangeDate', {
+ bounds,
+ min: min != null ? writeBound(min) : '',
+ max: max != null ? writeBound(max) : '',
+ });
+ }
+ return t('@astryx.dateInput.invalidDate');
+ },
+ [t, calendarName, format, locale, calendar, min, max],
+ );
+
+ const isProviderCalendar = isGregorian
+ ? isGregorianCalendar(providerCalendar)
+ : calendar === providerCalendar;
+
+ return {
+ calendar,
+ prepare,
+ parse,
+ formatCommitted,
+ getFormatHint,
+ calendarDescription: isProviderCalendar
+ ? null
+ : t('@astryx.dateInput.calendarDescription', {calendar: calendarName}),
+ errorMessage,
+ };
+}
+
+export interface UseTypedDateFieldOptions extends UseTypedDateOptions {
+ /** The committed date. */
+ value: ISODateString | undefined;
+ /** The date the field shows, which leads `value` while a commit is in flight. */
+ shownValue: ISODateString | undefined;
+ /** Reports a typed date. */
+ onChange: (value: ISODateString) => void;
+ /** Runs when Enter or blur commits emptied text. */
+ onClear: () => void;
+ /** Runs when typing completes a new date, such as to show its month. */
+ onTypedDate?: (value: ISODateString) => void;
+ /**
+ * A disabled or busy field ignores typing, Enter and blur, and hides a typed
+ * rejection. Typed text stays until the next Enter or blur once the field is
+ * editable, or until `value` changes. Once the field is editable, text whose
+ * date typing already reported gives way to the field's value.
+ */
+ isDisabled: boolean;
+ /** The caller's status. Rejected text that stays shows its own error instead. */
+ status?: InputStatus;
+ /** Whether the shown status announces itself, as Field's status does. */
+ isStatusAnnounced: boolean;
+ /** Whether the caller gave a placeholder, which replaces the format hint. */
+ hasPlaceholder: boolean;
+}
+
+export interface TypedDateField {
+ typedDate: TypedDate;
+ /** The text the input shows. */
+ displayValue: string;
+ /** The format hint for an empty focused field. */
+ formatHint: string | null;
+ /** Whether typed text waits to commit. */
+ isPending: boolean;
+ isInvalid: boolean;
+ /** The status the field shows. */
+ fieldStatus: InputStatus | undefined;
+ /** A typed rejection that the field status does not announce. */
+ alertMessage: string;
+ handleChange: (text: string) => void;
+ /** Commits typed text, on Enter or blur. */
+ commit: () => void;
+ handleFocus: () => void;
+ handleBlur: () => void;
+ /** Drops typed text after a date is picked another way. */
+ reset: () => void;
+}
+
+/** The typed entry of a date text field: its text, rejections, and commits. */
+export function useTypedDateField({
+ value,
+ shownValue,
+ onChange,
+ onClear,
+ onTypedDate,
+ isDisabled,
+ status,
+ isStatusAnnounced,
+ hasPlaceholder,
+ ...options
+}: UseTypedDateFieldOptions): TypedDateField {
+ const typedDate = useTypedDate(options);
+ // Typed text, or null when the field shows the committed value.
+ const [pendingInput, setPendingInput] = useState<string | null>(null);
+ // Set when Enter or blur keeps rejected text so the person can correct it.
+ const [isRejectionCommitted, setIsRejectionCommitted] = useState(false);
+ const [isFocused, setIsFocused] = useState(false);
+ // The date that typing last reported, so one typing session reports each
+ // date once.
+ const lastFiredRef = useRef<ISODateString | undefined>(undefined);
+
+ const typedResult =
+ pendingInput !== null && pendingInput.trim()
+ ? typedDate.parse(pendingInput)
+ : null;
+ // A locked field hides the rejection but keeps its state, so the rejection
+ // shows again once the field is editable.
+ const typedError = isDisabled
+ ? null
+ : typedDateError(typedResult, isRejectionCommitted);
+ const errorMessage =
+ typedError != null && typedResult != null
+ ? typedDate.errorMessage(typedResult)
+ : null;
+ // Text that stays in the field shows its reason as well as announcing it.
+ const isErrorShown =
+ typedError === 'nonexistent' ||
+ typedError === 'outOfRange' ||
+ (typedError === 'unreadable' && isRejectionCommitted);
+ const typedStatus: InputStatus | undefined =
+ isErrorShown && errorMessage != null
+ ? {type: 'error', message: errorMessage}
+ : undefined;
+ const fieldStatus = typedStatus ?? status;
+
+ const reset = useCallback(() => {
+ setPendingInput(null);
+ setIsRejectionCommitted(false);
+ }, []);
+
+ // A value from outside drops typed text. Computed during render, so it
+ // takes no extra render.
+ const prevValueRef = useRef(value);
+ if (value !== prevValueRef.current) {
+ prevValueRef.current = value;
+ if (value !== lastFiredRef.current) {
+ lastFiredRef.current = undefined;
+ if (pendingInput !== null) {
+ setPendingInput(null);
+ setIsRejectionCommitted(false);
+ }
+ }
+ }
+
+ // Typing already reported this date through `onChange`. Once the field is
+ // editable, it shows its value. A retyped date then reports again. A focused
+ // field keeps the text until Enter or blur, which end the typing session.
+ const wasDisabledRef = useRef(isDisabled);
+ if (isDisabled !== wasDisabledRef.current) {
+ wasDisabledRef.current = isDisabled;
+ if (
+ !isDisabled &&
+ !isFocused &&
+ typedResult?.kind === 'value' &&
+ plainDateToISO(typedResult.date) === lastFiredRef.current
+ ) {
+ lastFiredRef.current = undefined;
+ setPendingInput(null);
+ setIsRejectionCommitted(false);
+ }
+ }
+
+ const report = useCallback(
+ (date: ISODateString) => {
+ if (date === value || date === lastFiredRef.current) {
+ return false;
+ }
+ lastFiredRef.current = date;
+ onChange(date);
+ return true;
+ },
+ [value, onChange],
+ );
+
+ const handleChange = useCallback(
+ (text: string) => {
+ if (isDisabled) {
+ return;
+ }
+ setPendingInput(text);
+ setIsRejectionCommitted(false);
+ // Report a date only once more typing cannot change it.
+ const result = typedDate.parse(text);
+ if (result.kind === 'value' && result.isComplete) {
+ const date = plainDateToISO(result.date);
+ if (report(date)) {
+ onTypedDate?.(date);
+ }
+ }
+ },
+ [isDisabled, typedDate, report, onTypedDate],
+ );
+
+ const commit = useCallback(() => {
+ if (pendingInput === null || isDisabled) {
+ return;
+ }
+ if (!pendingInput.trim()) {
+ onClear();
+ reset();
+ return;
+ }
+ const result = typedDate.parse(pendingInput);
+ if (
+ result.kind === 'incomplete' ||
+ result.kind === 'nonexistent' ||
+ result.kind === 'outOfRange'
+ ) {
+ // Keep the text and show why it cannot commit; never finish or adjust
+ // the date.
+ setIsRejectionCommitted(true);
+ return;
+ }
+ if (result.kind === 'value') {
+ report(plainDateToISO(result.date));
+ }
+ // A new typing session reports a retyped date again.
+ lastFiredRef.current = undefined;
+ reset();
+ }, [pendingInput, isDisabled, onClear, typedDate, report, reset]);
+
+ const handleFocus = useCallback(() => {
+ setIsFocused(true);
+ typedDate.prepare();
+ }, [typedDate]);
+
+ const handleBlur = useCallback(() => {
+ setIsFocused(false);
+ commit();
+ }, [commit]);
+
+ const displayValue =
+ pendingInput !== null
+ ? pendingInput
+ : shownValue != null && /^\d{4}-\d{2}-\d{2}$/.test(shownValue)
+ ? typedDate.formatCommitted(shownValue)
+ : '';
+
+ return {
+ typedDate,
+ displayValue,
+ formatHint:
+ !hasPlaceholder && isFocused && !displayValue
+ ? typedDate.getFormatHint()
+ : null,
+ isPending: pendingInput !== null,
+ isInvalid: typedError != null,
+ fieldStatus,
+ alertMessage:
+ isStatusAnnounced && typedStatus != null ? '' : (errorMessage ?? ''),
+ handleChange,
+ commit,
+ handleFocus,
+ handleBlur,
+ reset,
+ };
+}
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.calendar.test.tsx b/packages/core/src/DateRangeInput/DateRangeInput.calendar.test.tsx
new file mode 100644
index 0000000000..21d9c9dae7
--- /dev/null
+++ b/packages/core/src/DateRangeInput/DateRangeInput.calendar.test.tsx
@@ -0,0 +1,158 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DateRangeInput.calendar.test.tsx
+ * @input Uses vitest, Testing Library, temporal-polyfill, DateRangeInput
+ * @output The range in a calendar: trigger text, the popover Calendar,
+ * Gregorian ISO values, and the fallback without Temporal
+ * @position Colocated test for DateRangeInput's `calendar` prop
+ */
+
+import {afterAll, afterEach, beforeAll, beforeEach} from 'vitest';
+import {describe, expect, it, vi} from 'vitest';
+import {fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {Temporal as TemporalPolyfill} from 'temporal-polyfill/full';
+import {DateRangeInput, type DateRangeInputProps} from './DateRangeInput';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import {__resetDevWarnings} from '../utils/devWarning';
+
+const host = globalThis as {Temporal?: unknown};
+const hadTemporal = host.Temporal != null;
+beforeAll(() => {
+ host.Temporal ??= TemporalPolyfill;
+});
+afterAll(() => {
+ if (!hadTemporal) {
+ delete host.Temporal;
+ }
+});
+
+beforeEach(() => {
+ vi.useFakeTimers({toFake: ['Date']});
+ vi.setSystemTime(new Date(2026, 10, 2, 12));
+ __resetDevWarnings();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+function renderRange(
+ locale: string,
+ props: Partial<DateRangeInputProps>,
+ providerCalendar?: 'persian',
+) {
+ const onChange = vi.fn();
+ render(
+ <InternationalizationProvider locale={locale} calendar={providerCalendar}>
+ <DateRangeInput
+ label="Stay"
+ value={{start: '2026-10-30', end: '2026-11-02'}}
+ onChange={onChange}
+ {...props}
+ />
+ </InternationalizationProvider>,
+ );
+ return {onChange};
+}
+
+/** The range trigger: the button that shows the range. */
+function triggerText(): string {
+ return (
+ document.querySelector<HTMLElement>(
+ 'button[aria-haspopup="dialog"]:not([tabindex="-1"])',
+ )?.textContent ?? ''
+ );
+}
+
+describe('DateRangeInput in a calendar', () => {
+ it('writes the trigger text and its accessible name in the Persian calendar', () => {
+ renderRange('en', {calendar: 'persian'});
+ expect(triggerText()).toContain('Aban 8 – Aban 11');
+ expect(
+ screen.getByRole('button', {name: 'Stay: Aban 8 – Aban 11'}),
+ ).toBeInTheDocument();
+ });
+
+ it('takes the calendar from the provider', () => {
+ renderRange('fa-IR', {}, 'persian');
+ expect(triggerText()).toContain('۸ آبان – ۱۱ آبان');
+ });
+
+ it('shows the year when the range leaves the current calendar year', () => {
+ // Both dates are in Gregorian 2026, but Nowruz falls between them.
+ renderRange('en', {
+ calendar: 'persian',
+ value: {start: '2026-03-15', end: '2026-03-25'},
+ });
+ expect(triggerText()).toContain('Esfand 24, 1404 AP');
+ expect(triggerText()).toContain('Farvardin 5, 1405 AP');
+ });
+
+ it('opens a Persian popover calendar and reports Gregorian ISO dates', async () => {
+ const {onChange} = renderRange('en', {calendar: 'persian', value: null});
+ fireEvent.click(screen.getByRole('button', {name: 'Open calendar'}));
+ const grid = await waitFor(() => {
+ const element = document.querySelector('[role="grid"]');
+ expect(element).not.toBeNull();
+ return element as HTMLElement;
+ });
+ expect(grid.getAttribute('aria-label')).toContain('1405');
+ const first = grid.querySelector<HTMLButtonElement>(
+ 'button[data-date="2026-10-23"]',
+ );
+ const last = grid.querySelector<HTMLButtonElement>(
+ 'button[data-date="2026-10-25"]',
+ );
+ fireEvent.click(first!);
+ fireEvent.click(last!);
+ expect(onChange).toHaveBeenLastCalledWith({
+ start: '2026-10-23',
+ end: '2026-10-25',
+ });
+ });
+
+ it('keeps Gregorian text by default', () => {
+ renderRange('en', {});
+ expect(triggerText()).toContain('Oct 30 – Nov 2');
+ });
+
+ it('writes Buddhist years', () => {
+ renderRange('th-TH', {
+ calendar: 'buddhist',
+ value: {start: '2025-12-30', end: '2026-01-02'},
+ });
+ expect(triggerText()).toContain('2568');
+ expect(triggerText()).toContain('2569');
+ });
+});
+
+describe('DateRangeInput in a calendar without Temporal', () => {
+ const saved = host.Temporal;
+ beforeEach(() => {
+ delete host.Temporal;
+ });
+ afterEach(() => {
+ host.Temporal = saved;
+ });
+
+ it('shows Gregorian dates for Persian and warns', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ renderRange('en', {calendar: 'persian'});
+ expect(triggerText()).toContain('Oct 30 – Nov 2');
+ expect(String(warn.mock.calls[0]?.[0])).toContain(
+ 'needs a Temporal that supports it',
+ );
+ });
+
+ it('still writes Buddhist years', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ renderRange('th-TH', {
+ calendar: 'buddhist',
+ value: {start: '2025-12-30', end: '2026-01-02'},
+ });
+ expect(triggerText()).toContain('2569');
+ expect(warn).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs b/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs
index 313d0ab3fe..9138867a94 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs
+++ b/packages/core/src/DateRangeInput/DateRangeInput.doc.mjs
@@ -165,6 +165,13 @@ export const docs = {
'First day of week in the calendar. A number (0 = Sunday to 6 = Saturday) or a three-letter day name.',
default: '0',
},
+ {
+ name: 'calendar',
+ type: "'gregory' | 'iso8601' | 'buddhist' | 'roc' | 'japanese' | 'persian' | 'indian' | 'hebrew' | 'chinese' | 'dangi' | 'coptic' | 'ethiopic' | 'ethioaa' | 'islamic-civil' | 'islamic-tbla' | 'islamic-umalqura'",
+ description:
+ "The calendar the trigger text and the popover calendar show, such as persian, hebrew, or buddhist. value, onChange, min, max, and presets stay Gregorian ISO dates. The field has no typed entry. Calendars other than gregory, iso8601, buddhist, roc, and japanese need Temporal, native or a polyfill the application loads; without it the field shows Gregorian dates and warns in development. Month starts in the Chinese and Dangi calendars come from the runtime's Temporal; when you render on the server, load the same Temporal implementation on the server and in the browser.",
+ default: "the InternationalizationProvider's calendar, else 'gregory'",
+ },
{
name: 'width',
type: 'SizeValue',
@@ -379,6 +386,8 @@ export const docsDense = {
'How status message is placed: attached overlaps below input; detached floats below w/ spacing; tooltip hides the box and shows it on the status icon.',
labelTooltip: 'tooltip via info icon at label end',
numberOfMonths: 'months in calendar (default 2)',
+ calendar:
+ "calendar for the trigger text + popover calendar (default: provider's, else 'gregory'); values and presets stay Gregorian ISO; no typed entry; non-Gregorian-aligned calendars need Temporal (native or app-loaded polyfill), else Gregorian",
weekStartsOn:
'first day of week in calendar (0=Sunday, or name e.g. "mon")',
changeAction:
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsx
index 64b642752f..411de12303 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx
@@ -4,7 +4,8 @@
/**
* @file DateRangeInput.tsx
- * @input Uses React, Field, Calendar (range mode), VisuallyHidden, usePopover
+ * @input Uses React, Field, Calendar (range mode), the resolved calendar,
+ * VisuallyHidden, usePopover
* @output Exports DateRangeInput component, DateRangeInputProps
* @position Core implementation; consumed by index.ts, tested by DateRangeInput.test.tsx
*
@@ -29,11 +30,18 @@ import {inputDisabledFocusStyles} from '../Field/inputDisabledFocus';
import {
plainDateFromISO,
plainDateToday,
- plainDateFormat,
plainDateDiffDays,
+ type PlainDate,
DATE_FORMAT_SHORT,
DATE_FORMAT_SHORT_WITH_YEAR,
} from '../utils/plainDate';
+import {
+ type CalendarSystem,
+ calendarMonthOf,
+ calendarYearMonthOf,
+ formatCalendarDate,
+} from '../utils/calendarSystem';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
import {
colorVars,
sizeVars,
@@ -262,17 +270,24 @@ const sizeStyles = stylex.create({
},
});
-function formatRangeDisplay(range: DateRange | null, locale: Locale): string {
+function formatRangeDisplay(
+ range: DateRange | null,
+ locale: Locale,
+ calendar: CalendarSystem,
+): string {
if (!range) {
return '';
}
const start = plainDateFromISO(range.start);
const end = plainDateFromISO(range.end);
- const currentYear = plainDateToday().year;
- const sameYear = start.year === end.year && start.year === currentYear;
+ const yearOf = (pd: PlainDate) =>
+ calendarYearMonthOf(calendar, calendarMonthOf(calendar, pd)).year;
+ const currentYear = yearOf(plainDateToday());
+ const sameYear =
+ yearOf(start) === yearOf(end) && yearOf(start) === currentYear;
const fmt = sameYear ? DATE_FORMAT_SHORT : DATE_FORMAT_SHORT_WITH_YEAR;
- return `${plainDateFormat(start, fmt, locale)} – ${plainDateFormat(end, fmt, locale)}`;
+ return `${formatCalendarDate(calendar, start, fmt, locale)} – ${formatCalendarDate(calendar, end, fmt, locale)}`;
}
function isRangeEqual(a: DateRange | null, b: DateRange | null): boolean {
@@ -497,6 +512,22 @@ export interface DateRangeInputProps extends Omit<
*/
numberOfMonths?: 1 | 2;
+ /**
+ * The calendar the trigger text and the popover calendar show, such as
+ * `'persian'`, `'hebrew'`, or `'buddhist'`. `value`, `onChange`, `min`,
+ * `max`, and presets stay Gregorian ISO dates in every calendar. Calendars
+ * other than `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese` need
+ * `Temporal`, native or a polyfill the application loads; without it the
+ * field shows Gregorian dates.
+ *
+ * @default the InternationalizationProvider's calendar, else `'gregory'`
+ * @example
+ * ```
+ * <DateRangeInput label="Stay" calendar="persian" value={range} onChange={setRange} />
+ * ```
+ */
+ calendar?: CalendarSystem;
+
/**
* First day of week in the calendar. Accepts a number
* (0 = Sunday … 6 = Saturday) or a three-letter day name ('sun'–'sat',
@@ -553,6 +584,7 @@ export function DateRangeInput({
labelTooltip,
numberOfMonths = 2,
weekStartsOn,
+ calendar: calendarProp,
width,
containerXstyle,
containerClassName,
@@ -578,6 +610,7 @@ export function DateRangeInput({
} = rest;
const t = useComponentTranslator();
const locale = useLocale();
+ const calendar = useCalendarSystem(calendarProp, 'DateRangeInput');
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
const placeholder =
placeholderFromProps ?? t('@astryx.dateRangeInput.placeholder');
@@ -632,8 +665,8 @@ export function DateRangeInput({
.join(' ') || undefined;
const displayValue = useMemo(
- () => formatRangeDisplay(optimisticValue, locale),
- [optimisticValue, locale],
+ () => formatRangeDisplay(optimisticValue, locale, calendar),
+ [optimisticValue, locale, calendar],
);
const popover = usePopover({
@@ -910,8 +943,7 @@ export function DateRangeInput({
calendar only while it is open. */}
{popover.isOpen && (
<Calendar
- // The field text is Gregorian, so the popover calendar is too.
- calendar="gregory"
+ calendar={calendar}
mode="range"
value={optimisticValue}
onChange={handleRangeSelect}
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.calendar.test.tsx b/packages/core/src/DateTimeInput/DateTimeInput.calendar.test.tsx
new file mode 100644
index 0000000000..92ede6fee3
--- /dev/null
+++ b/packages/core/src/DateTimeInput/DateTimeInput.calendar.test.tsx
@@ -0,0 +1,166 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DateTimeInput.calendar.test.tsx
+ * @input Uses vitest, Testing Library, temporal-polyfill, DateTimeInput
+ * @output Typed date entry in calendar systems for the DateTimeInput date
+ * field: digits, committed text, rejected dates, onChange counts
+ * @position Testing; validates DateTimeInput typed entry with a calendar
+ */
+
+import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest';
+import {fireEvent, render, screen, within} from '@testing-library/react';
+import {Temporal as TemporalPolyfill} from 'temporal-polyfill/full';
+import {
+ DateTimeInput,
+ type DateTimeInputProps,
+ type ISODateTimeString,
+} from './DateTimeInput';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+
+const host = globalThis as {Temporal?: unknown};
+const hadTemporal = host.Temporal != null;
+beforeAll(() => {
+ host.Temporal ??= TemporalPolyfill;
+});
+afterAll(() => {
+ if (!hadTemporal) {
+ delete host.Temporal;
+ }
+});
+
+function renderField(locale: string, props: Partial<DateTimeInputProps> = {}) {
+ const onChange = vi.fn();
+ const result = render(
+ <InternationalizationProvider locale={locale}>
+ <DateTimeInput label="Meeting" onChange={onChange} {...props} />
+ </InternationalizationProvider>,
+ );
+ const input = screen.getByRole('combobox');
+ return {...result, input, onChange};
+}
+
+// A shown status describes the input and announces itself; no alert repeats
+// it.
+function expectShown(input: HTMLElement, box: HTMLElement, text: string) {
+ expect(input).toHaveAccessibleDescription(expect.stringContaining(text));
+ const alerts = within(box).getAllByRole('alert');
+ expect(alerts.map(alert => alert.textContent)).not.toContain(text);
+}
+
+function typeSlowly(input: HTMLElement, text: string) {
+ let typed = '';
+ for (const ch of text) {
+ typed += ch;
+ fireEvent.change(input, {target: {value: typed}});
+ }
+}
+
+describe('DateTimeInput typed date entry with a calendar', () => {
+ it('reports one Persian date typed in Persian digits, only when complete', () => {
+ const {input, onChange} = renderField('fa-IR', {calendar: 'persian'});
+ typeSlowly(input, '۱۴۰۵/۸/۱۱');
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange.mock.calls[0][0]).toMatch(/^2026-11-02T/);
+ });
+
+ it('writes the committed date in the calendar', () => {
+ renderField('en', {
+ calendar: 'hebrew',
+ value: '2024-03-11T09:30' as ISODateTimeString,
+ });
+ expect(screen.getByRole('combobox')).toHaveValue('1 Adar II 5784 AM');
+ });
+
+ it('rejects a date the calendar does not have and names the calendar', () => {
+ const {input, onChange, container} = renderField('en', {
+ calendar: 'hebrew',
+ status: {type: 'warning', message: 'Check the date'},
+ });
+ fireEvent.change(input, {target: {value: '1 Adar I 5785'}});
+ fireEvent.blur(input);
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expectShown(
+ input,
+ container,
+ 'This date does not exist in the Hebrew Calendar',
+ );
+ expect(input).toHaveValue('1 Adar I 5785');
+ });
+
+ it('shows an out-of-range error with the bounds in the calendar', () => {
+ const {input, onChange, container} = renderField('en', {
+ calendar: 'japanese',
+ min: '2019-05-01T00:00' as ISODateTimeString,
+ });
+ fireEvent.change(input, {target: {value: 'April 30, 31 Heisei'}});
+ expect(onChange).not.toHaveBeenCalled();
+ expectShown(input, container, 'Enter a date on or after May 1, 1 Reiwa');
+ });
+
+ it('names the calendar and shows the hint when focused and empty', () => {
+ const {input} = renderField('en', {calendar: 'persian'});
+ expect(input).toHaveAccessibleDescription('Dates use the Persian Calendar');
+ fireEvent.focus(input);
+ expect(input.getAttribute('placeholder')).toMatch(/^e\.g\., .+ AP$/);
+ });
+
+ it('shows a caller placeholder instead of the format hint', () => {
+ const {input} = renderField('en', {
+ calendar: 'persian',
+ placeholder: 'Pick a day',
+ });
+ fireEvent.focus(input);
+ expect(input).toHaveValue('');
+ expect(input).toHaveAttribute('placeholder', 'Pick a day');
+ });
+
+ it('names no calendar when the field uses the provider calendar', () => {
+ render(
+ <InternationalizationProvider locale="fa-IR" calendar="persian">
+ <DateTimeInput label="Meeting" onChange={vi.fn()} />
+ </InternationalizationProvider>,
+ );
+ const input = screen.getByRole('combobox');
+ expect(input).not.toHaveAttribute('aria-describedby');
+ fireEvent.focus(input);
+ expect(input.getAttribute('placeholder')).toMatch(/^e\.g\./);
+ });
+
+ it('names the Gregorian calendar inside a Persian provider', () => {
+ render(
+ <InternationalizationProvider locale="en" calendar="persian">
+ <DateTimeInput label="Meeting" calendar="gregory" onChange={vi.fn()} />
+ </InternationalizationProvider>,
+ );
+ expect(screen.getByRole('combobox')).toHaveAccessibleDescription(
+ 'Dates use the Gregorian Calendar',
+ );
+ });
+
+ it('commits Gregorian text that only parseDateInput reads on blur', () => {
+ const {input, onChange} = renderField('en-US');
+ fireEvent.change(input, {target: {value: '2026-01-25 10:00'}});
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange.mock.calls[0][0]).toMatch(/^2026-01-25T/);
+ });
+
+ it('commits a day-first date that does not exist month-first, on blur only', () => {
+ const {input, onChange} = renderField('en-US');
+ typeSlowly(input, '13/5/2026');
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange.mock.calls[0][0]).toMatch(/^2026-05-13T/);
+ });
+
+ it('fires once for a day-first Gregorian date typed one key at a time', () => {
+ const {input, onChange} = renderField('en-GB');
+ typeSlowly(input, '12/01/2026');
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange.mock.calls[0][0]).toMatch(/^2026-01-12T/);
+ });
+});
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs
index c3d0cd49f6..581ca0d159 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs
+++ b/packages/core/src/DateTimeInput/DateTimeInput.doc.mjs
@@ -141,9 +141,16 @@ export const docs = {
name: 'placeholder',
type: 'string',
description:
- 'Placeholder text shown in the date portion when no date is selected.',
+ 'Placeholder text shown in the date portion when no date is selected. A caller placeholder replaces the calendar format hint.',
default: "'Select a date'",
},
+ {
+ name: 'calendar',
+ type: "'gregory' | 'iso8601' | 'buddhist' | 'roc' | 'japanese' | 'persian' | 'indian' | 'hebrew' | 'chinese' | 'dangi' | 'coptic' | 'ethiopic' | 'ethioaa' | 'islamic-civil' | 'islamic-tbla' | 'islamic-umalqura'",
+ description:
+ 'The calendar the date segment reads and writes typed dates in, and the calendar its popover and bottom sheet show. value, onChange, min, and max stay Gregorian ISO datetimes. People type a date the way the locale writes it in this calendar, in any decimal digits; the field reports a date only once it is complete, and names a date the calendar does not have. Years are years of this calendar, so set min and max on Buddhist and Minguo calendar fields to catch a Gregorian year typed by mistake. Calendars other than gregory, iso8601, buddhist, roc, and japanese need Temporal, native or a polyfill the application loads; without it the field shows Gregorian dates. With a calendar other than gregory or iso8601, a presentation that would show native controls shows the popovers on a fine pointer and the bottom sheet on a coarse pointer, because the native date control is Gregorian; the Date panel of the bottom sheet shows the months, leap months, and era years of the calendar. A year in which the era changes is labeled with the era of the shown month, such as 平成31 in January 2019 and 令和元 in July.',
+ default: "the InternationalizationProvider's calendar, else 'gregory'",
+ },
{
name: 'timePlaceholder',
type: 'string',
@@ -193,14 +200,14 @@ export const docs = {
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'native' | 'adaptive-bottom-sheet' | 'adaptive-native'",
description:
- "Which surfaces draw the date and time pickers. 'adaptive-native' (the default) uses Astryx's typed fields and popovers on a fine pointer and browser/OS controls on a coarse pointer — with per-segment Astryx fallbacks: hasSeconds, non-default timeIncrement, or timeOptionInterval retain Astryx's time field because iOS cannot express them faithfully; 'native' always uses both browser/OS controls with no fallback; 'adaptive-bottom-sheet' uses popovers on a fine pointer and Astryx's coordinated bottom sheet on a coarse pointer; 'popover' and 'bottom-sheet' force that Astryx surface on every pointer. Every value opens pickers; typed-only fields are TimeInput's alone. Use a non-native presentation 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.",
+ "Which surfaces draw the date and time pickers. 'adaptive-native' (the default) uses Astryx's typed fields and popovers on a fine pointer and browser/OS controls on a coarse pointer — with per-segment Astryx fallbacks: hasSeconds, non-default timeIncrement, or timeOptionInterval retain Astryx's time field because iOS cannot express them faithfully; 'native' always uses both browser/OS controls with no fallback; 'adaptive-bottom-sheet' uses popovers on a fine pointer and Astryx's coordinated bottom sheet on a coarse pointer; 'popover' and 'bottom-sheet' force that Astryx surface on every pointer. Every value opens pickers; typed-only fields are TimeInput's alone. Use a non-native presentation 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. With a calendar other than gregory or iso8601, 'native' and 'adaptive-native' use the popovers on a fine pointer and the bottom sheet on a coarse pointer, and an explicit 'native' warns in development.",
default: "'adaptive-native'",
},
{
name: 'nativePicker',
type: "'touch' | 'always' | 'never'",
description:
- "Deprecated: use presentation ('touch' = 'adaptive-native', 'always' = 'native', 'never' = 'adaptive-bottom-sheet'). Still works exactly as released; presentation wins when both are set.",
+ "Deprecated: use presentation ('touch' = 'adaptive-native', 'always' = 'native', 'never' = 'adaptive-bottom-sheet'). Still works exactly as released; presentation wins when both are set. With a calendar other than gregory or iso8601, 'touch' and 'always' use the popovers on a fine pointer and the bottom sheet on a coarse pointer.",
default: "'touch'",
},
{
@@ -262,6 +269,11 @@ export const docs = {
description:
'Use min and max to restrict selectable datetimes to valid ranges.',
},
+ {
+ guidance: true,
+ description:
+ 'Set min and max on a Buddhist or Minguo calendar field, so a Gregorian year typed by mistake shows an error instead of a date centuries away.',
+ },
{
guidance: true,
description:
@@ -385,6 +397,11 @@ export const docsZh = {
description:
'Use min and max to restrict selectable datetimes to valid ranges.',
},
+ {
+ guidance: true,
+ description:
+ 'Set min and max on a Buddhist or Minguo calendar field, so a Gregorian year typed by mistake shows an error instead of a date centuries away.',
+ },
{
guidance: true,
description:
@@ -445,7 +462,8 @@ export const docsZh = {
{
name: 'isDisabled',
type: 'boolean',
- description: '禁用输入框和选择器。字段仍可聚焦并暴露 `aria-disabled`,但不能输入或打开选择器。',
+ description:
+ '禁用输入框和选择器。字段仍可聚焦并暴露 `aria-disabled`,但不能输入或打开选择器。',
default: 'false',
},
{
@@ -522,9 +540,17 @@ export const docsZh = {
{
name: 'placeholder',
type: 'string',
- description: '日期部分未选择日期时显示的占位符文本。',
+ description:
+ '日期部分未选择日期时显示的占位符文本。调用方提供的占位符会替代日历格式提示。',
default: "'Select a date'",
},
+ {
+ name: 'calendar',
+ type: "'gregory' | 'iso8601' | 'buddhist' | 'roc' | 'japanese' | 'persian' | 'indian' | 'hebrew' | 'chinese' | 'dangi' | 'coptic' | 'ethiopic' | 'ethioaa' | 'islamic-civil' | 'islamic-tbla' | 'islamic-umalqura'",
+ description:
+ '日期部分读写输入日期所用的历法,也是其弹出日历和底部面板显示的历法。value、onChange、min 和 max 始终为公历 ISO 日期时间。用户按当前语言区域在该历法中的写法输入日期,可使用任意十进制数字;只有输入完整时字段才会报告日期,并会指出该历法中不存在的日期。年份是该历法的年份,因此请为佛历和民国纪年字段设置 min 和 max,以发现误输入的公历年份。gregory、iso8601、buddhist、roc 和 japanese 以外的历法需要 Temporal(原生或由应用加载的 polyfill);没有 Temporal 时字段显示公历日期。使用 gregory 或 iso8601 以外的历法时,原本显示原生控件的呈现会在精细指针上显示弹出层、在粗指针上显示底部面板,因为原生日期控件只显示公历;底部面板的日期页显示该历法的月份、闰月和带纪元的年份。年号更替的年份按所显示月份的年号标注,如 2019 年 1 月为“平成31”,7 月为“令和元”。',
+ default: "InternationalizationProvider 的历法,否则为 'gregory'",
+ },
{
name: 'timePlaceholder',
type: 'string',
@@ -572,14 +598,14 @@ export const docsZh = {
name: 'presentation',
type: "'popover' | 'bottom-sheet' | 'native' | 'adaptive-bottom-sheet' | 'adaptive-native'",
description:
- "选择由哪些界面绘制日期和时间选择器。'adaptive-native'(默认)在精细指针上使用 Astryx 文本字段与弹出层、在粗指针上使用浏览器/操作系统控件,并按段回退:hasSeconds、非默认 timeIncrement 或 timeOptionInterval 会保留 Astryx 时间字段;'native' 始终使用两个原生控件且不回退;'adaptive-bottom-sheet' 在精细指针上用弹出层、在粗指针上用 Astryx 协调底部面板;'popover' 与 'bottom-sheet' 在任何指针上强制使用对应 Astryx 界面。每个值都会打开选择器;仅文本字段的呈现只属于 TimeInput。需要 numberOfMonths、weekStartsOn 或可见 dateConstraints 行为时请使用非原生呈现。约束会在提交时执行,min/max 作为提示传给原生控件。hourFormat 格式化关闭状态的时间,而操作系统选择器遵循用户区域设置。",
+ "选择由哪些界面绘制日期和时间选择器。'adaptive-native'(默认)在精细指针上使用 Astryx 文本字段与弹出层、在粗指针上使用浏览器/操作系统控件,并按段回退:hasSeconds、非默认 timeIncrement 或 timeOptionInterval 会保留 Astryx 时间字段;'native' 始终使用两个原生控件且不回退;'adaptive-bottom-sheet' 在精细指针上用弹出层、在粗指针上用 Astryx 协调底部面板;'popover' 与 'bottom-sheet' 在任何指针上强制使用对应 Astryx 界面。每个值都会打开选择器;仅文本字段的呈现只属于 TimeInput。需要 numberOfMonths、weekStartsOn 或可见 dateConstraints 行为时请使用非原生呈现。约束会在提交时执行,min/max 作为提示传给原生控件。hourFormat 格式化关闭状态的时间,而操作系统选择器遵循用户区域设置。使用 gregory 或 iso8601 以外的历法时,'native' 与 'adaptive-native' 在精细指针上使用弹出层、在粗指针上使用底部面板,显式的 'native' 会在开发环境中发出警告。",
default: "'adaptive-native'",
},
{
name: 'nativePicker',
type: "'touch' | 'always' | 'never'",
description:
- "已弃用:请使用 presentation('touch'='adaptive-native'、'always'='native'、'never'='adaptive-bottom-sheet')。仍按已发布行为工作;同时设置时以 presentation 为准。",
+ "已弃用:请使用 presentation('touch'='adaptive-native'、'always'='native'、'never'='adaptive-bottom-sheet')。仍按已发布行为工作;同时设置时以 presentation 为准。使用 gregory 或 iso8601 以外的历法时,'touch' 与 'always' 在精细指针上使用弹出层、在粗指针上使用底部面板。",
default: "'touch'",
},
{
@@ -641,6 +667,11 @@ export const docsDense = {
description:
'Use min and max to restrict selectable datetimes to valid ranges.',
},
+ {
+ guidance: true,
+ description:
+ 'Set min and max on a Buddhist or Minguo calendar field, so a Gregorian year typed by mistake shows an error instead of a date centuries away.',
+ },
{
guidance: true,
description:
@@ -699,6 +730,8 @@ export const docsDense = {
'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',
+ calendar:
+ "calendar for typed + committed date text, the popover, and the sheet's Date panel (months, leap months, era years; an era-change year follows the shown month, e.g. 平成31 in Jan 2019, 令和元 in Jul) (default: provider's, else 'gregory'); values stay Gregorian ISO; years are the calendar's, so set min/max on buddhist/roc fields; non-Gregorian-aligned calendars need Temporal (native or app-loaded polyfill), else Gregorian; non-gregory/iso8601 never shows native controls: popovers fine / sheet coarse",
timePlaceholder:
'time-portion placeholder when empty; shown on touch closed time segment',
timeLabel:
@@ -711,9 +744,9 @@ export const docsDense = {
weekStartsOn:
'first day of week in Astryx calendars (0=Sunday, or name e.g. "mon"); ignored by native date controls',
presentation:
- "date+time surfaces: 'adaptive-native' (default) = Astryx popovers fine / browser/OS coarse w/ per-segment fallbacks (seconds/timeIncrement/timeOptionInterval); 'native' = browser/OS always, no fallback; 'adaptive-bottom-sheet' = popovers fine / coordinated sheet coarse; 'popover'/'bottom-sheet' force Astryx. every value opens pickers (no typed-only value; that is TimeInput's).",
+ "date+time surfaces: 'adaptive-native' (default) = Astryx popovers fine / browser/OS coarse w/ per-segment fallbacks (seconds/timeIncrement/timeOptionInterval); 'native' = browser/OS always, no fallback; 'adaptive-bottom-sheet' = popovers fine / coordinated sheet coarse; 'popover'/'bottom-sheet' force Astryx. every value opens pickers (no typed-only value; that is TimeInput's). non-gregory/iso8601 calendar: native + adaptive-native become popovers fine / sheet coarse; explicit 'native' warns in dev.",
nativePicker:
- "deprecated, use presentation: 'touch'='adaptive-native', 'always'='native', 'never'='adaptive-bottom-sheet'. still works as released; presentation wins if both set.",
+ "deprecated, use presentation: 'touch'='adaptive-native', 'always'='native', 'never'='adaptive-bottom-sheet'. still works as released, except that a calendar other than gregory or iso8601 never shows the native control; presentation wins if both set.",
containerXstyle:
'Field box (label+control+status); also containerClassName/containerStyle. no effect in InputGroup or horizontal-labels FormLayout',
controlXstyle:
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
index a379e1cc5a..aa1947ff7d 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
@@ -11,7 +11,7 @@
import {useState} from 'react';
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
-import {render, screen, fireEvent, waitFor} from '@testing-library/react';
+import {act, render, screen, fireEvent, waitFor} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import * as stylex from '@stylexjs/stylex';
import {colorVars} from '../theme/tokens.stylex';
@@ -242,8 +242,9 @@ describe('DateTimeInput', () => {
const onChange = vi.fn();
render(<DateTimeInput label="Meeting" onChange={onChange} />);
const dateInput = screen.getByRole('combobox');
- fireEvent.change(dateInput, {target: {value: '03/15/2026'}});
- onChange.mockClear();
+ // A two-digit year commits only on Enter or blur.
+ fireEvent.change(dateInput, {target: {value: '03/15/26'}});
+ expect(onChange).not.toHaveBeenCalled();
// The composing keydown (isComposing / legacy keyCode 229) that commits an
// IME candidate must not be read as "commit the typed date".
@@ -851,6 +852,259 @@ describe('DateTimeInput', () => {
});
});
+ describe('typed text while the field is disabled or busy', () => {
+ const locks = ['isLoading', 'isDisabled'] as const;
+ type Lock = (typeof locks)[number];
+ type Props = React.ComponentProps<typeof DateTimeInput>;
+
+ function renderField(value: string) {
+ const user = userEvent.setup();
+ const onChange = vi.fn();
+ const props = {
+ label: 'Starts',
+ value: value as ISODateTimeString,
+ onChange,
+ } satisfies Props;
+ const {rerender} = render(<DateTimeInput {...props} />);
+ const setProps = (lock?: Lock, value?: string) =>
+ rerender(
+ <DateTimeInput
+ {...props}
+ isLoading={lock === 'isLoading'}
+ isDisabled={lock === 'isDisabled'}
+ {...(value != null && {value: value as ISODateTimeString})}
+ />,
+ );
+ return {user, onChange, input: screen.getByRole('combobox'), setProps};
+ }
+
+ function expectNoRejection(input: HTMLElement) {
+ expect(input).not.toHaveAttribute('aria-invalid');
+ expect(screen.queryByText('Invalid date')).not.toBeInTheDocument();
+ }
+
+ it.each(locks)(
+ 'ignores Enter and blur while %s, then rejects the text once editable',
+ async lock => {
+ const {user, onChange, input, setProps} =
+ renderField('2026-03-15T09:00');
+ await user.clear(input);
+ await user.type(input, '3/15/2');
+
+ setProps(lock);
+ await user.keyboard('{Enter}');
+ await user.tab();
+ expect(input).toHaveValue('3/15/2');
+ expect(onChange).not.toHaveBeenCalled();
+ expectNoRejection(input);
+
+ setProps();
+ act(() => input.focus());
+ await user.tab();
+ expect(input).toHaveValue('3/15/2');
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expect(screen.getByText('Invalid date')).toBeInTheDocument();
+ },
+ );
+
+ it.each(locks)(
+ 'hides a shown rejection while %s and shows it again once editable',
+ async lock => {
+ const {user, input, setProps} = renderField('2026-03-15T09:00');
+ await user.clear(input);
+ await user.type(input, '3/15/2');
+ await user.tab();
+ expect(screen.getByText('Invalid date')).toBeInTheDocument();
+
+ setProps(lock);
+ expect(input).toHaveValue('3/15/2');
+ expectNoRejection(input);
+
+ setProps();
+ expect(input).toHaveAttribute('aria-invalid', 'true');
+ expect(screen.getByText('Invalid date')).toBeInTheDocument();
+ },
+ );
+
+ it.each(locks)(
+ 'commits a date typed before %s only once editable',
+ async lock => {
+ const {user, onChange, input, setProps} =
+ renderField('2026-01-12T09:00');
+ await user.clear(input);
+ // A two-digit year commits only on Enter or blur.
+ await user.type(input, '3/15/26');
+
+ setProps(lock);
+ await user.tab();
+ expect(input).toHaveValue('3/15/26');
+ expect(onChange).not.toHaveBeenCalled();
+
+ setProps();
+ act(() => input.focus());
+ await user.tab();
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('2026-03-15T09:00');
+ },
+ );
+
+ it.each(locks)(
+ 'replaces the text with a new value while %s',
+ async lock => {
+ const {user, onChange, input, setProps} =
+ renderField('2026-03-15T09:00');
+ await user.clear(input);
+ await user.type(input, '3/15/2');
+
+ setProps(lock);
+ setProps(lock, '2026-04-01T09:00');
+ expect(input).toHaveValue('April 1, 2026');
+
+ setProps(undefined, '2026-04-01T09:00');
+ act(() => input.focus());
+ await user.tab();
+ expect(input).toHaveValue('April 1, 2026');
+ expect(onChange).not.toHaveBeenCalled();
+ expectNoRejection(input);
+ },
+ );
+
+ it.each(locks)(
+ 'shows the old value once a %s change that did not take a typed date ends',
+ async lock => {
+ const {user, onChange, input, setProps} =
+ renderField('2026-01-12T09:00');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-15T09:00');
+
+ setProps(lock);
+ await user.tab();
+ expect(input).toHaveValue('3/15/2026');
+
+ setProps();
+ expect(input).toHaveValue('January 12, 2026');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+ expect(onChange).toHaveBeenCalledTimes(2);
+ },
+ );
+
+ it.each(
+ locks.flatMap(lock => [
+ [lock, 'blur'],
+ [lock, 'Enter'],
+ ]),
+ )(
+ 'keeps a reported date in the focused field when %s ends, until %s',
+ async (lock, commit) => {
+ const {user, onChange, input, setProps} =
+ renderField('2026-01-12T09:00');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2026-03-15T09:00');
+
+ setProps(lock);
+ setProps();
+ expect(input).toHaveFocus();
+ expect(input).toHaveValue('3/15/2026');
+
+ if (commit === 'blur') {
+ await user.tab();
+ } else {
+ await user.keyboard('{Enter}');
+ }
+ expect(input).toHaveValue('January 12, 2026');
+ expect(onChange).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ it.each(locks)(
+ 'shows the new value once a %s change that took a typed date ends',
+ async lock => {
+ const {user, input, setProps} = renderField('2026-01-12T09:00');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+
+ setProps(lock, '2026-03-15T09:00');
+ await user.tab();
+ expect(input).toHaveValue('3/15/2026');
+
+ setProps(undefined, '2026-03-15T09:00');
+ expect(input).toHaveValue('March 15, 2026');
+ },
+ );
+
+ it.each([
+ ['fails', false, 'January 12, 2026'],
+ ['succeeds', true, 'March 15, 2026'],
+ ])(
+ 'shows the resulting value after a changeAction save that %s',
+ async (_, takes, shown) => {
+ const user = userEvent.setup();
+ let settle = () => {};
+ function Field() {
+ const [value, setValue] = useState('2026-01-12T09:00');
+ const save = async (next: ISODateTimeString | undefined) =>
+ new Promise<void>(resolve => {
+ settle = () => {
+ if (takes && next) {
+ setValue(next);
+ }
+ resolve();
+ };
+ });
+ return (
+ <DateTimeInput
+ label="Starts"
+ value={value as ISODateTimeString}
+ onChange={() => {}}
+ changeAction={save}
+ />
+ );
+ }
+ render(<Field />);
+ const input = screen.getByRole('combobox');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+ expect(input).toHaveAttribute('aria-busy', 'true');
+ await user.tab();
+
+ await act(async () => settle());
+ expect(input).toHaveValue(shown);
+ },
+ );
+
+ it('keeps a reported date in the focused field when a changeAction save fails', async () => {
+ const user = userEvent.setup();
+ let fail = () => {};
+ function Field() {
+ const [value] = useState('2026-01-12T09:00');
+ const save = async () =>
+ new Promise<void>(resolve => {
+ fail = resolve;
+ });
+ return (
+ <DateTimeInput
+ label="Starts"
+ value={value as ISODateTimeString}
+ onChange={() => {}}
+ changeAction={save}
+ />
+ );
+ }
+ render(<Field />);
+ const input = screen.getByRole('combobox');
+ await user.clear(input);
+ await user.type(input, '3/15/2026');
+
+ await act(async () => fail());
+ expect(input).toHaveFocus();
+ expect(input).toHaveValue('3/15/2026');
+ });
+ });
+
describe('invalid typed input feedback (WCAG 3.3.1)', () => {
it('sets aria-invalid="true" on the date input when typed date is unparseable', () => {
render(<DateTimeInput label="Meeting" onChange={() => {}} />);
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsx
index b76d9d9723..be694498ef 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx
@@ -75,7 +75,6 @@ import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';
import {useInputStatusIcon} from '../hooks/useInputStatusIcon';
import {
type ISOTimeString,
- parseDateInput,
parseISOTime,
formatISOTime,
isTimeInRange,
@@ -86,12 +85,9 @@ import {
} from '../utils';
import {chainEventHandlers} from '../utils/chainEventHandlers';
import {joinAriaIDs} from '../utils/inputAria';
-import {
- plainDateFromISO,
- plainDateToISO,
- plainDateFormat,
- DATE_FORMAT_LONG,
-} from '../utils/plainDate';
+import type {CalendarSystem} from '../utils/calendarSystem';
+import {isRenderable} from '../utils/isRenderable';
+import {useTypedDateField} from '../DateInput/useTypedDate';
import {
useFieldInputStyling,
@@ -117,10 +113,10 @@ import {NativeDateSegment} from './NativeDateSegment';
import {NativeTimeSegment} from './NativeTimeSegment';
import {TouchDateTimeField} from './TouchDateTimeField';
import {
- effectivePickerPresentation,
resolvePickerPresentation,
type PickerPresentation,
} from '../utils/inputPresentation';
+import {useCalendarPresentation} from '../DateInput/useCalendarPresentation';
import {useDevWarning} from '../hooks/useDevWarning';
import {
registerEnglishFallback,
@@ -457,11 +453,27 @@ export interface DateTimeInputProps extends Omit<
hasClear?: boolean;
/**
- * Placeholder text shown in the date portion when no date is selected.
+ * Placeholder text shown in the date portion when no date is selected. A
+ * caller placeholder replaces the calendar format hint.
* @default "Select a date"
*/
placeholder?: string;
+ /**
+ * The calendar the date field reads and writes typed dates in, such as
+ * `'persian'`, `'hebrew'`, or `'buddhist'`. `value`, `onChange`, `min`, and
+ * `max` stay Gregorian ISO datetimes in every calendar. People type a date
+ * the way the locale writes it in this calendar, and the committed date
+ * text uses it. Years are years of this calendar, so set `min` and `max` to
+ * catch a year typed in the wrong calendar. Calendars other than `gregory`,
+ * `iso8601`, `buddhist`, `roc`, and `japanese` need `Temporal`, native or a
+ * polyfill the application loads; without it the field uses the Gregorian
+ * calendar.
+ *
+ * @default the InternationalizationProvider's calendar, else `'gregory'`
+ */
+ calendar?: CalendarSystem;
+
/**
* Placeholder text shown in the time portion when no time is selected.
* On touch, this appears in the closed time segment before a time is chosen.
@@ -534,6 +546,10 @@ export interface DateTimeInputProps extends Omit<
* JavaScript. `hourFormat` formats the closed value; the OS picker follows the
* user's locale.
*
+ * In a calendar other than `gregory` or `iso8601`, `'touch'` and `'always'`
+ * use Astryx's popovers on a fine pointer and the bottom sheet on a coarse
+ * pointer.
+ *
* @default 'touch'
* @deprecated Use `presentation` (`spec:AST-043` FR3):
* `'touch'` → `'adaptive-native'`, `'always'` → `'native'`,
@@ -550,13 +566,16 @@ export interface DateTimeInputProps extends Omit<
* - `'popover'`: Astryx's typed fields + popovers on every pointer
* - `'bottom-sheet'`: Astryx's bottom-sheet date/time wheels on every pointer
* - `'native'`: browser/OS date and time pickers on every pointer, with no
- * Astryx fallback (FR2)
+ * Astryx fallback (FR2), except in a calendar other than `gregory` or
+ * `iso8601`, where it is `'adaptive-bottom-sheet'` and warns in
+ * development
* - `'adaptive-bottom-sheet'`: popovers on a fine pointer, bottom sheet on
* a coarse pointer
* - `'adaptive-native'` (default): popovers on a fine pointer, browser/OS
* pickers on a coarse pointer, keeping the released per-segment Astryx
* fallbacks (seconds, non-default `timeIncrement`, `timeOptionInterval`)
- * where a native control cannot express the value (FR2)
+ * where a native control cannot express the value (FR2), and the bottom
+ * sheet in a calendar other than `gregory` or `iso8601`
*
* @default 'adaptive-native'
*/
@@ -635,6 +654,7 @@ function PointerDateTimeField({
timeOptionInterval,
hasClear = false,
placeholder: placeholderFromProps,
+ calendar,
timePlaceholder: timePlaceholderFromProps,
timeLabel,
size: sizeProp,
@@ -666,6 +686,7 @@ function PointerDateTimeField({
'aria-labelledby': ariaLabelledByProp,
onBlur: onBlurProp,
onClick: onClickProp,
+ onFocus: onFocusProp,
onKeyDown: onKeyDownProp,
...controlProps
} = rest;
@@ -705,12 +726,12 @@ function PointerDateTimeField({
const timeInputId = useId();
const descriptionID = useId();
const statusMessageID = useId();
+ const calendarDescriptionID = 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);
- const lastFiredDateRef = useRef<ISODateString | undefined>(undefined);
const [, startTransition] = useTransition();
const [optimisticValue, setOptimisticValue] = useOptimistic(value);
@@ -742,27 +763,6 @@ function PointerDateTimeField({
isEnabled: showsDisabledMessage,
});
- // DateTimeInput fixes its status presentation to the detached message box,
- // so the shared helper suppresses the on-field icon (the message box carries
- // its own leading glyph). Routed through the helper for consistency with the
- // rest of the bordered input family.
- const {statusIcon, describedBy: statusTooltipDescribedBy} =
- useInputStatusIcon({
- status,
- statusVariant: 'detached',
- });
-
- const ariaDescribedBy =
- [
- description ? descriptionID : null,
- status?.message ? statusMessageID : null,
- statusTooltipDescribedBy,
- showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
- ariaDescribedByProp,
- ]
- .filter(Boolean)
- .join(' ') || undefined;
-
// Split min/max and current value
const minParts = useMemo(() => splitDateTime(min), [min]);
const maxParts = useMemo(() => splitDateTime(max), [max]);
@@ -795,36 +795,6 @@ function PointerDateTimeField({
return valueParts.date === maxParts.date ? maxParts.time : undefined;
}, [maxParts.date, maxParts.time, valueParts.date]);
- // --- Date input state ---
- const [datePendingInput, setDatePendingInput] = useState<string | null>(null);
-
- const prevDateRef = useRef(valueParts.date);
- if (valueParts.date !== prevDateRef.current) {
- prevDateRef.current = valueParts.date;
- if (valueParts.date !== lastFiredDateRef.current) {
- lastFiredDateRef.current = undefined;
- if (datePendingInput !== null) {
- setDatePendingInput(null);
- }
- }
- }
-
- const dateDisplayValue =
- datePendingInput !== null
- ? datePendingInput
- : valueParts.date && /^\d{4}-\d{2}-\d{2}$/.test(valueParts.date)
- ? plainDateFormat(
- plainDateFromISO(valueParts.date),
- DATE_FORMAT_LONG,
- locale,
- )
- : '';
-
- const isDateInputValid =
- datePendingInput === null || !datePendingInput.trim()
- ? true
- : parseDateInput(datePendingInput, locale) !== null;
-
// --- Time input state ---
const [timePendingInput, setTimePendingInput] = useState<string | null>(null);
const [isTimeFocused, setIsTimeFocused] = useState(false);
@@ -1005,7 +975,6 @@ function PointerDateTimeField({
fireChange(combined);
}
if (source === 'calendar') {
- setDatePendingInput(null);
popover.hide();
}
},
@@ -1020,6 +989,71 @@ function PointerDateTimeField({
],
);
+ const handleTypedDateChange = useCallback(
+ (date: ISODateString) => handleDateChange(date, 'input'),
+ [handleDateChange],
+ );
+ const clearTypedDate = useCallback(() => {
+ if (value !== undefined) {
+ fireChange(undefined);
+ }
+ }, [value, fireChange]);
+ const navigateToTypedDate = useCallback((date: ISODateString) => {
+ calendarRef.current?.navigateTo(date);
+ }, []);
+ const {
+ typedDate,
+ displayValue: dateDisplayValue,
+ formatHint: dateFormatHint,
+ isPending: isDatePending,
+ isInvalid: isDateInvalid,
+ fieldStatus,
+ alertMessage: dateAlertMessage,
+ handleChange: handleTypedDateInput,
+ commit: commitDatePendingInput,
+ handleFocus: handleDateFocus,
+ handleBlur: handleDateBlur,
+ reset: resetTypedDate,
+ } = useTypedDateField({
+ source: 'DateTimeInput',
+ calendar,
+ format: 'date_long',
+ min: calendarMin,
+ max: calendarMax,
+ isDateDisabled,
+ value: splitDateTime(value).date,
+ shownValue: valueParts.date,
+ onChange: handleTypedDateChange,
+ onClear: clearTypedDate,
+ onTypedDate: navigateToTypedDate,
+ isDisabled: isEffectivelyDisabled,
+ status,
+ isStatusAnnounced: true,
+ hasPlaceholder: placeholderFromProps != null,
+ });
+
+ // The detached message box carries its own glyph, so the helper shows no
+ // on-field icon.
+ const {statusIcon, describedBy: statusTooltipDescribedBy} =
+ useInputStatusIcon({
+ status: fieldStatus,
+ statusVariant: 'detached',
+ });
+
+ const ariaDescribedBy =
+ [
+ description ? descriptionID : null,
+ !usesNativePicker && typedDate.calendarDescription != null
+ ? calendarDescriptionID
+ : null,
+ fieldStatus?.message ? statusMessageID : null,
+ statusTooltipDescribedBy,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
+ ariaDescribedByProp,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
const handleNativeDateChange = useCallback(
(newDate: ISODateString | undefined) => {
if (newDate === undefined) {
@@ -1057,70 +1091,11 @@ function PointerDateTimeField({
const handleDateInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
- // The input is never natively disabled (AST-085 FR1), so
- // guard value mutation explicitly (readOnly also blocks typing).
- if (isEffectivelyDisabled) {
- return;
- }
- const text = e.target.value;
- setDatePendingInput(text);
-
- const parsed = parseDateInput(text, locale);
- if (
- parsed &&
- plainDateToISO(parsed) !== valueParts.date &&
- !isDateDisabled(parsed)
- ) {
- const parsedISO = plainDateToISO(parsed);
- lastFiredDateRef.current = parsedISO;
- handleDateChange(parsedISO, 'input');
- calendarRef.current?.navigateTo(parsedISO);
- }
+ handleTypedDateInput(e.target.value);
},
- [
- valueParts.date,
- isDateDisabled,
- handleDateChange,
- isEffectivelyDisabled,
- locale,
- ],
+ [handleTypedDateInput],
);
- const commitDatePendingInput = useCallback(() => {
- if (datePendingInput === null) {
- return;
- }
-
- if (!datePendingInput.trim()) {
- if (value !== undefined) {
- fireChange(undefined);
- }
- setDatePendingInput(null);
- return;
- }
-
- const parsed = parseDateInput(datePendingInput, locale);
- if (parsed && !isDateDisabled(parsed)) {
- const parsedISO = plainDateToISO(parsed);
- if (parsedISO !== valueParts.date) {
- handleDateChange(parsedISO, 'input');
- }
- }
- setDatePendingInput(null);
- }, [
- datePendingInput,
- value,
- valueParts.date,
- fireChange,
- isDateDisabled,
- handleDateChange,
- locale,
- ]);
-
- const handleDateBlur = useCallback(() => {
- commitDatePendingInput();
- }, [commitDatePendingInput]);
-
const handleDateKeyDown = useCallback(
(e: React.KeyboardEvent) => {
// Guard the composing keydown (fires before compositionend): an IME uses
@@ -1145,7 +1120,7 @@ function PointerDateTimeField({
}
} else if (
e.key === 'Enter' &&
- (datePendingInput !== null || isEffectivelyDisabled)
+ (isDatePending || isEffectivelyDisabled)
) {
// Typed text holds Enter back, or a form would submit the value from
// before the commit. A disabled or busy field must not submit its
@@ -1154,7 +1129,7 @@ function PointerDateTimeField({
commitDatePendingInput();
}
},
- [popover, commitDatePendingInput, isEffectivelyDisabled, datePendingInput],
+ [popover, commitDatePendingInput, isEffectivelyDisabled, isDatePending],
);
// --- Time-option popover (#2727) ---
@@ -1676,11 +1651,11 @@ function PointerDateTimeField({
isRequired={isRequired}
isDisabled={isDisabled}
status={
- status
+ fieldStatus
? {
- type: status.type,
- message: status.message,
- messageID: status.message ? statusMessageID : undefined,
+ type: fieldStatus.type,
+ message: fieldStatus.message,
+ messageID: fieldStatus.message ? statusMessageID : undefined,
}
: undefined
}
@@ -1692,7 +1667,7 @@ function PointerDateTimeField({
{...mergeProps(
themeProps('date-time-input', {
size,
- status: status?.type ?? null,
+ status: fieldStatus?.type ?? null,
disabled: isDisabled ? 'disabled' : null,
}),
stylex.props(
@@ -1709,7 +1684,7 @@ function PointerDateTimeField({
{...mergeProps(
themeProps('date-time-input-date-segment', {
size,
- status: status?.type ?? null,
+ status: fieldStatus?.type ?? null,
}),
stylex.props(
inputWrapperStyles.base,
@@ -1717,11 +1692,11 @@ function PointerDateTimeField({
styles.dateWrapper,
isEffectivelyDisabled && inputWrapperStyles.disabled,
isEffectivelyDisabled && inputDisabledFocusStyles.withinRing,
- status && inputStatusBorderStyles[status.type],
- status &&
+ fieldStatus && inputStatusBorderStyles[fieldStatus.type],
+ fieldStatus &&
!isEffectivelyDisabled &&
- inputStatusHoverShadowStyles[status.type],
- status && inputStatusFocusWithinStyles[status.type],
+ inputStatusHoverShadowStyles[fieldStatus.type],
+ fieldStatus && inputStatusFocusWithinStyles[fieldStatus.type],
),
)}>
{usesNativePicker ? (
@@ -1744,6 +1719,7 @@ function PointerDateTimeField({
...controlProps,
'aria-labelledby': controlLabelledBy,
onBlur: onBlurProp,
+ onFocus: onFocusProp,
onClick: isEffectivelyDisabled ? undefined : onClickProp,
onKeyDown: onKeyDownProp,
}}
@@ -1794,6 +1770,7 @@ function PointerDateTimeField({
value={dateDisplayValue}
onChange={handleDateInputChange}
onBlur={chainEventHandlers(handleDateBlur, onBlurProp)}
+ onFocus={chainEventHandlers(handleDateFocus, onFocusProp)}
onClick={
isEffectivelyDisabled
? undefined
@@ -1801,13 +1778,13 @@ function PointerDateTimeField({
}
onKeyDown={chainEventHandlers(handleDateKeyDown, onKeyDownProp)}
aria-labelledby={controlLabelledBy}
- placeholder={placeholder}
+ placeholder={dateFormatHint ?? placeholder}
aria-disabled={isEffectivelyDisabled ? 'true' : undefined}
readOnly={isEffectivelyDisabled || undefined}
aria-describedby={ariaDescribedBy}
aria-required={isEffectivelyRequired ? 'true' : undefined}
aria-invalid={
- status?.type === 'error' || !isDateInputValid
+ fieldStatus?.type === 'error' || isDateInvalid
? 'true'
: undefined
}
@@ -1820,18 +1797,21 @@ function PointerDateTimeField({
{...stylex.props(
styles.input,
isEffectivelyDisabled && styles.inputDisabled,
- !isDateInputValid && styles.inputInvalid,
+ isDateInvalid && styles.inputInvalid,
)}
/>
{/*
- Live region announcing invalid typed date input to assistive
- technology. The value silently reverts on blur, so without this a
- screen-reader user would get no feedback that their entry was
- rejected (WCAG 3.3.1).
+ Announces a typed date rejection that the field status does not
+ announce. The field status announces the rest.
*/}
<VisuallyHidden as="div" role="alert" aria-live="assertive">
- {!isDateInputValid ? t('@astryx.dateInput.invalidDate') : ''}
+ {dateAlertMessage}
</VisuallyHidden>
+ {isRenderable(typedDate.calendarDescription) && (
+ <VisuallyHidden id={calendarDescriptionID}>
+ {typedDate.calendarDescription}
+ </VisuallyHidden>
+ )}
</>
)}
{hasClear && value !== undefined && !isEffectivelyDisabled && (
@@ -1976,12 +1956,14 @@ function PointerDateTimeField({
// opens on the current value.
!popover.isOpen ? null : (
<Calendar
- // The field text is Gregorian, so the popover calendar is too.
- calendar="gregory"
handleRef={calendarRef}
+ calendar={typedDate.calendar}
mode="single"
value={valueParts.date ?? null}
- onChange={(d: ISODateString) => handleDateChange(d, 'calendar')}
+ onChange={(d: ISODateString) => {
+ handleDateChange(d, 'calendar');
+ resetTypedDate();
+ }}
min={calendarMin}
max={calendarMax}
dateConstraints={dateConstraints}
@@ -2067,7 +2049,9 @@ export function DateTimeInput(props: DateTimeInputProps) {
'`nativePicker` is deprecated; use `presentation` instead (`touch` → `adaptive-native`, `always` → `native`, `never` → `adaptive-bottom-sheet`). `presentation` wins when both are set.',
props.nativePicker !== undefined,
);
- const effective = effectivePickerPresentation(
+ const {calendar, presentation: effective} = useCalendarPresentation(
+ 'DateTimeInput',
+ props.calendar,
props.presentation,
props.nativePicker,
);
@@ -2081,6 +2065,7 @@ export function DateTimeInput(props: DateTimeInputProps) {
// field's resting text, preset times, and the sheet wheels agree.
const rest = {
...surfaceProps,
+ calendar,
hourFormat: resolveHourFormat(locale, props.hourFormat),
};
if (effective === 'native') {
@@ -2100,7 +2085,8 @@ export function DateTimeInput(props: DateTimeInputProps) {
// Only `adaptive-native` on a coarse pointer resolves here (FR2).
return <PointerDateTimeField {...rest} nativeMode="adaptive" />;
case 'sheet':
- return <TouchDateTimeField {...rest} />;
+ // Month indexes depend on the calendar. A new calendar remounts the sheet.
+ return <TouchDateTimeField key={calendar} {...rest} />;
case 'desktop':
return <PointerDateTimeField {...rest} />;
}
diff --git a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx
index 9005f2f31f..db8afac811 100644
--- a/packages/core/src/DateTimeInput/TouchDateTimeField.tsx
+++ b/packages/core/src/DateTimeInput/TouchDateTimeField.tsx
@@ -4,7 +4,7 @@
/**
* @file TouchDateTimeField.tsx
- * @input Uses React, Field, BottomSheet, SegmentedControl, DateInput month picker primitives, Wheel and the pickers' touch layer (TimeWheels), the touch presentation, StyleX intrinsic flex layout
+ * @input Uses React, Field, BottomSheet, SegmentedControl, DateInput month picker primitives, the resolved calendar, Wheel and the pickers' touch layer (TimeWheels), the touch presentation, StyleX intrinsic flex layout
* @output Exports TouchDateTimeField — the coarse-pointer surface behind DateTimeInput
* @position Internal component; consumed by DateTimeInput.tsx
*
@@ -83,13 +83,16 @@ import {
import {chainEventHandlers} from '../utils/chainEventHandlers';
import {joinAriaIDs} from '../utils/inputAria';
import {
- DATE_FORMAT_LONG,
- plainDateFormat,
plainDateFromISO,
plainDateToday,
type PlainDate,
} from '../utils/plainDate';
-import {plainDateFormatStandaloneMonthYear} from '../utils/plainDate';
+import {
+ calendarDayOfMonth,
+ formatCalendarMonthLabel,
+} from '../utils/calendarSystem';
+import {formatCalendarDateText} from '../utils/calendarDateParser';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
import {
MonthScroller,
type MonthScrollerHandle,
@@ -114,8 +117,7 @@ import {
import {
DEFAULT_MONTH_REACH,
clampIndex,
- fromMonthIndex,
- monthIndexOf,
+ createMonthModel,
} from '../DateInput/monthGeometry';
import type {DateTimeInputProps, ISODateTimeString} from './DateTimeInput';
import {
@@ -448,6 +450,7 @@ export function TouchDateTimeField({
// Desktop-only: the touch Date panel shows one swipe-paged month at a time.
numberOfMonths: _numberOfMonths,
weekStartsOn: weekStartsOnProp = 0,
+ calendar: calendarProp,
width,
containerXstyle,
containerClassName,
@@ -578,6 +581,8 @@ export function TouchDateTimeField({
[timeForWheels],
);
const weekStartsOn = normalizeDayOfWeek(weekStartsOnProp);
+ const calendar = useCalendarSystem(calendarProp, 'DateTimeInput');
+ const monthModel = useMemo(() => createMonthModel(calendar), [calendar]);
// The draft follows the controlled time, and an external clear resets it.
// Adjusted during render when the value changes, so no commit paints the
@@ -599,16 +604,18 @@ export function TouchDateTimeField({
}
}
+ // Indexes belong to the calendar, so DateTimeInput remounts this surface
+ // when the calendar changes.
const [anchorMonthIndex] = useState(() =>
- monthIndexOf(selectedDate ?? plainDateToday()),
+ monthModel.indexOf(selectedDate ?? plainDateToday()),
);
const minMonthIndex =
calendarMin != null
- ? monthIndexOf(plainDateFromISO(calendarMin))
+ ? monthModel.indexOf(plainDateFromISO(calendarMin))
: anchorMonthIndex - DEFAULT_MONTH_REACH;
const maxMonthIndex =
calendarMax != null
- ? monthIndexOf(plainDateFromISO(calendarMax))
+ ? monthModel.indexOf(plainDateFromISO(calendarMax))
: anchorMonthIndex + DEFAULT_MONTH_REACH;
const [monthIndex, setMonthIndex] = useState(() =>
clampIndex(anchorMonthIndex, minMonthIndex, maxMonthIndex),
@@ -626,7 +633,6 @@ export function TouchDateTimeField({
if (!Object.is(clampedMonthIndex, monthIndex)) {
setMonthIndex(clampedMonthIndex);
}
- const {year, month} = fromMonthIndex(monthIndex);
const canStepBack = monthIndex > minMonthIndex;
const canStepForward = monthIndex < maxMonthIndex;
@@ -634,17 +640,23 @@ export function TouchDateTimeField({
() => getWeekdayHeaders(locale, weekStartsOn),
[locale, weekStartsOn],
);
- const monthYearLabel = plainDateFormatStandaloneMonthYear(
- {year, month, day: 1},
+ // The day the picker keeps: the selected date's day of its month. A month
+ // with an era change takes its heading era from this day.
+ const keptDay =
+ selectedDate == null ? 1 : calendarDayOfMonth(calendar, selectedDate);
+ const monthYearLabel = formatCalendarMonthLabel(
+ calendar,
+ monthModel.monthAt(monthIndex),
locale,
+ keptDay,
);
const dateDisplayValue = useMemo(() => {
if (selectedDate == null) {
return '';
}
- return plainDateFormat(selectedDate, DATE_FORMAT_LONG, locale);
- }, [selectedDate, locale]);
+ return formatCalendarDateText(selectedDate, 'date_long', locale, calendar);
+ }, [calendar, selectedDate, locale]);
const timeDisplayValue = useMemo(() => {
const displayTime = normalizedValueTime ?? draftTime;
@@ -753,13 +765,13 @@ export function TouchDateTimeField({
const handleResetInSheet = useCallback(() => {
fireChange(undefined);
setDraftTime(undefined);
- const currentMonth = monthIndexOf(today);
+ const currentMonth = monthModel.indexOf(today);
if (currentMonth < minMonthIndex || currentMonth > maxMonthIndex) {
return;
}
setMonthIndex(currentMonth);
scrollerHandleRef.current?.scrollToMonth(currentMonth, 'smooth');
- }, [fireChange, today, minMonthIndex, maxMonthIndex]);
+ }, [fireChange, monthModel, today, minMonthIndex, maxMonthIndex]);
const handleDateSelect = useCallback(
(nextDate: ISODateString) => {
@@ -1041,6 +1053,7 @@ export function TouchDateTimeField({
<MonthScroller
key={`${minMonthIndex}:${maxMonthIndex}`}
handleRef={scrollerHandleRef}
+ monthModel={monthModel}
minMonthIndex={minMonthIndex}
maxMonthIndex={maxMonthIndex}
initialMonthIndex={monthIndex}
@@ -1086,7 +1099,9 @@ export function TouchDateTimeField({
{...stylex.props(styles.touchWheelSpacer)}
/>
<MonthYearWheels
+ monthModel={monthModel}
monthIndex={monthIndex}
+ keptDay={keptDay}
minMonthIndex={minMonthIndex}
maxMonthIndex={maxMonthIndex}
onChange={next => {
diff --git a/packages/core/src/PowerSearch/PowerSearch.doc.mjs b/packages/core/src/PowerSearch/PowerSearch.doc.mjs
index e95d631824..831944a92f 100644
--- a/packages/core/src/PowerSearch/PowerSearch.doc.mjs
+++ b/packages/core/src/PowerSearch/PowerSearch.doc.mjs
@@ -142,7 +142,7 @@ export const docs = {
name: 'timezoneID',
type: 'string',
description:
- 'IANA zone a date-only date_absolute value, and each absolute part of a date_range, is read and written in: the day shows, edits and stores (as that midnight) in it; unset, a day is its UTC day. A date_absolute with isDateOnly: false shows and edits its date and time in it; unset, in the viewer\'s zone. E.g. "America/New_York". Date values are written in the InternationalizationProvider calendar, such as calendar="persian"; filter values stay Unix seconds. The value editor, a DateInput or DateRangeInput, shows the calendar that input resolves, which is Gregorian.',
+ 'IANA zone a date-only date_absolute value, and each absolute part of a date_range, is read and written in: the day shows, edits and stores (as that midnight) in it; unset, a day is its UTC day. A date_absolute with isDateOnly: false shows and edits its date and time in it; unset, in the viewer\'s zone. E.g. "America/New_York". Date values are written in the InternationalizationProvider calendar, such as calendar="persian"; filter values stay Unix seconds.',
},
{
name: 'handleRef',
@@ -450,7 +450,7 @@ export const docsZh = {
name: 'timezoneID',
type: 'string',
description:
- '仅日期的 date_absolute 值及 date_range 的每个绝对端点读写所用的 IANA 时区:该日在此时区显示、编辑并以其午夜存储;未设置时为 UTC 日。isDateOnly: false 的 date_absolute 值在此时区显示并编辑其日期和时间;未设置时为查看者所在时区。例如 "America/New_York"。日期值使用 InternationalizationProvider 的历法(如 calendar="persian")显示;筛选值仍为 Unix 秒数。值编辑器(DateInput 或 DateRangeInput)显示该输入框解析的历法,即公历。',
+ '仅日期的 date_absolute 值及 date_range 的每个绝对端点读写所用的 IANA 时区:该日在此时区显示、编辑并以其午夜存储;未设置时为 UTC 日。isDateOnly: false 的 date_absolute 值在此时区显示并编辑其日期和时间;未设置时为查看者所在时区。例如 "America/New_York"。日期值使用 InternationalizationProvider 的历法(如 calendar="persian")显示;筛选值仍为 Unix 秒数。',
},
{
name: 'handleRef',
@@ -572,7 +572,7 @@ export const docsDense = {
menuWidth: 'Main field/search menu width in pixels.',
popoverSaveButtonLabel: 'Label for save button in edit popover.',
timezoneID:
- 'IANA zone a date-only value reads and writes in; unset, its UTC day. Dates show in the provider calendar; their editor shows Gregorian dates.',
+ 'IANA zone a date-only value reads and writes in; unset, its UTC day. Dates show in the provider calendar.',
handleRef:
'Imperative handle w/ focusTypeahead() + blurTypeahead() methods.',
endContent:
diff --git a/packages/core/src/i18n/InternationalizationProvider.doc.mjs b/packages/core/src/i18n/InternationalizationProvider.doc.mjs
index bf7dea2f6a..959cc5b460 100644
--- a/packages/core/src/i18n/InternationalizationProvider.doc.mjs
+++ b/packages/core/src/i18n/InternationalizationProvider.doc.mjs
@@ -53,7 +53,7 @@ export const docs = {
{
guidance: true,
description:
- 'Set `calendar` to show `Calendar` in another calendar system and write Timestamp, PowerSearch, and Schedule dates in it; `DateInput`, `DateRangeInput`, and `DateTimeInput` show Gregorian dates. A locale never selects the calendar: `fa-IR` shows Gregorian dates until you set `calendar="persian"`, and a `-u-ca-` keyword in `locale`, as in `th-TH-u-ca-buddhist`, keeps Gregorian dates too. Date values stay Gregorian ISO strings.',
+ 'Set `calendar` to show `Calendar`, `DateInput`, `DateRangeInput`, and `DateTimeInput` in another calendar system and write Timestamp, PowerSearch, and Schedule dates in it. A locale never selects the calendar: `fa-IR` shows Gregorian dates until you set `calendar="persian"`, and a `-u-ca-` keyword in `locale`, as in `th-TH-u-ca-buddhist`, keeps Gregorian dates too. Date values stay Gregorian ISO strings.',
},
{
guidance: false,
@@ -96,7 +96,7 @@ export const docs = {
type: "'gregory' | 'iso8601' | 'buddhist' | 'roc' | 'japanese' | 'persian' | 'indian' | 'hebrew' | 'chinese' | 'dangi' | 'coptic' | 'ethiopic' | 'ethioaa' | 'islamic-civil' | 'islamic-tbla' | 'islamic-umalqura'",
required: false,
description:
- "Calendar system of the subtree, such as 'persian', 'hebrew', or 'buddhist'. `Calendar` shows it, and Timestamp, PowerSearch, and Lab's Schedule write their dates in it. `DateInput`, `DateRangeInput`, and `DateTimeInput` show Gregorian dates. When omitted, the calendar is Gregorian: a locale never selects it, neither by its default calendar nor by a `-u-ca-` keyword. A component's own `calendar` prop takes precedence. Values stay Gregorian ISO dates. Calendars other than gregory, iso8601, buddhist, roc, and japanese need `Temporal`; the context keeps the requested calendar, and where the runtime lacks `Temporal`, these components show Gregorian dates and warn in development. Load a polyfill such as `temporal-polyfill/full/global` on the server and in the browser.",
+ "Calendar system of the subtree, such as 'persian', 'hebrew', or 'buddhist'. `Calendar`, `DateInput`, `DateRangeInput`, and `DateTimeInput` show it, and Timestamp, PowerSearch, and Lab's Schedule write their dates in it. When omitted, the calendar is Gregorian: a locale never selects it, neither by its default calendar nor by a `-u-ca-` keyword. A component's own `calendar` prop takes precedence. Values stay Gregorian ISO dates. Calendars other than gregory, iso8601, buddhist, roc, and japanese need `Temporal`; the context keeps the requested calendar, and where the runtime lacks `Temporal`, these components show Gregorian dates and warn in development. Load a polyfill such as `temporal-polyfill/full/global` on the server and in the browser.",
},
{
name: 'children',
@@ -217,6 +217,6 @@ export const docsDense = {
overrides:
'sparse per-locale key overrides applied on top of shipped defaults',
calendar:
- 'calendar system for Calendar, Timestamp, PowerSearch, and Schedule dates; date inputs stay Gregorian (default: gregory; a -u-ca- keyword in locale does not select it); values stay Gregorian ISO; non-Gregorian-aligned calendars need Temporal',
+ 'calendar system for Calendar, DateInput, DateRangeInput, DateTimeInput, Timestamp, PowerSearch, and Schedule dates (default: gregory; a -u-ca- keyword in locale does not select it); values stay Gregorian ISO; non-Gregorian-aligned calendars need Temporal',
},
};
diff --git a/packages/core/src/i18n/InternationalizationProvider.tsx b/packages/core/src/i18n/InternationalizationProvider.tsx
index 543cca75eb..dbacf36fb7 100644
--- a/packages/core/src/i18n/InternationalizationProvider.tsx
+++ b/packages/core/src/i18n/InternationalizationProvider.tsx
@@ -107,7 +107,8 @@ export interface InternationalizationProviderProps {
/**
* The calendar system of this subtree, such as `'persian'` or `'hebrew'`.
* `Calendar` shows it, and Timestamp, PowerSearch, and Lab's Schedule write
- * their dates in it. The date inputs show Gregorian dates. Values stay
+ * their dates in it. `DateInput`, `DateRangeInput`, and `DateTimeInput`
+ * show it too. Values stay
* Gregorian ISO dates. When omitted, the calendar is Gregorian: a locale
* never selects it, neither by its default calendar nor by a `-u-ca-`
* keyword. A component's own `calendar` prop takes precedence. Calendars
diff --git a/packages/core/src/utils/calendarDateParser.ts b/packages/core/src/utils/calendarDateParser.ts
index 0001288fd1..1da16287e9 100644
--- a/packages/core/src/utils/calendarDateParser.ts
+++ b/packages/core/src/utils/calendarDateParser.ts
@@ -5,7 +5,7 @@
* @input Date text, locale, calendar; Intl, calendarSystem, unicodeDigits
* @output Cached per-locale lexicons, a typed-date parser with distinct rejection
* kinds, committed display text, the format hint, and calendar display names
- * @position Core utility; reads and writes dates typed in a calendar system
+ * @position Core utility; used by DateInput and DateTimeInput through useTypedDate
*
* SYNC: When modified, update:
* - /packages/core/src/utils/calendarDateParser.test.ts
diff --git a/packages/core/src/utils/calendarSystem.test.ts b/packages/core/src/utils/calendarSystem.test.ts
index 1f0a6b4c43..e7ec5a3ab2 100644
--- a/packages/core/src/utils/calendarSystem.test.ts
+++ b/packages/core/src/utils/calendarSystem.test.ts
@@ -17,6 +17,8 @@ import {
formatCalendarInstant,
formatCalendarInstantRange,
formatCalendarMonthLabel,
+ formatCalendarYearLabel,
+ calendarYearSpansEras,
isCalendarSystemAvailable,
isGregorianAligned,
isInCalendarMonth,
@@ -452,3 +454,115 @@ describe('dates from calendar fields', () => {
expect(calendarMonthsInYear('gregory', iso('2025-03-01'))).toBe(12);
});
});
+
+describe('formatCalendarYearLabel', () => {
+ it.each([
+ [2019, 1, 1, '平成31'],
+ [2019, 4, 30, '平成31'],
+ [2019, 5, 1, '令和元'],
+ [2019, 7, 1, '令和元'],
+ [1989, 1, 22, '平成元'],
+ [1989, 1, 3, '昭和64'],
+ [1989, 7, 1, '平成元'],
+ [1926, 12, 31, '昭和元'],
+ [1912, 7, 1, '明治45'],
+ ])(
+ 'labels Japanese year %i with month %i and day %i as %s',
+ (year, month, day, label) => {
+ expect(
+ formatCalendarYearLabel('japanese', year, 'ja-JP', {month, day}),
+ ).toBe(label);
+ },
+ );
+
+ it('clamps the day to the month', () => {
+ expect(
+ formatCalendarYearLabel('japanese', 1926, 'ja-JP', {month: 12, day: 99}),
+ ).toBe('昭和元');
+ });
+
+ it('keeps one label for a year without an era change', () => {
+ expect(
+ formatCalendarYearLabel('japanese', 2020, 'ja-JP', {month: 1, day: 1}),
+ ).toBe('令和2');
+ expect(formatCalendarYearLabel('japanese', 2020, 'ja-JP')).toBe('令和2');
+ expect(formatCalendarYearLabel('persian', 1405, 'en')).toBe('1405 AP');
+ expect(formatCalendarYearLabel('roc', 1912, 'zh-TW')).toBe('民國1');
+ expect(formatCalendarYearLabel('buddhist', 2026, 'th-TH')).toBe(
+ 'พ.ศ. 2569',
+ );
+ expect(formatCalendarYearLabel('chinese', 2027, 'zh')).toBe('2027');
+ expect(formatCalendarYearLabel('gregory', 2026, 'en')).toBe('2026');
+ });
+
+ it('writes the era year in the locale order', () => {
+ expect(
+ formatCalendarYearLabel('japanese', 2019, 'en', {month: 1, day: 1}),
+ ).toBe('31 Heisei');
+ });
+
+ it('finds the years that span an era change from the calendar data', () => {
+ const spans = [1868, 1912, 1926, 1989, 2019, 2020].filter(year =>
+ calendarYearSpansEras('japanese', year, 'ja-JP'),
+ );
+ expect(spans).toEqual([1868, 1912, 1926, 1989, 2019]);
+ expect(calendarYearSpansEras('chinese', 2027, 'zh')).toBe(false);
+ expect(calendarYearSpansEras('gregory', 2019, 'en')).toBe(false);
+ });
+});
+
+describe('formatCalendarMonthLabel with a kept day', () => {
+ const month = (isoDate: string) =>
+ calendarMonthOf('japanese', iso(isoDate as ISODateString));
+
+ it.each([
+ ['1989-01-01', 3, '昭和64年1月'],
+ ['1989-01-01', 22, '平成元年1月'],
+ ['1926-12-01', 26, '昭和元年12月'],
+ ['1926-12-01', 24, '大正15年12月'],
+ ['1912-07-01', 30, '大正元年7月'],
+ ['1868-10-01', 23, '明治元年10月'],
+ ])('names the era of day %s + %i as %s', (start, day, label) => {
+ expect(
+ formatCalendarMonthLabel('japanese', month(start), 'ja-JP', day),
+ ).toBe(label);
+ });
+
+ it('clamps the day to the month', () => {
+ expect(
+ formatCalendarMonthLabel('japanese', month('1926-12-01'), 'ja-JP', 99),
+ ).toBe('昭和元年12月');
+ });
+
+ it('keeps the middle-of-month label for a month without an era change', () => {
+ expect(
+ formatCalendarMonthLabel('japanese', month('2019-01-01'), 'ja-JP', 22),
+ ).toBe('平成31年1月');
+ expect(
+ formatCalendarMonthLabel('japanese', month('2019-05-01'), 'ja-JP', 1),
+ ).toBe('令和元年5月');
+ expect(
+ formatCalendarMonthLabel(
+ 'persian',
+ calendarMonthOf('persian', iso('2026-11-02')),
+ 'en',
+ 1,
+ ),
+ ).toBe(
+ formatCalendarMonthLabel(
+ 'persian',
+ calendarMonthOf('persian', iso('2026-11-02')),
+ 'en',
+ ),
+ );
+ expect(
+ formatCalendarMonthLabel('gregory', month('1989-01-01'), 'en', 3),
+ ).toBe('January 1989');
+ });
+
+ it('keeps the middle-of-month label without a day', () => {
+ expect(
+ formatCalendarMonthLabel('japanese', month('1989-01-01'), 'ja-JP'),
+ ).toBe('平成元年1月');
+ });
+});
diff --git a/packages/core/src/utils/calendarSystem.ts b/packages/core/src/utils/calendarSystem.ts
index 4ef39b86ed..5c2a2775de 100644
--- a/packages/core/src/utils/calendarSystem.ts
+++ b/packages/core/src/utils/calendarSystem.ts
@@ -7,13 +7,14 @@
* month numbers, month and year steps, dates from calendar fields,
* availability of each calendar, and calendar labels and digits
* @position Shared date utility; read by the i18n calendar resolution, by
- * Calendar, and by its public hooks. Values stay Gregorian PlainDates. Temporal owns the arithmetic of
+ * the date components, and by Calendar's public hooks. Values stay Gregorian PlainDates. Temporal owns the arithmetic of
* every calendar whose months are not Gregorian.
*/
import type {Locale} from '../i18n/types';
import type {PlainDate} from './dateTypes';
import {
+ DATE_FORMAT_MONTH_ONLY,
dateTimeFormatAtCall,
dateTimeFormatFor,
plainDateAddDays,
@@ -82,6 +83,14 @@ const GREGORIAN_ALIGNED: ReadonlySet<CalendarSystem> = new Set([
'japanese',
]);
+/**
+ * Whether `<input type="date">` can show the calendar. The native control is
+ * Gregorian by specification, so only `gregory` and `iso8601` qualify.
+ */
+export function isGregorianCalendar(calendar: CalendarSystem): boolean {
+ return calendar === 'gregory' || calendar === 'iso8601';
+}
+
/** Whether the calendar's months and days are the Gregorian ones. */
export function isGregorianAligned(calendar: CalendarSystem): boolean {
return GREGORIAN_ALIGNED.has(calendar);
@@ -101,6 +110,10 @@ interface TemporalPlainDate {
readonly monthsInYear: number;
with(fields: {year?: number; month?: number; day: number}): TemporalPlainDate;
add(duration: {months?: number; years?: number}): TemporalPlainDate;
+ until(
+ other: TemporalPlainDate,
+ options: {largestUnit: 'months'},
+ ): {readonly months: number};
withCalendar(calendar: 'iso8601'): TemporalPlainDate;
}
@@ -340,20 +353,44 @@ export function calendarMonthLabelDay(month: CalendarMonth): PlainDate {
/**
* The stand-alone month and year label of a calendar month, such as
- * "Aban 1405 AP", named by `calendarMonthLabelDay`.
+ * "Aban 1405 AP", named by `calendarMonthLabelDay`. When `day` is given and the
+ * month spans an era change, it formats that day instead, clamped to the
+ * month, so January 1989 reads 昭和64年1月 on the 3rd and 平成元年1月 on the
+ * 22nd.
*/
export function formatCalendarMonthLabel(
calendar: CalendarSystem,
month: CalendarMonth,
locale: Locale,
+ day?: number,
): string {
+ const labelDay =
+ day != null && calendarMonthSpansEras(calendar, month, locale)
+ ? plainDateAddDays(
+ month.start,
+ Math.min(Math.max(day, 1), month.length) - 1,
+ )
+ : calendarMonthLabelDay(month);
return plainDateFormatStandaloneMonthYear(
- calendarMonthLabelDay(month),
+ labelDay,
locale,
labelCalendar(calendar),
);
}
+/** Whether the first and last days of a calendar month fall in different eras. */
+function calendarMonthSpansEras(
+ calendar: CalendarSystem,
+ month: CalendarMonth,
+ locale: Locale,
+): boolean {
+ return (
+ !isGregorianCalendar(calendar) &&
+ eraYearAt(calendar, month.start, locale).era !==
+ eraYearAt(calendar, month.end, locale).era
+ );
+}
+
// Intl has no month names for `iso8601`. Labels use `gregory`, which has the
// same months and days.
function labelCalendar(calendar: CalendarSystem): CalendarSystem {
@@ -621,3 +658,175 @@ export function calendarMonthsInYear(
? 12
: inCalendar(calendar, pd).monthsInYear;
}
+
+/**
+ * The number of calendar months from the month `from` to the month `to`:
+ * positive when `to` is later.
+ */
+export function calendarMonthsBetween(
+ calendar: CalendarSystem,
+ from: CalendarMonth,
+ to: CalendarMonth,
+): number {
+ if (isGregorianAligned(calendar)) {
+ return (
+ (to.start.year - from.start.year) * 12 +
+ (to.start.month - from.start.month)
+ );
+ }
+ return inCalendar(calendar, from.start).until(
+ inCalendar(calendar, to.start),
+ {largestUnit: 'months'},
+ ).months;
+}
+
+/**
+ * The calendar month at a position in a year of the calendar. A
+ * Gregorian-aligned calendar counts Gregorian years here; the others count
+ * years as {@link calendarYearMonthOf} does.
+ */
+export function calendarMonthOfYear(
+ calendar: CalendarSystem,
+ year: number,
+ month: number,
+): CalendarMonth {
+ return isGregorianAligned(calendar)
+ ? gregorianMonth(year, month)
+ : calendarMonthFromYearMonth(calendar, {year, month});
+}
+
+/** The number of months in a year of the calendar. */
+export function calendarMonthsInCalendarYear(
+ calendar: CalendarSystem,
+ year: number,
+): number {
+ return isGregorianAligned(calendar)
+ ? 12
+ : calendarMonthsInYear(
+ calendar,
+ calendarMonthOfYear(calendar, year, 1).start,
+ );
+}
+
+/**
+ * The name of a calendar month, such as "Adar I". It formats the middle day of
+ * the month, for the reason {@link formatCalendarMonthLabel} gives.
+ */
+export function formatCalendarMonthName(
+ calendar: CalendarSystem,
+ month: CalendarMonth,
+ locale: Locale,
+): string {
+ return formatCalendarDate(
+ calendar,
+ plainDateAddDays(month.start, Math.floor(month.length / 2)),
+ DATE_FORMAT_MONTH_ONLY,
+ locale,
+ );
+}
+
+const YEAR_PART_TYPES: ReadonlySet<string> = new Set([
+ 'era',
+ 'year',
+ 'relatedYear',
+]);
+
+/** The era and year parts of a date, as the locale writes them in a long date. */
+function eraYearAt(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+ locale: Locale,
+): {readonly era: string | undefined; readonly label: string | null} {
+ const parts = formatToParts(
+ calendar,
+ pd,
+ {era: 'short', year: 'numeric', month: 'long', day: 'numeric'},
+ locale,
+ );
+ const era = parts.find(part => part.type === 'era')?.value;
+ const first = parts.findIndex(part => YEAR_PART_TYPES.has(part.type));
+ if (first === -1) {
+ return {era, label: null};
+ }
+ let last = first;
+ parts.forEach((part, index) => {
+ if (YEAR_PART_TYPES.has(part.type)) {
+ last = index;
+ }
+ });
+ const label = parts
+ .slice(first, last + 1)
+ .filter(part => YEAR_PART_TYPES.has(part.type) || part.type === 'literal')
+ .map(part => part.value)
+ .join('')
+ .replace(/\s+/g, ' ')
+ .trim();
+ return {era, label};
+}
+
+/**
+ * Whether the first and last days of a year of the calendar fall in different
+ * eras, as the Japanese year 2019 does (Heisei, then Reiwa). Only an era change
+ * counts: other parts, such as a Chinese related year, can disagree at the
+ * edges of a year when Intl and Temporal place a month start one day apart.
+ */
+export function calendarYearSpansEras(
+ calendar: CalendarSystem,
+ year: number,
+ locale: Locale,
+): boolean {
+ if (isGregorianCalendar(calendar)) {
+ return false;
+ }
+ const months = calendarMonthsInCalendarYear(calendar, year);
+ const start = eraYearAt(
+ calendar,
+ calendarMonthOfYear(calendar, year, 1).start,
+ locale,
+ );
+ const end = eraYearAt(
+ calendar,
+ calendarMonthOfYear(calendar, year, months).end,
+ locale,
+ );
+ return start.era !== end.era && start.label != null && end.label != null;
+}
+
+/**
+ * The label of a year of the calendar, with its era where the locale writes
+ * one in a date, such as "令和8" in `ja-JP` or "1405 AP" in English. It uses the
+ * era and year parts of a long date, in the locale's order and digits, with the
+ * text between them. A year that spans an era change takes its era from `at`,
+ * a month position and a day clamped to that month, so 2019 reads "平成31" in
+ * January and "令和元" in May. Without `at`, and for every other year, the label
+ * comes from the middle of the year. Gregorian years are plain numbers.
+ */
+export function formatCalendarYearLabel(
+ calendar: CalendarSystem,
+ year: number,
+ locale: Locale,
+ at?: {readonly month: number; readonly day: number},
+): string {
+ if (isGregorianCalendar(calendar)) {
+ return String(year);
+ }
+ const months = calendarMonthsInCalendarYear(calendar, year);
+ if (at != null && calendarYearSpansEras(calendar, year, locale)) {
+ const month = calendarMonthOfYear(
+ calendar,
+ year,
+ Math.min(Math.max(at.month, 1), months),
+ );
+ const day = Math.min(Math.max(at.day, 1), month.length);
+ return (
+ eraYearAt(calendar, plainDateAddDays(month.start, day - 1), locale)
+ .label ?? String(year)
+ );
+ }
+ const middle = eraYearAt(
+ calendar,
+ calendarMonthOfYear(calendar, year, Math.floor(months / 2) + 1).start,
+ locale,
+ );
+ return middle.label ?? String(year);
+}
diff --git a/packages/core/src/utils/inputPresentation.ts b/packages/core/src/utils/inputPresentation.ts
index efe2e1f75d..31c589e359 100644
--- a/packages/core/src/utils/inputPresentation.ts
+++ b/packages/core/src/utils/inputPresentation.ts
@@ -2,7 +2,8 @@
/**
* @file inputPresentation.ts
- * @input A presentation policy, the deprecated nativePicker value, and pointer type
+ * @input A presentation policy, the deprecated nativePicker value, whether the
+ * native date control can show the calendar, and pointer type
* @output The resolved picker surface for DateInput, DateTimeInput, and TimeInput
* @position Shared presentation vocabulary (AST-043)
*
@@ -113,6 +114,25 @@ export function effectiveInputPresentation(
return DEFAULT_INPUT_PRESENTATION;
}
+/**
+ * The policy a date picker follows in its calendar. `<input type="date">` is
+ * Gregorian, so in a calendar it cannot show, the policies that use it
+ * (`native` and `adaptive-native`) use the Astryx popover on a fine pointer and
+ * the bottom sheet on a coarse one instead.
+ */
+export function calendarPickerPresentation(
+ presentation: PickerPresentation,
+ isNativeCalendar: boolean,
+): PickerPresentation {
+ if (
+ !isNativeCalendar &&
+ (presentation === 'native' || presentation === 'adaptive-native')
+ ) {
+ return 'adaptive-bottom-sheet';
+ }
+ return presentation;
+}
+
/** Resolve a picker-only policy to the surface rendered for the current pointer. */
export function resolvePickerPresentation(
presentation: PickerPresentation,