Files
nianxx-h5/src/i18n/index.ts
DEV_DSW 63470f279c refactor(i18n): simplify locale resolution and clean up code
Simplify the locale resolution logic in the request utility by directly using stored locale with default fallback, remove the unused getNavigatorLanguages function, and streamline the initial locale setup in the i18n entrypoint while persisting the default locale when no stored locale is present.
2026-06-02 15:02:09 +08:00

48 lines
1.2 KiB
TypeScript

import { createI18n } from "vue-i18n";
import { isSupportedLocale } 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 setDocumentLanguage(locale: SupportedLocale): void {
if (typeof document === "undefined") {
return;
}
document.documentElement.lang = locale;
}
const storedLocale = readStoredLocale();
const initialLocale = storedLocale ?? defaultLocale;
if (!storedLocale) {
writeStoredLocale(defaultLocale);
}
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);
}