fix(i18n): outdated locale was used instead

This commit is contained in:
amsyarasyiq 2024-05-08 18:28:32 +08:00
parent 2560e9aeb5
commit 7c8ee06c7e

View file

@ -8,14 +8,16 @@ const IntlMessageFormat = findByName("MessageFormat") as typeof import("intl-mes
type I18nKey = keyof typeof langDefault; type I18nKey = keyof typeof langDefault;
let currentLocale: string | null; let _currentLocale: string | null = null;
let _lastSetLocale: string | null = null;
const _loadedLocale = new Set<string>(); const _loadedLocale = new Set<string>();
const _loadedStrings = {} as Record<string, typeof langDefault>; const _loadedStrings = {} as Record<string, typeof langDefault>;
export const Strings = new Proxy({}, { export const Strings = new Proxy({}, {
get: (_t, prop: keyof typeof langDefault) => { get: (_t, prop: keyof typeof langDefault) => {
if (currentLocale && _loadedStrings[currentLocale]?.[prop]) { if (_currentLocale && _loadedStrings[_currentLocale]?.[prop]) {
return _loadedStrings[currentLocale]?.[prop]; return _loadedStrings[_currentLocale]?.[prop];
} }
return langDefault[prop]; return langDefault[prop];
} }
@ -33,9 +35,10 @@ export function initFetchI18nStrings() {
"sv-SE": "sv" "sv-SE": "sv"
} as Record<string, string>; } as Record<string, string>;
const resolvedLocale = languageMap[locale] ?? locale; const resolvedLocale = _lastSetLocale = languageMap[locale] ?? locale;
if (resolvedLocale.startsWith("en-")) { if (resolvedLocale.startsWith("en-")) {
currentLocale = null; _currentLocale = null;
return; return;
} }
@ -45,10 +48,10 @@ export function initFetchI18nStrings() {
fetch(`https://raw.githubusercontent.com/pyoncord/i18n/main/resources/${resolvedLocale}/bunny.json`) fetch(`https://raw.githubusercontent.com/pyoncord/i18n/main/resources/${resolvedLocale}/bunny.json`)
.then(r => r.json()) .then(r => r.json())
.then(strings => _loadedStrings[resolvedLocale] = strings) .then(strings => _loadedStrings[resolvedLocale] = strings)
.then(() => currentLocale = resolvedLocale) .then(() => resolvedLocale === _lastSetLocale && (_currentLocale = resolvedLocale))
.catch(e => console.error(`An error occured while fetching strings for ${resolvedLocale}: ${e}`)); .catch(e => console.error(`An error occured while fetching strings for ${resolvedLocale}: ${e}`));
} else { } else {
currentLocale = resolvedLocale; _currentLocale = resolvedLocale;
} }
}; };