Spell check: Restore english region support

This commit is contained in:
Scott Nonnenberg 2022-07-15 15:37:19 -07:00 committed by GitHub
parent 3cd77b0d53
commit 1bb91758e6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 60 additions and 35 deletions

View file

@ -10,9 +10,10 @@ import type { LoggerType } from '../ts/types/Logging';
import type { LocaleMessagesType } from '../ts/types/I18N';
import type { LocalizerType } from '../ts/types/Util';
function normalizeLocaleName(locale: string): string {
if (/^en-/.test(locale)) {
return 'en';
function removeRegion(locale: string): string {
const match = /^([^-]+)(-.+)$/.exec(locale);
if (match) {
return match[1];
}
return locale;
@ -38,12 +39,29 @@ export type LocaleType = {
messages: LocaleMessagesType;
};
function finalize(
messages: LocaleMessagesType,
backupMessages: LocaleMessagesType,
localeName: string
) {
// We start with english, then overwrite that with anything present in locale
const finalMessages = merge(backupMessages, messages);
const i18n = setupI18n(localeName, finalMessages);
return {
i18n,
name: localeName,
messages: finalMessages,
};
}
export function load({
appLocale,
logger,
}: {
appLocale: string;
logger: Pick<LoggerType, 'error'>;
logger: Pick<LoggerType, 'error' | 'warn'>;
}): LocaleType {
if (!appLocale) {
throw new TypeError('`appLocale` is required');
@ -52,6 +70,9 @@ export function load({
if (!logger || !logger.error) {
throw new TypeError('`logger.error` is required');
}
if (!logger.warn) {
throw new TypeError('`logger.warn` is required');
}
const english = getLocaleMessages('en');
@ -59,30 +80,23 @@ export function load({
// default to 'en'
//
// possible locales:
// https://github.com/electron/electron/blob/master/docs/api/locales.md
let localeName = normalizeLocaleName(appLocale);
let messages;
// https://source.chromium.org/chromium/chromium/src/+/main:ui/base/l10n/l10n_util.cc
const normalized = removeRegion(appLocale);
try {
messages = getLocaleMessages(localeName);
// We start with english, then overwrite that with anything present in locale
messages = merge(english, messages);
return finalize(getLocaleMessages(appLocale), english, appLocale);
} catch (e) {
logger.error(
`Problem loading messages for locale ${localeName} ${e.stack}`
);
logger.error('Falling back to en locale');
localeName = 'en';
messages = english;
logger.warn(`Problem loading messages for locale ${appLocale}`);
}
const i18n = setupI18n(appLocale, messages);
try {
logger.warn(`Falling back to parent language: '${normalized}'`);
// Note: messages are from parent language, but we still keep the region
return finalize(getLocaleMessages(normalized), english, appLocale);
} catch (e) {
logger.error(`Problem loading messages for locale ${normalized}`);
return {
i18n,
name: localeName,
messages,
};
logger.warn("Falling back to 'en' locale");
return finalize(english, english, 'en');
}
}