An open source design system that's fully customizable and agent ready
TypeScript
feat(Calendar): useCalendarDays and useCalendarNavigation take an optional calendar (#10007)
nynexman4464aa7c50176c75
diff --git a/.changeset/calendar-hooks-calendar-option.md b/.changeset/calendar-hooks-calendar-option.mdnew file mode 100644index 0000000000..4fab6cc061--- /dev/null+++ b/.changeset/calendar-hooks-calendar-option.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[feat] `useCalendarDays` and `useCalendarNavigation` take an optional `calendar` (default `gregory`) for custom month views in other calendar systems; they never read the provider's calendar.++@nynexman4464diff --git a/docs/specs/components/Calendar/Calendar.spec.md b/docs/specs/components/Calendar/Calendar.spec.mdindex 1769701714..2c8e2d31d2 100644--- a/docs/specs/components/Calendar/Calendar.spec.md+++ b/docs/specs/components/Calendar/Calendar.spec.md@@ -16,6 +16,7 @@ verified_by: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/Calendar/hooks/calendarHooks.calendarSystems.test.tsx,packages/core/src/utils/calendarSystem.test.ts,packages/core/src/i18n/__tests__/calendarSystem.test.tsx,packages/core/src/hooks/useGridFocus.test.tsx,@@ -51,13 +52,13 @@ system_specs:| 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. |+| 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. The public `useCalendarDays` and `useCalendarNavigation` hooks take an optional `calendar` too (FR11). || 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. |+| 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, FR20, 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.@@ -73,8 +74,8 @@ keyboard model that moves through days; date fields compose it.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+- Compatibility class: additive optional `calendar` prop and hook option; no+ default, export, or DOM structure change; the weekday header text follows DD1. A provider localewith 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;@@ -116,18 +117,19 @@ Consumer migration instructions belong in consumer docs and release notes.## 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 |-| 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 |+| 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 |+| FR11 | The public `useCalendarDays` and `useCalendarNavigation` hooks take an optional `calendar` that defaults to `gregory`, and they never read the provider's calendar. With a calendar, `useCalendarDays` reads `year` and `month` as the calendar's year and the month's position in that year, as `Temporal.PlainDate` numbers them (1 through 13 in a Hebrew leap year); each day keeps its Gregorian date, and `dayNumber` is its day of the calendar month. `useCalendarNavigation` steps calendar months, writes `monthYearLabel` as the month header writes it, and reports each visible month in the calendar's numbers as `visibleCalendarMonths`, which `useCalendarDays` reads with the same `calendar`. `baseMonth` and `visibleMonths` stay the Gregorian first day of each month. Without `calendar`, both hooks show Gregorian months, exactly as with `calendar: 'gregory'`. | `spec:AST-111` FR4, FR5, FR20 |+| 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@@ -284,6 +286,7 @@ button.| 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` |+| FR11 (hooks) | `calendarHooks.calendarSystems.test.tsx` ("matches the released output for %s" against a fixed copy of the Gregorian grid algorithm, "gives the same output with calendar gregory", "lays out Aban 1405 in the Persian calendar", "reads Hebrew leap-year months as Temporal numbers them", "reads the year numbers of the Buddhist and Minguo calendars", "ignores the provider calendar" for both hooks, "matches the released months and label in %s", "steps Persian months and labels them in the calendar", "steps through Adar I, Adar II, and the thirteenth month", "labels %s months as Calendar heads them", "feeds visibleCalendarMonths into useCalendarDays in %s", "fall back to Gregorian months and warn once"); the unchanged `useCalendarDays.test.ts` and `useCalendarNavigation.test.ts` || 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` |diff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex 3f19cf8beb..c7f95ca9df 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -108,7 +108,6 @@"spec:AST-085"],"packages/core/src/Calendar/dayCellUtils.ts": ["#2715", "#2715"],- "packages/core/src/Calendar/hooks/useCalendarNavigation.ts": ["FR1"],"packages/core/src/Carousel/Carousel.tsx": ["2026-08-27","AST-025",diff --git a/packages/core/api-report.md b/packages/core/api-report.mdindex d5278ee8d3..1efd917e7e 100644--- a/packages/core/api-report.md+++ b/packages/core/api-report.md@@ -5786,6 +5786,7 @@ interface UseCalendarConstraintsReturnmaxDate: PlainDate | nullminDate: PlainDate | nullinterface UseCalendarDaysOptions+ calendar?: CalendarSystem = 'gregory'hasVariableRowCount?: booleanmonth: numberweekStartsOn?: DayOfWeek@@ -5796,6 +5797,7 @@ interface UseCalendarDaysReturntotalCells: numberweeks: CalendarDay[][]interface UseCalendarNavigationOptions+ calendar?: CalendarSystem = 'gregory'focusDate?: ISODateStringinitialValue?: ISODateStringnumberOfMonths?: 1 | 2@@ -5806,6 +5808,7 @@ interface UseCalendarNavigationReturnmonthYearLabel: stringnavigateMonth: (delta: number, focusedDate?: ISODateString, offset?: number) => voidpendingFocus: ISODateString | null+ visibleCalendarMonths: Array<{ year: number; month: number }>visibleMonths: PlainDate[]interface UseChatComposerTokensOptionseditableRef: React.RefObject<HTMLDivElement | null>diff --git a/packages/core/src/Calendar/Calendar.doc.mjs b/packages/core/src/Calendar/Calendar.doc.mjsindex 8277a403fd..8777556868 100644--- a/packages/core/src/Calendar/Calendar.doc.mjs+++ b/packages/core/src/Calendar/Calendar.doc.mjs@@ -39,6 +39,11 @@ export const docs = {description:'Show two months side by side when the user frequently selects dates that span a month boundary.',},+ {+ guidance: true,+ description:+ 'For a custom month view, use useCalendarNavigation and useCalendarDays from @astryxdesign/core/Calendar. To show another calendar system, pass the same calendar to both and feed visibleCalendarMonths into useCalendarDays. The hooks default to gregory and never read the InternationalizationProvider calendar.',+ },{guidance: false,description:@@ -195,6 +200,41 @@ export const docs = {default: 'the InternationalizationProvider calendar, else gregory',},],+ examples: [+ {+ label: 'A custom month view in the Persian calendar',+ code: `import {Button} from '@astryxdesign/core/Button';+import {+ useCalendarDays,+ useCalendarNavigation,+} from '@astryxdesign/core/Calendar';++function PersianMonth() {+ const {monthYearLabel, visibleCalendarMonths, navigateMonth} =+ useCalendarNavigation({initialValue: '2026-10-30', calendar: 'persian'});+ // visibleCalendarMonths[0] is {year: 1405, month: 8}: Aban 1405.+ const {weeks} = useCalendarDays({+ ...visibleCalendarMonths[0],+ calendar: 'persian',+ });+ return (+ <section aria-label={monthYearLabel}>+ <Button label="Previous month" onClick={() => navigateMonth(-1)} />+ <Button label="Next month" onClick={() => navigateMonth(1)} />+ {weeks.map(week => (+ <div key={week[0].iso}>+ {week.map(day => (+ <span key={day.iso} data-date={day.iso}>+ {day.isOutside ? '' : day.dayNumber}+ </span>+ ))}+ </div>+ ))}+ </section>+ );+}`,+ },+ ],theming: {targets: [{className: 'astryx-calendar', visualProps: ['mode']},@@ -239,6 +279,11 @@ export const docsZh = {description:'Show two months side by side when the user frequently selects dates that span a month boundary.',},+ {+ guidance: true,+ description:+ 'For a custom month view, use useCalendarNavigation and useCalendarDays from @astryxdesign/core/Calendar. To show another calendar system, pass the same calendar to both and feed visibleCalendarMonths into useCalendarDays. The hooks default to gregory and never read the InternationalizationProvider calendar.',+ },{guidance: false,description:@@ -391,6 +436,11 @@ export const docsDense = {description:'Show two months side by side when user frequently selects dates spanning a month boundary.',},+ {+ guidance: true,+ description:+ 'Custom month view: useCalendarNavigation + useCalendarDays; pass the same calendar to both, feed visibleCalendarMonths into useCalendarDays. Default gregory; never read the provider calendar.',+ },{guidance: false,description:diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsxindex 5ee3b9eb37..793c86cbf3 100644--- a/packages/core/src/Calendar/Calendar.tsx+++ b/packages/core/src/Calendar/Calendar.tsx@@ -32,7 +32,7 @@ import {Button} from '../Button';import {Icon} from '../Icon';import {useAnnounce, useGridFocus} from '../hooks';import {useCalendarConstraints, type CalendarDay} from './hooks';-import {useCalendarMonthDays} from './hooks/useCalendarDays';+import {useCalendarDays} from './hooks/useCalendarDays';import {calendarStyles,monthGridStyles,@@ -62,6 +62,7 @@ import {calendarMonthOf,calendarShiftMonths,calendarShiftYears,+ calendarYearMonthOf,formatCalendarDate,formatCalendarMonthLabel,isInCalendarMonth,@@ -864,8 +865,13 @@ function MonthGrid({const locale = useLocale();// Use hooks for days generation and constraints- const {days, weeks} = useCalendarMonthDays({- month,+ const yearMonth = useMemo(+ () => calendarYearMonthOf(calendar, month),+ [calendar, month],+ );+ const {days, weeks} = useCalendarDays({+ year: yearMonth.year,+ month: yearMonth.month,calendar,weekStartsOn,hasVariableRowCount,diff --git a/packages/core/src/Calendar/hooks/calendarHooks.calendarSystems.test.tsx b/packages/core/src/Calendar/hooks/calendarHooks.calendarSystems.test.tsxnew file mode 100644index 0000000000..aa8fa42381--- /dev/null+++ b/packages/core/src/Calendar/hooks/calendarHooks.calendarSystems.test.tsx@@ -0,0 +1,417 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file calendarHooks.calendarSystems.test.tsx+ * @input useCalendarDays, useCalendarNavigation, Calendar, the full Temporal+ * polyfill+ * @output Tests for the `calendar` option of the public calendar hooks, and+ * for their output without it against the released algorithm+ * @position Colocated tests for the hooks; 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 type {ReactNode} from 'react';+import {act, render, renderHook, screen} from '@testing-library/react';+import {+ useCalendarDays,+ type CalendarDay,+ type UseCalendarDaysOptions,+} from './useCalendarDays';+import {+ useCalendarNavigation,+ type UseCalendarNavigationOptions,+} from './useCalendarNavigation';+import {Calendar} from '../Calendar';+import {InternationalizationProvider} from '../../i18n/InternationalizationProvider';+import {getWeekdayHeaderNames} from '../getWeekdayHeaderNames';+import type {DayOfWeek, ISODateString} from '../../utils/dateTypes';+import {+ type PlainDate,+ getDaysInMonth,+ plainDateAddDays,+ plainDateAddMonths,+ plainDateDayOfWeek,+ plainDateFormatStandaloneMonthYear,+ plainDateToISO,+} from '../../utils/plainDate';+import type {CalendarSystem} from '../../utils/calendarSystem';+import {__resetDevWarnings} from '../../utils/devWarning';+import {__resetLiveRegionsForTest} from '../../hooks/useAnnounce';++afterEach(() => {+ __resetDevWarnings();+ __resetLiveRegionsForTest();+ vi.restoreAllMocks();+});++// The day grid of the released hook, kept verbatim so that a change to the+// shared code path cannot move the Gregorian output.+function releasedDays(+ year: number,+ month: number,+ weekStartsOn: DayOfWeek,+ hasVariableRowCount: boolean,+): CalendarDay[] {+ const totalDaysInMonth = getDaysInMonth(year, month);+ let startingDayOfWeek =+ plainDateDayOfWeek({year, month, day: 1}) - weekStartsOn;+ if (startingDayOfWeek < 0) {+ startingDayOfWeek += 7;+ }+ const totalDays = totalDaysInMonth + startingDayOfWeek;+ const totalRows = hasVariableRowCount ? Math.ceil(totalDays / 7) : 6;+ const firstOfMonth: PlainDate = {year, month, day: 1};+ const result: CalendarDay[] = [];+ for (let i = 0; i < totalRows * 7; 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;+}++function inMonth(days: CalendarDay[]): CalendarDay[] {+ return days.filter(day => !day.isOutside);+}++function persianProvider({children}: {children: ReactNode}) {+ return (+ <InternationalizationProvider locale="en" calendar="persian">+ {children}+ </InternationalizationProvider>+ );+}++function withoutTemporal(run: () => void) {+ const globals = globalThis as {Temporal?: unknown};+ const saved = globals.Temporal;+ delete globals.Temporal;+ try {+ run();+ } finally {+ globals.Temporal = saved;+ }+}++describe('useCalendarDays without calendar', () => {+ const cases: [string, UseCalendarDaysOptions][] = [+ // May 2026 starts on a Friday, so its 31 days reach a sixth row.+ ['a six-row month', {year: 2026, month: 5}],+ ['a 28-day month on weekStartsOn', {year: 2026, month: 2}],+ ['a leap February', {year: 2024, month: 2, weekStartsOn: 1}],+ ['a variable-row month', {year: 2026, month: 2, hasVariableRowCount: true}],+ [+ 'a variable-row month with six rows',+ {year: 2026, month: 8, hasVariableRowCount: true},+ ],+ ['a month across a year end', {year: 2025, month: 12, weekStartsOn: 6}],+ ];++ it.each(cases)('matches the released output for %s', (_name, options) => {+ const {result} = renderHook(() => useCalendarDays(options));+ const weekStartsOn = options.weekStartsOn ?? 0;+ const expected = releasedDays(+ options.year,+ options.month,+ weekStartsOn,+ options.hasVariableRowCount ?? false,+ );+ expect(result.current.days).toEqual(expected);+ expect(result.current.totalCells).toBe(expected.length);+ expect(result.current.weeks.flat()).toEqual(expected);+ expect(result.current.dayNames).toEqual(+ getWeekdayHeaderNames('en', weekStartsOn),+ );+ });++ it('includes the six-row and variable-row shapes', () => {+ const fixed = renderHook(() => useCalendarDays({year: 2026, month: 8}));+ const variable = renderHook(() =>+ useCalendarDays({year: 2026, month: 2, hasVariableRowCount: true}),+ );+ // August 2026 starts on a Saturday: its 30th and 31st fill the sixth row.+ expect(inMonth(fixed.result.current.weeks[5])).toHaveLength(2);+ expect(variable.result.current.weeks).toHaveLength(4);+ });++ it('gives the same output with calendar gregory', () => {+ const options = {year: 2026, month: 5, weekStartsOn: 1} as const;+ const plain = renderHook(() => useCalendarDays(options));+ const gregory = renderHook(() =>+ useCalendarDays({...options, calendar: 'gregory'}),+ );+ expect(gregory.result.current).toEqual(plain.result.current);+ });+});++describe('useCalendarDays with calendar', () => {+ it('lays out Aban 1405 in the Persian calendar', () => {+ const {result} = renderHook(() =>+ useCalendarDays({year: 1405, month: 8, calendar: 'persian'}),+ );+ const days = inMonth(result.current.days);+ expect(days.map(day => day.dayNumber)).toEqual(+ Array.from({length: 30}, (_, i) => i + 1),+ );+ expect(days[0]).toEqual({+ date: {year: 2026, month: 10, day: 23},+ iso: '2026-10-23',+ isOutside: false,+ dayNumber: 1,+ });+ expect(days[29].iso).toBe('2026-11-21');+ // 2026-10-23 is a Friday: five Mehr days lead the first row.+ expect(result.current.days[0]).toMatchObject({+ iso: '2026-10-18',+ isOutside: true,+ dayNumber: 26,+ });+ expect(result.current.totalCells).toBe(42);+ expect(result.current.dayNames).toEqual(getWeekdayHeaderNames('en', 0));+ });++ it('reads Hebrew leap-year months as Temporal numbers them', () => {+ const month = (n: number) =>+ inMonth(+ renderHook(() =>+ useCalendarDays({year: 5784, month: n, calendar: 'hebrew'}),+ ).result.current.days,+ );+ const adarI = month(6);+ const adarII = month(7);+ const elul = month(13);+ expect([adarI[0].iso, adarI.length]).toEqual(['2024-02-10', 30]);+ expect([adarII[0].iso, adarII.length]).toEqual(['2024-03-11', 29]);+ expect([elul[0].iso, elul.length]).toEqual(['2024-09-04', 29]);+ expect(elul.map(day => day.dayNumber).at(-1)).toBe(29);+ });++ it('reads the year numbers of the Buddhist and Minguo calendars', () => {+ const buddhist = renderHook(() =>+ useCalendarDays({year: 2569, month: 10, calendar: 'buddhist'}),+ );+ const roc = renderHook(() =>+ useCalendarDays({year: 115, month: 10, calendar: 'roc'}),+ );+ const expected = releasedDays(2026, 10, 0, false);+ expect(buddhist.result.current.days).toEqual(expected);+ expect(roc.result.current.days).toEqual(expected);+ });++ it('ignores the provider calendar', () => {+ const {result} = renderHook(+ () => useCalendarDays({year: 2026, month: 10}),+ {+ wrapper: persianProvider,+ },+ );+ expect(result.current.days).toEqual(releasedDays(2026, 10, 0, false));+ });+});++describe('useCalendarNavigation without calendar', () => {+ it.each(['en', 'th-TH', 'fa-IR', 'ca'])(+ 'matches the released months and label in %s',+ locale => {+ const options: UseCalendarNavigationOptions = {+ initialValue: '2026-01-15',+ numberOfMonths: 2,+ };+ const {result} = renderHook(() => useCalendarNavigation(options), {+ wrapper: ({children}) => (+ <InternationalizationProvider locale={locale}>+ {children}+ </InternationalizationProvider>+ ),+ });+ const first = {year: 2026, month: 1, day: 1};+ const months = [first, plainDateAddMonths(first, 1)];+ expect(result.current.baseMonth).toEqual(first);+ expect(result.current.visibleMonths).toEqual(months);+ expect(result.current.visibleCalendarMonths).toEqual([+ {year: 2026, month: 1},+ {year: 2026, month: 2},+ ]);+ expect(result.current.monthYearLabel).toBe(+ months+ .map(m => plainDateFormatStandaloneMonthYear(m, locale))+ .join(' – '),+ );+ },+ );++ it('ignores the provider calendar', () => {+ const {result} = renderHook(+ () => useCalendarNavigation({initialValue: '2026-10-30'}),+ {wrapper: persianProvider},+ );+ expect(result.current.baseMonth).toEqual({year: 2026, month: 10, day: 1});+ expect(result.current.monthYearLabel).toBe('October 2026');+ act(() => result.current.navigateMonth(1));+ expect(result.current.baseMonth).toEqual({year: 2026, month: 11, day: 1});+ });+});++describe('useCalendarNavigation with calendar', () => {+ it('steps Persian months and labels them in the calendar', () => {+ const {result} = renderHook(() =>+ useCalendarNavigation({initialValue: '2026-10-30', calendar: 'persian'}),+ );+ expect(result.current.baseMonth).toEqual({year: 2026, month: 10, day: 23});+ expect(result.current.visibleCalendarMonths).toEqual([+ {year: 1405, month: 8},+ ]);+ expect(result.current.monthYearLabel).toBe('Aban 1405 AP');++ act(() => result.current.navigateMonth(1));+ expect(result.current.baseMonth).toEqual({year: 2026, month: 11, day: 22});+ expect(result.current.visibleCalendarMonths).toEqual([+ {year: 1405, month: 9},+ ]);+ expect(result.current.monthYearLabel).toBe('Azar 1405 AP');++ act(() => result.current.navigateMonth(-9));+ expect(result.current.visibleCalendarMonths).toEqual([+ {year: 1404, month: 12},+ ]);+ });++ it('steps through Adar I, Adar II, and the thirteenth month', () => {+ const {result} = renderHook(() =>+ useCalendarNavigation({initialValue: '2024-02-15', calendar: 'hebrew'}),+ );+ expect(result.current.visibleCalendarMonths).toEqual([+ {year: 5784, month: 6},+ ]);+ expect(result.current.monthYearLabel).toBe('Adar I 5784');+ act(() => result.current.navigateMonth(1));+ expect(result.current.monthYearLabel).toBe('Adar II 5784');+ act(() => result.current.navigateMonth(6));+ expect(result.current.visibleCalendarMonths).toEqual([+ {year: 5784, month: 13},+ ]);+ expect(result.current.baseMonth).toEqual({year: 2024, month: 9, day: 4});+ });++ it('reports a controlled month change as the Gregorian first day', () => {+ const onFocusDateChange = vi.fn();+ const {result} = renderHook(() =>+ useCalendarNavigation({+ focusDate: '2026-10-30',+ onFocusDateChange,+ calendar: 'persian',+ }),+ );+ act(() => result.current.navigateMonth(-1, '2026-10-24', 7));+ expect(onFocusDateChange).toHaveBeenCalledWith('2026-09-23');+ expect(result.current.pendingFocus).toBe('2026-10-17');+ });++ it.each<[CalendarSystem, ISODateString, 1 | 2]>([+ ['persian', '2026-10-30', 2],+ ['hebrew', '2024-02-15', 2],+ ['japanese', '2019-04-30', 1],+ ['buddhist', '2026-10-30', 1],+ ])('labels %s months as Calendar heads them', (calendar, iso, n) => {+ const {result} = renderHook(() =>+ useCalendarNavigation({+ initialValue: iso,+ numberOfMonths: n,+ calendar,+ }),+ );+ render(<Calendar calendar={calendar} focusDate={iso} numberOfMonths={n} />);+ expect(+ screen.getByText(result.current.monthYearLabel, {selector: 'span'}),+ ).toBeInTheDocument();+ });++ it.each<[CalendarSystem, ISODateString]>([+ ['persian', '2026-10-30'],+ ['hebrew', '2024-08-15'],+ ['ethiopic', '2026-09-08'],+ ['chinese', '2025-07-01'],+ ['roc', '2026-10-30'],+ ])(+ 'feeds visibleCalendarMonths into useCalendarDays in %s',+ (calendar, iso) => {+ const {result} = renderHook(() => {+ const nav = useCalendarNavigation({+ initialValue: iso,+ numberOfMonths: 2,+ calendar,+ });+ const grids = [+ useCalendarDays({...nav.visibleCalendarMonths[0], calendar}),+ useCalendarDays({...nav.visibleCalendarMonths[1], calendar}),+ ];+ return {nav, grids};+ });+ const {nav, grids} = result.current;+ grids.forEach((grid, i) => {+ const days = inMonth(grid.days);+ expect(days[0].date).toEqual(nav.visibleMonths[i]);+ expect(days[0].dayNumber).toBe(1);+ });+ // The second grid starts the day after the first grid ends.+ expect(plainDateAddDays(inMonth(grids[0].days).at(-1)!.date, 1)).toEqual(+ nav.visibleMonths[1],+ );+ },+ );+});++describe('the calendar hooks without Temporal', () => {+ it('fall back to Gregorian months and warn once', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ withoutTemporal(() => {+ const days = renderHook(() =>+ useCalendarDays({year: 2026, month: 10, calendar: 'persian'}),+ );+ expect(days.result.current.days).toEqual(+ releasedDays(2026, 10, 0, false),+ );+ const nav = renderHook(() =>+ useCalendarNavigation({+ initialValue: '2026-10-30',+ calendar: 'persian',+ }),+ );+ expect(nav.result.current.monthYearLabel).toBe('October 2026');+ expect(nav.result.current.visibleCalendarMonths).toEqual([+ {year: 2026, month: 10},+ ]);+ });+ expect(warn).toHaveBeenCalledTimes(1);+ expect(String(warn.mock.calls[0]?.[0])).toContain(+ 'needs a Temporal that supports it',+ );+ });++ it('keeps Gregorian-aligned calendars without a warning', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ withoutTemporal(() => {+ const {result} = renderHook(() =>+ useCalendarNavigation({+ initialValue: '2026-10-30',+ calendar: 'buddhist',+ }),+ );+ expect(result.current.visibleCalendarMonths).toEqual([+ {year: 2569, month: 10},+ ]);+ expect(result.current.monthYearLabel).toContain('2569');+ });+ expect(warn).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/src/Calendar/hooks/useCalendarDays.ts b/packages/core/src/Calendar/hooks/useCalendarDays.tsindex 3d6e7c72c8..9437e40c76 100644--- a/packages/core/src/Calendar/hooks/useCalendarDays.ts+++ b/packages/core/src/Calendar/hooks/useCalendarDays.ts@@ -6,9 +6,9 @@* @file useCalendarDays.ts* @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+ * @output Exports useCalendarDays, the day grid of one month of any calendar+ * system (Gregorian by default)+ * @position Calendar-specific hook; used by Calendar and MonthScroller** SYNC: When modified, update:* - /packages/core/src/Calendar/hooks/index.ts@@ -19,17 +19,17 @@ import type {DayOfWeek, ISODateString} from '../../utils/dateTypes';import {type PlainDate,plainDateToISO,- getDaysInMonth,plainDateDayOfWeek,plainDateAddDays,} from '../../utils/plainDate';import {useLocale} from '../../i18n';import {getWeekdayHeaderNames} from '../getWeekdayHeaderNames';import {- type CalendarMonth,type CalendarSystem,calendarDayOfMonth,+ calendarMonthFromYearMonth,} from '../../utils/calendarSystem';+import {resolveShownCalendar} from '../../i18n/useCalendarSystem';/*** Represents a single day in the calendar grid.@@ -49,14 +49,27 @@ export interface CalendarDay {* Configuration for calendar days generation*/export interface UseCalendarDaysOptions {- /** The year to generate days for */+ /** The year to generate days for, in `calendar`'s numbering */year: number;- /** The month (1-based: 1 = January, 12 = December) */+ /**+ * The month's position in its year (1-based). In the Gregorian calendar,+ * 1 is January and 12 is December. In other calendars it is numbered as+ * `Temporal.PlainDate` numbers it: 1 through 13 in a Hebrew leap year.+ */month: number;/** First day of week (0=Sunday through 6=Saturday) */weekStartsOn?: DayOfWeek;/** Use variable rows per month vs. fixed 6-row grid */hasVariableRowCount?: boolean;+ /**+ * The calendar system that numbers `year`, `month`, and each `dayNumber`.+ * Each day keeps its Gregorian `date` and `iso`. The hook never reads the+ * InternationalizationProvider calendar. Calendars other than gregory,+ * iso8601, buddhist, roc, and japanese need Temporal; without it, the hook+ * reads Gregorian numbers and warns once in development.+ * @default 'gregory'+ */+ calendar?: CalendarSystem;}/**@@ -87,66 +100,35 @@ export interface UseCalendarDaysReturn {* weekStartsOn: 0, // Sunday* });* // days[i].date is a PlainDate { year, month (1-based), day }+ *+ * // Aban 1405 in the Persian calendar; dates stay Gregorian+ * useCalendarDays({year: 1405, month: 8, calendar: 'persian'});* ```*/export function useCalendarDays(options: UseCalendarDaysOptions,-): UseCalendarDaysReturn {- const {year, month, weekStartsOn = 0, hasVariableRowCount = false} = options;- 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);-}--/** 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;-}--/**- * 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 {+ year,month,- calendar,weekStartsOn = 0,hasVariableRowCount = false,+ calendar: calendarOption = 'gregory',} = 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],- );+ const calendar = resolveShownCalendar(calendarOption, 'useCalendarDays');+ const days = useMemo(() => {+ const calendarMonth = calendarMonthFromYearMonth(calendar, {year, month});+ return layOutMonthDays({+ first: calendarMonth.start,+ length: calendarMonth.length,+ weekStartsOn,+ hasVariableRowCount,+ dayNumberOf: (pd, offset) =>+ offset >= 0 && offset < calendarMonth.length+ ? offset + 1+ : calendarDayOfMonth(calendar, pd),+ });+ }, [year, month, calendar, weekStartsOn, hasVariableRowCount]);return useMonthGrid(days, weekStartsOn);}diff --git a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts b/packages/core/src/Calendar/hooks/useCalendarNavigation.tsindex 000ddf15b6..0806559b18 100644--- a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts+++ b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts@@ -4,9 +4,11 @@/*** @file useCalendarNavigation.ts- * @input Uses React useState, useMemo, useCallback, useLocale, PlainDate utilities- * @output Exports useCalendarNavigation hook for month navigation- * @position Calendar-specific hook; used by Calendar+ * @input Uses React useState, useMemo, useCallback, useLocale, PlainDate and+ * calendar-system utilities+ * @output Exports useCalendarNavigation hook for month navigation in any+ * calendar system (Gregorian by default)+ * @position Calendar-specific public hook** SYNC: When modified, update:* - /packages/core/src/Calendar/hooks/index.ts@@ -19,12 +21,17 @@ import {plainDateFromISO,plainDateToISO,plainDateToday,- plainDateSetFirstOfMonth,- plainDateAddMonths,plainDateAddDays,} from '../../utils/plainDate';-import {plainDateFormatStandaloneMonthYear} from '../../utils/plainDate';+import {+ type CalendarSystem,+ calendarAddMonths,+ calendarMonthOf,+ calendarYearMonthOf,+ formatCalendarMonthLabel,+} from '../../utils/calendarSystem';import {useLocale} from '../../i18n';+import {resolveShownCalendar} from '../../i18n/useCalendarSystem';/*** Configuration for calendar navigation@@ -38,17 +45,31 @@ export interface UseCalendarNavigationOptions {onFocusDateChange?: (focusDate: ISODateString) => void;/** Number of months to display */numberOfMonths?: 1 | 2;+ /**+ * The calendar system whose months the hook steps and labels. Dates stay+ * Gregorian ISO. The hook never reads the InternationalizationProvider+ * calendar. Calendars other than gregory, iso8601, buddhist, roc, and+ * japanese need Temporal; without it, the hook steps Gregorian months and+ * warns once in development.+ * @default 'gregory'+ */+ calendar?: CalendarSystem;}/*** Return type for useCalendarNavigation hook*/export interface UseCalendarNavigationReturn {- /** The base month (first day of the focus month) as a PlainDate */+ /** The Gregorian first day of the focus month */baseMonth: PlainDate;- /** Array of visible months to render as PlainDates */+ /** The Gregorian first day of each visible month */visibleMonths: PlainDate[];- /** Formatted label for the month header */+ /**+ * The year and month numbers of each visible month in `calendar`, as+ * `useCalendarDays` reads them with the same `calendar`+ */+ visibleCalendarMonths: {year: number; month: number}[];+ /** Formatted label for the month header, in `calendar` */monthYearLabel: string;/** Navigate to previous/next month */navigateMonth: (@@ -87,6 +108,13 @@ export interface UseCalendarNavigationReturn {* // Navigate from arrow key (with focus tracking)* navigateMonth(1, focusedDate, 1); // horizontal offset* navigateMonth(1, focusedDate, 7); // vertical offset+ *+ * // Persian months, laid out by useCalendarDays+ * const nav = useCalendarNavigation({initialValue, calendar: 'persian'});+ * const {weeks} = useCalendarDays({+ * ...nav.visibleCalendarMonths[0],+ * calendar: 'persian',+ * });* ```*/export function useCalendarNavigation(@@ -97,8 +125,13 @@ export function useCalendarNavigation(focusDate: focusDateProp,onFocusDateChange,numberOfMonths = 1,+ calendar: calendarOption = 'gregory',} = options;const locale = useLocale();+ const calendar = resolveShownCalendar(+ calendarOption,+ 'useCalendarNavigation',+ );// Pending focus target after month navigationconst [pendingFocus, setPendingFocus] = useState<ISODateString | null>(null);@@ -121,32 +154,40 @@ export function useCalendarNavigation(? plainDateFromISO(focusDateProp): internalFocusDate;- // 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 shownMonths = useMemo(() => {+ const first = calendarMonthOf(calendar, plainDateFromISO(focusIso));+ return Array.from({length: numberOfMonths}, (_, i) =>+ calendarAddMonths(calendar, first, i),+ );+ }, [calendar, focusIso, numberOfMonths]);++ const visibleMonths = useMemo(+ () => shownMonths.map(month => month.start),+ [shownMonths],+ );+ const baseMonth = visibleMonths[0];- // Generate visible months- const visibleMonths = useMemo(() => {- return Array.from({length: numberOfMonths}, (_, i) => {- return plainDateAddMonths(baseMonth, i);- });- }, [baseMonth, numberOfMonths]);+ const visibleCalendarMonths = useMemo(+ () => shownMonths.map(month => calendarYearMonthOf(calendar, month)),+ [calendar, shownMonths],+ );- // Format month header- // Each month is its own stand-alone label (Calendar FR1).+ // Each month is its own stand-alone label.const monthYearLabel = useMemo(() =>- visibleMonths- .map(m => plainDateFormatStandaloneMonthYear(m, locale))+ shownMonths+ .map(month => formatCalendarMonthLabel(calendar, month, locale)).join(' – '),- [visibleMonths, locale],+ [calendar, shownMonths, locale],);// Navigate to previous/next monthconst navigateMonth = useCallback((delta: number, focusedDate?: ISODateString, offset?: number) => {- const newMonth = plainDateAddMonths(baseMonth, delta);+ const newMonth = calendarAddMonths(calendar, shownMonths[0], delta).start;const newISO = plainDateToISO(newMonth);// Calculate target focus date if provided@@ -164,7 +205,7 @@ export function useCalendarNavigation(setInternalFocusDate(newMonth);}},- [baseMonth, onFocusDateChange],+ [calendar, shownMonths, onFocusDateChange],);// Clear pending focus@@ -175,6 +216,7 @@ export function useCalendarNavigation(return {baseMonth,visibleMonths,+ visibleCalendarMonths,monthYearLabel,navigateMonth,pendingFocus,diff --git a/packages/core/src/i18n/useCalendarSystem.ts b/packages/core/src/i18n/useCalendarSystem.tsindex ac72368f3a..9b72a28502 100644--- a/packages/core/src/i18n/useCalendarSystem.ts+++ b/packages/core/src/i18n/useCalendarSystem.ts@@ -5,10 +5,11 @@/*** @file useCalendarSystem.ts* @input InternationalizationContext, an optional component `calendar`- * @output The calendar system a date component shows, and the helper that- * normalizes a calendar identifier- * @position Internal i18n hook; read by InternationalizationProvider and date- * components. Not re-exported from the i18n barrel.+ * @output The calendar system a date component shows, and the helpers that+ * normalize a calendar identifier+ * @position Internal i18n hook; read by InternationalizationProvider, date+ * components, and the public calendar hooks. Not re-exported from the i18n+ * barrel.*/import {use} from 'react';@@ -62,6 +63,21 @@ function availableCalendarOrGregorian(return 'gregory';}+/**+ * The calendar that a caller names, without the provider: an unknown+ * identifier, or one this runtime cannot show, becomes `gregory` and warns+ * once in development.+ */+export function resolveShownCalendar(+ calendar: string,+ source: string,+): CalendarSystem {+ return availableCalendarOrGregorian(+ resolveCalendarSystem(calendar, source),+ source,+ );+}+/*** The calendar a date component shows: its own `calendar`, else the* provider's resolved calendar, else `gregory`. It resolves during render, so@@ -72,9 +88,8 @@ export function useCalendarSystem(source: string,): CalendarSystem {const context = use(InternationalizationContext);- const requested =- calendar != null- ? resolveCalendarSystem(calendar, source)- : (context.calendar ?? 'gregory');- return availableCalendarOrGregorian(requested, source);+ return resolveShownCalendar(+ calendar ?? context.calendar ?? 'gregory',+ source,+ );}diff --git a/packages/core/src/utils/calendarSystem.ts b/packages/core/src/utils/calendarSystem.tsindex b300e9adec..db163a03e5 100644--- a/packages/core/src/utils/calendarSystem.ts+++ b/packages/core/src/utils/calendarSystem.ts@@ -3,11 +3,11 @@/*** @file calendarSystem.ts* @input A calendar identifier and Gregorian PlainDates- * @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 and by- * Calendar. Values stay Gregorian PlainDates. Temporal owns the arithmetic of+ * @output Calendar months located by their Gregorian days, their year and+ * month numbers, month and year steps, dates from calendar fields,+ * availability of each calendar, and calendar labels and digits+ * @position Shared date utility; read by the i18n calendar resolution, by+ * Calendar, and by its public hooks. Values stay Gregorian PlainDates. Temporal owns the arithmetic of* every calendar whose months are not Gregorian.*/@@ -97,7 +97,7 @@ interface TemporalPlainDate {readonly day: number;readonly daysInMonth: number;readonly monthsInYear: number;- with(fields: {day: number}): TemporalPlainDate;+ with(fields: {year?: number; month?: number; day: number}): TemporalPlainDate;add(duration: {months?: number; years?: number}): TemporalPlainDate;withCalendar(calendar: 'iso8601'): TemporalPlainDate;}@@ -216,6 +216,61 @@ export function calendarMonthOf(return temporalMonth(inCalendar(calendar, pd).with({day: 1}));}+/**+ * A calendar month by its year and its position in that year, as+ * `Temporal.PlainDate` numbers them: month 13 exists in a Hebrew leap year.+ */+export interface CalendarYearMonth {+ readonly year: number;+ readonly month: number;+}++// Temporal counts the years of these Gregorian-aligned calendars from another+// epoch: 2026 is 2569 in `buddhist` and 115 in `roc`.+const GREGORIAN_YEAR_OFFSETS: Partial<Record<CalendarSystem, number>> = {+ buddhist: 543,+ roc: -1911,+};++/** The year and month numbers of a calendar month. */+export function calendarYearMonthOf(+ calendar: CalendarSystem,+ month: CalendarMonth,+): CalendarYearMonth {+ if (isGregorianAligned(calendar)) {+ return {+ year: month.start.year + (GREGORIAN_YEAR_OFFSETS[calendar] ?? 0),+ month: month.start.month,+ };+ }+ const {year, month: monthOfYear} = inCalendar(calendar, month.start);+ return {year, month: monthOfYear};+}++/**+ * The calendar month with these year and month numbers. A month past the end+ * of its year becomes the last month of that year, as Temporal constrains it.+ */+export function calendarMonthFromYearMonth(+ calendar: CalendarSystem,+ {year, month}: CalendarYearMonth,+): CalendarMonth {+ if (isGregorianAligned(calendar)) {+ return gregorianMonth(+ year - (GREGORIAN_YEAR_OFFSETS[calendar] ?? 0),+ month,+ );+ }+ // `with` replaces the year and month of any date in the calendar.+ return temporalMonth(+ inCalendar(calendar, {year: 2000, month: 1, day: 1}).with({+ year,+ month,+ day: 1,+ }),+ );+}+/** The calendar month `n` months after `month`, or before it when negative. */export function calendarAddMonths(calendar: CalendarSystem,