Files
clash-verge-rev/src/services/preload.ts
T
Tunglies 16ef6fbc34 fix(i18n): resolve startup locales consistently
Prefer a supported saved language over the cache and browser locale.
Align frontend alias resolution with Rust and ignore unsupported saved
values when the layout mounts so they cannot overwrite the fallback.

In Rust, walk borrowed prefixes instead of rebuilding strings. This
preserves locale resolution and removes quadratic work on long tags.
Across all 14 shipped locale IDs (equally weighted),
median lookup time fell from 40.0 to 22.4 ns and heap allocations fell
from 4 to 2 per lookup. A synthetic 64 KiB tag fell from 771 ms to 240 µs.
2026-12-03 12:59:02 +08:00

72 lines
1.9 KiB
TypeScript

import { getVergeConfig } from './cmds'
import {
getCachedLanguage,
initializeLanguage,
resolveLanguage,
resolveSupportedLanguage,
} from './i18n'
let vergeConfigCache: IVergeConfig | null | undefined
const detectSystemTheme = (): 'light' | 'dark' => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function')
return 'light'
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
const getThemeModeFromWindow = (): IVergeConfig['theme_mode'] | undefined => {
if (typeof window === 'undefined') return undefined
const mode = (
window as typeof window & {
__VERGE_INITIAL_THEME_MODE?: unknown
}
).__VERGE_INITIAL_THEME_MODE
if (mode === 'light' || mode === 'dark' || mode === 'system') {
return mode
}
return undefined
}
export const resolveThemeMode = (
vergeConfig?: IVergeConfig | null,
): 'light' | 'dark' => {
const initialMode = vergeConfig?.theme_mode ?? getThemeModeFromWindow()
if (initialMode === 'dark' || initialMode === 'light') {
return initialMode
}
return detectSystemTheme()
}
export const setPreloadConfig = (config: IVergeConfig | null) => {
vergeConfigCache = config
}
export const getPreloadConfig = () => vergeConfigCache
const preloadConfig = async () => {
try {
const config = await getVergeConfig()
setPreloadConfig(config)
return config
} catch (error) {
console.warn('[preload.ts] Failed to read Verge config:', error)
setPreloadConfig(null)
return null
}
}
export const preloadAppData = async () => {
const config = await preloadConfig()
const initialLanguage =
resolveSupportedLanguage(config?.language ?? undefined) ??
getCachedLanguage() ??
resolveLanguage(
typeof navigator !== 'undefined' ? navigator.language : undefined,
)
await initializeLanguage(initialLanguage)
const initialThemeMode = resolveThemeMode(config)
return { initialThemeMode }
}