Load Intl locale data in parallel (#18120)

* Load Intl locale data in parallel

* Switch to check result.ok
This commit is contained in:
Steve Repsher 2023-10-05 10:26:15 -04:00 committed by GitHub
parent 0c32d1eb4e
commit 4a4d9a08d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,70 +1,36 @@
// Loads the static locale data for a given language from FormatJS
// Parents need to load polyfills first; they are not imported here to avoid a circular reference
const loadedPolyfillLocale = new Set();
const INTL_POLYFILLS = [
"DateTimeFormat",
"DisplayNames",
"ListFormat",
"NumberFormat",
"RelativeTimeFormat",
] as const satisfies readonly (keyof typeof Intl)[];
export const polyfillLocaleData = async (language: string) => {
if (loadedPolyfillLocale.has(language)) {
return;
}
loadedPolyfillLocale.add(language);
try {
if (
Intl.NumberFormat &&
// @ts-ignore
typeof Intl.NumberFormat.__addLocaleData === "function"
) {
const result = await fetch(
`${__STATIC_PATH__}locale-data/intl-numberformat/${language}.json`
);
// @ts-ignore
Intl.NumberFormat.__addLocaleData(await result.json());
const loadedLocales: Set<string> = new Set();
const addData = async (
obj: (typeof INTL_POLYFILLS)[number],
language: string
) => {
// Add function will only exist if constructor is polyfilled
if (typeof (Intl[obj] as any)?.__addLocaleData === "function") {
const result = await fetch(
`${__STATIC_PATH__}locale-data/intl-${obj.toLowerCase()}/${language}.json`
);
// Ignore if polyfill data does not exist for language
if (result.ok) {
(Intl[obj] as any).__addLocaleData(await result.json());
}
if (
Intl.RelativeTimeFormat &&
// @ts-ignore
typeof Intl.RelativeTimeFormat.__addLocaleData === "function"
) {
const result = await fetch(
`${__STATIC_PATH__}locale-data/intl-relativetimeformat/${language}.json`
);
// @ts-ignore
Intl.RelativeTimeFormat.__addLocaleData(await result.json());
}
if (
Intl.DateTimeFormat &&
// @ts-ignore
typeof Intl.DateTimeFormat.__addLocaleData === "function"
) {
const result = await fetch(
`${__STATIC_PATH__}locale-data/intl-datetimeformat/${language}.json`
);
// @ts-ignore
Intl.DateTimeFormat.__addLocaleData(await result.json());
}
if (
Intl.DisplayNames &&
// @ts-ignore
typeof Intl.DisplayNames.__addLocaleData === "function"
) {
const result = await fetch(
`${__STATIC_PATH__}locale-data/intl-displaynames/${language}.json`
);
// @ts-ignore
Intl.DisplayNames.__addLocaleData(await result.json());
}
if (
Intl.ListFormat &&
// @ts-ignore
typeof Intl.ListFormat.__addLocaleData === "function"
) {
const result = await fetch(
`${__STATIC_PATH__}locale-data/intl-listformat/${language}.json`
);
// @ts-ignore
Intl.ListFormat.__addLocaleData(await result.json());
}
} catch (e) {
// Ignore
}
};
export const polyfillLocaleData = async (language: string) => {
if (loadedLocales.has(language)) {
return;
}
loadedLocales.add(language);
await Promise.all(INTL_POLYFILLS.map((obj) => addData(obj, language)));
};