Skip to content

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

TypeScript

feat(i18n): InternationalizationProvider takes a calendar and exposes the resolved calendar (#9791)

nynexman44644e7823a56b3d
diff --git a/.changeset/calendar-system-boundary.md b/.changeset/calendar-system-boundary.md
new file mode 100644
index 0000000000..f53096ce5e
--- /dev/null
+++ b/.changeset/calendar-system-boundary.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] InternationalizationProvider takes a `calendar` prop (`CalendarSystem`, exported from `@astryxdesign/core/i18n`), such as `'persian'`, `'hebrew'`, `'islamic-umalqura'`, or `'buddhist'`, and exposes the resolved calendar on `InternationalizationContext` as `calendar`. A locale never selects the calendar: `fa-IR` resolves to Gregorian until you set `calendar="persian"`, and a provider locale with a `-u-ca-` keyword, such as `th-TH-u-ca-buddhist`, keeps Gregorian dates; set `calendar` to choose one. An unknown identifier resolves to Gregorian and warns once in development. The Gregorian-aligned calendars (`gregory`, `iso8601`, `buddhist`, `roc`, `japanese`) work everywhere; the others 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. Astryx date components keep showing Gregorian dates, and date values stay Gregorian ISO strings.
+
+@nynexman4464
diff --git a/docs/architecture/internationalization.md b/docs/architecture/internationalization.md
index a1f4c8c692..338d5696a2 100644
--- a/docs/architecture/internationalization.md
+++ b/docs/architecture/internationalization.md
@@ -19,6 +19,7 @@ applies_to:
scripts/i18n-english-fallback.mjs,
packages/build/src/vite.ts,
packages/core/src/utils/plainDate.ts,
+ packages/core/src/utils/calendarSystem.ts,
packages/core/src/utils/dateParser.ts,
packages/core/src/PowerSearch/formatFilterValue.ts,
packages/core/src/Timestamp/tooltipEntries.ts,
@@ -36,6 +37,8 @@ verified_by:
packages/core/src/i18n/__tests__/useDirection.test.tsx,
packages/core/src/i18n/__tests__/getLocaleDirection.test.ts,
packages/core/src/i18n/__tests__/useCollator.test.tsx,
+ packages/core/src/i18n/__tests__/calendarSystem.test.tsx,
+ packages/core/src/utils/calendarSystem.test.ts,
packages/core/src/i18n/useTranslator.test.tsx,
packages/core/src/i18n/__tests__/englishFallback.test.ts,
scripts/i18n-english-fallback.test.mjs,
@@ -122,7 +125,7 @@ Component and module contracts own which content is Astryx-authored versus
caller-authored, the semantic role of a content prop, local formatting inputs,
state-dependent behavior, and the evidence that proves those local outcomes.
Shared string ownership, helper boundaries, deterministic locale defaults, and
-Gregorian calendar requirements remain here. `component:InternationalizationProvider`
+calendar requirements remain here. `component:InternationalizationProvider`
owns the provider's local API and precedence contract, not a second set of rules
for every component.
@@ -272,15 +275,18 @@ for all 30 shipped locales plus `pseudo`.
The charts `currency()` helper does not yet conform: an omitted locale follows
the host default. That is a known conformance gap, not a recorded default;
making it deterministic is a separate compatibility change.
-- **INV10 — Default date and calendar semantics are Gregorian.** Locale changes
- language, numbering, and field order; it MUST NOT silently select a different
- calendar for built-in Astryx date displays or date-component behavior. Shared
- built-in date formatters pin the Gregorian calendar instead of inheriting the
- locale's default calendar. `PlainDate` parsing, arithmetic, constraints, grids,
- and navigation remain Gregorian. The existing low-level `plainDateFormat`
- display-calendar override remains a supported explicit caller choice; it does
- not establish alternative-calendar component semantics or permission to switch
- a built-in format merely because its locale has a different default calendar.
+- **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`
+ display-calendar override remains a supported explicit caller choice.
- **INV11 — Rendered direction comes from the DOM.** The provider exposes a
semantic direction default, but Astryx layout, mirroring, and interaction SHOULD
resolve from the rendered region through CSS logical properties,
@@ -350,8 +356,8 @@ ownership, deterministic defaults, runtime-update behavior, and output type rema
true.
A new public provider or hook, application-catalog ownership, rich-message output,
-server translation runtime, implicit host-locale behavior, or non-Gregorian
-component semantics is a new human API or ownership decision. It cannot be
+server translation runtime, implicit host-locale behavior, or calendar
+semantics beyond `spec:AST-111` is a new human API or ownership decision. It cannot be
inferred from an implementation pull request.
## Owning code
@@ -445,6 +451,6 @@ callers remain conformance work and do not relax INV1a, INV8, INV9, or INV10.
| INV15 | generator tests, `check:i18n-runtime`, package-export drift check, provider/resolver runtime-catalog tests; per-module English resolution-parity test (every key each Core module names, in every shipped locale’s fallback path, its own map versus the whole catalog); import-cost check (component bundles carry only the English they name; public paths keep the whole catalog) | a generated module carries descriptions or is committed, a malformed entry projects instead of failing, a rich export path changes, or a `RuntimeCatalog` input is rejected or leaks a non-rich context shape, a key a module names resolves differently from the whole catalog, a component bundle carries the whole catalog, or a public path stops resolving a shipped key |
| INV16 | build-plugin unit and real-build tests | a rich or generated locale import fails to resolve through the standard plugin |
| INV8, INV9 | raw-Intl-locale lint (module allowlist plus date-helper locale-argument check) and provider-locale regression tests, including a server/client render pair | Astryx output follows the host locale, raw `Intl` appears outside a named formatter module, an owned call omits the locale argument, or server and client output differ for the same provider locale |
-| INV10 | PlainDate and built-in date formatter tests, including locales with non-Gregorian defaults | locale selects a non-Gregorian built-in date display, changes PlainDate calendar semantics, or loses the explicit low-level display override |
+| INV10 | PlainDate and built-in date formatter tests, including locales with non-Gregorian defaults; calendar resolution and calendar-system tests (`calendarSystem.test.tsx`, `calendarSystem.test.ts`) | a locale, with or without `-u-ca-`, selects a non-Gregorian calendar, a value or constraint leaves Gregorian ISO, a calendar that needs `Temporal` breaks where it is missing, or the explicit low-level display override is lost |
| INV11, INV12 | direction helper/provider tests plus rendered RTL audit | component layout reads provider direction instead of the region, provider mutates DOM, or overrides stop composing |
| INV17 | `typeaheadMatch.test.ts`, `useTypeahead` and `useTreeFocus` tests and type-to-select tests in Selector, MultiSelector, DropdownMenu and TreeList, one case each: a combining mark ("a" reaches "Ánh"); each stroked letter (đ, ł, ø, ħ, ŧ, ƀ); ı and İ ("i" and "ı" reach "Isparta" and "İzmir"); and a typed diacritic, stroked letter, ı or İ preferring the exact match ("đ" reaches "Đào" before "Dung", "ı" reaches "Isparta" before "İzmir", "İ" reaches "İzmir" before "Isparta"); under en, vi, pl, sv and tr providers | a plain letter misses a marked or stroked first letter in any locale, i or ı misses an İ or I label, a typed diacritic, stroked letter, ı or İ does not prefer the exact match, ı or İ pairs case the non-Turkish way, two paths disagree, or folding reaches sorting or displayed text |
diff --git a/docs/specs/components/i18n/InternationalizationProvider.spec.md b/docs/specs/components/i18n/InternationalizationProvider.spec.md
index 57deef0398..f958a84806 100644
--- a/docs/specs/components/i18n/InternationalizationProvider.spec.md
+++ b/docs/specs/components/i18n/InternationalizationProvider.spec.md
@@ -18,28 +18,29 @@ verified_by:
packages/core/src/i18n/__tests__/getLocaleDirection.test.ts,
packages/core/src/i18n/__tests__/useLocale.test.tsx,
packages/core/src/i18n/useTranslator.test.tsx,
+ packages/core/src/i18n/__tests__/calendarSystem.test.tsx,
]
modules: []
families: []
design_specs: []
architecture: [architecture:internationalization]
contributing: []
-system_specs: []
+system_specs: [spec:AST-111/FR1, spec:AST-111/FR2]
---
# InternationalizationProvider component contract
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | `messages` accepts `ProviderMessagesByLocale`: each locale maps to a rich `Catalog` or a generated `RuntimeCatalog` string map. `RuntimeCatalog` and `ProviderMessagesByLocale` are exported from `@astryxdesign/core/i18n`. Existing props and the rich `MessagesByLocale` context shape are unchanged. |
-| Behavior | Astryx strings resolve override → supplied catalog → shipped English, walking exact → parent locale. Rich and runtime catalogs resolve identically; the context always exposes the rich shape. Changing any provider prop updates the subtree. A nested provider replaces its parent's context. Without a provider: locale `en`, direction `ltr`, shipped English. |
-| End-user impact | People using a translated locale see Astryx interface and assistive text in that locale where a translation exists and meaningful English otherwise; a missing translation never removes an accessible name or announcement. |
-| Builder impact | Optional: import `@astryxdesign/core/locales/<tag>.generated.js` for a smaller bundle; `<tag>.json` keeps working. Render the provider once, supply partial catalogs freely, and keep DOM `dir` aligned with the provider direction. |
-| Compatibility/readiness | Released default preserved; the provider, subpath, props, hooks, and rich context shape are stable public API; runtime-catalog input is additive. Re-render, nested-provider, and runtime-catalog behavior is covered by focused tests. |
-| Review checks | Reject reordering fallback (FR1, ORD1); hiding a key missing from every applicable source, including shipped English (FR2); a nested provider that merges parent context (FR8); the provider setting DOM `lang`/`dir` (FR5) or persisting locale (FR4); non-string translator results (FR7); host-locale output without a provider (FR6); a context value that exposes string-map entries or resolves rich and runtime input differently (FR9). |
-| Governing rules | `architecture:internationalization` INV2–INV5, INV7, INV12, INV13, INV15. |
+| Area | Contract |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | `messages` accepts `ProviderMessagesByLocale`: each locale maps to a rich `Catalog` or a generated `RuntimeCatalog` string map. `RuntimeCatalog` and `ProviderMessagesByLocale` are exported from `@astryxdesign/core/i18n`. An optional `calendar` takes a `CalendarSystem`, also exported from there; the context carries the resolved calendar as an optional `calendar`. Existing props and the rich `MessagesByLocale` context shape are unchanged. |
+| Behavior | Astryx strings resolve override → supplied catalog → shipped English, walking exact → parent locale. Rich and runtime catalogs resolve identically; the context always exposes the rich shape. Changing any provider prop updates the subtree. A nested provider replaces its parent's context. The calendar resolves from `calendar`, else `gregory`; a locale never selects it, even with a `-u-ca-` keyword. Without a provider: locale `en`, direction `ltr`, shipped English, Gregorian dates. |
+| End-user impact | People using a translated locale see Astryx interface and assistive text in that locale where a translation exists and meaningful English otherwise; a missing translation never removes an accessible name or announcement. |
+| Builder impact | Optional: import `@astryxdesign/core/locales/<tag>.generated.js` for a smaller bundle; `<tag>.json` keeps working. Render the provider once, supply partial catalogs freely, and keep DOM `dir` aligned with the provider direction. |
+| Compatibility/readiness | Released default preserved; the provider, subpath, props, hooks, and rich context shape are stable public API; runtime-catalog input is additive. Re-render, nested-provider, and runtime-catalog behavior is covered by focused tests. |
+| Review checks | Reject reordering fallback (FR1, ORD1); hiding a key missing from every applicable source, including shipped English (FR2); a nested provider that merges parent context (FR8); the provider setting DOM `lang`/`dir` (FR5) or persisting locale (FR4); non-string translator results (FR7); host-locale output without a provider (FR6); a context value that exposes string-map entries or resolves rich and runtime input differently (FR9). |
+| Governing rules | `architecture:internationalization` INV2–INV5, INV7, INV12, INV13, INV15; `spec:AST-111` FR1, FR2. |
This table is a review projection; the body below is authoritative.
@@ -71,6 +72,8 @@ Consumer migration instructions belong in consumer docs and release notes.
- The active Astryx locale and optional explicit direction for one React subtree.
- Binding supplied locale catalogs, rich or generated, and sparse overrides to a
stable translator function, and exposing them to consumers in the rich shape.
+- Resolving the subtree's calendar system from `calendar`, and exposing it on
+ the context.
- Updating provider consumers when any provider input changes.
- The no-provider English/LTR context defaults exposed by the i18n entry point.
@@ -86,29 +89,31 @@ Consumer migration instructions belong in consumer docs and release notes.
## Public concepts
-| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
-| --------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------- | ---------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Locale | Valid BCP 47 locale string | Selects lookup, ICU formatting, and provider-aware locale operations | Every provider subtree | Required on provider; `en` without one | `component:InternationalizationProvider` | stable | Callers must pass a valid tag; malformed tags may throw when formatting or collating, while static key lookup may still reach English |
-| 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 |
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| --------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------- | ---------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Locale | Valid BCP 47 locale string | Selects lookup, ICU formatting, and provider-aware locale operations | Every provider subtree | Required on provider; `en` without one | `component:InternationalizationProvider` | stable | Callers must pass a valid tag; malformed tags may throw when formatting or collating, while static key lookup may still reach English |
+| 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 |
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, and direction with values derived solely from the child provider's own props rather than merge parent context. | Released provider and nested-provider tests | 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. 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 |
### Allowed variation
@@ -145,6 +150,9 @@ Consumer prop syntax and examples remain in
the context receives the normalized rich map.
- **ORD2 — Direction resolution.** Use explicit `dir` when supplied; otherwise
derive direction from locale; outside a provider use `ltr`.
+- **ORD3 — Calendar resolution.** Use `calendar` when supplied; otherwise
+ `gregory`, also when the locale has a `-u-ca-` keyword; outside a provider use
+ `gregory` (FR10).
### Performance and resources
@@ -199,15 +207,16 @@ Consumer prop syntax and examples remain in
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| -------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
-| FR1, FR2, ORD1 | `resolve.test.ts` | exact, parent, English, missing source key | Reordering fallback or hiding a missing source key fails focused tests | `audit:InternationalizationProvider/behavior` |
-| FR3, PR1 | `useTranslator.test.tsx`, `useLocale.test.tsx`, `InternationalizationProvider.test.tsx` | stable inputs; locale, message, override, and dir swaps | A stale translator/direction or needless identity churn fails these tests | `audit:InternationalizationProvider/performance` |
-| FR5, ORD2 | `useDirection.test.tsx`, `getLocaleDirection.test.ts` | derived, explicit, invalid locale, no provider | Setting DOM direction or ignoring explicit override fails source/tests | `audit:InternationalizationProvider/rtl` |
-| FR6 | `useTranslator.test.tsx`, `useLocale.test.tsx`, `useDirection.test.tsx` | no provider | Host locale or missing English output fails | `audit:InternationalizationProvider/behavior` |
-| FR7, AR1, AR2 | component translation tests and hardcoded-string lint | visible text, aria label, announcement, missing translation | Non-string output or untranslated owned text fails tests/lint | `audit:InternationalizationProvider/accessibility` |
-| FR8 | `InternationalizationProvider.test.tsx` | parent plus child provider | Parent messages, overrides, or direction leaking into the child fails | `audit:InternationalizationProvider/behavior` |
-| FR9, ORD1a | `useTranslator.test.tsx`, `resolve.test.ts` runtime-catalog cases | generated string map, rich catalog, mixed | A rejected string map, a string-map entry on the context, or divergent output between shapes fails | `audit:InternationalizationProvider/behavior` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| -------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
+| FR1, FR2, ORD1 | `resolve.test.ts` | exact, parent, English, missing source key | Reordering fallback or hiding a missing source key fails focused tests | `audit:InternationalizationProvider/behavior` |
+| FR3, PR1 | `useTranslator.test.tsx`, `useLocale.test.tsx`, `InternationalizationProvider.test.tsx` | stable inputs; locale, message, override, and dir swaps | A stale translator/direction or needless identity churn fails these tests | `audit:InternationalizationProvider/performance` |
+| FR5, ORD2 | `useDirection.test.tsx`, `getLocaleDirection.test.ts` | derived, explicit, invalid locale, no provider | Setting DOM direction or ignoring explicit override fails source/tests | `audit:InternationalizationProvider/rtl` |
+| FR6 | `useTranslator.test.tsx`, `useLocale.test.tsx`, `useDirection.test.tsx` | no provider | Host locale or missing English output fails | `audit:InternationalizationProvider/behavior` |
+| FR7, AR1, AR2 | component translation tests and hardcoded-string lint | visible text, aria label, announcement, missing translation | Non-string output or untranslated owned text fails tests/lint | `audit:InternationalizationProvider/accessibility` |
+| FR8 | `InternationalizationProvider.test.tsx` | parent plus child provider | Parent messages, overrides, or direction leaking into the child fails | `audit:InternationalizationProvider/behavior` |
+| FR9, ORD1a | `useTranslator.test.tsx`, `resolve.test.ts` runtime-catalog cases | generated string map, rich catalog, mixed | A rejected string map, a string-map entry on the context, or divergent output between shapes fails | `audit:InternationalizationProvider/behavior` |
+| FR10, ORD3 | `i18n/__tests__/calendarSystem.test.tsx` resolution-order and identifier cases | every identifier; unknown identifier, including `islamic`; component over provider over default; bare `fa-IR` and `th-TH`; a `-u-ca-` locale stays `gregory` | A locale selecting a calendar, a changed precedence, or an unknown identifier that throws or warns twice fails | `audit:InternationalizationProvider/behavior` |
## Decision log
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index 496618e758..a5f3198c6b 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -1362,6 +1362,7 @@ component InputGroupText(props: InputGroupTextProps)
prop xstyle?: StyleXStyles
inherits AriaAttributes, DOMAttributes, HTMLAttributes
component InternationalizationProvider(props: InternationalizationProviderProps)
+ prop calendar?: CalendarSystem
prop children: ReactNode
prop dir?: 'ltr' | 'rtl'
prop locale: Locale
@@ -3759,6 +3760,7 @@ interface CalendarDay
interface CalendarHandle
navigateTo: (date: ISODateString) => void
type CalendarProps = CalendarSingleProps | CalendarRangeProps (props of Calendar)
+type CalendarSystem = 'gregory' | 'iso8601' | 'buddhist' | 'roc' | 'japanese' | 'persian' | 'indian' | 'hebrew' | 'chinese' | 'dangi' | 'coptic' | 'ethiopic' | 'ethioaa' | 'islamic-c … #85e5f84c
interface CardProps extends BaseProps<HTMLDivElement> (props of Card)
type CardVariant = keyof CardVariantMap
interface CardVariantMap
@@ -4546,6 +4548,7 @@ interface IntegerOperatorValue
units?: string
type InteractiveRole = 'link' | 'button' | 'inert'
interface InternationalizationContextValue
+ calendar?: CalendarSystem
direction: 'ltr' | 'rtl'
locale: Locale
messages: MessagesByLocale
@@ -9172,6 +9175,7 @@ useTypeahead (.)
### Also exported from an earlier entry point
```text
+CalendarSystem (.)
Catalog (.)
InternationalizationContext (.)
InternationalizationContextValue (.)
diff --git a/packages/core/package.json b/packages/core/package.json
index dacf3da380..4d2003defd 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -899,7 +899,8 @@
"@testing-library/jest-dom": "catalog:",
"@testing-library/react": "catalog:",
"@types/babel__core": "^7.20.5",
- "tailwindcss": "^4.3.2"
+ "tailwindcss": "^4.3.2",
+ "temporal-polyfill": "^1.0.6"
},
"dependencies": {
"intl-messageformat": "^11.2.9"
diff --git a/packages/core/src/i18n/InternationalizationContext.ts b/packages/core/src/i18n/InternationalizationContext.ts
index 0e2c451fc2..3372813fb7 100644
--- a/packages/core/src/i18n/InternationalizationContext.ts
+++ b/packages/core/src/i18n/InternationalizationContext.ts
@@ -25,10 +25,16 @@
import {createContext} from 'react';
import {getResolve} from './resolve';
import type {Locale, MessagesByLocale, Overrides} from './types';
+import type {CalendarSystem} from '../utils/calendarSystem';
export interface InternationalizationContextValue {
locale: Locale;
direction: 'ltr' | 'rtl';
+ /**
+ * The provider's resolved calendar system. A context without it means
+ * Gregorian dates.
+ */
+ calendar?: CalendarSystem;
messages: MessagesByLocale;
overrides?: Overrides;
translate: ReturnType<typeof getResolve>;
diff --git a/packages/core/src/i18n/InternationalizationProvider.doc.mjs b/packages/core/src/i18n/InternationalizationProvider.doc.mjs
index 4878cc3c5e..8325e353c8 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, and direction to descendant Astryx components. It renders no DOM element.',
+ '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.',
},
],
bestPractices: [
@@ -50,6 +50,11 @@ export const docs = {
description:
"Set the `dir` attribute on `<html>` (or a wrapping element) yourself; the provider does not set it. Astryx components mirror layout and directional icons from the DOM `dir`, so an RTL locale won't visually mirror without it. Use `getLocaleDirection(locale)` to derive the value for both the provider and the DOM.",
},
+ {
+ 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.',
+ },
{
guidance: false,
description:
@@ -86,6 +91,13 @@ export const docs = {
description:
'Explicit text-direction override for the context. When omitted, direction is derived from `locale` via `Intl.Locale.getTextInfo()`. This sets the direction Astryx reads, but it does NOT set the DOM `dir` attribute; you must set `dir` on `<html>` (or a wrapping element) yourself, since Astryx components mirror layout and directional icons from the DOM `dir`, not from this prop. Set both to the same value and keep them in sync.',
},
+ {
+ name: 'calendar',
+ 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.",
+ },
{
name: 'children',
type: 'ReactNode',
@@ -124,6 +136,20 @@ export function AppI18n({children}: {children: ReactNode}) {
{children}
</InternationalizationProvider>
);
+}`,
+ },
+ {
+ label: 'Select the Persian calendar',
+ code: `import type {ReactNode} from 'react';
+import {InternationalizationProvider} from '@astryxdesign/core/i18n';
+
+// Values stay Gregorian ISO dates, for example '2026-10-30'.
+export function AppI18n({children}: {children: ReactNode}) {
+ return (
+ <InternationalizationProvider locale="fa-IR" calendar="persian">
+ {children}
+ </InternationalizationProvider>
+ );
}`,
},
{
@@ -190,5 +216,7 @@ export const docsDense = {
'map of BCP 47 tag to a rich Catalog or generated RuntimeCatalog; "en" is always available',
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',
},
};
diff --git a/packages/core/src/i18n/InternationalizationProvider.tsx b/packages/core/src/i18n/InternationalizationProvider.tsx
index 84f2f91fc9..87d069fd96 100644
--- a/packages/core/src/i18n/InternationalizationProvider.tsx
+++ b/packages/core/src/i18n/InternationalizationProvider.tsx
@@ -4,9 +4,9 @@
/**
* @file InternationalizationProvider.tsx
- * @input React, InternationalizationContext, i18n types
+ * @input React, InternationalizationContext, i18n types, calendar resolution
* @output Exports InternationalizationProvider component and props type
- * @position Provider component for astryx i18n locale + messages
+ * @position Provider component for astryx i18n locale, messages, and calendar
*
* Wraps a subtree with a locale and (optional) additional message catalogs +
* overrides. Astryx components inside the subtree resolve their strings via
@@ -22,6 +22,8 @@
import {useMemo, type ReactNode} from 'react';
import {InternationalizationContext} from './InternationalizationContext';
import {getLocaleDirection} from './getLocaleDirection';
+import {resolveCalendarSystem} from './useCalendarSystem';
+import type {CalendarSystem} from '../utils/calendarSystem';
import type {
Locale,
MessagesByLocale,
@@ -30,6 +32,8 @@ import type {
} from './types';
import {getResolve} from './resolve';
+const PROVIDER_NAME = 'InternationalizationProvider';
+
function normalizeMessages(
messages: ProviderMessagesByLocale,
): MessagesByLocale {
@@ -100,6 +104,23 @@ export interface InternationalizationProviderProps {
* in sync (e.g. `dir={getLocaleDirection(locale)}` on both).
*/
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.
+ *
+ * @example
+ * ```
+ * <InternationalizationProvider locale="fa-IR" calendar="persian">
+ * ```
+ */
+ calendar?: CalendarSystem;
children: ReactNode;
}
@@ -112,19 +133,28 @@ export function InternationalizationProvider({
messages,
overrides,
dir,
+ calendar: calendarProp,
children,
}: InternationalizationProviderProps) {
const direction = dir ?? getLocaleDirection(locale);
+ const calendar = useMemo(
+ () =>
+ calendarProp != null
+ ? resolveCalendarSystem(calendarProp, PROVIDER_NAME)
+ : 'gregory',
+ [calendarProp],
+ );
const value = useMemo(() => {
const providedMessages = messages ?? {};
return {
locale,
direction,
+ calendar,
messages: normalizeMessages(providedMessages),
overrides,
translate: getResolve(locale, providedMessages, overrides),
};
- }, [locale, direction, messages, overrides]);
+ }, [locale, direction, calendar, messages, overrides]);
return (
<InternationalizationContext value={value}>
{children}
diff --git a/packages/core/src/i18n/__tests__/calendarSystem.test.tsx b/packages/core/src/i18n/__tests__/calendarSystem.test.tsx
new file mode 100644
index 0000000000..289f6ece4e
--- /dev/null
+++ b/packages/core/src/i18n/__tests__/calendarSystem.test.tsx
@@ -0,0 +1,195 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file calendarSystem.test.tsx
+ * @input InternationalizationProvider, useCalendarSystem
+ * @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 {use} from 'react';
+import {InternationalizationProvider} from '../InternationalizationProvider';
+import {InternationalizationContext} from '../InternationalizationContext';
+import {useCalendarSystem} from '../useCalendarSystem';
+import {
+ CALENDAR_SYSTEMS,
+ type CalendarSystem,
+} from '../../utils/calendarSystem';
+import {__resetDevWarnings} from '../../utils/devWarning';
+
+const globals = globalThis as {Temporal?: unknown};
+let savedTemporal: unknown;
+
+beforeAll(() => {
+ savedTemporal = globals.Temporal;
+ delete globals.Temporal;
+});
+
+afterAll(() => {
+ if (savedTemporal !== undefined) {
+ globals.Temporal = savedTemporal;
+ }
+});
+
+afterEach(() => {
+ __resetDevWarnings();
+ vi.restoreAllMocks();
+});
+
+function Probe({calendar}: {calendar?: CalendarSystem}) {
+ const requested = use(InternationalizationContext).calendar;
+ const shown = useCalendarSystem(calendar, 'Probe');
+ return (
+ <>
+ <span data-testid="requested">{requested ?? 'none'}</span>
+ <span data-testid="shown">{shown}</span>
+ </>
+ );
+}
+
+function renderProbe(
+ provider: {locale: string; calendar?: CalendarSystem} | null,
+ calendar?: CalendarSystem,
+) {
+ const probe = <Probe calendar={calendar} />;
+ const view = render(
+ provider == null ? (
+ probe
+ ) : (
+ <InternationalizationProvider {...provider}>
+ {probe}
+ </InternationalizationProvider>
+ ),
+ );
+ const result = {
+ requested: view.getByTestId('requested').textContent,
+ shown: view.getByTestId('shown').textContent,
+ };
+ view.unmount();
+ return result;
+}
+
+function silenceWarnings() {
+ return vi.spyOn(console, 'warn').mockImplementation(() => {});
+}
+
+describe('calendar resolution order', () => {
+ it('is Gregorian without a provider', () => {
+ expect(renderProbe(null).shown).toBe('gregory');
+ });
+
+ it("uses the component's calendar over the provider's", () => {
+ expect(
+ renderProbe({locale: 'th-TH-u-ca-buddhist', calendar: 'roc'}, 'japanese')
+ .shown,
+ ).toBe('japanese');
+ });
+
+ it("uses the provider's calendar over a -u-ca- keyword in its locale", () => {
+ expect(
+ renderProbe({locale: 'th-TH-u-ca-buddhist', calendar: 'roc'}).shown,
+ ).toBe('roc');
+ });
+
+ it('ignores a -u-ca- keyword in the provider locale', () => {
+ const result = renderProbe({locale: 'th-TH-u-ca-buddhist'});
+ expect(result.requested).toBe('gregory');
+ expect(result.shown).toBe('gregory');
+ });
+
+ it("never applies a locale's default calendar", () => {
+ expect(renderProbe({locale: 'fa-IR'}).shown).toBe('gregory');
+ expect(renderProbe({locale: 'th-TH'}).shown).toBe('gregory');
+ });
+
+ it('keeps the calendar independent of the language', () => {
+ expect(renderProbe({locale: 'en', calendar: 'buddhist'}).shown).toBe(
+ 'buddhist',
+ );
+ });
+});
+
+describe('calendar identifiers', () => {
+ it.each(CALENDAR_SYSTEMS)('the provider accepts %s', calendar => {
+ silenceWarnings();
+ expect(renderProbe({locale: 'en', calendar}).requested).toBe(calendar);
+ });
+
+ it('resolves the islamic identifier to gregory and warns', () => {
+ const warn = silenceWarnings();
+ const islamic = 'islamic' as CalendarSystem;
+ expect(renderProbe({locale: 'ar', calendar: islamic}).requested).toBe(
+ 'gregory',
+ );
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('"islamic"'));
+ });
+
+ it('ignores a -u-ca-islamic keyword without a warning', () => {
+ const warn = silenceWarnings();
+ expect(renderProbe({locale: 'ar-u-ca-islamic'}).requested).toBe('gregory');
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('resolves an unknown identifier to gregory and warns once', () => {
+ const warn = silenceWarnings();
+ const unknown = 'martian' as CalendarSystem;
+ expect(renderProbe({locale: 'en', calendar: unknown}).shown).toBe(
+ 'gregory',
+ );
+ expect(renderProbe(null, unknown).shown).toBe('gregory');
+ const unsupported = warn.mock.calls.filter(([message]) =>
+ String(message).includes('"martian"'),
+ );
+ expect(unsupported).toHaveLength(1);
+ });
+});
+
+describe('without Temporal', () => {
+ it('shows Gregorian for a calendar that needs Temporal and warns once for it', () => {
+ const warn = silenceWarnings();
+ expect(renderProbe({locale: 'fa-IR', calendar: 'persian'}).shown).toBe(
+ 'gregory',
+ );
+ expect(renderProbe(null, 'persian').shown).toBe('gregory');
+ expect(renderProbe(null, 'hebrew').shown).toBe('gregory');
+
+ const messages = warn.mock.calls.map(([message]) => String(message));
+ expect(messages.filter(m => m.includes('"persian"'))).toHaveLength(1);
+ expect(messages.filter(m => m.includes('"hebrew"'))).toHaveLength(1);
+ expect(messages[0]).toContain('temporal-polyfill/full/global');
+ });
+
+ it('treats a Temporal without the calendar as missing', () => {
+ const warn = silenceWarnings();
+ // The default temporal-polyfill build knows only the ISO calendar.
+ globals.Temporal = {
+ PlainDate: class {
+ constructor(_y: number, _m: number, _d: number, calendar: string) {
+ if (calendar !== 'iso8601') {
+ throw new RangeError(`Unknown calendar ${calendar}`);
+ }
+ }
+ },
+ };
+ try {
+ expect(renderProbe(null, 'persian').shown).toBe('gregory');
+ } finally {
+ delete globals.Temporal;
+ }
+ expect(String(warn.mock.calls[0]?.[0])).toContain(
+ 'needs a Temporal that supports it',
+ );
+ });
+
+ it.each(['gregory', 'iso8601', 'buddhist', 'roc', 'japanese'] as const)(
+ 'shows %s with no warning',
+ calendar => {
+ const warn = silenceWarnings();
+ expect(renderProbe(null, calendar).shown).toBe(calendar);
+ expect(warn).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/packages/core/src/i18n/index.ts b/packages/core/src/i18n/index.ts
index fe9077e999..7f16a6cef0 100644
--- a/packages/core/src/i18n/index.ts
+++ b/packages/core/src/i18n/index.ts
@@ -15,6 +15,7 @@
* - useDirection — hook returning the ambient text direction
* - getLocaleDirection — server-safe locale → direction helper
* - Translator — interface for consumer-injected runtimes
+ * - CalendarSystem — the calendars date components can show
*
* `useTranslator` and `InternationalizationContext` are the public paths
* that resolve any Astryx key, so they register the whole English catalog.
@@ -39,6 +40,7 @@ export {useLocale} from './useLocale';
export {useCollator} from './useCollator';
export {useDirection} from './useDirection';
export {getLocaleDirection} from './getLocaleDirection';
+export type {CalendarSystem} from '../utils/calendarSystem';
export type {Translator} from './translator';
export type {
Locale,
diff --git a/packages/core/src/i18n/useCalendarSystem.ts b/packages/core/src/i18n/useCalendarSystem.ts
new file mode 100644
index 0000000000..ac72368f3a
--- /dev/null
+++ b/packages/core/src/i18n/useCalendarSystem.ts
@@ -0,0 +1,80 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @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.
+ */
+
+import {use} from 'react';
+import {InternationalizationContext} from './InternationalizationContext';
+import {
+ type CalendarSystem,
+ isCalendarSystem,
+ isCalendarSystemAvailable,
+} from '../utils/calendarSystem';
+import {warnOnce} from '../utils/devWarning';
+
+/**
+ * Normalizes a calendar identifier. An identifier outside `CalendarSystem`
+ * resolves to `gregory` and warns once in development.
+ */
+export function resolveCalendarSystem(
+ id: string,
+ source: string,
+): CalendarSystem {
+ if (isCalendarSystem(id)) {
+ return id;
+ }
+ warnOnce(
+ `calendar-unsupported:${id}`,
+ source,
+ `The calendar "${id}" is not supported; showing Gregorian dates.`,
+ );
+ return 'gregory';
+}
+
+/**
+ * A calendar this runtime can show, else `gregory`. Calendars outside the
+ * Gregorian-aligned set need a `Temporal` that supports them. The fallback
+ * warns once for each calendar, on the server and in the browser.
+ */
+function availableCalendarOrGregorian(
+ calendar: CalendarSystem,
+ source: string,
+): CalendarSystem {
+ if (isCalendarSystemAvailable(calendar)) {
+ return calendar;
+ }
+ warnOnce(
+ `calendar-unavailable:${calendar}`,
+ source,
+ `The "${calendar}" calendar needs a Temporal that supports it, and this ` +
+ 'runtime has none; showing Gregorian dates. Load a Temporal polyfill ' +
+ "with every calendar, such as 'temporal-polyfill/full/global', on the " +
+ 'server and in the browser.',
+ );
+ return 'gregory';
+}
+
+/**
+ * The calendar a date component shows: its own `calendar`, else the
+ * provider's resolved calendar, else `gregory`. It resolves during render, so
+ * the server and the browser agree when both have `Temporal` or both lack it.
+ */
+export function useCalendarSystem(
+ calendar: CalendarSystem | undefined,
+ source: string,
+): CalendarSystem {
+ const context = use(InternationalizationContext);
+ const requested =
+ calendar != null
+ ? resolveCalendarSystem(calendar, source)
+ : (context.calendar ?? 'gregory');
+ return availableCalendarOrGregorian(requested, source);
+}
diff --git a/packages/core/src/utils/calendarSystem.test.ts b/packages/core/src/utils/calendarSystem.test.ts
new file mode 100644
index 0000000000..c361f2bdc4
--- /dev/null
+++ b/packages/core/src/utils/calendarSystem.test.ts
@@ -0,0 +1,350 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import 'temporal-polyfill/full/global';
+import {describe, expect, it} from 'vitest';
+import {
+ CALENDAR_SYSTEMS,
+ type CalendarMonth,
+ type CalendarSystem,
+ calendarAddMonths,
+ calendarDateFromFields,
+ calendarDayOfMonth,
+ calendarMonthOf,
+ calendarMonthsInYear,
+ calendarShiftMonths,
+ calendarShiftYears,
+ formatCalendarDate,
+ formatCalendarMonthLabel,
+ isCalendarSystemAvailable,
+ isGregorianAligned,
+ isInCalendarMonth,
+} from './calendarSystem';
+import {
+ DATE_FORMAT_WITH_WEEKDAY,
+ type PlainDate,
+ plainDateAddDays,
+ plainDateFromISO,
+ plainDateIsAfter,
+ plainDateToISO,
+} from './plainDate';
+import type {ISODateString} from './dateTypes';
+
+const iso = plainDateFromISO;
+
+interface OracleDate {
+ readonly month: number;
+ readonly monthsInYear: number;
+}
+
+// The polyfill loaded above is the independent oracle for month positions.
+function oracle(calendar: CalendarSystem, pd: PlainDate): OracleDate {
+ const temporal = (
+ globalThis as unknown as {
+ Temporal: {
+ PlainDate: new (
+ y: number,
+ m: number,
+ d: number,
+ c: string,
+ ) => OracleDate;
+ };
+ }
+ ).Temporal;
+ return new temporal.PlainDate(pd.year, pd.month, pd.day, calendar);
+}
+
+function monthAt(calendar: CalendarSystem, date: ISODateString) {
+ const month = calendarMonthOf(calendar, iso(date));
+ return {
+ start: plainDateToISO(month.start),
+ end: plainDateToISO(month.end),
+ length: month.length,
+ };
+}
+
+describe('calendar month structure at known dates', () => {
+ it('Persian Aban 1405 runs from 2026-10-23 to 2026-11-21', () => {
+ expect(monthAt('persian', '2026-10-30')).toEqual({
+ start: '2026-10-23',
+ end: '2026-11-21',
+ length: 30,
+ });
+ expect(calendarDayOfMonth('persian', iso('2026-10-30'))).toBe(8);
+ });
+
+ it('Hebrew leap year 5784 has Adar I of 30 days and Adar II of 29 days', () => {
+ expect(monthAt('hebrew', '2024-02-20')).toEqual({
+ start: '2024-02-10',
+ end: '2024-03-10',
+ length: 30,
+ });
+ expect(monthAt('hebrew', '2024-03-20')).toEqual({
+ start: '2024-03-11',
+ end: '2024-04-08',
+ length: 29,
+ });
+ });
+
+ it('Ethiopic Pagume 2018 has 5 days from 2026-09-06', () => {
+ expect(monthAt('ethiopic', '2026-09-08')).toEqual({
+ start: '2026-09-06',
+ end: '2026-09-10',
+ length: 5,
+ });
+ });
+
+ it('Japanese months stay Gregorian across the era change of 2019-05-01', () => {
+ expect(monthAt('japanese', '2019-04-30')).toEqual({
+ start: '2019-04-01',
+ end: '2019-04-30',
+ length: 30,
+ });
+ expect(monthAt('japanese', '2019-05-01')).toEqual({
+ start: '2019-05-01',
+ end: '2019-05-31',
+ length: 31,
+ });
+ expect(
+ formatCalendarMonthLabel(
+ 'japanese',
+ calendarMonthOf('japanese', iso('2019-04-30')),
+ 'en',
+ ),
+ ).toContain('Heisei');
+ expect(
+ formatCalendarMonthLabel(
+ 'japanese',
+ calendarMonthOf('japanese', iso('2019-05-01')),
+ 'en',
+ ),
+ ).toContain('Reiwa');
+ });
+
+ it('Chinese 2023 has a leap second month after the second month', () => {
+ const second = calendarMonthOf('chinese', iso('2023-03-01'));
+ const leapSecond = calendarAddMonths('chinese', second, 1);
+ expect(plainDateToISO(second.start)).toBe('2023-02-20');
+ expect(second.length).toBe(30);
+ expect(plainDateToISO(leapSecond.start)).toBe('2023-03-22');
+ expect(leapSecond.length).toBe(29);
+ expect(oracle('chinese', leapSecond.start).monthsInYear).toBe(13);
+ });
+
+ it('labels a Persian month in the calendar and the locale', () => {
+ const aban = calendarMonthOf('persian', iso('2026-10-30'));
+ expect(formatCalendarMonthLabel('persian', aban, 'en')).toContain(
+ 'Aban 1405',
+ );
+ expect(formatCalendarMonthLabel('persian', aban, 'fa-IR')).toContain(
+ 'آبان',
+ );
+ });
+});
+
+describe('calendar month invariants from 1900 through 2100', () => {
+ const last = iso('2100-12-31');
+ const temporalCalendars = CALENDAR_SYSTEMS.filter(
+ calendar => !isGregorianAligned(calendar),
+ );
+
+ it.each(temporalCalendars)(
+ '%s months are contiguous, of sane length, and 12 or 13 to a year',
+ calendar => {
+ let month: CalendarMonth = calendarMonthOf(calendar, iso('1900-01-01'));
+ let monthsSinceYearStart: number | null = null;
+ let expectedMonthsInYear = 0;
+ while (!plainDateIsAfter(month.start, last)) {
+ expect(month.length).toBeGreaterThanOrEqual(5);
+ expect(month.length).toBeLessThanOrEqual(31);
+ expect(isInCalendarMonth(month.start, month)).toBe(true);
+ expect(isInCalendarMonth(month.end, month)).toBe(true);
+
+ const position = oracle(calendar, month.start);
+ if (position.month === 1) {
+ if (monthsSinceYearStart != null) {
+ expect(monthsSinceYearStart).toBe(expectedMonthsInYear);
+ }
+ monthsSinceYearStart = 0;
+ expectedMonthsInYear = position.monthsInYear;
+ expect([12, 13]).toContain(expectedMonthsInYear);
+ }
+ if (monthsSinceYearStart != null) {
+ monthsSinceYearStart += 1;
+ }
+
+ const next = calendarAddMonths(calendar, month, 1);
+ expect(plainDateToISO(next.start)).toBe(
+ plainDateToISO(plainDateAddDays(month.end, 1)),
+ );
+ month = next;
+ }
+ },
+ );
+
+ it.each(['gregory', 'iso8601', 'buddhist', 'roc', 'japanese'] as const)(
+ '%s months are the Gregorian months',
+ calendar => {
+ expect(monthAt(calendar, '2024-02-15')).toEqual({
+ start: '2024-02-01',
+ end: '2024-02-29',
+ length: 29,
+ });
+ },
+ );
+});
+
+describe('calendar month and year steps', () => {
+ it('a month step keeps the day of the month and clamps it', () => {
+ // 31 Shahrivar 1405 → Mehr has 30 days.
+ expect(
+ plainDateToISO(calendarShiftMonths('persian', iso('2026-09-22'), 1)),
+ ).toBe('2026-10-22');
+ expect(
+ plainDateToISO(calendarShiftMonths('gregory', iso('2026-01-31'), 1)),
+ ).toBe('2026-02-28');
+ });
+
+ it('a Hebrew year step from Adar I lands in Adar, clamped', () => {
+ // 30 Adar I 5784 → 5785 has no Adar I; Adar has 29 days.
+ expect(
+ plainDateToISO(calendarShiftYears('hebrew', iso('2024-03-10'), 1)),
+ ).toBe('2025-03-29');
+ });
+
+ it('an Ethiopic year step keeps the month, unlike twelve month steps', () => {
+ const meskerem2018 = iso('2025-09-11');
+ expect(
+ plainDateToISO(calendarShiftMonths('ethiopic', meskerem2018, 12)),
+ ).toBe('2026-09-06');
+ expect(
+ plainDateToISO(calendarShiftYears('ethiopic', meskerem2018, 1)),
+ ).toBe('2026-09-11');
+ });
+
+ it('a Gregorian year step moves to the same day a year away, clamped', () => {
+ expect(
+ plainDateToISO(calendarShiftYears('gregory', iso('2026-06-15'), -1)),
+ ).toBe('2025-06-15');
+ expect(
+ plainDateToISO(calendarShiftYears('gregory', iso('2024-02-29'), 1)),
+ ).toBe('2025-02-28');
+ });
+});
+
+describe('calendar availability', () => {
+ it('every calendar is available with the full polyfill', () => {
+ for (const calendar of CALENDAR_SYSTEMS) {
+ expect(isCalendarSystemAvailable(calendar)).toBe(true);
+ }
+ });
+});
+
+describe('calendar labels', () => {
+ const day = iso('2027-02-06');
+ const label = (calendar: CalendarSystem) =>
+ formatCalendarDate(calendar, day, DATE_FORMAT_WITH_WEEKDAY, 'en');
+ const heading = (calendar: CalendarSystem) =>
+ formatCalendarMonthLabel(calendar, calendarMonthOf(calendar, day), 'en');
+
+ it.each([
+ ['gregory', '2027'],
+ ['iso8601', '2027'],
+ ['buddhist', '2570'],
+ ['roc', '116'],
+ ['japanese', 'Reiwa'],
+ ] as const)(
+ '%s names the Gregorian month, the day, and its own year',
+ (calendar, year) => {
+ expect(label(calendar)).toMatch(/^Saturday, February 6, /);
+ expect(label(calendar)).toContain(year);
+ expect(heading(calendar)).toMatch(/^February /);
+ expect(heading(calendar)).toContain(year);
+ },
+ );
+
+ it('labels iso8601 exactly as gregory', () => {
+ expect(label('iso8601')).toBe(label('gregory'));
+ expect(heading('iso8601')).toBe(heading('gregory'));
+ });
+
+ it('keeps the Intl label where Intl and Temporal agree', () => {
+ expect(
+ formatCalendarDate(
+ 'persian',
+ iso('2026-10-30'),
+ DATE_FORMAT_WITH_WEEKDAY,
+ 'en',
+ ),
+ ).toBe('Friday, Aban 8, 1405 AP');
+ });
+});
+
+describe('dates from calendar fields', () => {
+ const toISO = (pd: PlainDate | null) =>
+ pd == null ? null : plainDateToISO(pd);
+
+ it('converts calendar fields to the Gregorian date', () => {
+ expect(
+ toISO(
+ calendarDateFromFields('persian', {
+ year: 1405,
+ monthCode: 'M08',
+ day: 11,
+ }),
+ ),
+ ).toBe('2026-11-02');
+ expect(
+ toISO(calendarDateFromFields('hebrew', {year: 5784, month: 6, day: 1})),
+ ).toBe('2024-02-10');
+ expect(
+ toISO(
+ calendarDateFromFields('ethiopic', {
+ era: 'aa',
+ eraYear: 7519,
+ monthCode: 'M01',
+ day: 1,
+ }),
+ ),
+ ).toBe('2026-09-11');
+ });
+
+ it('returns null for a date the calendar does not have', () => {
+ expect(
+ calendarDateFromFields('persian', {
+ year: 1404,
+ monthCode: 'M12',
+ day: 30,
+ }),
+ ).toBeNull();
+ expect(
+ calendarDateFromFields('hebrew', {year: 5785, monthCode: 'M05L', day: 1}),
+ ).toBeNull();
+ expect(
+ calendarDateFromFields('ethiopic', {
+ year: 2016,
+ monthCode: 'M13',
+ day: 6,
+ }),
+ ).toBeNull();
+ expect(
+ calendarDateFromFields('chinese', {
+ year: 2026,
+ monthCode: 'M06L',
+ day: 1,
+ }),
+ ).toBeNull();
+ expect(
+ calendarDateFromFields('islamic-umalqura', {
+ year: 1448,
+ monthCode: 'M01',
+ day: 30,
+ }),
+ ).toBeNull();
+ });
+
+ it('counts the months of the calendar year', () => {
+ expect(calendarMonthsInYear('hebrew', iso('2024-02-10'))).toBe(13);
+ expect(calendarMonthsInYear('hebrew', iso('2025-03-01'))).toBe(12);
+ expect(calendarMonthsInYear('gregory', iso('2025-03-01'))).toBe(12);
+ });
+});
diff --git a/packages/core/src/utils/calendarSystem.ts b/packages/core/src/utils/calendarSystem.ts
new file mode 100644
index 0000000000..f0edbc3f45
--- /dev/null
+++ b/packages/core/src/utils/calendarSystem.ts
@@ -0,0 +1,426 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @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. Values
+ * stay Gregorian PlainDates. Temporal owns the arithmetic of every calendar
+ * whose months are not Gregorian.
+ */
+
+import type {Locale} from '../i18n/types';
+import type {PlainDate} from './dateTypes';
+import {
+ dateTimeFormatFor,
+ plainDateAddDays,
+ plainDateAddMonths,
+ plainDateFormat,
+ plainDateFormatDayNumber,
+ plainDateFormatStandaloneMonthYear,
+ plainDateFormatToParts,
+ plainDateIsInRange,
+ getDaysInMonth,
+} from './plainDate';
+
+/**
+ * A calendar system that date components can show: the calendars that
+ * ECMA-402 and Temporal require. Values stay Gregorian ISO dates in every
+ * calendar.
+ */
+export type CalendarSystem =
+ | 'gregory'
+ | 'iso8601'
+ | 'buddhist'
+ | 'roc'
+ | 'japanese'
+ | 'persian'
+ | 'indian'
+ | 'hebrew'
+ | 'chinese'
+ | 'dangi'
+ | 'coptic'
+ | 'ethiopic'
+ | 'ethioaa'
+ | 'islamic-civil'
+ | 'islamic-tbla'
+ | 'islamic-umalqura';
+
+// A record, so the compiler checks that it lists every calendar exactly once.
+const KNOWN_CALENDARS: Readonly<Record<CalendarSystem, true>> = {
+ gregory: true,
+ iso8601: true,
+ buddhist: true,
+ roc: true,
+ japanese: true,
+ persian: true,
+ indian: true,
+ hebrew: true,
+ chinese: true,
+ dangi: true,
+ coptic: true,
+ ethiopic: true,
+ ethioaa: true,
+ 'islamic-civil': true,
+ 'islamic-tbla': true,
+ 'islamic-umalqura': true,
+};
+
+export const CALENDAR_SYSTEMS = Object.keys(
+ KNOWN_CALENDARS,
+) as ReadonlyArray<CalendarSystem>;
+
+const GREGORIAN_ALIGNED: ReadonlySet<CalendarSystem> = new Set([
+ 'gregory',
+ 'iso8601',
+ 'buddhist',
+ 'roc',
+ 'japanese',
+]);
+
+/** Whether the calendar's months and days are the Gregorian ones. */
+export function isGregorianAligned(calendar: CalendarSystem): boolean {
+ return GREGORIAN_ALIGNED.has(calendar);
+}
+
+export function isCalendarSystem(value: string): value is CalendarSystem {
+ return Object.hasOwn(KNOWN_CALENDARS, value);
+}
+
+// The published types must not need the `esnext.temporal` library.
+// This module declares only the Temporal members it reads.
+interface TemporalPlainDate {
+ readonly year: number;
+ readonly month: number;
+ readonly day: number;
+ readonly daysInMonth: number;
+ readonly monthsInYear: number;
+ with(fields: {day: number}): TemporalPlainDate;
+ add(duration: {months?: number; years?: number}): TemporalPlainDate;
+ withCalendar(calendar: 'iso8601'): TemporalPlainDate;
+}
+
+interface TemporalPlainDateConstructor {
+ new (
+ isoYear: number,
+ isoMonth: number,
+ isoDay: number,
+ calendar: string,
+ ): TemporalPlainDate;
+ from(
+ fields: CalendarDateFields & {calendar: string},
+ options: {overflow: 'reject'},
+ ): TemporalPlainDate;
+}
+
+interface TemporalNamespace {
+ PlainDate: TemporalPlainDateConstructor;
+}
+
+function getTemporal(): TemporalNamespace | undefined {
+ const temporal = (globalThis as {Temporal?: Partial<TemporalNamespace>})
+ .Temporal;
+ return typeof temporal?.PlainDate === 'function'
+ ? (temporal as TemporalNamespace)
+ : undefined;
+}
+
+// The key is the Temporal object, so a polyfill that loads later gets its
+// own probe.
+const supportedCalendars = new WeakMap<object, Map<CalendarSystem, boolean>>();
+
+/**
+ * Whether this runtime can show the calendar. Gregorian-aligned calendars
+ * always can. The others need a `Temporal` that knows the calendar: a
+ * polyfill build without non-ISO calendars throws for them.
+ */
+export function isCalendarSystemAvailable(calendar: CalendarSystem): boolean {
+ if (isGregorianAligned(calendar)) {
+ return true;
+ }
+ const temporal = getTemporal();
+ if (temporal == null) {
+ return false;
+ }
+ let known = supportedCalendars.get(temporal);
+ if (known == null) {
+ known = new Map();
+ supportedCalendars.set(temporal, known);
+ }
+ let isSupported = known.get(calendar);
+ if (isSupported == null) {
+ try {
+ new temporal.PlainDate(2000, 1, 1, calendar);
+ isSupported = true;
+ } catch {
+ isSupported = false;
+ }
+ known.set(calendar, isSupported);
+ }
+ return isSupported;
+}
+
+function inCalendar(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+): TemporalPlainDate {
+ const temporal = getTemporal();
+ if (temporal == null) {
+ throw new Error(`The "${calendar}" calendar needs Temporal.`);
+ }
+ return new temporal.PlainDate(pd.year, pd.month, pd.day, calendar);
+}
+
+function toGregorian(date: TemporalPlainDate): PlainDate {
+ const iso = date.withCalendar('iso8601');
+ return {year: iso.year, month: iso.month, day: iso.day};
+}
+
+/** A month of a calendar, located by its first and last Gregorian days. */
+export interface CalendarMonth {
+ readonly start: PlainDate;
+ readonly end: PlainDate;
+ readonly length: number;
+}
+
+function makeMonth(start: PlainDate, length: number): CalendarMonth {
+ return {start, end: plainDateAddDays(start, length - 1), length};
+}
+
+function gregorianMonth(year: number, month: number): CalendarMonth {
+ return makeMonth({year, month, day: 1}, getDaysInMonth(year, month));
+}
+
+function temporalMonth(firstDay: TemporalPlainDate): CalendarMonth {
+ return makeMonth(toGregorian(firstDay), firstDay.daysInMonth);
+}
+
+/** The day of the calendar month that a Gregorian date falls on. */
+export function calendarDayOfMonth(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+): number {
+ return isGregorianAligned(calendar) ? pd.day : inCalendar(calendar, pd).day;
+}
+
+/** The calendar month that contains a Gregorian date. */
+export function calendarMonthOf(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+): CalendarMonth {
+ if (isGregorianAligned(calendar)) {
+ return gregorianMonth(pd.year, pd.month);
+ }
+ return temporalMonth(inCalendar(calendar, pd).with({day: 1}));
+}
+
+/** The calendar month `n` months after `month`, or before it when negative. */
+export function calendarAddMonths(
+ calendar: CalendarSystem,
+ month: CalendarMonth,
+ n: number,
+): CalendarMonth {
+ if (n === 0) {
+ return month;
+ }
+ if (isGregorianAligned(calendar)) {
+ const {year, month: monthOfYear} = plainDateAddMonths(month.start, n);
+ return gregorianMonth(year, monthOfYear);
+ }
+ return temporalMonth(inCalendar(calendar, month.start).add({months: n}));
+}
+
+/**
+ * Moves a date by `n` calendar months. It keeps the day of the month and
+ * clamps it to the length of the target month.
+ */
+export function calendarShiftMonths(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+ n: number,
+): PlainDate {
+ if (isGregorianAligned(calendar)) {
+ return plainDateAddMonths(pd, n);
+ }
+ return toGregorian(inCalendar(calendar, pd).add({months: n}));
+}
+
+/**
+ * Moves a date by `n` calendar years, to the same month of the target year.
+ * It clamps the day of the month. A leap month that the target year does not
+ * have becomes its common counterpart, because Temporal keeps the month code
+ * and constrains it.
+ */
+export function calendarShiftYears(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+ n: number,
+): PlainDate {
+ if (isGregorianAligned(calendar)) {
+ return plainDateAddMonths(pd, n * 12);
+ }
+ return toGregorian(inCalendar(calendar, pd).add({years: n}));
+}
+
+/** Whether a Gregorian date falls inside a calendar month. */
+export function isInCalendarMonth(
+ pd: PlainDate,
+ month: CalendarMonth,
+): boolean {
+ return plainDateIsInRange(pd, [month.start, month.end]);
+}
+
+/**
+ * The stand-alone month and year label of a calendar month, such as
+ * "Aban 1405 AP". It formats a day in the middle of the month: in the
+ * Japanese calendar an era can start inside a month, and most days of that
+ * month then belong to the era of its middle day.
+ */
+export function formatCalendarMonthLabel(
+ calendar: CalendarSystem,
+ month: CalendarMonth,
+ locale: Locale,
+): string {
+ return plainDateFormatStandaloneMonthYear(
+ plainDateAddDays(month.start, Math.floor(month.length / 2)),
+ locale,
+ labelCalendar(calendar),
+ );
+}
+
+// Intl has no month names for `iso8601`. Labels use `gregory`, which has the
+// same months and days.
+function labelCalendar(calendar: CalendarSystem): CalendarSystem {
+ return calendar === 'iso8601' ? 'gregory' : calendar;
+}
+
+function formatToParts(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+): Intl.DateTimeFormatPart[] {
+ return plainDateFormatToParts(pd, {...options, calendar}, locale);
+}
+
+const MONTH_PART_TYPES: ReadonlySet<string> = new Set([
+ 'era',
+ 'year',
+ 'relatedYear',
+ 'yearName',
+ 'month',
+]);
+
+function monthPartsKey(parts: Intl.DateTimeFormatPart[]): string {
+ return parts
+ .filter(part => MONTH_PART_TYPES.has(part.type))
+ .map(part => part.value)
+ .join('|');
+}
+
+/**
+ * Formats a Gregorian date in the calendar, such as "Friday, Aban 8, 1405 AP".
+ * The label always names the month and day that the grid shows. Intl and the
+ * runtime's Temporal can disagree on where a month of the Chinese or Dangi
+ * calendar starts; the label then takes its month and year from the middle of
+ * the Temporal month, its day from Temporal, and its weekday from the date.
+ */
+export function formatCalendarDate(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+): string {
+ if (isGregorianAligned(calendar)) {
+ return plainDateFormat(
+ pd,
+ {...options, calendar: labelCalendar(calendar)},
+ locale,
+ );
+ }
+ const date = inCalendar(calendar, pd);
+ const parts = formatToParts(calendar, pd, options, locale);
+ const middle = plainDateAddDays(
+ pd,
+ Math.floor(date.daysInMonth / 2) - (date.day - 1),
+ );
+ const middleParts = formatToParts(calendar, middle, options, locale);
+ const intlDay = formatToParts(
+ calendar,
+ pd,
+ {day: 'numeric'},
+ 'en-u-nu-latn',
+ ).find(part => part.type === 'day')?.value;
+ if (
+ Number(intlDay) === date.day &&
+ monthPartsKey(parts) === monthPartsKey(middleParts)
+ ) {
+ return parts.map(part => part.value).join('');
+ }
+ const {numberingSystem} = dateTimeFormatFor(locale, {
+ ...options,
+ calendar,
+ timeZone: 'UTC',
+ }).resolvedOptions();
+ const weekday = parts.find(part => part.type === 'weekday')?.value;
+ return middleParts
+ .map(part =>
+ part.type === 'day'
+ ? plainDateFormatDayNumber(date.day, locale, numberingSystem)
+ : part.type === 'weekday' && weekday != null
+ ? weekday
+ : part.value,
+ )
+ .join('');
+}
+
+/**
+ * The fields of a date written in a calendar. A field gives either `year` or
+ * `era` with `eraYear`, and either `monthCode` (such as `M05L` for a leap
+ * month) or `month`, the month's position in its year.
+ */
+export interface CalendarDateFields {
+ readonly year?: number;
+ readonly era?: string;
+ readonly eraYear?: number;
+ readonly monthCode?: string;
+ readonly month?: number;
+ readonly day: number;
+}
+
+/**
+ * The Gregorian date for fields written in a calendar that needs Temporal,
+ * or null when the calendar does not have that date. Temporal validates the
+ * fields and never adjusts them: 30 Esfand in a common Persian year is null.
+ */
+export function calendarDateFromFields(
+ calendar: CalendarSystem,
+ fields: CalendarDateFields,
+): PlainDate | null {
+ const temporal = getTemporal();
+ if (temporal == null) {
+ throw new Error(`The "${calendar}" calendar needs Temporal.`);
+ }
+ try {
+ return toGregorian(
+ temporal.PlainDate.from({...fields, calendar}, {overflow: 'reject'}),
+ );
+ } catch (error) {
+ if (error instanceof RangeError || error instanceof TypeError) {
+ return null;
+ }
+ throw error;
+ }
+}
+
+/** The number of months in the calendar year that contains a date. */
+export function calendarMonthsInYear(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+): number {
+ return isGregorianAligned(calendar)
+ ? 12
+ : inCalendar(calendar, pd).monthsInYear;
+}
diff --git a/packages/core/src/utils/plainDate.test.ts b/packages/core/src/utils/plainDate.test.ts
index 3d89751f28..a4481989b2 100644
--- a/packages/core/src/utils/plainDate.test.ts
+++ b/packages/core/src/utils/plainDate.test.ts
@@ -36,6 +36,7 @@ import {
DATE_FORMAT_WITH_WEEKDAY,
DATE_FORMAT_MONTH_YEAR,
plainDateWeekFieldName,
+ plainDateFormatToParts,
} from './plainDate';
import type {ISODateString} from './dateTypes';
@@ -783,6 +784,20 @@ describe('plainDateFormatStandaloneMonthYear', () => {
});
});
+describe('plainDateFormatToParts', () => {
+ it.each([
+ [{dateStyle: 'full'}],
+ [{timeZone: 'Asia/Tokyo', dateStyle: 'long'}],
+ [{hour: 'numeric', day: 'numeric'}],
+ ] as const)('joins to the plainDateFormat text for %o', options => {
+ const pd = plainDateFromISO('2026-11-03');
+ const parts = plainDateFormatToParts(pd, options, 'fa-IR');
+ expect(parts.map(part => part.value).join('')).toBe(
+ plainDateFormat(pd, options, 'fa-IR'),
+ );
+ });
+});
+
describe('plainDateFormat', () => {
it('keeps one formatter per locale and options, whatever order the options are in', () => {
// A month of day labels, as a calendar renders them, reuses one formatter.
@@ -984,6 +999,12 @@ describe('plainDateFormatDayNumber', () => {
it('adds no grouping separator', () => {
expect(plainDateFormatDayNumber(1234, 'en')).toBe('1234');
});
+
+ it('writes the digits of a given numbering system', () => {
+ expect(plainDateFormatDayNumber(8, 'fa-IR', 'latn')).toBe('8');
+ expect(plainDateFormatDayNumber(8, 'en', 'arabext')).toBe('۸');
+ expect(plainDateFormatDayNumber(8, 'fa-IR')).toBe('۸');
+ });
});
describe('plainDateWeekdayNames', () => {
diff --git a/packages/core/src/utils/plainDate.ts b/packages/core/src/utils/plainDate.ts
index 183b55e900..11a2552097 100644
--- a/packages/core/src/utils/plainDate.ts
+++ b/packages/core/src/utils/plainDate.ts
@@ -374,8 +374,13 @@ export const DATE_FORMAT_MONTH_YEAR: Intl.DateTimeFormatOptions = {
export function plainDateFormatStandaloneMonthYear(
pd: PlainDate,
locale: Locale,
+ calendar: Intl.DateTimeFormatOptions['calendar'] = 'gregory',
): string {
- const label = plainDateFormat(pd, DATE_FORMAT_MONTH_YEAR, locale);
+ const label = plainDateFormat(
+ pd,
+ {...DATE_FORMAT_MONTH_YEAR, calendar},
+ locale,
+ );
let language: string;
try {
language = new Intl.Locale(locale).language;
@@ -457,28 +462,51 @@ export function plainDateFormat(
options: Intl.DateTimeFormatOptions,
locale: Locale = 'en',
): string {
+ const [format, date] = plainDateFormatInput(pd, options, locale);
+ return format.format(date);
+}
+
+/**
+ * The parts of `plainDateFormat`'s output, from the same formatter and date.
+ * Internal: not re-exported from `utils/index.ts`.
+ */
+export function plainDateFormatToParts(
+ pd: PlainDate,
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+): Intl.DateTimeFormatPart[] {
+ const [format, date] = plainDateFormatInput(pd, options, locale);
+ return format.formatToParts(date);
+}
+
+function plainDateFormatInput(
+ pd: PlainDate,
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+): [Intl.DateTimeFormat, Date | number] {
const calendar = options.calendar ?? 'gregory';
if (options.timeZone != null) {
- return dateTimeFormatFor(locale, {...options, calendar}).format(
+ return [
+ dateTimeFormatFor(locale, {...options, calendar}),
plainDateToDate(pd),
- );
+ ];
}
if (TIME_OF_DAY_FIELDS.some(field => options[field] != null)) {
// A zone name or a time of day reads local midnight in the zone current
// at the call. A cached formatter would keep the zone it was built in,
// so this one is built for the call.
- return new Intl.DateTimeFormat(locale, {...options, calendar}).format(
+ return [
+ new Intl.DateTimeFormat(locale, {...options, calendar}),
plainDateToDate(pd),
- );
+ ];
}
// Date fields alone: UTC midnight formatted in UTC, so neither the cached
// formatter nor the date depends on the host's zone, which can change while
// a page is open.
- return dateTimeFormatFor(locale, {
- ...options,
- calendar,
- timeZone: 'UTC',
- }).format(utcTime(pd.year, pd.month - 1, pd.day));
+ return [
+ dateTimeFormatFor(locale, {...options, calendar, timeZone: 'UTC'}),
+ utcTime(pd.year, pd.month - 1, pd.day),
+ ];
}
/** Options that print a time of day or a zone, which a PlainDate lacks. */
@@ -543,23 +571,29 @@ export function plainDateWeekFieldName(locale: Locale = 'en'): string {
return 'week';
}
-const dayNumberFormats = new Map<Locale, Intl.NumberFormat>();
+const dayNumberFormats = new Map<string, Intl.NumberFormat>();
/**
* A day of the month or a week number in the locale's own digits: `15` in
- * English, `۱۵` in Persian, `١٥` in Egyptian Arabic. Only the digits follow the
- * locale. The number stays the Gregorian day or ISO week that it names, so no
- * other calendar applies, and no grouping separator or unit word is added.
+ * English, `۱۵` in Persian, `١٥` in Egyptian Arabic. A `numberingSystem`
+ * replaces the locale's digits. Only the digits change. The number stays the
+ * value that it is given, so no calendar applies, and no grouping separator or
+ * unit word is added.
* Internal: not re-exported from `utils/index.ts`.
*/
export function plainDateFormatDayNumber(
value: number,
locale: Locale,
+ numberingSystem?: string,
): string {
- let format = dayNumberFormats.get(locale);
+ const key = `${locale}|${numberingSystem ?? ''}`;
+ let format = dayNumberFormats.get(key);
if (format == null) {
- format = new Intl.NumberFormat(locale, {useGrouping: false});
- dayNumberFormats.set(locale, format);
+ format = new Intl.NumberFormat(locale, {
+ useGrouping: false,
+ numberingSystem,
+ });
+ dayNumberFormats.set(key, format);
}
return format.format(value);
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b47f06a8b6..3ea8fea3d2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -936,6 +936,9 @@ importers:
tailwindcss:
specifier: ^4.3.2
version: 4.3.2
+ temporal-polyfill:
+ specifier: ^1.0.6
+ version: 1.0.6
packages/lab:
dependencies:
@@ -6667,6 +6670,15 @@ packages:
resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-tYyEry1HLGUDbm2356W3iYD0OZdo7rlP7h98Zr/EnjqLZQwTAfcBDUvJnJbfA15v/vQad57hJZScG5O0W2oKEA==}
+
+ resolution: {integrity: sha512-wxVoanmDeavXie1vu2JaQ3WIc3JZnWAOYFBsJyATaVsXsycKYUflGsyBmrRSnoCpZJpwPyr38VpgSUlQ8CbFxg==}
+
+ resolution: {integrity: sha512-9jbTSX3HvkOWvDpNpFzwX/d1mkCrgQgwLmVTOEiuocZGKHsrQJtttGZFmybJ2zYP5zCSZuU5ZyeS8+eOEPABiQ==}
+
resolution: {integrity: sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg==}
engines: {node: '>=8'}
@@ -12768,6 +12780,15 @@ snapshots:
+ dependencies:
+ temporal-spec: 1.0.1
+ temporal-utils: 1.0.3
+
+
+