fix(theme-translations): always try all possible locale resolutions (#7166)

This commit is contained in:
Joshua Chen 2022-04-13 16:32:46 +08:00 committed by GitHub
parent ec109737e9
commit 4d9a0edf21
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 20 deletions

View file

@ -18,21 +18,45 @@ describe('codeTranslationLocalesToTry', () => {
'fr',
'fr-FR',
'fr-Latn',
'fr',
]);
expect(codeTranslationLocalesToTry('fr-FR')).toEqual([
'fr-FR',
'fr-FR',
'fr-Latn',
'fr',
]);
expect(codeTranslationLocalesToTry('fr-FR')).toEqual(['fr-FR', 'fr']);
// Note: "pt" is expanded into "pt-BR", not "pt-PT", as "pt-BR" is more
// widely used! See https://github.com/facebook/docusaurus/pull/4536#issuecomment-810088783
expect(codeTranslationLocalesToTry('pt')).toEqual([
'pt',
'pt-BR',
'pt-Latn',
'pt',
]);
expect(codeTranslationLocalesToTry('pt-BR')).toEqual([
'pt-BR',
'pt-BR',
'pt-Latn',
'pt',
]);
expect(codeTranslationLocalesToTry('pt-PT')).toEqual([
'pt-PT',
'pt-PT',
'pt-Latn',
'pt',
]);
expect(codeTranslationLocalesToTry('pt-BR')).toEqual(['pt-BR', 'pt']);
expect(codeTranslationLocalesToTry('pt-PT')).toEqual(['pt-PT', 'pt']);
expect(codeTranslationLocalesToTry('zh')).toEqual([
'zh',
'zh-CN',
'zh-Hans',
'zh',
]);
expect(codeTranslationLocalesToTry('zh-cn')).toEqual([
'zh-cn',
'zh-CN',
'zh-Hans',
'zh',
]);
});
});
@ -48,12 +72,7 @@ describe('readDefaultCodeTranslationMessages', () => {
async function readAsJSON(locale: string, filename: string = name) {
console.log(path.resolve(dirPath, locale, `${filename}.json`));
return JSON.parse(
await fs.readFile(
path.resolve(dirPath, locale, `${filename}.json`),
'utf8',
),
);
return fs.readJSON(path.resolve(dirPath, locale, `${filename}.json`));
}
it('for empty locale', async () => {

View file

@ -18,17 +18,18 @@ export function codeTranslationLocalesToTry(locale: string): string[] {
const intlLocale = new Intl.Locale(locale);
// if locale is just a simple language like "pt", we want to fallback to pt-BR
// (not pt-PT!) See https://github.com/facebook/docusaurus/pull/4536#issuecomment-810088783
if (intlLocale.language === locale) {
const maximizedLocale = intlLocale.maximize(); // pt-Latn-BR`
// ["pt","pt-BR"]; ["zh", "zh-Hans"]
return [
locale,
`${maximizedLocale.language}-${maximizedLocale.region}`,
`${maximizedLocale.language}-${maximizedLocale.script}`,
];
}
// if locale is like "pt-BR", we want to fallback to "pt"
return [locale, intlLocale.language!];
const maximizedLocale = intlLocale.maximize(); // pt-Latn-BR
return [
// May be "zh", "zh-CN", "zh-Hans", "zh-cn", or anything: very likely to be
// unresolved except for simply locales
locale,
// zh-CN / pt-BR
`${maximizedLocale.language}-${maximizedLocale.region}`,
// zh-Hans / pt-Latn
`${maximizedLocale.language}-${maximizedLocale.script}`,
// zh / pt
maximizedLocale.language!,
];
}
// Useful to implement getDefaultCodeTranslationMessages() in themes