Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): fix default i18n calendar used, infer it from locale if possible #9878

Merged
merged 2 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/docusaurus/src/server/__tests__/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,15 @@ describe('defaultLocaleConfig', () => {
label: 'فارسی',
direction: 'rtl',
htmlLang: 'fa',
calendar: 'gregory',
calendar: 'persian',
path: 'fa',
});
expect(getDefaultLocaleConfig('fa-IR')).toEqual({
// cSpell:ignore ایران فارسیا
label: 'فارسی (ایران)',
direction: 'rtl',
htmlLang: 'fa-IR',
calendar: 'gregory',
calendar: 'persian',
path: 'fa-IR',
});
expect(getDefaultLocaleConfig('en-US-u-ca-buddhist')).toEqual({
Expand Down
27 changes: 25 additions & 2 deletions packages/docusaurus/src/server/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,36 @@ function getDefaultLocaleLabel(locale: string) {
);
}

function getDefaultCalendar(localeStr: string) {
const locale = new Intl.Locale(localeStr);

// If the locale name includes -u-ca-xxx the calendar will be defined
if (locale.calendar) {
return locale.calendar;
}

// Not well-supported but server code can infer a calendar from the locale
// See https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCalendars
// See https://caniuse.com/mdn-javascript_builtins_intl_locale_getcalendars
const calendars =
// @ts-expect-error: new std method (Bun/JSC/WebKit)
locale.getCalendars?.() ??
// @ts-expect-error: non-std attribute (V8/Chromium/Node)
locale.calendars;

if (calendars instanceof Array && calendars[0]) {
return calendars[0];
}

return 'gregory';
}

export function getDefaultLocaleConfig(locale: string): I18nLocaleConfig {
return {
label: getDefaultLocaleLabel(locale),
direction: getLangDir(locale),
htmlLang: locale,
// If the locale name includes -u-ca-xxx the calendar will be defined
calendar: new Intl.Locale(locale).calendar ?? 'gregory',
calendar: getDefaultCalendar(locale),
path: locale,
};
}
Expand Down
Loading