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.
This commit is contained in:
DEV_DSW
2026-06-02 15:02:09 +08:00
parent e617e303d4
commit 63470f279c
2 changed files with 9 additions and 25 deletions

View File

@@ -1,25 +1,11 @@
import { createI18n } from "vue-i18n";
import { isSupportedLocale, resolveInitialLocale } from "./locales.ts";
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 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;
@@ -28,10 +14,11 @@ function setDocumentLanguage(locale: SupportedLocale): void {
document.documentElement.lang = locale;
}
const initialLocale = resolveInitialLocale({
storedLocale: readStoredLocale(),
navigatorLanguages: getNavigatorLanguages(),
});
const storedLocale = readStoredLocale();
const initialLocale = storedLocale ?? defaultLocale;
if (!storedLocale) {
writeStoredLocale(defaultLocale);
}
syncVantLocale(initialLocale);
setDocumentLanguage(initialLocale);

View File

@@ -1,6 +1,7 @@
import axios from "axios";
import type { AxiosError, AxiosRequestConfig } from "axios";
import { getCurrentLocale } from "@/i18n";
import { readStoredLocale } from "@/i18n/storage";
import { defaultLocale } from "@/i18n/types";
import type {
ApiResponse,
NormalizedError,
@@ -89,11 +90,7 @@ function resolveRequestLanguage(): string | null {
if (context.language) {
return context.language;
}
try {
return getCurrentLocale();
} catch {
return null;
}
return readStoredLocale() ?? defaultLocale;
}
function buildContextHeaders(options?: RequestOptions): Record<string, string> {