Skip to content

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

TypeScript

fix(utils): read back calendar text in Latvian, Amharic and Hindi (#9840)

nynexman446452e65f3ef421
diff --git a/.changeset/calendar-parser-more-locales.md b/.changeset/calendar-parser-more-locales.md
new file mode 100644
index 0000000000..9931f6bbf1
--- /dev/null
+++ b/.changeset/calendar-parser-more-locales.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] The internal calendar date parser reads back the text it writes in more locales. It reads month names that start with a number, such as Latvian `1. adars` for Adar I and `1. rabī` for Rabi' I, and still reads `1. adars` as day 1 of Adar when no other number can be the day. It reads a numeric pattern that uses two separators, such as the Hindi Buddhist format hint. In the Japanese and Minguo calendars, whose era changes between 1900 and 2100, a year without its era can read as the wrong date. There, a format hint that would otherwise leave out the era shows the narrow era when it keeps the locale's field order, such as Amharic `1/1/8 R`. Where every era width moves the fields, a date of an earlier era adds the era, such as Colognian `BROC 1. Jan. 12`, which no longer reads as a date in 1923. Calendars with one era in that range, such as Buddhist, Ethiopic or Hijri, write the same text as before. No public API changes.
+
+@nynexman4464
diff --git a/packages/core/src/utils/calendarDateParser.roundtrip.test.ts b/packages/core/src/utils/calendarDateParser.roundtrip.test.ts
index 9737b031b3..cc5d762c43 100644
--- a/packages/core/src/utils/calendarDateParser.roundtrip.test.ts
+++ b/packages/core/src/utils/calendarDateParser.roundtrip.test.ts
@@ -50,17 +50,21 @@ const NATIVE_LOCALES: Readonly<Record<CalendarSystem, string>> = {
'islamic-umalqura': 'ar-SA',
};
-// Weekday words that name months or eras, digit month names, cycle years.
+// Weekday words that name months or eras, digit month names, cycle years,
+// eras left out of a numeric pattern, numeric patterns with two separators.
const MORE_LOCALES: Partial<Record<CalendarSystem, string>> = {
gregory: 'fr-FR it-IT es-ES ro-RO vi-VN',
- buddhist: 'fr-FR',
- roc: 'de-DE',
- japanese: 'it-IT hu-HU',
+ buddhist: 'fr-FR hi-IN',
+ roc: 'de-DE am-ET',
+ japanese: 'it-IT hu-HU am-ET',
persian: 'nb-NO',
+ hebrew: 'lv-LV',
chinese: 'ca-ES cs-CZ de-DE fi-FI fr-FR it-IT nl-NL pl-PL pt-PT ru-RU',
dangi: 'pt-BR fi-FI',
ethiopic: 'pt-BR',
- 'islamic-civil': 'fr-FR hu-HU sr-RS',
+ 'islamic-civil': 'fr-FR hu-HU sr-RS lv-LV',
+ 'islamic-tbla': 'lv-LV',
+ 'islamic-umalqura': 'lv-LV',
};
// Text in the lunisolar calendars costs far more to compose under the
@@ -80,12 +84,11 @@ function sampleDays(step: number, offset: number): PlainDate[] {
function failures(
locale: string,
calendar: CalendarSystem,
- step: number,
- offset: number,
+ dates: ReadonlyArray<PlainDate>,
) {
const lexicon = getCalendarDateLexicon(locale, calendar);
const failed: string[] = [];
- for (const date of sampleDays(step, offset)) {
+ for (const date of dates) {
const texts = [
formatCalendarDateHint(date, locale, calendar),
formatCalendarDateText(date, 'date', locale, calendar),
@@ -115,14 +118,60 @@ describe('committed text reads back as the same date (FR13)', () => {
const isLunisolar = calendar === 'chinese' || calendar === 'dangi';
it(`${calendar} in ${native}, en, and sv-SE`, () => {
const step = isLunisolar ? 42 : 14;
- expect(failures(native, calendar, step, 0)).toEqual([]);
- expect(failures('en', calendar, step * 3, 2)).toEqual([]);
- expect(failures('sv-SE', calendar, step * 3, 4)).toEqual([]);
+ expect(failures(native, calendar, sampleDays(step, 0))).toEqual([]);
+ expect(failures('en', calendar, sampleDays(step * 3, 2))).toEqual([]);
+ expect(failures('sv-SE', calendar, sampleDays(step * 3, 4))).toEqual([]);
});
}
it.each(Object.entries(MORE_LOCALES))('%s in %s', (calendar, locales) => {
for (const locale of locales.split(' ')) {
- expect(failures(locale, calendar as CalendarSystem, 997, 1)).toEqual([]);
+ expect(
+ failures(locale, calendar as CalendarSystem, sampleDays(997, 1)),
+ ).toEqual([]);
}
});
+ // Month names that start with a number, an era that the locale's numeric
+ // pattern leaves out, and a numeric pattern with two separators.
+ it.each<[string, CalendarSystem, ...[number, number, number][]]>([
+ ['lv-LV', 'hebrew', [1900, 2, 1], [1900, 3, 2], [1901, 2, 20]],
+ ['lv-LV', 'islamic-civil', [1900, 7, 1], [1900, 8, 26]],
+ ['am-ET', 'roc', [1900, 1, 1], [1911, 12, 31], [1912, 1, 1], [2026, 1, 1]],
+ ['ksh', 'roc', [1900, 1, 1], [1912, 1, 1]],
+ [
+ 'am-ET',
+ 'japanese',
+ [1900, 1, 1],
+ [1950, 6, 15],
+ [2000, 6, 15],
+ [2019, 5, 1],
+ [2026, 1, 1],
+ ],
+ ['hi-IN', 'buddhist', [1900, 1, 1], [2026, 11, 2]],
+ ])('%s %s', (locale, calendar, ...dates) => {
+ const days = dates.map(([year, month, day]) => ({year, month, day}));
+ expect(failures(locale, calendar, days)).toEqual([]);
+ });
+ it.each([
+ ['86. g. 1. adars', {year: 2026, month: 2, day: 18}],
+ ['26. g. 1. adars', {year: 1966, month: 2, day: 21}],
+ ])('reads a two-digit year before a Latvian month name: %s', (text, date) => {
+ const lexicon = getCalendarDateLexicon('lv-LV', 'hebrew');
+ const today = {year: 2026, month: 11, day: 2};
+ expect(parseCalendarDate(text, lexicon, {today})).toMatchObject({date});
+ });
+ it('writes the narrow era in the Amharic numeric pattern', () => {
+ const hint = (year: number, calendar: CalendarSystem) =>
+ formatCalendarDateHint({year, month: 1, day: 1}, 'am-ET', calendar);
+ expect(hint(2026, 'japanese')).toBe('1/1/8 R');
+ expect(hint(1990, 'japanese')).toBe('1/1/2 H');
+ expect(hint(2026, 'roc')).toBe('1/1/115 ROC');
+ expect(hint(1900, 'roc')).toBe('1/1/12 BROC');
+ });
+ it('adds no era to a calendar whose era does not change', () => {
+ const day = {year: 2026, month: 1, day: 1};
+ expect(formatCalendarDateHint(day, 'am-ET', 'ethiopic')).toBe('23/4/2018');
+ expect(
+ formatCalendarDateHint({year: 2026, month: 11, day: 2}, 'tk', 'buddhist'),
+ ).toBe('02.11.2569');
+ });
});
diff --git a/packages/core/src/utils/calendarDateParser.ts b/packages/core/src/utils/calendarDateParser.ts
index f49f7d2e9b..0001288fd1 100644
--- a/packages/core/src/utils/calendarDateParser.ts
+++ b/packages/core/src/utils/calendarDateParser.ts
@@ -91,6 +91,8 @@ export interface CalendarDateLexicon {
readonly eras: ReadonlyMap<string, string>;
readonly yearAliases: ReadonlyMap<string, string>;
readonly trailers: ReadonlySet<string>;
+ readonly yearMarkers: ReadonlySet<string>;
+ readonly separators: ReadonlySet<string>;
readonly weekdays: ReadonlySet<string>;
readonly vocabulary: ReadonlyArray<string>;
readonly vocabularySet: ReadonlySet<string>;
@@ -352,6 +354,8 @@ function buildLexicon(
const yearAliases = new Map<string, string>();
const skip = new Set<string>();
const trailers = new Set<string>();
+ const yearMarkers = new Set<string>();
+ const separators = new Set<string>();
const weekdays = new Set<string>();
const addSkip = (text: string, words = skip) => {
@@ -439,10 +443,13 @@ function buildLexicon(
for (const options of literalFormats) {
for (const pd of literalDates) {
const parts = partsOf(loc, calendar, options, pd);
- for (const part of parts) {
+ for (const [k, part] of parts.entries()) {
if (part.type === 'literal' || partType(part) === 'yearName') {
addSkip(part.value);
}
+ if (part.type === 'literal' && parts[k - 1]?.type === 'year') {
+ addSkip(part.value, yearMarkers);
+ }
}
if (loc === locale) {
const tail = parts.at(-1);
@@ -472,6 +479,13 @@ function buildLexicon(
}
}
}
+ const hint = displayOptions(locale, calendar, NUMERIC);
+ for (const part of partsOf(locale, calendar, hint, literalDates[0])) {
+ const separator = norm(part.value).replace(/\s+/g, '');
+ if (part.type === 'literal' && separator) {
+ separators.add(separator);
+ }
+ }
if (LUNISOLAR.has(calendar)) {
// Year names cycle every 60 years.
for (let year = 1996; year < 2057; year++) {
@@ -576,6 +590,8 @@ function buildLexicon(
eras,
yearAliases,
trailers,
+ yearMarkers,
+ separators,
weekdays,
vocabulary: [...vocabularySet].sort((a, b) => b.length - a.length),
vocabularySet,
@@ -617,13 +633,18 @@ type Token =
| {readonly t: 'monthNum'; readonly v: string; readonly isLeap: boolean}
| {readonly t: 'era'; readonly code: string; readonly isWeekday?: boolean}
| {readonly t: 'leap'}
- | {readonly t: 'word'}
+ | {readonly t: 'word'; readonly isYearMarker?: boolean}
| {readonly t: 'sep'; readonly v: string};
type Tokens = Token[] | 'incomplete' | 'unreadable';
-function tokenize(s: string, lex: CalendarDateLexicon): Tokens {
+function tokenize(
+ s: string,
+ lex: CalendarDateLexicon,
+ isDigitNameRead = true,
+): Tokens {
const out: Token[] = [];
+ let hasDigitName = false;
let i = 0;
const end = s.trimEnd().length;
while (i < end) {
@@ -638,6 +659,13 @@ function tokenize(s: string, lex: CalendarDateLexicon): Tokens {
i = template.end;
continue;
}
+ const digitName = isDigitNameRead && /\d/.test(ch) && matchWord(s, i, lex);
+ if (digitName) {
+ out.push(wordToken(digitName, lex));
+ hasDigitName = true;
+ i += digitName.length;
+ continue;
+ }
if (/\d/.test(ch)) {
let j = i;
while (j < s.length && /\d/.test(s[j])) {
@@ -684,6 +712,17 @@ function tokenize(s: string, lex: CalendarDateLexicon): Tokens {
}
return 'unreadable';
}
+ // Latvian "1. adars" is a month, and also day 1 of "adars". It is the day
+ // when no other number can be the day. A number before the year word, as in
+ // "26. g.", is the year.
+ const canBeDay = (token: Token, k: number) => {
+ const next = out.slice(k + 1).find(t => t.t !== 'sep');
+ const isYear = next?.t === 'word' && next.isYearMarker === true;
+ return token.t === 'num' && Number(token.v) <= 31 && !isYear;
+ };
+ if (hasDigitName && !out.some(canBeDay)) {
+ return tokenize(s, lex, false);
+ }
return out;
}
@@ -777,7 +816,7 @@ function wordToken(word: string, lex: CalendarDateLexicon): Token {
if (alias != null) {
return {t: 'num', v: alias, isAlias: true};
}
- return {t: 'word'};
+ return {t: 'word', isYearMarker: lex.yearMarkers.has(word)};
}
/** The month a typed abbreviation names when it starts only one month name. */
@@ -913,7 +952,7 @@ export function parseCalendarDate(
if (nums.length < 2) {
return INCOMPLETE;
}
- if (nums.length > 3 || !sameSeparators(tokens)) {
+ if (nums.length > 3 || !sameSeparators(tokens, lex)) {
return UNREADABLE;
}
let order: ReadonlyArray<DateField> =
@@ -1022,7 +1061,11 @@ function finish(
return {kind: 'value', date, isComplete};
}
-function sameSeparators(tokens: Token[]): boolean {
+/**
+ * Whether the numbers share one separator. Two separators of the locale's own
+ * numeric pattern also match, such as Hindi Buddhist "1/1`/2443".
+ */
+function sameSeparators(tokens: Token[], lex: CalendarDateLexicon): boolean {
let previous: string | null = null;
let seenNumber = false;
let pending: string | null = null;
@@ -1030,7 +1073,11 @@ function sameSeparators(tokens: Token[]): boolean {
if (token.t === 'num') {
if (seenNumber) {
const separator = pending ?? '';
- if (previous != null && separator !== previous) {
+ if (
+ previous != null &&
+ separator !== previous &&
+ !(lex.separators.has(separator) && lex.separators.has(previous))
+ ) {
return false;
}
previous = separator;
@@ -1195,10 +1242,30 @@ const displayOptionCache = new WeakMap<
Map<string, Intl.DateTimeFormatOptions>
>();
+const eraChangeCache = new Map<CalendarSystem, boolean>();
+
+/**
+ * Whether the era changes between 1900 and 2100. Only then can a year without
+ * its era read as two dates.
+ */
+function hasEraChange(calendar: CalendarSystem): boolean {
+ let result = eraChangeCache.get(calendar);
+ if (result == null) {
+ const eraOf = (date: PlainDate) =>
+ calendarEraYear('en', calendar, date).era;
+ result =
+ eraOf({year: 1900, month: 1, day: 1}) !==
+ eraOf({year: 2100, month: 12, day: 31});
+ eraChangeCache.set(calendar, result);
+ }
+ return result;
+}
+
/**
* Adds the era to a format that omits it, so a year never reads as a
* Gregorian year. Keeps the locale's own pattern when the era would reorder
- * the fields.
+ * the fields. Where the era changes, it uses a narrow era that keeps the
+ * order instead, such as Amharic Japanese "1/1/8 R".
*/
function displayOptions(
locale: Locale,
@@ -1219,11 +1286,18 @@ function displayOptions(
const sample = {year: 2026, month: 11, day: 2};
const parts = partsOf(locale, calendar, options, sample);
result = options;
+ const order = fieldOrder(parts).join();
if (!parts.some(p => p.type === 'era')) {
- const withEra = {...options, era: 'short'} as const;
- const eraParts = partsOf(locale, calendar, withEra, sample);
- if (fieldOrder(parts).join() === fieldOrder(eraParts).join()) {
- result = withEra;
+ const widths = hasEraChange(calendar)
+ ? (['short', 'narrow'] as const)
+ : (['short'] as const);
+ for (const era of widths) {
+ const withEra = {...options, era};
+ const eraParts = partsOf(locale, calendar, withEra, sample);
+ if (fieldOrder(eraParts).join() === order) {
+ result = withEra;
+ break;
+ }
}
}
byLocale.set(key, result);
@@ -1242,11 +1316,27 @@ function formatInCalendar(
relatedYear: true,
});
}
- return plainDateFormat(
- pd,
- {...displayOptions(locale, calendar, options), calendar},
- locale,
- );
+ const display = displayOptions(locale, calendar, options);
+ const text = plainDateFormat(pd, {...display, calendar}, locale);
+ // When every era width reorders the fields, such as the Amharic short-month
+ // date, the text has no era. Text without an era reads in the latest era.
+ // So a date of an earlier era adds the era. It goes at the start or the
+ // end, as in the era format.
+ const eraOf = (date: PlainDate) => calendarEraYear('en', calendar, date).era;
+ if (
+ !hasEraChange(calendar) ||
+ eraOf(pd) === eraOf({year: 9999, month: 12, day: 31}) ||
+ partsOf(locale, calendar, display, pd).some(p => p.type === 'era')
+ ) {
+ return text;
+ }
+ const withEra = partsOf(locale, calendar, {...options, era: 'short'}, pd);
+ const at = withEra.findIndex(p => p.type === 'era');
+ const era = withEra
+ .slice(at === 0 ? 0 : at - 1, at === 0 ? 2 : at + 1)
+ .map(p => p.value)
+ .join('');
+ return at === 0 ? era + text : text + era;
}
/**