Skip to content

Commit

Permalink
perf: only loads selected locales (#3152)
Browse files Browse the repository at this point in the history
  • Loading branch information
amir20 authored Jul 26, 2024
1 parent cbed761 commit 19d0355
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
41 changes: 32 additions & 9 deletions assets/modules/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,45 @@
import { type App } from "vue";
import { createI18n } from "vue-i18n";
import { locale } from "@/stores/settings";
import type { Locale } from "vue-i18n";

import messages from "@intlify/unplugin-vue-i18n/messages";
const localesMap = Object.fromEntries(
Object.entries(import.meta.glob("../../locales/*.yml")).map(([path, loadLocale]) => [
path.match(/([\w-]*)\.yml$/)?.[1],
loadLocale,
]),
) as Record<Locale, () => Promise<{ default: Record<string, string> }>>;

const defaultLocale = messages?.hasOwnProperty(navigator.language)
? navigator.language
: navigator.language.slice(0, 2);
export const availableLocales = Object.keys(localesMap);

function setI18nLanguage(lang: Locale) {
i18n.global.locale.value = lang;
return lang;
}

const loadedLanguages: string[] = [];
async function loadLanguage(lang: string): Promise<Locale> {
if (i18n.global.locale.value === lang) return setI18nLanguage(lang);
if (loadedLanguages.includes(lang)) return setI18nLanguage(lang);

const messages = await localesMap[lang]();
i18n.global.setLocaleMessage(lang, messages.default);
loadedLanguages.push(lang);
return setI18nLanguage(lang);
}

const i18n = createI18n({
legacy: false,
locale: locale.value || defaultLocale,
fallbackLocale: "en",
messages,
locale: "",
messages: {},
});

watch(locale, (value) => {
i18n.global.locale.value = value || defaultLocale;
watchEffect(() => {
loadLanguage(
locale.value ||
[navigator.language, navigator.language.slice(0, 2)].find((l) => availableLocales.includes(l)) ||
"en",
);
});

export const install = (app: App) => app.use(i18n);
Expand Down
4 changes: 3 additions & 1 deletion assets/pages/settings.vue
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ import {
locale,
} from "@/stores/settings";
const { t, availableLocales } = useI18n();
import { availableLocales } from "@/modules/i18n";
const { t } = useI18n();
setTitle(t("title.settings"));
const { latest, hasUpdate } = useReleases();
Expand Down

0 comments on commit 19d0355

Please sign in to comment.