mirror of
https://github.com/System-End/scraps.git
synced 2026-04-19 22:05:09 +00:00
better language detection
This commit is contained in:
parent
aa16e2a844
commit
5b52d9c5cc
1 changed files with 29 additions and 1 deletions
|
|
@ -8,11 +8,39 @@ export type Translations = typeof en;
|
|||
|
||||
const translations: Record<Locale, Translations> = { en, es };
|
||||
|
||||
const SUPPORTED_LOCALES: Locale[] = ['en', 'es'];
|
||||
|
||||
function matchLocale(lang: string): Locale | null {
|
||||
const lower = lang.toLowerCase();
|
||||
// Exact match
|
||||
if (SUPPORTED_LOCALES.includes(lower as Locale)) return lower as Locale;
|
||||
// Match language prefix (e.g. es-MX, es-AR, es-ES -> es)
|
||||
const prefix = lower.split('-')[0];
|
||||
if (SUPPORTED_LOCALES.includes(prefix as Locale)) return prefix as Locale;
|
||||
return null;
|
||||
}
|
||||
|
||||
function getBrowserLocale(): Locale | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
// Check navigator.languages first (ordered by preference)
|
||||
if (navigator.languages?.length) {
|
||||
for (const lang of navigator.languages) {
|
||||
const matched = matchLocale(lang);
|
||||
if (matched) return matched;
|
||||
}
|
||||
}
|
||||
// Fallback to navigator.language
|
||||
if (navigator.language) {
|
||||
return matchLocale(navigator.language);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function getInitialLocale(): Locale {
|
||||
if (typeof window === 'undefined') return 'en';
|
||||
const stored = localStorage.getItem('locale');
|
||||
if (stored === 'en' || stored === 'es') return stored;
|
||||
return 'en';
|
||||
return getBrowserLocale() || 'en';
|
||||
}
|
||||
|
||||
function createLocaleStore() {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue