feat(web): use browser language by default (#10849)

This commit is contained in:
Michel Heusschen 2024-07-05 05:56:54 +02:00 committed by GitHub
parent 6629bf50ae
commit 6030349a6f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 55 additions and 10 deletions

View file

@ -1,3 +1,4 @@
import { langs } from '$lib/constants';
import { locale, t, waitLocale } from 'svelte-i18n';
import { get, type Unsubscriber } from 'svelte/store';
@ -11,3 +12,22 @@ export async function getFormatter() {
await waitLocale();
return get(t);
}
// https://github.com/kaisermann/svelte-i18n/blob/780932a3e1270d521d348aac8ba03be9df309f04/src/runtime/stores/locale.ts#L11
function getSubLocales(refLocale: string) {
return refLocale
.split('-')
.map((_, i, arr) => arr.slice(0, i + 1).join('-'))
.reverse();
}
export function getClosestAvailableLocale(locales: readonly string[], allLocales: readonly string[]) {
const allLocalesSet = new Set(allLocales);
return locales.find((locale) => getSubLocales(locale).some((subLocale) => allLocalesSet.has(subLocale)));
}
export const langCodes = langs.map((lang) => lang.code);
export function getPreferredLocale() {
return getClosestAvailableLocale(navigator.languages, langCodes);
}