feat: add modular i18n foundation
This commit is contained in:
60
src/i18n/index.ts
Normal file
60
src/i18n/index.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { isSupportedLocale, resolveInitialLocale } from "./locales.ts";
|
||||
import { messages } from "./messages.ts";
|
||||
import { readStoredLocale, writeStoredLocale } from "./storage.ts";
|
||||
import { defaultLocale } from "./types.ts";
|
||||
import type { SupportedLocale } from "./types.ts";
|
||||
import { syncVantLocale } from "./vant.ts";
|
||||
|
||||
function getNavigatorLanguages(): string[] {
|
||||
if (typeof navigator === "undefined") {
|
||||
return [];
|
||||
}
|
||||
|
||||
const languages = navigator.languages ? [...navigator.languages] : [];
|
||||
|
||||
if (languages.length > 0) {
|
||||
return languages;
|
||||
}
|
||||
|
||||
return navigator.language ? [navigator.language] : [];
|
||||
}
|
||||
|
||||
function setDocumentLanguage(locale: SupportedLocale): void {
|
||||
if (typeof document === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
document.documentElement.lang = locale;
|
||||
}
|
||||
|
||||
const initialLocale = resolveInitialLocale({
|
||||
storedLocale: readStoredLocale(),
|
||||
navigatorLanguages: getNavigatorLanguages(),
|
||||
});
|
||||
|
||||
syncVantLocale(initialLocale);
|
||||
setDocumentLanguage(initialLocale);
|
||||
|
||||
export const i18n = createI18n({
|
||||
legacy: false,
|
||||
locale: initialLocale,
|
||||
fallbackLocale: defaultLocale,
|
||||
messages,
|
||||
});
|
||||
|
||||
export function getCurrentLocale(): SupportedLocale {
|
||||
const locale = i18n.global.locale.value;
|
||||
return isSupportedLocale(locale) ? locale : defaultLocale;
|
||||
}
|
||||
|
||||
export function setLocale(locale: string): void {
|
||||
if (!isSupportedLocale(locale)) {
|
||||
return;
|
||||
}
|
||||
|
||||
i18n.global.locale.value = locale;
|
||||
writeStoredLocale(locale);
|
||||
syncVantLocale(locale);
|
||||
setDocumentLanguage(locale);
|
||||
}
|
||||
Reference in New Issue
Block a user