Skip to content

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

TypeScript

fix(Calendar): localize compact weekday headers from CLDR (#5190)

nynexman446446b053251544
diff --git a/.changeset/calendar-weekday-headers-now-follow-the-selected-a95h.md b/.changeset/calendar-weekday-headers-now-follow-the-selected-a95h.md
new file mode 100644
index 0000000000..d556e93fa2
--- /dev/null
+++ b/.changeset/calendar-weekday-headers-now-follow-the-selected-a95h.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Calendar weekday headers now use compact CLDR stand-alone-short names for the selected locale, while preserving the existing `Su` / `Mo` / `Tu` English labels.
+@nynexman4464
diff --git a/.github/workflows/crowdin-download.yml b/.github/workflows/crowdin-download.yml
index c8f4b5cf04..c98ef2358a 100644
--- a/.github/workflows/crowdin-download.yml
+++ b/.github/workflows/crowdin-download.yml
@@ -106,6 +106,9 @@ jobs:
echo "No translated locale files present; nothing to normalize."
fi
+ - name: Generate Calendar CLDR weekdays
+ run: pnpm generate:cldr-weekdays
+
# peter-evans/[email protected] — pinned by SHA per repo policy.
- name: Open translations PR
uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 107ab50e64..b545684042 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -755,6 +755,9 @@ into your language, visit <https://crowdin.com/project/astryx>. New locales are
picked up automatically after a maintainer reviews the auto-generated
translations PR.
+Calendar’s compact weekday labels, such as `Su` and `Mo`, are generated from
+Unicode CLDR data because browsers do not provide that format.
+
## Contributor License Agreement ("CLA")
In order to accept your pull request, we need you to submit a CLA. You only need
diff --git a/package.json b/package.json
index f1fe8bf6fa..5c3931b3c9 100644
--- a/package.json
+++ b/package.json
@@ -11,7 +11,9 @@
"test:watch": "vitest",
"test:coverage": "vitest --coverage",
"check:package-boundaries": "node scripts/check-package-boundaries.js",
- "check:repo": "pnpm check:sync && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-catalog",
+ "check:repo": "pnpm check:sync && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-catalog && pnpm check:cldr-weekdays",
+ "generate:cldr-weekdays": "node scripts/generate-cldr-weekdays.mjs",
+ "check:cldr-weekdays": "node scripts/generate-cldr-weekdays.mjs --check",
"check:changesets": "node scripts/check-changesets.mjs",
"check:portable-scripts": "node scripts/check-portable-scripts.mjs",
"check:cli-structure": "node scripts/check-cli-structure.mjs",
@@ -58,6 +60,8 @@
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.2.0",
"@vitest/coverage-v8": "^4.1.9",
+ "cldr-core": "^48.2.0",
+ "cldr-dates-full": "^48.2.0",
"dom-accessibility-api": "^0.6.3",
"esbuild": "^0.28.1",
"eslint": "^10.6.0",
diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsx
index 312ad4ac41..cbaf1a177b 100644
--- a/packages/core/src/Calendar/Calendar.test.tsx
+++ b/packages/core/src/Calendar/Calendar.test.tsx
@@ -21,6 +21,8 @@ import {calendarStyles} from './styles';
import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import {standaloneShortWeekdayNamesByLocale} from './standaloneShortWeekdayNames.generated';
function generateThemeTestCSS(theme: Parameters<typeof generateThemeCSS>[0]) {
const {prose, component} = generateThemeCSS(theme);
@@ -120,6 +122,45 @@ describe('Calendar', () => {
expect(screen.getByText('Sa')).toBeInTheDocument();
});
+ it('uses the provider locale for stand-alone short day names', () => {
+ const localizedNames = standaloneShortWeekdayNamesByLocale.es;
+ const englishNames = standaloneShortWeekdayNamesByLocale.en;
+ expect(localizedNames).not.toEqual(englishNames);
+
+ const {rerender} = render(
+ <InternationalizationProvider locale="es-ES">
+ <Calendar />
+ </InternationalizationProvider>,
+ );
+
+ expect(
+ screen.getAllByRole('columnheader').map(header => header.textContent),
+ ).toEqual(localizedNames);
+
+ rerender(
+ <InternationalizationProvider locale="en">
+ <Calendar />
+ </InternationalizationProvider>,
+ );
+ expect(
+ screen.getAllByRole('columnheader').map(header => header.textContent),
+ ).toEqual(englishNames);
+ });
+
+ it('rotates localized day names by numeric weekday index', () => {
+ const localizedNames = standaloneShortWeekdayNamesByLocale.es;
+
+ render(
+ <InternationalizationProvider locale="es-ES">
+ <Calendar weekStartsOn={1} />
+ </InternationalizationProvider>,
+ );
+
+ expect(
+ screen.getAllByRole('columnheader').map(header => header.textContent),
+ ).toEqual([...localizedNames.slice(1), localizedNames[0]]);
+ });
+
it('displays correct number of day cells', () => {
render(<Calendar />);
diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsx
index 96b22456ca..9ac921a8f7 100644
--- a/packages/core/src/Calendar/Calendar.tsx
+++ b/packages/core/src/Calendar/Calendar.tsx
@@ -654,6 +654,14 @@ function MonthGrid({
weekStartsOn,
hasVariableRowCount,
});
+ const dayNameHeaders = useMemo(
+ () =>
+ dayNames.map((name, offset) => ({
+ dayOfWeek: ((weekStartsOn + offset) % 7) as DayOfWeek,
+ name,
+ })),
+ [dayNames, weekStartsOn],
+ );
const rangeAnchor = useMemo(
() =>
@@ -888,9 +896,9 @@ function MonthGrid({
)}
/>
)}
- {dayNames.map(name => (
+ {dayNameHeaders.map(({dayOfWeek, name}) => (
<div
- key={name}
+ key={dayOfWeek}
role="columnheader"
{...stylex.props(monthGridStyles.dayName)}>
{name}
diff --git a/packages/core/src/Calendar/getStandaloneShortWeekdayNames.test.ts b/packages/core/src/Calendar/getStandaloneShortWeekdayNames.test.ts
new file mode 100644
index 0000000000..f2692d7aa2
--- /dev/null
+++ b/packages/core/src/Calendar/getStandaloneShortWeekdayNames.test.ts
@@ -0,0 +1,54 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file getStandaloneShortWeekdayNames.test.ts
+ * @input Private Calendar weekday locale resolver and generated CLDR data
+ * @output Regression coverage for exact, language, extension, and safe fallback
+ * @position Tests for getStandaloneShortWeekdayNames.ts
+ */
+
+import {describe, expect, it} from 'vitest';
+import {getStandaloneShortWeekdayNames} from './getStandaloneShortWeekdayNames';
+import {standaloneShortWeekdayNamesByLocale} from './standaloneShortWeekdayNames.generated';
+
+describe('getStandaloneShortWeekdayNames', () => {
+ it('preserves the default English weekday names', () => {
+ expect(getStandaloneShortWeekdayNames('en')).toEqual([
+ 'Su',
+ 'Mo',
+ 'Tu',
+ 'We',
+ 'Th',
+ 'Fr',
+ 'Sa',
+ ]);
+ });
+
+ it('returns an exact generated locale entry', () => {
+ expect(getStandaloneShortWeekdayNames('ar-SA')).toBe(
+ standaloneShortWeekdayNamesByLocale['ar-SA'],
+ );
+ });
+
+ it('ignores Unicode extensions when resolving an exact locale', () => {
+ const expected = standaloneShortWeekdayNamesByLocale['zh-TW'];
+
+ expect(getStandaloneShortWeekdayNames('zh-TW')).toBe(expected);
+ expect(getStandaloneShortWeekdayNames('zh-TW-u-ca-chinese')).toBe(expected);
+ });
+
+ it('falls back from a regional locale to its base language', () => {
+ expect(getStandaloneShortWeekdayNames('es-ES')).toBe(
+ standaloneShortWeekdayNamesByLocale.es,
+ );
+ });
+
+ it('safely falls back to English for malformed and unsupported locales', () => {
+ expect(getStandaloneShortWeekdayNames('not_a_locale')).toBe(
+ standaloneShortWeekdayNamesByLocale.en,
+ );
+ expect(getStandaloneShortWeekdayNames('xx-ZZ')).toBe(
+ standaloneShortWeekdayNamesByLocale.en,
+ );
+ });
+});
diff --git a/packages/core/src/Calendar/getStandaloneShortWeekdayNames.ts b/packages/core/src/Calendar/getStandaloneShortWeekdayNames.ts
new file mode 100644
index 0000000000..5022483124
--- /dev/null
+++ b/packages/core/src/Calendar/getStandaloneShortWeekdayNames.ts
@@ -0,0 +1,38 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file getStandaloneShortWeekdayNames.ts
+ * @input Generated CLDR stand-alone-short weekday table
+ * @output Private locale resolver for Calendar weekday headers
+ * @position Calendar-internal pure utility; not exported from the package
+ */
+
+import {
+ standaloneShortWeekdayNamesByLocale,
+ type StandaloneShortWeekdayNames,
+} from './standaloneShortWeekdayNames.generated';
+
+const weekdayNamesByLocale: Readonly<
+ Record<string, StandaloneShortWeekdayNames>
+> = standaloneShortWeekdayNamesByLocale;
+const englishWeekdayNames = weekdayNamesByLocale.en;
+
+/**
+ * Resolve generated weekday reference data as exact locale -> language -> English.
+ * Unicode extensions are ignored through Intl.Locale.baseName. Invalid tags and
+ * valid but unsupported languages safely use English.
+ */
+export function getStandaloneShortWeekdayNames(
+ locale: string,
+): StandaloneShortWeekdayNames {
+ try {
+ const parsed = new Intl.Locale(locale);
+ return (
+ weekdayNamesByLocale[parsed.baseName] ??
+ weekdayNamesByLocale[parsed.language] ??
+ englishWeekdayNames
+ );
+ } catch {
+ return englishWeekdayNames;
+ }
+}
diff --git a/packages/core/src/Calendar/hooks/useCalendarDays.ts b/packages/core/src/Calendar/hooks/useCalendarDays.ts
index 3b46bc4392..2295f795fd 100644
--- a/packages/core/src/Calendar/hooks/useCalendarDays.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarDays.ts
@@ -4,7 +4,7 @@
/**
* @file useCalendarDays.ts
- * @input Uses React useMemo, PlainDate utilities
+ * @input Uses React context via use(), useMemo, PlainDate utilities, generated CLDR weekday data
* @output Exports useCalendarDays hook for generating calendar day grids
* @position Calendar-specific hook; used by Calendar
*
@@ -12,7 +12,7 @@
* - /packages/core/src/Calendar/hooks/index.ts
*/
-import {useMemo} from 'react';
+import {use, useMemo} from 'react';
import type {DayOfWeek, ISODateString} from '../../utils/dateTypes';
import {
type PlainDate,
@@ -21,6 +21,8 @@ import {
plainDateDayOfWeek,
plainDateAddDays,
} from '../../utils/plainDate';
+import {InternationalizationContext} from '../../i18n/InternationalizationContext';
+import {getStandaloneShortWeekdayNames} from '../getStandaloneShortWeekdayNames';
/**
* Represents a single day in the calendar grid.
@@ -84,6 +86,7 @@ export function useCalendarDays(
options: UseCalendarDaysOptions,
): UseCalendarDaysReturn {
const {year, month, weekStartsOn = 0, hasVariableRowCount = false} = options;
+ const {locale} = use(InternationalizationContext);
// Calculate grid structure
const gridInfo = useMemo(() => {
@@ -108,15 +111,15 @@ export function useCalendarDays(
};
}, [year, month, weekStartsOn, hasVariableRowCount]);
- // Generate day names
+ // Generated strings avoid Date anchors, so weekday headers cannot shift with
+ // the runtime timezone. Keep numeric indices as the rotation source of truth.
const dayNames = useMemo(() => {
- const names = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
- const rotated: string[] = [];
- for (let i = 0; i < 7; i++) {
- rotated.push(names[(i + weekStartsOn) % 7]);
- }
- return rotated;
- }, [weekStartsOn]);
+ const names = getStandaloneShortWeekdayNames(locale);
+ return Array.from(
+ {length: 7},
+ (_, index) => names[(index + weekStartsOn) % 7],
+ );
+ }, [locale, weekStartsOn]);
// Generate days array
const days = useMemo(() => {
diff --git a/packages/core/src/Calendar/standaloneShortWeekdayNames.generated.ts b/packages/core/src/Calendar/standaloneShortWeekdayNames.generated.ts
new file mode 100644
index 0000000000..a95c571c7c
--- /dev/null
+++ b/packages/core/src/Calendar/standaloneShortWeekdayNames.generated.ts
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @generated by scripts/generate-cldr-weekdays.mjs from Unicode CLDR 48.2.0.
+ * Do not edit by hand. Run `pnpm generate:cldr-weekdays` instead.
+ */
+
+export type StandaloneShortWeekdayNames = readonly [
+ string,
+ string,
+ string,
+ string,
+ string,
+ string,
+ string,
+];
+
+export const standaloneShortWeekdayNamesByLocale = {
+ af: ['So.', 'Ma.', 'Di.', 'Wo.', 'Do.', 'Vr.', 'Sa.'],
+ ar: ['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'],
+ 'ar-SA': ['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت'],
+ ca: ['dg.', 'dl.', 'dt.', 'dc.', 'dj.', 'dv.', 'ds.'],
+ cs: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
+ da: ['sø.', 'ma.', 'ti.', 'on.', 'to.', 'fr.', 'lø.'],
+ de: ['So.', 'Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.'],
+ el: ['Κυ', 'Δε', 'Τρ', 'Τε', 'Πέ', 'Πα', 'Σά'],
+ en: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
+ es: ['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA'],
+ fi: ['su', 'ma', 'ti', 'ke', 'to', 'pe', 'la'],
+ fr: ['di', 'lu', 'ma', 'me', 'je', 've', 'sa'],
+ he: ['א׳', 'ב׳', 'ג׳', 'ד׳', 'ה׳', 'ו׳', 'ש׳'],
+ hu: ['V', 'H', 'K', 'Sze', 'Cs', 'P', 'Szo'],
+ it: ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'],
+ ja: ['日', '月', '火', '水', '木', '金', '土'],
+ ko: ['일', '월', '화', '수', '목', '금', '토'],
+ nl: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
+ no: ['sø.', 'ma.', 'ti.', 'on.', 'to.', 'fr.', 'lø.'],
+ pl: ['nie', 'pon', 'wto', 'śro', 'czw', 'pią', 'sob'],
+ pt: ['dom.', 'seg.', 'ter.', 'qua.', 'qui.', 'sex.', 'sáb.'],
+ 'pt-PT': ['dom.', 'seg.', 'ter.', 'qua.', 'qui.', 'sex.', 'sáb.'],
+ ro: ['du.', 'lu.', 'ma.', 'mi.', 'joi', 'vi.', 'sâ.'],
+ ru: ['вс', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'],
+ sr: ['не', 'по', 'ут', 'ср', 'че', 'пе', 'су'],
+ sv: ['sö', 'må', 'ti', 'on', 'to', 'fr', 'lö'],
+ tr: ['Pa', 'Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct'],
+ uk: ['нд', 'пн', 'вт', 'ср', 'чт', 'пт', 'сб'],
+ vi: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'],
+ zh: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
+ 'zh-TW': ['日', '一', '二', '三', '四', '五', '六'],
+} as const satisfies Readonly<Record<string, StandaloneShortWeekdayNames>>;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a6c515ac17..e028febb28 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -73,6 +73,12 @@ importers:
'@vitest/coverage-v8':
specifier: ^4.1.9
version: 4.1.10([email protected])
+ cldr-core:
+ specifier: ^48.2.0
+ version: 48.2.0
+ cldr-dates-full:
+ specifier: ^48.2.0
dom-accessibility-api:
specifier: ^0.6.3
version: 0.6.3
@@ -3960,6 +3966,19 @@ packages:
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
+ resolution: {integrity: sha512-zfmLothncSwfv2jlevoSrgI2VGgH8SDGHXst6jUEotHA8nq9Igeg9jzdJDFtBso9pgJuG89DK16TzrmZDdo2Bg==}
+
+ resolution: {integrity: sha512-zMrKvjMO414HDftLr6vKH1fNQHakFNe+F1h4S0eg+zmL4WRi9pI41fxB3UrTJDY42MEM87jCuAw/qlqCgYKcAQ==}
+ peerDependencies:
+ cldr-numbers-full: 48.2.0
+
+ resolution: {integrity: sha512-0EQ+UkVDsyXOlxnWnL1RIENVZFqCnb04D1Yrku0obnOyttbuZz8tHmUd5c5AEvhGS/Gg2zI4fTaCm51LSGITog==}
+ peerDependencies:
+ cldr-core: 48.2.0
+
resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==}
engines: {node: '>=18'}
@@ -9279,6 +9298,16 @@ snapshots:
dependencies:
clsx: 2.1.1
+
+ dependencies:
+ cldr-numbers-full: 48.2.0([email protected])
+
+ dependencies:
+ cldr-core: 48.2.0
+
dependencies:
restore-cursor: 5.1.0
diff --git a/scripts/generate-cldr-weekdays.mjs b/scripts/generate-cldr-weekdays.mjs
new file mode 100644
index 0000000000..9e88a72681
--- /dev/null
+++ b/scripts/generate-cldr-weekdays.mjs
@@ -0,0 +1,266 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Generates Calendar's compact CLDR stand-alone-short weekday table.
+ *
+ * The runtime package consumes only the checked-in TypeScript output. Raw CLDR
+ * data stays in root development dependencies and is read only by this script.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {createRequire} from 'node:module';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {format, resolveConfig} from 'prettier';
+
+const require = createRequire(import.meta.url);
+const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(SCRIPT_DIR, '..');
+const LOCALES_DIR = path.join(REPO_ROOT, 'packages', 'core', 'locales');
+const OUTPUT_FILE = path.join(
+ REPO_ROOT,
+ 'packages',
+ 'core',
+ 'src',
+ 'Calendar',
+ 'standaloneShortWeekdayNames.generated.ts',
+);
+const CLDR_DATES_ROOT = path.dirname(
+ require.resolve('cldr-dates-full/package.json'),
+);
+const CLDR_CORE_ROOT = path.dirname(require.resolve('cldr-core/package.json'));
+const CLDR_MAIN_DIR = path.join(CLDR_DATES_ROOT, 'main');
+const CLDR_DATES_PACKAGE = readJson(path.join(CLDR_DATES_ROOT, 'package.json'));
+const CLDR_CORE_PACKAGE = readJson(path.join(CLDR_CORE_ROOT, 'package.json'));
+const PARENT_LOCALES = readJson(
+ path.join(CLDR_CORE_ROOT, 'supplemental', 'parentLocales.json'),
+).supplemental.parentLocales.parentLocale;
+const LIKELY_SUBTAGS = readJson(
+ path.join(CLDR_CORE_ROOT, 'supplemental', 'likelySubtags.json'),
+).supplemental.likelySubtags;
+const DAY_KEYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
+const EXCLUDED_LOCALE_FILES = new Set(['en.json', 'pseudo.json']);
+
+if (CLDR_DATES_PACKAGE.version !== CLDR_CORE_PACKAGE.version) {
+ throw new Error(
+ `CLDR package version mismatch: cldr-dates-full=${CLDR_DATES_PACKAGE.version}, cldr-core=${CLDR_CORE_PACKAGE.version}`,
+ );
+}
+
+function readJson(file) {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+}
+
+function compareStrings(left, right) {
+ return left < right ? -1 : left > right ? 1 : 0;
+}
+
+/** Return canonical shipped locale tags, with English added explicitly. */
+export function getShippedLocales() {
+ const locales = fs
+ .readdirSync(LOCALES_DIR, {withFileTypes: true})
+ .filter(
+ entry =>
+ entry.isFile() &&
+ entry.name.endsWith('.json') &&
+ !EXCLUDED_LOCALE_FILES.has(entry.name),
+ )
+ .map(entry => entry.name.slice(0, -'.json'.length));
+
+ locales.push('en');
+ return locales
+ .map(locale => {
+ try {
+ return new Intl.Locale(locale).baseName;
+ } catch (error) {
+ throw new Error(
+ `Invalid locale filename ${locale}.json: ${error.message}`,
+ );
+ }
+ })
+ .sort(compareStrings);
+}
+
+function findLikelySubtag(parsed) {
+ const candidates = [
+ parsed.baseName,
+ parsed.region && `${parsed.language}-${parsed.region}`,
+ parsed.script && `${parsed.language}-${parsed.script}`,
+ parsed.language,
+ ].filter(Boolean);
+
+ for (const candidate of candidates) {
+ if (LIKELY_SUBTAGS[candidate]) {
+ return LIKELY_SUBTAGS[candidate];
+ }
+ }
+ return null;
+}
+
+/** Resolve a supported tag to a concrete locale payload in cldr-dates-full. */
+export function resolveCldrSourceLocale(locale, availableLocales) {
+ if (availableLocales.has(locale)) {
+ return locale;
+ }
+
+ const visited = new Set([locale]);
+ let parent = PARENT_LOCALES[locale];
+ while (parent && parent !== 'root' && parent !== 'und') {
+ if (visited.has(parent)) {
+ throw new Error(`CLDR parent-locale cycle while resolving ${locale}`);
+ }
+ if (availableLocales.has(parent)) {
+ return parent;
+ }
+ visited.add(parent);
+ parent = PARENT_LOCALES[parent];
+ }
+
+ const parsed = new Intl.Locale(locale);
+ const likelySubtag = findLikelySubtag(parsed);
+ if (likelySubtag) {
+ const likely = new Intl.Locale(likelySubtag);
+ if (likely.script) {
+ const languageScript = `${parsed.language}-${likely.script}`;
+ if (availableLocales.has(languageScript)) {
+ return languageScript;
+ }
+ }
+ }
+
+ if (availableLocales.has(parsed.language)) {
+ return parsed.language;
+ }
+
+ throw new Error(
+ `cldr-dates-full ${CLDR_DATES_PACKAGE.version} has no usable Gregorian locale data for ${locale}`,
+ );
+}
+
+/**
+ * Select the smallest useful CLDR locale set for shipped catalogs.
+ *
+ * Intl.Locale canonicalizes BCP-47 aliases. CLDR's explicit parents and likely
+ * scripts live in cldr-core supplemental data, so the generator uses those to
+ * resolve concrete cldr-dates-full payloads (notably zh-TW -> zh-Hant). Every
+ * shipped locale contributes its language fallback; an exact entry is emitted
+ * only when CLDR publishes it or its resolved values differ from the language.
+ * Runtime lookup mirrors this as exact locale -> language -> English.
+ */
+export function getGeneratedLocaleSources() {
+ const availableLocales = new Set(fs.readdirSync(CLDR_MAIN_DIR));
+ const sources = new Map();
+
+ for (const locale of getShippedLocales()) {
+ const parsed = new Intl.Locale(locale);
+ const languageSource = resolveCldrSourceLocale(
+ parsed.language,
+ availableLocales,
+ );
+ const exactSource = resolveCldrSourceLocale(locale, availableLocales);
+
+ sources.set(parsed.language, languageSource);
+ if (
+ availableLocales.has(parsed.baseName) ||
+ JSON.stringify(readStandaloneShortWeekdays(exactSource)) !==
+ JSON.stringify(readStandaloneShortWeekdays(languageSource))
+ ) {
+ sources.set(parsed.baseName, exactSource);
+ }
+ }
+
+ if (!sources.has('en')) {
+ throw new Error('The generated locale set must include English');
+ }
+
+ return Object.fromEntries(
+ [...sources].sort(([left], [right]) => compareStrings(left, right)),
+ );
+}
+
+export function getGeneratedLocales() {
+ return Object.keys(getGeneratedLocaleSources());
+}
+
+/** Read one CLDR locale's Gregorian stand-alone-short weekdays, Sunday first. */
+export function readStandaloneShortWeekdays(locale) {
+ const file = path.join(CLDR_MAIN_DIR, locale, 'ca-gregorian.json');
+ if (!fs.existsSync(file)) {
+ throw new Error(
+ `Missing Gregorian CLDR data for ${locale}: ${path.relative(REPO_ROOT, file)}`,
+ );
+ }
+
+ const document = readJson(file);
+ const localeData = document.main?.[locale];
+ const shortDays =
+ localeData?.dates?.calendars?.gregorian?.days?.['stand-alone']?.short;
+
+ if (!shortDays || typeof shortDays !== 'object') {
+ throw new Error(
+ `Missing dates.calendars.gregorian.days["stand-alone"].short for ${locale} in ${path.relative(REPO_ROOT, file)}`,
+ );
+ }
+
+ return DAY_KEYS.map(day => {
+ const value = shortDays[day];
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new Error(
+ `Missing stand-alone-short value for ${locale}.${day} in ${path.relative(REPO_ROOT, file)}`,
+ );
+ }
+ return value;
+ });
+}
+
+export function generateWeekdayData() {
+ return Object.fromEntries(
+ Object.entries(getGeneratedLocaleSources()).map(([locale, source]) => [
+ locale,
+ readStandaloneShortWeekdays(source),
+ ]),
+ );
+}
+
+export async function renderGeneratedFile() {
+ const data = generateWeekdayData();
+ const source = `// Copyright (c) Meta Platforms, Inc. and affiliates.\n\n/**\n * @generated by scripts/generate-cldr-weekdays.mjs from Unicode CLDR ${CLDR_DATES_PACKAGE.version}.\n * Do not edit by hand. Run \`pnpm generate:cldr-weekdays\` instead.\n */\n\nexport type StandaloneShortWeekdayNames = readonly [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n];\n\nexport const standaloneShortWeekdayNamesByLocale = ${JSON.stringify(data)} as const satisfies Readonly<\n Record<string, StandaloneShortWeekdayNames>\n>;\n`;
+
+ const prettierConfig = await resolveConfig(OUTPUT_FILE);
+ return format(source, {...prettierConfig, filepath: OUTPUT_FILE});
+}
+
+async function main() {
+ const check = process.argv.slice(2).includes('--check');
+ const expected = await renderGeneratedFile();
+ const localeCount = Object.keys(generateWeekdayData()).length;
+
+ if (check) {
+ const actual = fs.existsSync(OUTPUT_FILE)
+ ? fs.readFileSync(OUTPUT_FILE, 'utf8')
+ : '';
+ if (actual !== expected) {
+ console.error(
+ '✗ Calendar CLDR weekday data is stale. Run `pnpm generate:cldr-weekdays` and commit the result.',
+ );
+ process.exitCode = 1;
+ return;
+ }
+ console.log(
+ `✓ Calendar CLDR weekday data matches ${localeCount} generated locale entries`,
+ );
+ return;
+ }
+
+ fs.writeFileSync(OUTPUT_FILE, expected);
+ console.log(
+ `Generated ${path.relative(REPO_ROOT, OUTPUT_FILE)} with ${localeCount} locale entries`,
+ );
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ await main();
+}
diff --git a/scripts/generate-cldr-weekdays.test.mjs b/scripts/generate-cldr-weekdays.test.mjs
new file mode 100644
index 0000000000..a4a1c259ae
--- /dev/null
+++ b/scripts/generate-cldr-weekdays.test.mjs
@@ -0,0 +1,75 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {createRequire} from 'node:module';
+import {fileURLToPath} from 'node:url';
+import {describe, expect, it} from 'vitest';
+import {
+ getGeneratedLocales,
+ getGeneratedLocaleSources,
+ renderGeneratedFile,
+ resolveCldrSourceLocale,
+} from './generate-cldr-weekdays.mjs';
+import {standaloneShortWeekdayNamesByLocale} from '../packages/core/src/Calendar/standaloneShortWeekdayNames.generated';
+
+const require = createRequire(import.meta.url);
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const CLDR_ROOT = path.dirname(require.resolve('cldr-dates-full/package.json'));
+const OUTPUT_FILE = path.join(
+ ROOT,
+ 'packages/core/src/Calendar/standaloneShortWeekdayNames.generated.ts',
+);
+const DAY_KEYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
+
+function readRawCldr(locale) {
+ const document = JSON.parse(
+ fs.readFileSync(
+ path.join(CLDR_ROOT, 'main', locale, 'ca-gregorian.json'),
+ 'utf8',
+ ),
+ );
+ const days =
+ document.main[locale].dates.calendars.gregorian.days['stand-alone'].short;
+ return DAY_KEYS.map(day => days[day]);
+}
+
+describe('generate-cldr-weekdays', () => {
+ it('matches checked-in generated output deterministically', async () => {
+ const first = await renderGeneratedFile();
+ const second = await renderGeneratedFile();
+
+ expect(first).toBe(second);
+ expect(first).toBe(fs.readFileSync(OUTPUT_FILE, 'utf8'));
+ });
+
+ it('resolves exact, base-language, and script-parent CLDR sources', () => {
+ expect(resolveCldrSourceLocale('en', new Set(['en']))).toBe('en');
+ expect(resolveCldrSourceLocale('es-MX', new Set(['es']))).toBe('es');
+ expect(resolveCldrSourceLocale('zh-TW', new Set(['zh', 'zh-Hant']))).toBe(
+ 'zh-Hant',
+ );
+ });
+
+ it('matches every generated locale to its pinned raw CLDR source', () => {
+ const generatedLocales = getGeneratedLocales();
+ const sources = getGeneratedLocaleSources();
+ const checkedInLocales = Object.keys(standaloneShortWeekdayNamesByLocale);
+
+ expect(checkedInLocales.toSorted()).toEqual(generatedLocales.toSorted());
+
+ for (const locale of generatedLocales) {
+ const source = sources[locale];
+ const weekdays = standaloneShortWeekdayNamesByLocale[locale];
+
+ expect(source).toBeDefined();
+ expect(weekdays).toEqual(readRawCldr(source));
+ expect(weekdays).toHaveLength(7);
+ for (const weekday of weekdays) {
+ expect(typeof weekday).toBe('string');
+ expect(weekday.length).toBeGreaterThan(0);
+ }
+ expect(new Set(weekdays).size).toBe(7);
+ }
+ });
+});