An open source design system that's fully customizable and agent ready
TypeScript
feat(Calendar): show the months of the selected calendar system (#9622)
nynexman4464fe1cf0c6d8fb
diff --git a/.changeset/calendar-systems-core.md b/.changeset/calendar-systems-core.mdnew file mode 100644index 0000000000..0c128d4f38--- /dev/null+++ b/.changeset/calendar-systems-core.md@@ -0,0 +1,7 @@+---+'@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.++@nynexman4464diff --git a/apps/storybook/stories/CalendarSystems.stories.tsx b/apps/storybook/stories/CalendarSystems.stories.tsxnew file mode 100644index 0000000000..80901840aa--- /dev/null+++ b/apps/storybook/stories/CalendarSystems.stories.tsx@@ -0,0 +1,221 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CalendarSystems.stories.tsx+ * @input InternationalizationProvider locale and calendar, Calendar+ * @output Calendar in each kind of calendar system, with its Gregorian value+ * @position Storybook verification stories for calendar systems; excluded from+ * the visual matrix because the months depend on the runtime's Temporal+ */++import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import * as stylex from '@stylexjs/stylex';+import {Calendar, type ISODateString} from '@astryxdesign/core/Calendar';+import {+ InternationalizationProvider,+ getLocaleDirection,+ type CalendarSystem,+ type Locale,+} from '@astryxdesign/core/i18n';+import {Heading, Text} from '@astryxdesign/core/Text';+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';++const meta = {+ title: 'Core/Internationalization/Calendar systems',+ tags: ['no-visual'],+ parameters: {layout: 'padded'},+} satisfies Meta;++export default meta;+type Story = StoryObj<typeof meta>;++interface CalendarCase {+ title: string;+ locale: Locale;+ /** The provider's calendar. */+ calendar?: CalendarSystem;+ /** The Calendar's own calendar, over the provider's. */+ componentCalendar?: CalendarSystem;+ value: ISODateString;+ numberOfMonths?: 1 | 2;+ weekStartsOn?: 'sun' | 'mon' | 'sat';+}++function CalendarCaseView({+ title,+ locale,+ calendar,+ componentCalendar,+ value: initialValue,+ numberOfMonths,+ weekStartsOn,+}: CalendarCase) {+ const [value, setValue] = useState<ISODateString>(initialValue);+ return (+ <InternationalizationProvider locale={locale} calendar={calendar}>+ <section aria-label={title} {...stylex.props(styles.panel)}>+ <Heading level={2}>{title}</Heading>+ <div dir={getLocaleDirection(locale)}>+ <Calendar+ calendar={componentCalendar}+ value={value}+ onChange={setValue}+ numberOfMonths={numberOfMonths}+ weekStartsOn={weekStartsOn}+ />+ </div>+ <Text>+ value: <code data-testid="value">{value}</code>+ </Text>+ </section>+ </InternationalizationProvider>+ );+}++function story(calendarCase: CalendarCase, description: string): Story {+ return {+ render: () => <CalendarCaseView {...calendarCase} />,+ parameters: {docs: {description: {story: description}}},+ };+}++export const PersianFarsi = story(+ {+ title: 'Persian, fa-IR',+ locale: 'fa-IR',+ calendar: 'persian',+ value: '2026-10-30',+ weekStartsOn: 'sat',+ },+ 'Aban 1405 in Farsi with Persian digits. The value stays the Gregorian ISO date.',+);++export const PersianEnglish = story(+ {+ title: 'Persian calendar, English',+ locale: 'en',+ calendar: 'persian',+ value: '2026-10-30',+ weekStartsOn: 'sat',+ },+ 'The calendar is independent of the language.',+);++export const LocaleKeywordStaysGregorian = story(+ {+ title: 'fa-IR-u-ca-persian, no calendar',+ locale: 'fa-IR-u-ca-persian',+ value: '2026-10-30',+ weekStartsOn: 'sat',+ },+ 'A `-u-ca-` keyword in the provider locale does not select the calendar: the months stay Gregorian.',+);++export const LocaleAloneStaysGregorian = story(+ {+ title: 'fa-IR, no calendar',+ locale: 'fa-IR',+ value: '2026-10-30',+ weekStartsOn: 'sat',+ },+ "A locale's default calendar never applies: `fa-IR` alone shows Gregorian months.",+);++export const ComponentCalendarOverProvider = story(+ {+ title: 'Gregorian Calendar in a Persian provider',+ locale: 'fa-IR',+ calendar: 'persian',+ componentCalendar: 'gregory',+ value: '2026-10-30',+ weekStartsOn: 'sat',+ },+ "The Calendar's own `calendar` prop takes precedence over the provider's.",+);++export const HebrewLeapYear = story(+ {+ title: 'Hebrew leap year',+ locale: 'en',+ calendar: 'hebrew',+ value: '2024-03-01',+ numberOfMonths: 2,+ },+ 'Adar I and Adar II of 5784 are distinct months. Shift+PageDown from Adar I lands in Adar of 5785.',+);++export const JapaneseEraChange = story(+ {+ title: 'Japanese era change',+ locale: 'ja-JP',+ calendar: 'japanese',+ value: '2019-04-30',+ numberOfMonths: 2,+ },+ 'Heisei 31 April and Reiwa 1 May. Japanese months are Gregorian, so no Temporal is needed.',+);++export const ChineseLeapMonth = story(+ {+ title: 'Chinese leap second month',+ locale: 'zh-CN',+ calendar: 'chinese',+ value: '2023-03-01',+ numberOfMonths: 2,+ weekStartsOn: 'mon',+ },+ 'The second month of 2023 is followed by a leap second month.',+);++export const EthiopicThirteenthMonth = story(+ {+ title: 'Ethiopic thirteenth month',+ locale: 'am-ET',+ calendar: 'ethiopic',+ value: '2026-09-08',+ numberOfMonths: 2,+ },+ 'Pagume 2018 has five days and keeps the fixed six-row grid.',+);++export const IslamicUmmAlQura = story(+ {+ title: 'Islamic (Umm al-Qura), ar-SA',+ locale: 'ar-SA',+ calendar: 'islamic-umalqura',+ value: '2026-10-30',+ weekStartsOn: 'sat',+ },+ 'A right-to-left locale with Arabic-Indic digits.',+);++export const BuddhistThai = story(+ {+ title: 'Buddhist, th-TH',+ locale: 'th-TH',+ calendar: 'buddhist',+ value: '2026-10-30',+ },+ 'Buddhist years on Gregorian months. No Temporal is needed.',+);++export const Iso8601 = story(+ {+ title: 'ISO 8601, English',+ locale: 'en',+ calendar: 'iso8601',+ value: '2026-10-30',+ weekStartsOn: 'mon',+ },+ 'The ISO 8601 calendar has Gregorian months and uses Gregorian month names.',+);++const styles = stylex.create({+ panel: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-4'],+ alignItems: 'flex-start',+ },+});diff --git a/docs/architecture/internationalization.md b/docs/architecture/internationalization.mdindex 338d5696a2..9f5c5f3abb 100644--- a/docs/architecture/internationalization.md+++ b/docs/architecture/internationalization.md@@ -275,17 +275,18 @@ for all 30 shipped locales plus `pseudo`.The charts `currency()` helper does not yet conform: an omitted locale followsthe host default. That is a known conformance gap, not a recorded default;making it deterministic is a separate compatibility change.-- **INV10 — The application selects the calendar; values stay Gregorian.** The- provider resolves its calendar from its `calendar` prop, and otherwise the- Gregorian calendar (`spec:AST-111` FR2). Astryx date components show Gregorian- dates. 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 of every- calendar whose months are not Gregorian; where it is missing, a date component- that resolves such a calendar shows Gregorian dates (`spec:AST-111` FR5).- Shared built-in date formatters pin the Gregorian calendar unless an Astryx- call site passes the resolved calendar. The low-level `plainDateFormat`+- **INV10 — The application selects the calendar; values stay Gregorian.** A+ `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+ 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+ of every calendar whose months are not Gregorian; where it is missing, a date+ component that resolves such a calendar shows Gregorian dates (`spec:AST-111`+ FR5). Shared built-in date formatters pin the Gregorian calendar unless an+ Astryx call site passes the resolved calendar. The low-level `plainDateFormat`display-calendar override remains a supported explicit caller choice.- **INV11 — Rendered direction comes from the DOM.** The provider exposes asemantic direction default, but Astryx layout, mirroring, and interaction SHOULDdiff --git a/docs/specs/components/Calendar/Calendar.spec.md b/docs/specs/components/Calendar/Calendar.spec.mdindex 86dceabba7..1769701714 100644--- a/docs/specs/components/Calendar/Calendar.spec.md+++ b/docs/specs/components/Calendar/Calendar.spec.md@@ -14,6 +14,10 @@ verified_by:[packages/core/src/Calendar/Calendar.test.tsx,packages/core/src/Calendar/getWeekdayHeaderNames.test.ts,+ packages/core/src/Calendar/Calendar.calendarSystems.test.tsx,+ packages/core/src/Calendar/Calendar.ssr.test.tsx,+ packages/core/src/utils/calendarSystem.test.ts,+ packages/core/src/i18n/__tests__/calendarSystem.test.tsx,packages/core/src/hooks/useGridFocus.test.tsx,packages/core/src/Calendar/__tests__/Calendar.a11y.test.tsx,packages/core/src/Calendar/__tests__/Calendar.a11y.chromium.spec.ts,@@ -31,22 +35,29 @@ architecture:architecture:react-component-runtime,]contributing: []-system_specs: [spec:AST-020/FR15, spec:AST-085, spec:AST-102]+system_specs:+ [+ spec:AST-013/FR12,+ spec:AST-020/FR15,+ spec:AST-085,+ spec:AST-102,+ spec:AST-111,+ ]---# Calendar component contract## Contract at a glance-| Area | Contract |-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |-| Public contract | None changes. `Calendar` and `CalendarProps` are exported from `@astryxdesign/core/Calendar`; `mode` selects a single date or a range, with `value`/`defaultValue`/`onChange`, bounds, constraints, span limits, focus date, and display options. |-| Behavior | One or two months render as day grids under weekday headers (DD1); a day is picked by pointer or keyboard; each month grid holds at most one roving Tab stop, which arrow, Home/End, and Page keys move, following the reading direction. |-| End-user impact | A keyboard or screen-reader user meets a named month grid, moves through it by day, week, and month, and hears each day's name, selection, today marker, and disabled state. |-| Builder impact | None. |-| Compatibility/readiness | Records shipped behavior; no API or default change. The month buttons use native `disabled` at a bound and scale under reduced motion, day buttons hold a fixed size, and a key-moved Tab stop can go stale; all are listed under Current-state impact. |-| Review checks | Reject a day grid without `role="grid"` or a name, two days in one month holding a Tab stop, an arrow key that stops following the reading direction, a selection or today state carried only by colour, a weekday header cut to a fixed number of characters, or a header row mixing abbreviated and short names. |-| Governing rules | DD1 for the weekday headers; `architecture:public-component-api/INV1,INV5–INV8`; `architecture:component-theming-surface/INV3–INV7`; `spec:AST-020/FR15`; `spec:AST-085/FR1, FR4`; `spec:AST-102` FR4; `design:bidirectionality` DR6; `design:reduced-motion` DR1; `architecture:internationalization` INV8. |+| Area | Contract |+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `Calendar` and `CalendarProps` are exported from `@astryxdesign/core/Calendar`; `mode` selects a single date or a range, with `value`/`defaultValue`/`onChange`, bounds, constraints, span limits, focus date, display options, and an optional `calendar` (`CalendarSystem`). Every value stays a Gregorian ISO date. |+| Behavior | One or two months of the resolved calendar system render as day grids under weekday headers (DD1); a day is picked by pointer or keyboard; each month grid holds at most one roving Tab stop, which arrow, Home/End, and Page keys move, following the reading direction. Page keys step calendar months, and with Shift calendar years. |+| End-user impact | A keyboard or screen-reader user meets a named month grid, moves through it by day, week, and month (and year with Shift and a Page key), and hears each day's name, selection, today marker, and disabled state, in the calendar the application chose. |+| Builder impact | Optional: set `calendar` on the Calendar or its provider; for a calendar that needs `Temporal`, load a polyfill where the runtime lacks it. |+| Compatibility/readiness | The `calendar` prop is additive and the default stays Gregorian. A provider locale with a `-u-ca-` keyword keeps Gregorian dates (`spec:AST-111` DEC-2); set `calendar` to choose one. Calendars that need `Temporal` fall back to Gregorian where it is missing (the `spec:AST-013` FR12 exception). The month buttons use native `disabled` at a bound and scale under reduced motion, day buttons hold a fixed size, and a key-moved Tab stop can go stale; all are listed under Current-state impact. |+| Review checks | Reject a day grid without `role="grid"` or a name, two days in one month holding a Tab stop, an arrow key that stops following the reading direction, a selection or today state carried only by colour, a weekday header cut to a fixed number of characters, or a header row mixing abbreviated and short names. |+| Governing rules | DD1 for the weekday headers; `architecture:public-component-api/INV1,INV5–INV8`; `architecture:component-theming-surface/INV3–INV7`; `spec:AST-020/FR15`; `spec:AST-085/FR1, FR4`; `spec:AST-102` FR4; `spec:AST-111` FR1–FR8, AR1; `spec:AST-013` FR12; `design:bidirectionality` DR6; `design:reduced-motion` DR1; `architecture:internationalization` INV8. |This table is a review projection; the body below is authoritative.@@ -58,11 +69,14 @@ keyboard model that moves through days; date fields compose it.## Compatibility and migration-- Released default preserved: `yes`, except DD1: `no`, since Calendars in- locales whose abbreviated names fit (English among them) show those names,- with no prop to keep the short names-- Compatibility class: no public prop, default, or export change; the- weekday header text follows DD1+- Released default preserved: `yes` — without a `calendar` prop or a+ provider calendar, the grid shows Gregorian months — except DD1: `no`,+ since Calendars in locales whose abbreviated names fit (English among them)+ show those names, with no prop to keep the short names+- Compatibility class: additive optional `calendar` prop; no default, export, or+ DOM structure change; the weekday header text follows DD1. A provider locale+ with a `-u-ca-` keyword keeps Gregorian dates (`spec:AST-111` DEC-2); set+ `calendar` to choose one- Controlled/uncontrolled behavior: `value` with `onChange` is controlled;`defaultValue` starts internal state- Migration decision: none@@ -76,6 +90,8 @@ Consumer migration instructions belong in consumer docs and release notes.- The month grid: its weekday column headers, week rows, day cells, outside days,week numbers, and variable row count.- Month navigation, the focused day, and the keyboard model that moves it.+- The calendar months it lays out, their labels, and month and year steps in+ the resolved calendar system.- Single and range selection semantics, bounds, constraints, and span limits.**Does not own / non-goals**@@ -83,29 +99,35 @@ Consumer migration instructions belong in consumer docs and release notes.- The text field, popover, and bottom sheet that present a Calendar — owned byDateInput and its siblings.- Time of day — owned by DateTimeInput.+- Calendar resolution and the `Temporal` boundary — owned by `spec:AST-111`+ FR1, FR2, and FR5; calendar arithmetic — owned by `Temporal`.- `handleRef`, `onFocusDateChange`, the opening month inside the `min`/`max`window, `weekStartsOn`, and `numberOfMonths` clamping — shipped and coveredby the consumer docs and tests, uncontracted here beyond FR1–FR7.## Public concepts-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |-| ----------- | -------------------------------------------- | ----------------------------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -------------------- | --------- | ---------------------------- |-| `mode` | `single`, `range` | Whether one date or a start–end pair is picked. | Always | `single` | `component:Calendar` | stable | Type-rejected |-| Focused day | one visible day | The day whose button holds the grid's Tab stop. | Always | selected day (`single`) or today when it is in that month and enabled, else the month's first enabled day (AR1) | `component:Calendar` | stable | Clamped to the visible range |-| Day state | selected, in range, today, disabled, outside | What a day cell exposes and paints. | Per cell | none | `component:Calendar` | stable | Not applicable |+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ----------- | -------------------------------------------- | ------------------------------------------------ | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -------------------- | --------- | --------------------------------------------------- |+| `mode` | `single`, `range` | Whether one date or a start–end pair is picked. | Always | `single` | `component:Calendar` | stable | Type-rejected |+| Focused day | one visible day | The day whose button holds the grid's Tab stop. | Always | selected day (`single`) or today when it is in that month and enabled, else the month's first enabled day (AR1) | `component:Calendar` | stable | Clamped to the visible range |+| Day state | selected, in range, today, disabled, outside | What a day cell exposes and paints. | Per cell | none | `component:Calendar` | stable | Not applicable |+| `calendar` | a `CalendarSystem` (`spec:AST-111` FR1) | The calendar system whose months the grid shows. | Always | the provider's resolved calendar, else `gregory` (`spec:AST-111` FR2) | `spec:AST-111` | stable | Resolves to `gregory` and warns once in development |## Behavioral and layout contract-| ID | Invariant | Basis |-| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- |-| FR1 | Each rendered month is one `role="grid"` named for its month and year, with a `columnheader` per weekday (and, with week numbers, a named `columnheader` above the `rowheader` column) and one `row` per week. Month and year labels and weekday names (DD1) come from the provider locale. A month label that stands alone (the header, each grid's name, and `useCalendarNavigation`'s `monthYearLabel`) starts with a capital where CLDR's stand-alone context transform titlecases the month (`titlecase-firstword`); in a two-month view each month's label does. Day and week numbers MUST use the locale's digits (`architecture:internationalization` INV8). | shipped source and focused tests; `architecture:internationalization` INV8 |-| FR2 | At most one day button in each month's grid holds `tabIndex={0}`; every other day button in that grid is `-1`. Each day button is the shared `sm` element size (inside an `md`-sized cell) as a minimum that grows with a set text size (`spec:AST-102` FR4). Implementation gap: the day buttons hold a fixed size. | shipped `useGridFocus` behavior; `Calendar.test.tsx` single-Tab-stop assertion; `spec:AST-102` FR4 |-| FR3 | A disabled day (outside bounds or rejected by a constraint) stays in the grid, stays focusable with `aria-disabled` and no native `disabled`, never holds the grid's Tab stop, and cannot be picked. Implementation gap: once a key move (arrow, Home, End, or Page key) has placed the Tab stop, it stays on that day when every day of the month becomes disabled (for example a range span cap in a two-month view). | `spec:AST-085` FR1, FR2; shipped source and focused tests |-| FR4 | In `range` mode the first pick starts the range and the second ends it, a second pick before the start swapping the two so the end never precedes the start; `minRangeSpan`/`maxRangeSpan` bound it. Escape, or picking the start day again when `minRangeSpan` is above 1, clears an in-progress range. | shipped source and focused tests |-| FR5 | Moving the focused day across a month boundary navigates the visible month so the focused day stays visible, in one month or two; a borrowed adjacent-month day is exposed `aria-disabled` and cannot be picked; arrow keys, Home and End skip it, and a page never lands on it. | shipped source and focused tests |-| FR6 | The month header shows the month and year between Previous and Next month buttons (ghost, icon-only Buttons whose chevrons mirror under RTL), which carry `calendar-nav` with `data-nav` and `data-disabled`. A button whose direction would leave `min` or `max` MUST stay focusable with `aria-disabled`, change nothing, and keep focus (`spec:AST-085` FR1, FR4). Implementation gap: it is natively disabled, so a focused button that reaches the bound drops focus. The month buttons are `component:Button`s, so their press scale MUST NOT apply under reduced motion (`design:reduced-motion` DR1). Implementation gap: it still applies under reduced motion. | `spec:AST-085`; shipped source and focused tests; `design:reduced-motion` DR1 |-| FR7 | When the visible month changes, by the month buttons, a Page key, an arrow across a month edge, or the handle, the new month (both months in a two-month view) is announced politely; the first render and a pick that leaves the month in place announce nothing. In `range` mode the first pick announces the start and prompts for an end, the second announces the completed range in chronological order, and picking the start again when `minRangeSpan` is above 1 announces the cleared start; Escape clears an in-progress range without an announcement. Every announcement uses the provider locale. | shipped source and focused tests |+| ID | Invariant | Basis |+| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |+| FR1 | Each rendered month is one `role="grid"` named for its month and year, with a `columnheader` per weekday (and, with week numbers, a named `columnheader` above the `rowheader` column) and one `row` per week. Month and year labels and weekday names (DD1) come from the provider locale. A month label that stands alone (the header, each grid's name, and `useCalendarNavigation`'s `monthYearLabel`) starts with a capital where CLDR's stand-alone context transform titlecases the month (`titlecase-firstword`); in a two-month view each month's label does. Day and week numbers MUST use the locale's digits (`architecture:internationalization` INV8). | shipped source and focused tests; `architecture:internationalization` INV8 |+| FR2 | At most one day button in each month's grid holds `tabIndex={0}`; every other day button in that grid is `-1`. Each day button is the shared `sm` element size (inside an `md`-sized cell) as a minimum that grows with a set text size (`spec:AST-102` FR4). Implementation gap: the day buttons hold a fixed size. | shipped `useGridFocus` behavior; `Calendar.test.tsx` single-Tab-stop assertion; `spec:AST-102` FR4 |+| FR3 | A disabled day (outside bounds or rejected by a constraint) stays in the grid, stays focusable with `aria-disabled` and no native `disabled`, never holds the grid's Tab stop, and cannot be picked. Implementation gap: once a key move (arrow, Home, End, or Page key) has placed the Tab stop, it stays on that day when every day of the month becomes disabled (for example a range span cap in a two-month view). | `spec:AST-085` FR1, FR2; shipped source and focused tests |+| FR4 | In `range` mode the first pick starts the range and the second ends it, a second pick before the start swapping the two so the end never precedes the start; `minRangeSpan`/`maxRangeSpan` bound it. Escape, or picking the start day again when `minRangeSpan` is above 1, clears an in-progress range. | shipped source and focused tests |+| FR5 | Moving the focused day across a month boundary navigates the visible month so the focused day stays visible, in one month or two; a borrowed adjacent-month day is exposed `aria-disabled` and cannot be picked; arrow keys, Home and End skip it, and a page never lands on it. | shipped source and focused tests |+| FR6 | The month header shows the month and year between Previous and Next month buttons (ghost, icon-only Buttons whose chevrons mirror under RTL), which carry `calendar-nav` with `data-nav` and `data-disabled`. A button whose direction would leave `min` or `max` MUST stay focusable with `aria-disabled`, change nothing, and keep focus (`spec:AST-085` FR1, FR4). Implementation gap: it is natively disabled, so a focused button that reaches the bound drops focus. The month buttons are `component:Button`s, so their press scale MUST NOT apply under reduced motion (`design:reduced-motion` DR1). Implementation gap: it still applies under reduced motion. | `spec:AST-085`; shipped source and focused tests; `design:reduced-motion` DR1 |+| FR8 | The grid shows the months of the resolved calendar system (`spec:AST-111` FR2). Each grid lays out one calendar month: its first day sits in its weekday column and outside days fill the other cells. The default grid has six rows for every month, including the five- or six-day thirteenth month of the Coptic and Ethiopic calendars; `hasVariableRowCount` gives each month only the rows it needs. A leap month is a distinct month with its own name. The month heading, each grid's name, day-button names, and announcements use the calendar, and day numbers are the calendar's days in the locale's digits. Every name gives the month and day that the grid shows, and `iso8601` uses the Gregorian month names. `value`, `min`, `max`, `focusDate`, and every callback stay Gregorian ISO dates in every calendar. | `spec:AST-111` FR3, FR4, FR6; `Temporal` month structure |+| FR9 | Previous and Next move one calendar month. PageUp and PageDown move the focused day one calendar month, keep its day of the month, and clamp it to the target month's length. Shift+PageUp and Shift+PageDown move the focused day one calendar year, to the same month of that year; a leap month that the target year does not have becomes its common counterpart (Adar I becomes Adar). In the Gregorian calendar a year step lands on the same day one year away, clamped. `min` and `max` bound navigation by day in every calendar, and a year step meets them and constraints as a month step does (AR1). | `spec:AST-111` FR7; APG date picker dialog keyboard model |+| FR10 | `hasWeekNumbers` shows ISO 8601 week numbers in every calendar. | `spec:AST-111` FR8 |+| FR7 | When the visible month changes, by the month buttons, a Page key, an arrow across a month edge, or the handle, the new month (both months in a two-month view) is announced politely; the first render and a pick that leaves the month in place announce nothing. In `range` mode the first pick announces the start and prompts for an end, the second announces the completed range in chronological order, and picking the start again when `minRangeSpan` is above 1 announces the cleared start; Escape clears an in-progress range without an announcement. Every announcement uses the provider locale. | shipped source and focused tests |### Allowed variation@@ -154,15 +176,18 @@ Consumer migration instructions belong in consumer docs and release notes.ArrowLeft and ArrowRight move by a day following the reading direction(`design:bidirectionality` DR6),ArrowUp and ArrowDown by a week, Home and End to the first and last enabled day of the- week, PageUp and PageDown by a month, Shift+PageUp and Shift+PageDown by a- year (a named exception, as in the APG date picker dialog; a day the target- month lacks clamps to its last day), and Enter or Space picks the focused day;+ week, PageUp and PageDown by a calendar month, Shift+PageUp and+ Shift+PageDown by a calendar year (a named exception, as in the APG date+ picker dialog; a day the target month lacks clamps to its last day; FR9),+ and Enter or Space picks the focused day;an arrow skips a day disabled by a constraint and continues in thesame direction, crossing the month edge when it must; an arrow or Page key whose targetlies past `min` or `max` changes nothing and keeps focus where it is, andso does an arrow whose direction has no enabled day within a year; a pageonto a day disabled by a constraint focuses that month's first enabled day- instead, and changes nothing when that month has no enabled day.+ instead, and changes nothing when that month has no enabled day. Spoken+ dates (day-button names, grid names, and announcements) use the calendar+ that the grid shows (`spec:AST-111` AR1).## Design relationships@@ -216,20 +241,53 @@ button.- `spec:AST-085` owns disabled focusability; days meet it and the monthbuttons do not (FR6).- `component:Button` renders the month buttons.+- `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.++### `spec:AST-013` FR12 exception — calendars that need `Temporal`++- **Capability:** calendars other than `gregory`, `iso8601`, `buddhist`,+ `roc`, and `japanese`, which need the runtime's `Temporal`.+- **Reduction:** where `Temporal` is missing or does not support the calendar,+ as in Safari on macOS and iOS, such a calendar resolves to `gregory` before+ the first render and warns once in development, on the server and in the+ browser, naming `temporal-polyfill/full/global` (`spec:AST-111` FR5). An+ application that loads a `Temporal` polyfill gets the full calendar. A+ server without `Temporal` renders Gregorian markup, which a browser with+ `Temporal` does not match, so a server-rendered application loads `Temporal`+ on the server too. `chinese` and `dangi` month starts follow the runtime's+ `Temporal`; a server and a browser whose implementations disagree on a+ month start render that month differently, and React renders it again on+ the client during hydration (`spec:AST-111` FR19). Day and month names+ follow the month and day that the grid shows in every case.+- **Preserved obligations:** `spec:AST-013` FR7 and FR8, and FR9 whenever the+ server and the browser resolve the calendar the same way, outside the+ `chinese` and `dangi` case. The Gregorian grid keeps+ the primary task, accessibility, Gregorian ISO values and callbacks, and+ repeated use; nothing throws; a server and a browser that both have+ `Temporal`, or both lack it, render the same markup.+- **Evidence:** real Chromium and Firefox with native `Temporal`, with+ `Temporal` removed and a polyfill loaded, and with `Temporal` removed and no+ polyfill; server render and hydration with `Temporal` on both sides, on+ neither side, and on the browser only.+- **Owner:** `nynexman4464`.+- **Review condition:** Safari ships `Temporal`.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |-| FR1–FR5 | `Calendar.test.tsx` structure ("renders a valid APG grid: one grid, header row of columnheaders inside it, week rows of gridcells", "with week numbers, the header row's corner cell is a named columnheader, so every row child is a grid cell"), locale digits ("shows day and week numbers in the locale digits in %s" for `fa-IR`, `ar-EG`, and `en`), selection ("handles reverse range selection (end before start)", "caps the range highlight next to a disabled mid-range day (#2715)", "Escape cancels range selection in progress", "clears the in-progress start when the anchor is clicked again"), bounds ("prev button is disabled when focusDate month contains min", "next button is disabled when focusDate month contains max"), and navigation ("navigates to next month", "calls onFocusDateChange when navigating") suites | single, range, two months, bounded | A missing header row, a reverse pick that does not swap, a range highlight that reaches a disabled day, or a Previous/Next button enabled past `min`/`max` fails. Day or week numbers in Latin digits under `fa-IR` or `ar-EG` fail. | `audit:Calendar/behavior` |-| AR1 | `Calendar.test.tsx` ("has accessible grid structure", "sets aria-multiselectable on both grids in a two-month range view", "does not set aria-multiselectable in single mode", "announces the new month politely when clicking next", "displays day names") and `useGridFocus.test.tsx` ("ArrowDown moves the tab stop one row down", "flips ArrowLeft/ArrowRight under RTL"); `Calendar.test.tsx` "ArrowUp skips a disabled cell in the same column to the next enabled row (complex-2)" for the disabled-day skip; `Calendar.test.tsx` Page-key cases ("moves the focused day by a month with PageDown and PageUp, into the month now shown", "pages from a borrowed adjacent-month day onto the real day in the month already shown", "an arrow past max changes nothing and leaves no pending target behind", "a page into a month with no enabled day changes nothing and keeps focus", "a page onto a day disabled by a constraint moves the month and focuses its first enabled day", "a page whose target lies past max changes nothing and keeps focus", "in a two-month view a boundary blocks only out-of-range targets, not month movement", "in a two-month view PageDown from the second month moves both months and a later Next click selects no stale day", "moves the focused day by a year with Shift+PageDown and Shift+PageUp", "a year from February 29 lands on February 28", "a year step whose target lies past max changes nothing and keeps focus", "a year step onto a day disabled by a constraint focuses that month's first enabled day", "in a two-month view a year step forward makes the target month the second one shown"); borrowed-day cases ("skips borrowed adjacent-month days and crosses into their month instead", "in a two-month view an arrow from the first month lands on the real day, never a borrowed one", "an arrow toward a direction where every remaining day is disabled changes nothing", "an arrow resolves the next enabled day in its direction first: weekdays-only ArrowRight from Friday January 30 reaches Monday February 2", "an arrow whose next day in range does not exist changes nothing: max January 25, ArrowDown from January 21"); the single-Tab-stop assertion in the AST-085 range-cap case (FR2). `Calendar.test.tsx` selection-state accessible-name cases ("appends 'selected' to the selected day's button name in single mode", "marks range start, end, and in-range days in their accessible names"). Evidence gap: no Calendar-level test of Home, End, Enter, or Space; no test covers the Tab stop after a key move followed by a pointer pick or a fully disabled month | LTR and RTL; month boundary; selected, today, disabled days | A day loses its role, name or state, two days in one month hold a Tab stop, or an arrow, Home/End, Page or activation key stops moving or picking. | `audit:Calendar/accessibility` |-| FR6 | `Calendar.test.tsx` navigation, bound, theming-target ("renders the astryx-calendar-nav target on both month-nav buttons", "reflects the disabled nav state as a data attribute at the range edges", "keeps the default nav rendering unchanged (still a ghost icon button)"), and RTL month-navigation cases | Previous and Next; at `min` and `max`; `dir="rtl"` | A button enabled past a bound, a missing `calendar-nav` target or state attribute, or a lost shared chevron wrapper fails. Evidence gap: no test asserts focus kept at a bound (the FR6 gap), the mirrored chevron pixels, or the press under reduced motion. | `audit:Calendar/behavior` |-| FR7 | `Calendar.test.tsx` month-change announcement cases ("does not announce on initial render", "announces the new month politely when clicking next", "announces the next month when paging the grid with PageDown", "announces both months in a two-month view", "does not announce when selecting a date leaves the visible month unchanged") and range announcement cases ("announces the start pick and prompts for an end date", "announces the completed range in chronological order for a reverse pick") | Month buttons, Page keys, handle; single and two months; range start, complete, cleared | A missing, extra, or out-of-order announcement fails. Evidence gap: no test reaches the cleared-start announcement (the cleared-range case sets no `minRangeSpan`). | `audit:Calendar/accessibility` |-| FR1 (labels) | `Calendar.test.tsx` ("starts each stand-alone month label with a capital in %s", "leaves the month label as Intl gives it where CLDR does not capitalize in %s"), `plainDate.test.ts` `plainDateFormatStandaloneMonthYear` | es, fr, pl, ru two-month view; vi, de, en | A lower-case stand-alone month where CLDR titlecases it, a capital where it does not, or a second month left lower case fails. | `audit:Calendar/behavior` |-| FR2 (size) | Evidence gap: no test asserts day-button size or text growth | — | — | `audit:Calendar/layout` |-| DD1 | `Calendar.test.tsx` ("displays day names", "uses the provider locale for weekday header names", "rotates localized day names by numeric weekday index", "shows abbreviated weekday names in a locale where all seven fit in four characters", "keeps short weekday names in %s, where an abbreviated name runs past four characters" for `pt-PT` and `pl-PL`, "shows the platform abbreviated names for a locale with no shipped weekday data" for `id-ID`, "shows the platform narrow names for an unshipped locale whose abbreviated names run past four characters" for `sw-KE`); `getWeekdayHeaderNames.test.ts`; `scripts/generate-cldr-weekdays.test.mjs` ("matches every generated locale to its pinned raw CLDR source", "picks abbreviated names only where all seven fit in four characters") | English; a locale whose abbreviated names are all within four characters, such as `fr`; a locale above it, such as `pt-PT` or `pl`; `weekStartsOn` rotation; with week numbers | A locale within the limit showing short names, a locale above it showing abbreviated names, a row mixing the two, or a name cut short fails. | `audit:Calendar/layout` |-| AR1 (browser) | `Calendar.a11y.test.tsx` and `Calendar.a11y.chromium.spec.ts` over the shared grid states | Every representative state | A lost grid name, role, or start neighbourhood fails; browser-owned outcomes are reported. | `audit:Calendar/accessibility` |-| ORD1, ORD2, PR1 | ORD1 and ORD2 are covered by the FR3–FR5 and AR1 rows. Evidence gap: no test asserts the absence of per-cell listeners | — | — | `audit:Calendar/behavior` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |+| FR1–FR5 | `Calendar.test.tsx` structure ("renders a valid APG grid: one grid, header row of columnheaders inside it, week rows of gridcells", "with week numbers, the header row's corner cell is a named columnheader, so every row child is a grid cell"), locale digits ("shows day and week numbers in the locale digits in %s" for `fa-IR`, `ar-EG`, and `en`), selection ("handles reverse range selection (end before start)", "caps the range highlight next to a disabled mid-range day (#2715)", "Escape cancels range selection in progress", "clears the in-progress start when the anchor is clicked again"), bounds ("prev button is disabled when focusDate month contains min", "next button is disabled when focusDate month contains max"), and navigation ("navigates to next month", "calls onFocusDateChange when navigating") suites | single, range, two months, bounded | A missing header row, a reverse pick that does not swap, a range highlight that reaches a disabled day, or a Previous/Next button enabled past `min`/`max` fails. Day or week numbers in Latin digits under `fa-IR` or `ar-EG` fail. | `audit:Calendar/behavior` |+| AR1 | `Calendar.test.tsx` ("has accessible grid structure", "sets aria-multiselectable on both grids in a two-month range view", "does not set aria-multiselectable in single mode", "announces the new month politely when clicking next", "displays day names") and `useGridFocus.test.tsx` ("ArrowDown moves the tab stop one row down", "flips ArrowLeft/ArrowRight under RTL"); `Calendar.test.tsx` "ArrowUp skips a disabled cell in the same column to the next enabled row (complex-2)" for the disabled-day skip; `Calendar.test.tsx` Page-key cases ("moves the focused day by a month with PageDown and PageUp, into the month now shown", "pages from a borrowed adjacent-month day onto the real day in the month already shown", "an arrow past max changes nothing and leaves no pending target behind", "a page into a month with no enabled day changes nothing and keeps focus", "a page onto a day disabled by a constraint moves the month and focuses its first enabled day", "a page whose target lies past max changes nothing and keeps focus", "in a two-month view a boundary blocks only out-of-range targets, not month movement", "in a two-month view PageDown from the second month moves both months and a later Next click selects no stale day", "moves the focused day by a year with Shift+PageDown and Shift+PageUp", "a year from February 29 lands on February 28", "a year step whose target lies past max changes nothing and keeps focus", "a year step onto a day disabled by a constraint focuses that month's first enabled day", "in a two-month view a year step forward makes the target month the second one shown"); borrowed-day cases ("skips borrowed adjacent-month days and crosses into their month instead", "in a two-month view an arrow from the first month lands on the real day, never a borrowed one", "an arrow toward a direction where every remaining day is disabled changes nothing", "an arrow resolves the next enabled day in its direction first: weekdays-only ArrowRight from Friday January 30 reaches Monday February 2", "an arrow whose next day in range does not exist changes nothing: max January 25, ArrowDown from January 21"); the single-Tab-stop assertion in the AST-085 range-cap case (FR2). `Calendar.test.tsx` selection-state accessible-name cases ("appends 'selected' to the selected day's button name in single mode", "marks range start, end, and in-range days in their accessible names"). Evidence gap: no Calendar-level test of Home, End, Enter, or Space; no test covers the Tab stop after a key move followed by a pointer pick or a fully disabled month | LTR and RTL; month boundary; selected, today, disabled days | A day loses its role, name or state, two days in one month hold a Tab stop, or an arrow, Home/End, Page or activation key stops moving or picking. | `audit:Calendar/accessibility` |+| FR6 | `Calendar.test.tsx` navigation, bound, theming-target ("renders the astryx-calendar-nav target on both month-nav buttons", "reflects the disabled nav state as a data attribute at the range edges", "keeps the default nav rendering unchanged (still a ghost icon button)"), and RTL month-navigation cases | Previous and Next; at `min` and `max`; `dir="rtl"` | A button enabled past a bound, a missing `calendar-nav` target or state attribute, or a lost shared chevron wrapper fails. Evidence gap: no test asserts focus kept at a bound (the FR6 gap), the mirrored chevron pixels, or the press under reduced motion. | `audit:Calendar/behavior` |+| FR7 | `Calendar.test.tsx` month-change announcement cases ("does not announce on initial render", "announces the new month politely when clicking next", "announces the next month when paging the grid with PageDown", "announces both months in a two-month view", "does not announce when selecting a date leaves the visible month unchanged") and range announcement cases ("announces the start pick and prompts for an end date", "announces the completed range in chronological order for a reverse pick") | Month buttons, Page keys, handle; single and two months; range start, complete, cleared | A missing, extra, or out-of-order announcement fails. Evidence gap: no test reaches the cleared-start announcement (the cleared-range case sets no `minRangeSpan`). | `audit:Calendar/accessibility` |+| FR1 (labels) | `Calendar.test.tsx` ("starts each stand-alone month label with a capital in %s", "leaves the month label as Intl gives it where CLDR does not capitalize in %s"), `plainDate.test.ts` `plainDateFormatStandaloneMonthYear` | es, fr, pl, ru two-month view; vi, de, en | A lower-case stand-alone month where CLDR titlecases it, a capital where it does not, or a second month left lower case fails. | `audit:Calendar/behavior` |+| FR8–FR10, AR1 (calendars) | `Calendar.calendarSystems.test.tsx` ("lays out Aban 1405 with its calendar day numbers and labels", "keeps the fixed six-row grid", "reports a pick as a Gregorian ISO date", "steps one calendar month with Previous and Next", "pages one calendar month and clamps the day of the month", "bounds the month buttons by day", "shows ISO 8601 week numbers", "writes day numbers and labels in the locale", "shows Adar I and Adar II as distinct months of a leap year", "steps a year from Adar I to Adar with Shift+PageDown, clamped", "keeps six rows for the five-day thirteenth month", "gives the thirteenth month only its rows with hasVariableRowCount", "steps a year to the same month with Shift+PageUp", "names the era of each month", "names each day by the month and day the grid shows when Intl disagrees", Gregorian year-paging cases); `Calendar.ssr.test.tsx` server render and hydration with `Temporal` on both sides, neither side, and the browser only; `calendarSystem.test.ts` month structure at known dates, labels of every Gregorian-aligned calendar, and contiguity, length, and months-per-year invariants for every calendar from 1900 through 2100; `i18n/__tests__/calendarSystem.test.tsx` resolution order and the fallback without `Temporal`; real Chromium and Firefox runs with native `Temporal`, with a polyfill, and without `Temporal` | Persian, Hebrew leap year, Ethiopic thirteenth month, Japanese era change, Chinese leap month; `fa-IR` digits; no `Temporal` | A month start, length, label, or step that differs from `Temporal`, a vanished leap month, a non-ISO value, a non-ISO week number, or a crash or missing warning without `Temporal` fails. Evidence gap: no Safari or WebKit run. | `audit:Calendar/behavior` |+| FR2 (size) | Evidence gap: no test asserts day-button size or text growth | — | — | `audit:Calendar/layout` |+| DD1 | `Calendar.test.tsx` ("displays day names", "uses the provider locale for weekday header names", "rotates localized day names by numeric weekday index", "shows abbreviated weekday names in a locale where all seven fit in four characters", "keeps short weekday names in %s, where an abbreviated name runs past four characters" for `pt-PT` and `pl-PL`, "shows the platform abbreviated names for a locale with no shipped weekday data" for `id-ID`, "shows the platform narrow names for an unshipped locale whose abbreviated names run past four characters" for `sw-KE`); `getWeekdayHeaderNames.test.ts`; `scripts/generate-cldr-weekdays.test.mjs` ("matches every generated locale to its pinned raw CLDR source", "picks abbreviated names only where all seven fit in four characters") | English; a locale whose abbreviated names are all within four characters, such as `fr`; a locale above it, such as `pt-PT` or `pl`; `weekStartsOn` rotation; with week numbers | A locale within the limit showing short names, a locale above it showing abbreviated names, a row mixing the two, or a name cut short fails. | `audit:Calendar/layout` |+| AR1 (browser) | `Calendar.a11y.test.tsx` and `Calendar.a11y.chromium.spec.ts` over the shared grid states | Every representative state | A lost grid name, role, or start neighbourhood fails; browser-owned outcomes are reported. | `audit:Calendar/accessibility` |+| ORD1, ORD2, PR1 | ORD1 and ORD2 are covered by the FR3–FR5 and AR1 rows. Evidence gap: no test asserts the absence of per-cell listeners | — | — | `audit:Calendar/behavior` |## Current-state impactdiff --git a/docs/specs/components/i18n/InternationalizationProvider.spec.md b/docs/specs/components/i18n/InternationalizationProvider.spec.mdindex f958a84806..2d0e105ea5 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 of the subtree, exposed on the context; 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` 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 |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. Astryx date components 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` 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 |### Allowed variationdiff --git a/packages/core/api-report.md b/packages/core/api-report.mdindex a5f3198c6b..6cb763a9b0 100644--- a/packages/core/api-report.md+++ b/packages/core/api-report.md@@ -295,6 +295,7 @@ component ButtonGroup(props: ButtonGroupProps)prop xstyle?: StyleXStylesinherits AriaAttributes, DOMAttributes, HTMLAttributescomponent Calendar(props: CalendarProps)+ prop calendar?: CalendarSystemprop dateConstraints?: ReadonlyArray<(date: Date) => boolean>prop defaultValue?: ISODateStringprop focusDate?: ISODateStringdiff --git a/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx b/packages/core/src/Calendar/Calendar.calendarSystems.test.tsxnew file mode 100644index 0000000000..01d9459bb3--- /dev/null+++ b/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx@@ -0,0 +1,390 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Calendar.calendarSystems.test.tsx+ * @input Calendar, InternationalizationProvider, the full Temporal polyfill+ * @output Tests for Calendar months, labels, navigation, and values in+ * calendar systems other than Gregorian+ * @position Colocated tests for Calendar.tsx; the polyfill stands in for the+ * native Temporal of a supporting runtime+ */++import 'temporal-polyfill/full/global';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {render, screen, waitFor, within} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {Calendar} from './Calendar';+import {DateInput} from '../DateInput/DateInput';+import {DateRangeInput} from '../DateRangeInput/DateRangeInput';+import {+ DateTimeInput,+ type ISODateTimeString,+} from '../DateTimeInput/DateTimeInput';+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';++afterEach(() => {+ __resetLiveRegionsForTest();+});++function dayButton(iso: string): HTMLElement {+ const button = document.querySelector<HTMLElement>(+ `button[data-date="${iso}"]`,+ );+ if (button == null) {+ throw new Error(`No day button for ${iso}`);+ }+ return button;+}++function inMonthDates(grid: HTMLElement): string[] {+ return within(grid)+ .getAllByRole('gridcell')+ .map(cell => cell.querySelector('button'))+ .filter(+ (button): button is HTMLButtonElement =>+ button != null && !button.hasAttribute('aria-disabled'),+ )+ .map(button => button.getAttribute('data-date') ?? '');+}++function focusedDate(): string | null {+ return document.activeElement?.getAttribute('data-date') ?? null;+}++describe('Calendar in the Persian calendar', () => {+ it('lays out Aban 1405 with its calendar day numbers and labels', () => {+ render(<Calendar calendar="persian" focusDate="2026-10-30" />);+ const grid = screen.getByRole('grid');+ expect(grid.getAttribute('aria-label')).toContain('Aban 1405');++ const dates = inMonthDates(grid);+ expect(dates).toHaveLength(30);+ expect(dates[0]).toBe('2026-10-23');+ expect(dates[29]).toBe('2026-11-21');++ expect(dayButton('2026-10-23')).toHaveTextContent(/^1$/);+ expect(dayButton('2026-10-30')).toHaveTextContent(/^8$/);+ expect(dayButton('2026-10-30').getAttribute('aria-label')).toMatch(+ /Friday, Aban 8, 1405/,+ );+ });++ it('keeps the fixed six-row grid', () => {+ render(<Calendar calendar="persian" focusDate="2026-10-30" />);+ expect(+ within(screen.getByRole('grid')).getAllByRole('gridcell'),+ ).toHaveLength(42);+ });++ it('reports a pick as a Gregorian ISO date', async () => {+ const user = userEvent.setup();+ const onChange = vi.fn();+ render(+ <Calendar+ calendar="persian"+ focusDate="2026-10-30"+ onChange={onChange}+ />,+ );+ await user.click(dayButton('2026-10-30'));+ expect(onChange).toHaveBeenCalledWith('2026-10-30', expect.any(Date));+ });++ it('steps one calendar month with Previous and Next', async () => {+ const user = userEvent.setup();+ render(<Calendar calendar="persian" defaultValue="2026-10-30" />);+ await user.click(screen.getByRole('button', {name: 'Next month'}));+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'Azar 1405',+ );+ expect(inMonthDates(screen.getByRole('grid'))[0]).toBe('2026-11-22');++ await user.click(screen.getByRole('button', {name: 'Previous month'}));+ await user.click(screen.getByRole('button', {name: 'Previous month'}));+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'Mehr 1405',+ );+ });++ it('pages one calendar month and clamps the day of the month', async () => {+ const user = userEvent.setup();+ // 31 Shahrivar 1405; Mehr has 30 days.+ render(<Calendar calendar="persian" defaultValue="2026-09-22" />);+ dayButton('2026-09-22').focus();+ await user.keyboard('{PageDown}');+ await waitFor(() => expect(focusedDate()).toBe('2026-10-22'));+ // 30 Mehr → 30 Shahrivar: the day of the month stays 30.+ await user.keyboard('{PageUp}');+ await waitFor(() => expect(focusedDate()).toBe('2026-09-21'));+ });++ it('bounds the month buttons by day', () => {+ render(+ <Calendar+ calendar="persian"+ focusDate="2026-10-30"+ min="2026-10-23"+ max="2026-11-22"+ />,+ );+ // min is the first day of Aban: no earlier day is in range.+ expect(screen.getByRole('button', {name: 'Previous month'})).toBeDisabled();+ // max is the first day of Azar: a later day is in range.+ expect(screen.getByRole('button', {name: 'Next month'})).toBeEnabled();+ });++ it('shows ISO 8601 week numbers', () => {+ render(+ <Calendar+ calendar="persian"+ focusDate="2026-10-30"+ weekStartsOn="mon"+ hasWeekNumbers+ />,+ );+ const row = dayButton('2026-10-30').closest('[role="row"]');+ expect(row?.querySelector('[role="rowheader"]')?.textContent).toBe('44');+ });++ it('writes day numbers and labels in the locale', () => {+ render(+ <InternationalizationProvider locale="fa-IR" calendar="persian">+ <Calendar focusDate="2026-10-30" />+ </InternationalizationProvider>,+ );+ expect(dayButton('2026-10-30')).toHaveTextContent(/^۸$/);+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'آبان',+ );+ });+});++describe('Calendar in the Hebrew calendar', () => {+ it('shows Adar I and Adar II as distinct months of a leap year', async () => {+ const user = userEvent.setup();+ render(<Calendar calendar="hebrew" focusDate="2024-02-20" />);+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'Adar I 5784',+ );+ expect(inMonthDates(screen.getByRole('grid'))).toHaveLength(30);+ await user.click(screen.getByRole('button', {name: 'Next month'}));+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'Adar II 5784',+ );+ expect(inMonthDates(screen.getByRole('grid'))).toHaveLength(29);+ });++ it('steps a year from Adar I to Adar with Shift+PageDown, clamped', async () => {+ const user = userEvent.setup();+ // 30 Adar I 5784; 5785 has no Adar I, and its Adar has 29 days.+ render(<Calendar calendar="hebrew" defaultValue="2024-03-10" />);+ dayButton('2024-03-10').focus();+ await user.keyboard('{Shift>}{PageDown}{/Shift}');+ await waitFor(() => expect(focusedDate()).toBe('2025-03-29'));+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'Adar 5785',+ );+ });+});++describe('Calendar in the Ethiopic calendar', () => {+ it('keeps six rows for the five-day thirteenth month', () => {+ render(<Calendar calendar="ethiopic" focusDate="2026-09-08" />);+ const grid = screen.getByRole('grid');+ expect(grid.getAttribute('aria-label')).toContain('Pagumen 2018');+ expect(inMonthDates(grid)).toEqual([+ '2026-09-06',+ '2026-09-07',+ '2026-09-08',+ '2026-09-09',+ '2026-09-10',+ ]);+ expect(within(grid).getAllByRole('gridcell')).toHaveLength(42);+ });++ it('gives the thirteenth month only its rows with hasVariableRowCount', () => {+ render(+ <Calendar+ calendar="ethiopic"+ focusDate="2026-09-08"+ hasVariableRowCount+ />,+ );+ // 2026-09-06 is a Sunday, so the five days fill one row.+ expect(+ within(screen.getByRole('grid')).getAllByRole('gridcell'),+ ).toHaveLength(7);+ });++ it('steps a year to the same month with Shift+PageUp', async () => {+ const user = userEvent.setup();+ // 1 Meskerem 2019 → 1 Meskerem 2018.+ render(<Calendar calendar="ethiopic" defaultValue="2026-09-11" />);+ dayButton('2026-09-11').focus();+ await user.keyboard('{Shift>}{PageUp}{/Shift}');+ await waitFor(() => expect(focusedDate()).toBe('2025-09-11'));+ });+});++interface TestPlainDate {+ readonly year: number;+ readonly month: number;+ readonly day: number;+ readonly daysInMonth: number;+ with(fields: {day: number}): TestPlainDate;+ add(duration: object): TestPlainDate;+ subtract(duration: object): TestPlainDate;+ withCalendar(calendar: string): TestPlainDate;+}++type TestPlainDateConstructor = new (+ isoYear: number,+ isoMonth: number,+ isoDay: number,+ calendar: string,+) => TestPlainDate;++/**+ * Runs `run` with a Temporal whose Chinese calendar is one day ahead of+ * Intl's, as native Temporal is at some month starts, such as 2027-02-06.+ */+function withChineseTemporalAheadOfIntl(run: () => void) {+ const globals = globalThis as unknown as {+ Temporal: {PlainDate: TestPlainDateConstructor};+ };+ const real = globals.Temporal;+ const shift = (inner: TestPlainDate): TestPlainDate => ({+ year: inner.year,+ month: inner.month,+ day: inner.day,+ daysInMonth: inner.daysInMonth,+ with: fields => shift(inner.with(fields)),+ add: duration => shift(inner.add(duration)),+ subtract: duration => shift(inner.subtract(duration)),+ withCalendar: calendar => inner.withCalendar(calendar).subtract({days: 1}),+ });+ function PlainDate(y: number, m: number, d: number, calendar: string) {+ return calendar === 'chinese'+ ? shift(+ new real.PlainDate(y, m, d, 'iso8601')+ .add({days: 1})+ .withCalendar('chinese'),+ )+ : new real.PlainDate(y, m, d, calendar);+ }+ globals.Temporal = {+ PlainDate: PlainDate as unknown as TestPlainDateConstructor,+ };+ try {+ run();+ } finally {+ globals.Temporal = real;+ }+}++describe('Calendar in the Chinese calendar', () => {+ it('names each day by the month and day the grid shows when Intl disagrees', () => {+ withChineseTemporalAheadOfIntl(() => {+ render(<Calendar calendar="chinese" focusDate="2027-02-06" />);+ // Intl alone calls this day "Saturday, Twelfth Month 30, 2026".+ expect(dayButton('2027-02-06')).toHaveTextContent(/^1$/);+ expect(dayButton('2027-02-06').getAttribute('aria-label')).toMatch(+ /^Saturday, First Month 1, 2027/,+ );+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'First Month',+ );+ // A day inside the month keeps Intl's own label.+ expect(dayButton('2027-02-20').getAttribute('aria-label')).toMatch(+ /^Saturday, First Month 15, 2027/,+ );+ });+ });+});++describe('Calendar in the Japanese calendar', () => {+ it('names the era of each month', async () => {+ const user = userEvent.setup();+ render(<Calendar calendar="japanese" focusDate="2019-04-30" />);+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'Heisei',+ );+ await user.click(screen.getByRole('button', {name: 'Next month'}));+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ 'Reiwa',+ );+ });+});++describe('Calendar year paging in the Gregorian calendar', () => {+ it('moves to the same day a year away with Shift+PageUp and Shift+PageDown', async () => {+ const user = userEvent.setup();+ render(<Calendar defaultValue="2026-06-15" />);+ dayButton('2026-06-15').focus();+ await user.keyboard('{Shift>}{PageUp}{/Shift}');+ await waitFor(() => expect(focusedDate()).toBe('2025-06-15'));+ await user.keyboard('{Shift>}{PageDown}{/Shift}');+ await waitFor(() => expect(focusedDate()).toBe('2026-06-15'));+ });++ it('clamps February 29 to February 28', async () => {+ const user = userEvent.setup();+ render(<Calendar defaultValue="2024-02-29" />);+ dayButton('2024-02-29').focus();+ await user.keyboard('{Shift>}{PageDown}{/Shift}');+ await waitFor(() => expect(focusedDate()).toBe('2025-02-28'));+ });++ it('changes nothing when the year target lies past max', async () => {+ const user = userEvent.setup();+ render(<Calendar defaultValue="2026-06-15" max="2027-01-31" />);+ dayButton('2026-06-15').focus();+ await user.keyboard('{Shift>}{PageDown}{/Shift}');+ expect(focusedDate()).toBe('2026-06-15');+ });+});++describe('date inputs under a provider calendar', () => {+ // Their field text is Gregorian, so their popover calendars stay Gregorian.+ it.each([+ [+ 'DateInput',+ <DateInput key="d" label="Date" value="2026-10-30" onChange={() => {}} />,+ ],+ [+ 'DateTimeInput',+ <DateTimeInput+ key="dt"+ label="When"+ value={'2026-10-30T09:00' as ISODateTimeString}+ 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');+ });+});diff --git a/packages/core/src/Calendar/Calendar.doc.mjs b/packages/core/src/Calendar/Calendar.doc.mjsindex b7005104f4..8277a403fd 100644--- a/packages/core/src/Calendar/Calendar.doc.mjs+++ b/packages/core/src/Calendar/Calendar.doc.mjs@@ -169,13 +169,15 @@ export const docs = {{name: 'hasWeekNumbers',type: 'boolean',- description: 'Show ISO week numbers.',+ description:+ 'Show ISO 8601 week numbers. They are ISO 8601 week numbers in every calendar system.',default: 'false',},{name: 'hasVariableRowCount',type: 'boolean',- description: 'Variable vs fixed 6-row grid.',+ description:+ 'Give each month only the rows it needs. The default fixed 6-row grid keeps the same height from month to month; a variable row count trades that fixed height for a more compact grid.',default: 'false',},{@@ -185,6 +187,13 @@ export const docs = {'First day of week. Accepts a number (0=Sunday) or a three-letter day name (e.g. "mon").',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:+ "Calendar system the grid shows, such as 'persian', 'hebrew', or 'islamic-umalqura'. It sets the months, their names, and month and year navigation. value, min, max, focusDate, and every callback stay Gregorian ISO dates. Calendars other than gregory, iso8601, buddhist, roc, and japanese need Temporal; where the runtime lacks it, load a polyfill such as temporal-polyfill/full/global on the server and in the browser, or the grid shows Gregorian months. Month starts in the Chinese and Dangi calendars come from the runtime's Temporal, and some polyfills start a few months one day apart from native Temporal; when you render on the server, load the same Temporal implementation on the server and in the browser.",+ default: 'the InternationalizationProvider calendar, else gregory',+ },],theming: {targets: [@@ -311,13 +320,14 @@ export const docsZh = {{name: 'hasWeekNumbers',type: 'boolean',- description: '显示 ISO 周数。',+ description: '显示 ISO 8601 周数。在任何历法中都是 ISO 8601 周数。',default: 'false',},{name: 'hasVariableRowCount',type: 'boolean',- description: '可变行数与固定 6 行网格。',+ description:+ '每个月只显示所需的行数。默认的固定 6 行网格使每个月高度相同;可变行数以固定高度换取更紧凑的网格。',default: 'false',},{@@ -327,6 +337,13 @@ export const docsZh = {'每周起始日。可为数字(0=周日)或三字母星期缩写(如 "mon")。',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:+ "网格显示的历法,如 'persian'、'hebrew' 或 'islamic-umalqura'。它决定月份、月份名称以及按月和按年的导航。value、min、max、focusDate 和所有回调仍为公历 ISO 日期。gregory、iso8601、buddhist、roc 和 japanese 以外的历法需要 Temporal;运行环境没有 Temporal 时,请在服务端和浏览器中加载 polyfill(如 temporal-polyfill/full/global),否则网格显示公历月份。农历(chinese)和檀纪历(dangi)的月初取自运行环境的 Temporal,部分 polyfill 与原生 Temporal 有少数月份的月初相差一天;服务端渲染时,请在服务端和浏览器中加载同一种 Temporal 实现。",+ default: 'InternationalizationProvider 的历法,否则为 gregory',+ },],theming: {targets: [@@ -400,8 +417,11 @@ export const docsDense = {onFocusDateChange: 'navigation callback',handleRef: 'imperative navigation handle',hasOutsideDays: 'show days from adjacent months',- hasWeekNumbers: 'show ISO week numbers',- hasVariableRowCount: 'variable vs fixed 6-row grid',+ hasWeekNumbers: 'show ISO 8601 week numbers, in every calendar system',+ hasVariableRowCount:+ 'only the rows each month needs; trades the fixed 6-row height for a compact grid',weekStartsOn: 'first day of week (0=Sunday, or name e.g. "mon")',+ calendar:+ 'calendar system shown (default: provider calendar, else gregory); values stay Gregorian ISO; non-Gregorian-aligned calendars need Temporal',},};diff --git a/packages/core/src/Calendar/Calendar.ssr.test.tsx b/packages/core/src/Calendar/Calendar.ssr.test.tsxnew file mode 100644index 0000000000..7a57bc15ed--- /dev/null+++ b/packages/core/src/Calendar/Calendar.ssr.test.tsx@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Calendar.ssr.test.tsx+ * @input Calendar server markup and React hydration under a provider calendar+ * @output Proves a Persian Calendar hydrates without an error when the server+ * and the browser both have Temporal or both lack it, and that a server+ * without Temporal disagrees with a browser that has it+ * @position SSR acceptance test for Calendar calendar systems+ */++import 'temporal-polyfill/full/global';+import {act} from 'react';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {Calendar} from './Calendar';+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';+import {__resetDevWarnings} from '../utils/devWarning';++const globals = globalThis as {Temporal?: unknown};+const temporal = globals.Temporal;++afterEach(() => {+ globals.Temporal = temporal;+ __resetDevWarnings();+ vi.restoreAllMocks();+ document.body.replaceChildren();+});++const tree = (+ <InternationalizationProvider locale="en" calendar="persian">+ <Calendar focusDate="2026-10-30" />+ </InternationalizationProvider>+);++function setTemporal(isPresent: boolean) {+ if (isPresent) {+ globals.Temporal = temporal;+ } else {+ delete globals.Temporal;+ }+}++async function serverThenHydrate(server: boolean, browser: boolean) {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ setTemporal(server);+ const container = document.createElement('div');+ container.innerHTML = renderToString(tree);+ const serverLabel = container+ .querySelector('[role="grid"]')+ ?.getAttribute('aria-label');+ document.body.appendChild(container);++ setTemporal(browser);+ const consoleErrors = vi.spyOn(console, 'error').mockImplementation(() => {});+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree, {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });+ const browserLabel = container+ .querySelector('[role="grid"]')+ ?.getAttribute('aria-label');+ const errors = [...recoverableErrors, ...consoleErrors.mock.calls];+ act(() => root.unmount());+ return {serverLabel, browserLabel, errors};+}++describe('Calendar server render and hydration in the Persian calendar', () => {+ it('hydrates without an error when both sides have Temporal', async () => {+ const result = await serverThenHydrate(true, true);+ expect(result.serverLabel).toBe('Aban 1405 AP');+ expect(result.browserLabel).toBe('Aban 1405 AP');+ expect(result.errors).toEqual([]);+ });++ it('hydrates without an error when both sides lack Temporal', async () => {+ const result = await serverThenHydrate(false, false);+ expect(result.serverLabel).toBe('October 2026');+ expect(result.browserLabel).toBe('October 2026');+ expect(result.errors).toEqual([]);+ });++ it('does not match when only the browser has Temporal', async () => {+ const result = await serverThenHydrate(false, true);+ expect(result.serverLabel).toBe('October 2026');+ expect(result.browserLabel).toBe('Aban 1405 AP');+ expect(result.errors).not.toEqual([]);+ });+});diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsxindex 18f69f4b78..5ee3b9eb37 100644--- a/packages/core/src/Calendar/Calendar.tsx+++ b/packages/core/src/Calendar/Calendar.tsx@@ -31,11 +31,8 @@ import * as stylex from '@stylexjs/stylex';import {Button} from '../Button';import {Icon} from '../Icon';import {useAnnounce, useGridFocus} from '../hooks';-import {- useCalendarDays,- useCalendarConstraints,- type CalendarDay,-} from './hooks';+import {useCalendarConstraints, type CalendarDay} from './hooks';+import {useCalendarMonthDays} from './hooks/useCalendarDays';import {calendarStyles,monthGridStyles,@@ -48,23 +45,27 @@ import {plainDateToISO,plainDateToDate,plainDateToday,- plainDateSetFirstOfMonth,- plainDateAddMonths,plainDateAddDays,plainDateDiffDays,- getDaysInMonth,plainDateIsAfter,plainDateIsBefore,plainDateIsEqual,plainDateGetWeekNumber,- plainDateFormat,plainDateWeekFieldName,+ plainDateFormatDayNumber,DATE_FORMAT_WITH_WEEKDAY,} from '../utils/plainDate';import {- plainDateFormatDayNumber,- plainDateFormatStandaloneMonthYear,-} from '../utils/plainDate';+ type CalendarMonth,+ type CalendarSystem,+ calendarAddMonths,+ calendarMonthOf,+ calendarShiftMonths,+ calendarShiftYears,+ formatCalendarDate,+ formatCalendarMonthLabel,+ isInCalendarMonth,+} from '../utils/calendarSystem';import {mergeProps, composeEventHandlers, rtlStyles} from '../utils';import {focusOutlineProps} from '../utils/focusOutline.stylex';import {interactionOverlayStyles} from '../utils/interactionOverlay.stylex';@@ -99,6 +100,7 @@ import type {import {normalizeDayOfWeek} from '../utils/dateTypes';import {themeProps} from '../utils/themeProps';import {useLocale} from '../i18n';+import {useCalendarSystem} from '../i18n/useCalendarSystem';import {VisuallyHidden} from '../VisuallyHidden';import {registerEnglishFallback,@@ -108,7 +110,7 @@ import english from '../i18n/generated-english/Calendar/Calendar.generated';registerEnglishFallback(english);-/** How a month navigation moves the focused day: by its row offset in days, or by whole months or years. */+/** How a month navigation moves the focused day: by its row offset in days, or by whole calendar months or years. */type NavigationUnit = 'days' | 'months' | 'years';/** Imperative handle for Calendar handleRef */@@ -181,13 +183,15 @@ interface CalendarBaseProps extends Omit<hasOutsideDays?: boolean;/**- * Show ISO week numbers in a side column.+ * Show ISO 8601 week numbers in a side column. They are ISO 8601 week+ * numbers in every calendar system.* Default: false*/hasWeekNumbers?: boolean;/**- * Use variable rows per month vs. fixed 6-row grid.+ * Give each month only the rows it needs instead of a fixed 6-row grid.+ * The fixed grid keeps the same height from month to month.* Default: false (fixed 6 rows for consistent height)*/hasVariableRowCount?: boolean;@@ -198,6 +202,16 @@ interface CalendarBaseProps extends Omit<* Default: 0 (Sunday)*/weekStartsOn?: DayOfWeek | DayOfWeekName;++ /**+ * The calendar system the grid shows, such as `'persian'` or `'hebrew'`.+ * It sets the months, their labels, and month and year navigation. `value`,+ * `min`, `max`, `focusDate`, and every callback stay Gregorian ISO dates.+ * Default: the `InternationalizationProvider` calendar, else Gregorian.+ * Calendars other than `gregory`, `iso8601`, `buddhist`, `roc`, and+ * `japanese` need `Temporal`; without it the grid shows Gregorian months.+ */+ calendar?: CalendarSystem;}// ─── Mode-specific Props (discriminated union) ────────────────@@ -232,14 +246,12 @@ interface CalendarRangeProps extends CalendarBaseProps {export type CalendarProps = CalendarSingleProps | CalendarRangeProps;-/** The first day of `month`'s month that `isDisabled` allows, or null. */function firstEnabledDayOfMonth(- month: PlainDate,+ month: CalendarMonth,isDisabled: (pd: PlainDate) => boolean,): PlainDate | null {- const days = getDaysInMonth(month.year, month.month);- for (let day = 1; day <= days; day += 1) {- const pd = {year: month.year, month: month.month, day};+ for (let offset = 0; offset < month.length; offset += 1) {+ const pd = plainDateAddDays(month.start, offset);if (!isDisabled(pd)) {return pd;}@@ -247,6 +259,15 @@ function firstEnabledDayOfMonth(return null;}+/** A day's full label, such as "Friday, Aban 8, 1405 AP", in the calendar. */+function formatDateLabel(+ date: PlainDate,+ calendar: CalendarSystem,+ locale: string,+): string {+ return formatCalendarDate(calendar, date, DATE_FORMAT_WITH_WEEKDAY, locale);+}+// =============================================================================// Main Component// =============================================================================@@ -280,12 +301,14 @@ export function Calendar({ref, ...props}: CalendarProps) {hasWeekNumbers = false,hasVariableRowCount = false,weekStartsOn: weekStartsOnProp = 0,+ calendar: calendarProp,xstyle,className,style,onKeyDown,...rest} = props;+ const calendar = useCalendarSystem(calendarProp, 'Calendar');// Normalize `weekStartsOn` (number or three-letter day name) to a numeric// DayOfWeek so all downstream date math keeps working with an index.@@ -329,6 +352,7 @@ export function Calendar({ref, ...props}: CalendarProps) {max,numberOfMonths,today,+ calendar,}),);@@ -354,17 +378,21 @@ export function Calendar({ref, ...props}: CalendarProps) {[isControlledFocus, onFocusDateChange],);- // Base month (first day of focus month)- const baseMonth = useMemo(() => {- return plainDateSetFirstOfMonth(focusDate);- }, [focusDate]);+ // A controlled focus date is a new object on each render. Key the memo on+ // its ISO string.+ const focusIso = plainDateToISO(focusDate);+ const baseMonth = useMemo(+ () => calendarMonthOf(calendar, plainDateFromISO(focusIso)),+ [calendar, focusIso],+ );// Generate visible monthsconst visibleMonths = useMemo(() => {return Array.from({length: numberOfMonths}, (_, i) => {- return plainDateAddMonths(baseMonth, i);+ return calendarAddMonths(calendar, baseMonth, i);});- }, [baseMonth, numberOfMonths]);+ }, [calendar, baseMonth, numberOfMonths]);+ const lastVisibleMonth = visibleMonths[visibleMonths.length - 1];// A pending target is claimed by the grid that shows its month, or dropped// by the next focus move that is not onto the target day: when a controlled@@ -378,9 +406,7 @@ export function Calendar({ref, ...props}: CalendarProps) {return null;}const target = plainDateFromISO(pendingFocus);- return visibleMonths.some(- pd => pd.year === target.year && pd.month === target.month,- )+ return visibleMonths.some(month => isInCalendarMonth(target, month))? pendingFocus: null;}, [pendingFocus, visibleMonths]);@@ -405,9 +431,9 @@ export function Calendar({ref, ...props}: CalendarProps) {const monthYearLabel = useMemo(() =>visibleMonths- .map(m => plainDateFormatStandaloneMonthYear(m, locale))+ .map(m => formatCalendarMonthLabel(calendar, m, locale)).join(' – '),- [visibleMonths, locale],+ [calendar, visibleMonths, locale],);// Announce the newly visible month to screen readers whenever it changes.@@ -439,31 +465,13 @@ export function Calendar({ref, ...props}: CalendarProps) {[max],);- const canNavigatePrevious = useMemo(() => {- if (!min) {- return true;- }- const minDate = plainDateFromISO(min);- // Can't go back if min is in the current focus month- return (- minDate.year < baseMonth.year ||- (minDate.year === baseMonth.year && minDate.month < baseMonth.month)- );- }, [min, baseMonth]);-- const canNavigateNext = useMemo(() => {- if (!max) {- return true;- }- const maxDate = plainDateFromISO(max);- // Check against the last visible month, not just baseMonth- const lastVisibleMonth = plainDateAddMonths(baseMonth, numberOfMonths - 1);- return (- maxDate.year > lastVisibleMonth.year ||- (maxDate.year === lastVisibleMonth.year &&- maxDate.month > lastVisibleMonth.month)- );- }, [max, baseMonth, numberOfMonths]);+ // A month button is available while a day past the shown months is in range.+ const canNavigatePrevious =+ minDateForKeys == null ||+ plainDateIsBefore(minDateForKeys, baseMonth.start);+ const canNavigateNext =+ maxDateForKeys == null ||+ plainDateIsAfter(maxDateForKeys, lastVisibleMonth.end);// Navigation handlers// The same constraint view the grids use, so a key can resolve its target@@ -491,10 +499,6 @@ export function Calendar({ref, ...props}: CalendarProps) {offset?: number,unit: NavigationUnit = 'days',) => {- const monthIndex = (pd: PlainDate) => pd.year * 12 + pd.month;- const firstShown = monthIndex(baseMonth);- const lastShown = firstShown + numberOfMonths - 1;-// The Previous/Next buttons move the month with no focused day.if (!focusedDate) {if (@@ -503,7 +507,7 @@ export function Calendar({ref, ...props}: CalendarProps) {) {return;}- const newPd = plainDateAddMonths(baseMonth, delta);+ const newPd = calendarAddMonths(calendar, baseMonth, delta).start;if (onFocusDateChange) {onFocusDateChange(plainDateToISO(newPd));} else {@@ -523,19 +527,19 @@ export function Calendar({ref, ...props}: CalendarProps) {!(maxDateForKeys && plainDateIsAfter(pd, maxDateForKeys));let targetPd: PlainDate;if (unit === 'months' || unit === 'years') {- // A page or a year step keeps the day of the month and clamps it to the- // target month's length. A month with no enabled day is no target, the- // same as for an arrow.- const candidate = plainDateAddMonths(- currentPd,- unit === 'years' ? delta * 12 : delta,- );+ // A page or a year step keeps the day of the calendar month and clamps+ // it to the target month's length. A month with no enabled day is no+ // target, the same as for an arrow.+ const candidate =+ unit === 'years'+ ? calendarShiftYears(calendar, currentPd, delta)+ : calendarShiftMonths(calendar, currentPd, delta);if (!inRange(candidate)) {return;}if (isRootDateDisabled(candidate)) {const firstEnabled = firstEnabledDayOfMonth(- candidate,+ calendarMonthOf(calendar, candidate),isRootDateDisabled,);if (firstEnabled == null) {@@ -572,16 +576,15 @@ export function Calendar({ref, ...props}: CalendarProps) {// key's direction, so the target month becomes the first (backwards)// or last (forwards) month shown.const resolved: PlainDate = targetPd;- const targetMonth = monthIndex(resolved);setPendingFocus(plainDateToISO(resolved));- if (targetMonth >= firstShown && targetMonth <= lastShown) {+ const isBeforeShown = plainDateIsBefore(resolved, baseMonth.start);+ if (!isBeforeShown && !plainDateIsAfter(resolved, lastVisibleMonth.end)) {return;}- const targetFirst = {year: resolved.year, month: resolved.month, day: 1};- const newPd =- targetMonth < firstShown- ? targetFirst- : plainDateAddMonths(targetFirst, -(numberOfMonths - 1));+ const targetMonth = calendarMonthOf(calendar, resolved);+ const newPd = isBeforeShown+ ? targetMonth.start+ : calendarAddMonths(calendar, targetMonth, -(numberOfMonths - 1)).start;if (onFocusDateChange) {onFocusDateChange(plainDateToISO(newPd));} else {@@ -590,9 +593,11 @@ export function Calendar({ref, ...props}: CalendarProps) {},[baseMonth,+ calendar,canNavigateNext,canNavigatePrevious,isRootDateDisabled,+ lastVisibleMonth,maxDateForKeys,minDateForKeys,numberOfMonths,@@ -637,7 +642,7 @@ export function Calendar({ref, ...props}: CalendarProps) {setRangeSelectionStart(iso);announce(t('@astryx.calendar.rangeStartAnnounce', {- date: plainDateFormat(date, DATE_FORMAT_WITH_WEEKDAY, locale),+ date: formatDateLabel(date, calendar, locale),}),);} else {@@ -653,7 +658,7 @@ export function Calendar({ref, ...props}: CalendarProps) {setRangeSelectionStart(null);announce(t('@astryx.calendar.rangeClearedAnnounce', {- date: plainDateFormat(date, DATE_FORMAT_WITH_WEEKDAY, locale),+ date: formatDateLabel(date, calendar, locale),}),);return;@@ -679,22 +684,23 @@ export function Calendar({ref, ...props}: CalendarProps) {// swapped {start, end} above even for a reverse pick).announce(t('@astryx.calendar.rangeCompleteAnnounce', {- start: plainDateFormat(- plainDateFromISO(start),- DATE_FORMAT_WITH_WEEKDAY,- locale,- ),- end: plainDateFormat(- plainDateFromISO(end),- DATE_FORMAT_WITH_WEEKDAY,- locale,- ),+ start: formatDateLabel(plainDateFromISO(start), calendar, locale),+ end: formatDateLabel(plainDateFromISO(end), calendar, locale),}),);}}},- [mode, onChange, rangeSelectionStart, minRangeSpan, announce, t, locale],+ [+ mode,+ onChange,+ rangeSelectionStart,+ minRangeSpan,+ announce,+ t,+ locale,+ calendar,+ ],);return (@@ -756,8 +762,9 @@ export function Calendar({ref, ...props}: CalendarProps) {<div {...stylex.props(calendarStyles.monthsContainer)}>{visibleMonths.map(month => (<MonthGrid- key={`${month.year}-${month.month}`}+ key={plainDateToISO(month.start)}month={month}+ calendar={calendar}value={effectiveValue}mode={mode}rangeSelectionStart={rangeSelectionStart}@@ -798,7 +805,8 @@ Calendar.displayName = 'Calendar';// =============================================================================interface MonthGridProps {- month: PlainDate;+ month: CalendarMonth;+ calendar: CalendarSystem;value: ISODateString | DateRange | undefined;mode: 'single' | 'range';rangeSelectionStart: ISODateString | null;@@ -831,6 +839,7 @@ interface MonthGridProps {function MonthGrid({month,+ calendar,value,mode,rangeSelectionStart,@@ -853,12 +862,11 @@ function MonthGrid({onPendingFocusHandled,}: MonthGridProps) {const locale = useLocale();- const year = month.year;// Use hooks for days generation and constraints- const {days, weeks} = useCalendarDays({- year,- month: month.month,+ const {days, weeks} = useCalendarMonthDays({+ month,+ calendar,weekStartsOn,hasVariableRowCount,});@@ -899,15 +907,16 @@ function MonthGrid({// enabled) > today (if visible and enabled) > first enabled in-month day.const seedTabbableIso = useMemo((): ISODateString | null => {if (selectedDateForTabindex) {- const isSelectedInMonth =- selectedDateForTabindex.year === year &&- selectedDateForTabindex.month === month.month;+ const isSelectedInMonth = isInCalendarMonth(+ selectedDateForTabindex,+ month,+ );if (isSelectedInMonth && !isDateDisabled(selectedDateForTabindex)) {return plainDateToISO(selectedDateForTabindex);}}- const isTodayInMonth = today.year === year && today.month === month.month;+ const isTodayInMonth = isInCalendarMonth(today, month);if (isTodayInMonth && !isDateDisabled(today)) {return plainDateToISO(today);}@@ -919,7 +928,7 @@ function MonthGrid({}return null;- }, [days, today, year, month.month, isDateDisabled, selectedDateForTabindex]);+ }, [days, today, month, isDateDisabled, selectedDateForTabindex]);// Helper to get the focused date from the currently focused element.// Reads the machine-readable `data-date` (ISO) attribute rather than parsing@@ -1028,7 +1037,7 @@ function MonthGrid({}const targetPd = plainDateFromISO(pendingFocus);- if (targetPd.year !== year || targetPd.month !== month.month) {+ if (!isInCalendarMonth(targetPd, month)) {return;}const targetIso = plainDateToISO(targetPd);@@ -1063,7 +1072,7 @@ function MonthGrid({targetButton.focus();}onPendingFocusHandled?.();- }, [pendingFocus, gridRef, month.month, onPendingFocusHandled, year]);+ }, [pendingFocus, gridRef, month, onPendingFocusHandled]);// Parse selectionlet selectedDate: PlainDate | null = null;@@ -1103,8 +1112,8 @@ function MonthGrid({// Month label for announcementsconst monthLabel = useMemo(() => {- return plainDateFormatStandaloneMonthYear(month, locale);- }, [month, locale]);+ return formatCalendarMonthLabel(calendar, month, locale);+ }, [calendar, month, locale]);return (<div {...stylex.props(monthGridStyles.monthGrid)}>@@ -1198,6 +1207,7 @@ function MonthGrid({neighbors={neighbors}isTabbable={day.iso === seedTabbableIso}isRangeSelectionInProgress={rangeSelectionStart !== null}+ calendar={calendar}onDayClick={onDayClick}onDayHover={onDayHover}/>@@ -1246,6 +1256,8 @@ interface DayCellProps {* "range start and range end" (rangeStart === rangeEnd in both cases).*/isRangeSelectionInProgress: boolean;+ /** The calendar system that writes the day's accessible name. */+ calendar: CalendarSystem;onDayClick: (date: PlainDate) => void;onDayHover: (date: PlainDate | null) => void;}@@ -1265,6 +1277,7 @@ function DayCell({neighbors,isTabbable: isTabbableDay,isRangeSelectionInProgress,+ calendar,onDayClick,onDayHover,}: DayCellProps) {@@ -1316,7 +1329,7 @@ function DayCell({// params rather than string concatenation. A mid-flight first pick (where// rangeStart === rangeEnd) reads as "range start" only; a completed one-day// range reads as both start and end.- const dateLabel = plainDateFormat(date, DATE_FORMAT_WITH_WEEKDAY, locale);+ const dateLabel = formatDateLabel(date, calendar, locale);const dayLabel = state.isSelected? t('@astryx.calendar.daySelected', {date: dateLabel}): state.isRangeStart && state.isRangeEnddiff --git a/packages/core/src/Calendar/getInitialFocusDate.ts b/packages/core/src/Calendar/getInitialFocusDate.tsindex 63ecbb45d2..a4cffd2cf2 100644--- a/packages/core/src/Calendar/getInitialFocusDate.ts+++ b/packages/core/src/Calendar/getInitialFocusDate.ts@@ -2,7 +2,7 @@/*** @file getInitialFocusDate.ts- * @input PlainDate utilities, min/max bounds, today+ * @input PlainDate and calendar-system utilities, min/max bounds, today* @output Exports getInitialFocusDate — the month Calendar opens on* @position Calendar-specific helper; used by Calendar.tsx*@@ -15,11 +15,14 @@ import type {ISODateString, DateRange} from '../utils/dateTypes';import {type PlainDate,plainDateFromISO,- plainDateSetFirstOfMonth,- plainDateAddMonths,plainDateIsBefore,plainDateIsAfter,} from '../utils/plainDate';+import {+ type CalendarSystem,+ calendarAddMonths,+ calendarMonthOf,+} from '../utils/calendarSystem';export interface InitialFocusDateOptions {/** Controlled visible month, if the consumer supplied one. */@@ -34,6 +37,8 @@ export interface InitialFocusDateOptions {numberOfMonths: number;/** Today, injected so the caller keeps a single memoized source of "now". */today: PlainDate;+ /** The calendar system whose months the panes show. Default: `gregory`. */+ calendar?: CalendarSystem;}/**@@ -57,7 +62,15 @@ export interface InitialFocusDateOptions {export function getInitialFocusDate(options: InitialFocusDateOptions,): PlainDate {- const {focusDate, value, min, max, numberOfMonths, today} = options;+ const {+ focusDate,+ value,+ min,+ max,+ numberOfMonths,+ today,+ calendar = 'gregory',+ } = options;if (focusDate) {return plainDateFromISO(focusDate);@@ -76,13 +89,14 @@ export function getInitialFocusDate(if (maxDate && plainDateIsAfter(today, maxDate)) {const lastPaneOffset = Math.max(0, numberOfMonths - 1);- const shifted = plainDateAddMonths(- plainDateSetFirstOfMonth(maxDate),+ const shifted = calendarAddMonths(+ calendar,+ calendarMonthOf(calendar, maxDate),-lastPaneOffset,- );+ ).start;if (minDate &&- plainDateIsBefore(shifted, plainDateSetFirstOfMonth(minDate))+ plainDateIsBefore(shifted, calendarMonthOf(calendar, minDate).start)) {return minDate;}diff --git a/packages/core/src/Calendar/hooks/useCalendarDays.ts b/packages/core/src/Calendar/hooks/useCalendarDays.tsindex ac9b7799c1..3d6e7c72c8 100644--- a/packages/core/src/Calendar/hooks/useCalendarDays.ts+++ b/packages/core/src/Calendar/hooks/useCalendarDays.ts@@ -4,9 +4,11 @@/*** @file useCalendarDays.ts- * @input Uses React useMemo, useLocale, PlainDate utilities, generated CLDR weekday data- * @output Exports useCalendarDays hook for generating calendar day grids- * @position Calendar-specific hook; used by Calendar+ * @input Uses React useMemo, useLocale, PlainDate and calendar-system+ * utilities, generated CLDR weekday data+ * @output Exports useCalendarDays (a Gregorian month) and useCalendarMonthDays+ * (a month of any calendar system) for generating calendar day grids+ * @position Calendar-specific hooks; useCalendarMonthDays is used by Calendar** SYNC: When modified, update:* - /packages/core/src/Calendar/hooks/index.ts@@ -23,6 +25,11 @@ import {} from '../../utils/plainDate';import {useLocale} from '../../i18n';import {getWeekdayHeaderNames} from '../getWeekdayHeaderNames';+import {+ type CalendarMonth,+ type CalendarSystem,+ calendarDayOfMonth,+} from '../../utils/calendarSystem';/*** Represents a single day in the calendar grid.@@ -86,65 +93,107 @@ export function useCalendarDays(options: UseCalendarDaysOptions,): UseCalendarDaysReturn {const {year, month, weekStartsOn = 0, hasVariableRowCount = false} = options;- const locale = useLocale();+ const days = useMemo(+ () =>+ layOutMonthDays({+ first: {year, month, day: 1},+ length: getDaysInMonth(year, month),+ weekStartsOn,+ hasVariableRowCount,+ dayNumberOf: pd => pd.day,+ }),+ [year, month, weekStartsOn, hasVariableRowCount],+ );+ return useMonthGrid(days, weekStartsOn);+}- // Calculate grid structure- const gridInfo = useMemo(() => {- const totalDaysInMonth = getDaysInMonth(year, month);+/** Configuration for the day grid of one month of a calendar system. */+export interface UseCalendarMonthDaysOptions {+ /** The month to lay out, located by its Gregorian days. */+ month: CalendarMonth;+ /** The calendar system the month belongs to; it numbers the days. */+ calendar: CalendarSystem;+ /** First day of week (0=Sunday through 6=Saturday) */+ weekStartsOn?: DayOfWeek;+ /** Use variable rows per month vs. fixed 6-row grid */+ hasVariableRowCount?: boolean;+}- // Calculate starting offset based on weekStartsOn- let startingDayOfWeek =- plainDateDayOfWeek({year, month, day: 1}) - weekStartsOn;- if (startingDayOfWeek < 0) {- startingDayOfWeek += 7;- }+/**+ * The day grid of one month of any calendar system. Each day keeps its+ * Gregorian date; `dayNumber` is its day of the calendar month. Internal to+ * Calendar.+ */+export function useCalendarMonthDays(+ options: UseCalendarMonthDaysOptions,+): UseCalendarDaysReturn {+ const {+ month,+ calendar,+ weekStartsOn = 0,+ hasVariableRowCount = false,+ } = options;+ const days = useMemo(+ () =>+ layOutMonthDays({+ first: month.start,+ length: month.length,+ weekStartsOn,+ hasVariableRowCount,+ dayNumberOf: (pd, offset) =>+ offset >= 0 && offset < month.length+ ? offset + 1+ : calendarDayOfMonth(calendar, pd),+ }),+ [month, calendar, weekStartsOn, hasVariableRowCount],+ );+ return useMonthGrid(days, weekStartsOn);+}- // Calculate total cells- const totalDays = totalDaysInMonth + startingDayOfWeek;- const totalRows = hasVariableRowCount ? Math.ceil(totalDays / 7) : 6;- const totalCells = totalRows * 7;+interface MonthLayout {+ first: PlainDate;+ length: number;+ weekStartsOn: DayOfWeek;+ hasVariableRowCount: boolean;+ /** The day number of a grid day, given its offset from the month's first day. */+ dayNumberOf: (pd: PlainDate, offset: number) => number;+}- return {- daysInMonth: totalDaysInMonth,- startingDayOfWeek,- totalCells,- };- }, [year, month, weekStartsOn, hasVariableRowCount]);+function layOutMonthDays(layout: MonthLayout): CalendarDay[] {+ const {first, length, weekStartsOn, hasVariableRowCount, dayNumberOf} =+ layout;+ let startingDayOfWeek = plainDateDayOfWeek(first) - weekStartsOn;+ if (startingDayOfWeek < 0) {+ startingDayOfWeek += 7;+ }+ const totalRows = hasVariableRowCount+ ? Math.ceil((length + startingDayOfWeek) / 7)+ : 6;+ const result: CalendarDay[] = [];+ for (let i = 0; i < totalRows * 7; i++) {+ const offset = i - startingDayOfWeek;+ const pd = plainDateAddDays(first, offset);+ result.push({+ date: pd,+ iso: plainDateToISO(pd),+ isOutside: offset < 0 || offset >= length,+ dayNumber: dayNumberOf(pd, offset),+ });+ }+ return result;+}++function useMonthGrid(+ days: CalendarDay[],+ weekStartsOn: DayOfWeek,+): UseCalendarDaysReturn {+ const locale = useLocale();const dayNames = useMemo(() => getWeekdayHeaderNames(locale, weekStartsOn),[locale, weekStartsOn],);- // Generate days array- const days = useMemo(() => {- const {- daysInMonth: totalDaysInMonth,- startingDayOfWeek,- totalCells,- } = gridInfo;- const firstOfMonth: PlainDate = {year, month, day: 1};- const result: CalendarDay[] = [];-- for (let i = 0; i < totalCells; i++) {- const dayOffset = i - startingDayOfWeek + 1;- const isOutside = dayOffset < 1 || dayOffset > totalDaysInMonth;- const pd: PlainDate = isOutside- ? plainDateAddDays(firstOfMonth, dayOffset - 1)- : {year, month, day: dayOffset};-- result.push({- date: pd,- iso: plainDateToISO(pd),- isOutside,- dayNumber: pd.day,- });- }-- return result;- }, [year, month, gridInfo]);-- // Group days into weeksconst weeks = useMemo(() => {const result: CalendarDay[][] = [];for (let i = 0; i < days.length; i += 7) {@@ -153,10 +202,5 @@ export function useCalendarDays(return result;}, [days]);- return {- days,- weeks,- dayNames,- totalCells: gridInfo.totalCells,- };+ return {days, weeks, dayNames, totalCells: days.length};}diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsxindex 5ddccca198..ef88660bbf 100644--- a/packages/core/src/DateInput/DateInput.tsx+++ b/packages/core/src/DateInput/DateInput.tsx@@ -1030,6 +1030,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}mode="single"value={optimisticValue ?? null}diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsxindex 7b062c33e6..64b642752f 100644--- a/packages/core/src/DateRangeInput/DateRangeInput.tsx+++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx@@ -910,6 +910,8 @@ 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"mode="range"value={optimisticValue}onChange={handleRangeSelect}diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsxindex 909c04ff75..b76d9d9723 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx@@ -1976,6 +1976,8 @@ 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}mode="single"value={valueParts.date ?? null}diff --git a/packages/core/src/i18n/InternationalizationContext.ts b/packages/core/src/i18n/InternationalizationContext.tsindex 3372813fb7..11a0650c2b 100644--- a/packages/core/src/i18n/InternationalizationContext.ts+++ b/packages/core/src/i18n/InternationalizationContext.ts@@ -31,7 +31,7 @@ export interface InternationalizationContextValue {locale: Locale;direction: 'ltr' | 'rtl';/**- * The provider's resolved calendar system. A context without it means+ * The provider's requested calendar system. A context without it means* Gregorian dates.*/calendar?: CalendarSystem;diff --git a/packages/core/src/i18n/InternationalizationProvider.doc.mjs b/packages/core/src/i18n/InternationalizationProvider.doc.mjsindex 8325e353c8..e66f4afd40 100644--- a/packages/core/src/i18n/InternationalizationProvider.doc.mjs+++ b/packages/core/src/i18n/InternationalizationProvider.doc.mjs@@ -26,7 +26,7 @@ export const docs = {name: 'Provider boundary',required: true,description:- 'A nonvisual context boundary that supplies locale, message catalogs, overrides, direction, and a resolved calendar system to descendant Astryx components. It renders no DOM element.',+ 'A nonvisual context boundary that supplies locale, message catalogs, overrides, and direction to descendant Astryx components, and a calendar system to `Calendar`. It renders no DOM element.',},],bestPractices: [@@ -53,7 +53,7 @@ export const docs = {{guidance: true,description:- 'Set `calendar` to select the calendar system of the subtree. A locale never selects the calendar: `fa-IR` resolves to Gregorian until you set `calendar="persian"`, and a `-u-ca-` keyword in `locale`, as in `th-TH-u-ca-buddhist`, keeps Gregorian dates too. Astryx date components show Gregorian dates, and date values stay Gregorian ISO strings.',+ 'Set `calendar` to show `Calendar` in another calendar system; `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.',},{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'. The provider resolves it and exposes it on the context as `calendar`; Astryx date components 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. 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`, a date component that resolves it shows Gregorian dates and warns in development. Load a polyfill such as `temporal-polyfill/full/global` on the server and in the browser.",+ "Calendar system that `Calendar` in the subtree shows, such as 'persian', 'hebrew', or 'buddhist'. `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`, `Calendar` shows Gregorian dates and warns in development. Load a polyfill such as `temporal-polyfill/full/global` on the server and in the browser.",},{name: 'children',@@ -139,7 +139,7 @@ export function AppI18n({children}: {children: ReactNode}) {}`,},{- label: 'Select the Persian calendar',+ label: 'Show Calendar in the Persian calendar',code: `import type {ReactNode} from 'react';import {InternationalizationProvider} from '@astryxdesign/core/i18n';@@ -217,6 +217,6 @@ export const docsDense = {overrides:'sparse per-locale key overrides applied on top of shipped defaults',calendar:- 'calendar system the provider resolves and exposes on the context; date components show 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; 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',},};diff --git a/packages/core/src/i18n/InternationalizationProvider.tsx b/packages/core/src/i18n/InternationalizationProvider.tsxindex 87d069fd96..503ae53c66 100644--- a/packages/core/src/i18n/InternationalizationProvider.tsx+++ b/packages/core/src/i18n/InternationalizationProvider.tsx@@ -105,15 +105,14 @@ export interface InternationalizationProviderProps {*/dir?: 'ltr' | 'rtl';/**- * The calendar system of this subtree, such as `'persian'` or `'hebrew'`. The- * provider resolves it and exposes it on the context as `calendar`. Astryx- * date components show Gregorian dates. 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. Calendars other than- * `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese` need `Temporal`.- * The context keeps the requested calendar; where `Temporal` is missing, a- * date component that resolves it shows Gregorian dates and warns once in- * development.+ * The calendar system that `Calendar` in this subtree shows, such as+ * `'persian'` or `'hebrew'`. The date inputs show Gregorian dates. 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+ * other than `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese` need+ * `Temporal`. The context keeps the requested calendar; where `Temporal` is+ * missing, `Calendar` shows Gregorian dates and warns once in development.** @example* ```diff --git a/packages/core/src/i18n/__tests__/calendarSystem.test.tsx b/packages/core/src/i18n/__tests__/calendarSystem.test.tsxindex 289f6ece4e..ae57ddcca2 100644--- a/packages/core/src/i18n/__tests__/calendarSystem.test.tsx+++ b/packages/core/src/i18n/__tests__/calendarSystem.test.tsx@@ -2,18 +2,19 @@/*** @file calendarSystem.test.tsx- * @input InternationalizationProvider, useCalendarSystem+ * @input InternationalizationProvider, useCalendarSystem, Calendar* @output Tests for calendar resolution and the fallback without Temporal* @position Runs without a Temporal polyfill, as an application that loads* none does; the Gregorian-aligned calendars need no Temporal.*/import {afterAll, afterEach, beforeAll, describe, expect, it, vi} from 'vitest';-import {render} from '@testing-library/react';+import {render, screen} from '@testing-library/react';import {use} from 'react';import {InternationalizationProvider} from '../InternationalizationProvider';import {InternationalizationContext} from '../InternationalizationContext';import {useCalendarSystem} from '../useCalendarSystem';+import {Calendar} from '../../Calendar/Calendar';import {CALENDAR_SYSTEMS,type CalendarSystem,@@ -192,4 +193,23 @@ describe('without Temporal', () => {expect(warn).not.toHaveBeenCalled();},);++ it('renders a Persian Calendar as a Gregorian month', () => {+ silenceWarnings();+ render(<Calendar calendar="persian" focusDate="2026-10-30" />);+ expect(+ screen.getByRole('grid', {name: 'October 2026'}),+ ).toBeInTheDocument();+ });++ it('renders a Buddhist Calendar with Buddhist years', () => {+ render(+ <InternationalizationProvider locale="en" calendar="buddhist">+ <Calendar focusDate="2026-10-30" />+ </InternationalizationProvider>,+ );+ expect(screen.getByRole('grid').getAttribute('aria-label')).toContain(+ '2569',+ );+ });});diff --git a/packages/core/src/utils/calendarSystem.ts b/packages/core/src/utils/calendarSystem.tsindex f0edbc3f45..b300e9adec 100644--- a/packages/core/src/utils/calendarSystem.ts+++ b/packages/core/src/utils/calendarSystem.ts@@ -6,9 +6,9 @@* @output Calendar months located by their Gregorian days, 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. Values- * stay Gregorian PlainDates. Temporal owns the arithmetic of every calendar- * whose months are not Gregorian.+ * @position Shared date utility; read by the i18n calendar resolution and by+ * Calendar. Values stay Gregorian PlainDates. Temporal owns the arithmetic of+ * every calendar whose months are not Gregorian.*/import type {Locale} from '../i18n/types';