diff options
Diffstat (limited to 'packages/web-util/src/hooks/useLang.ts')
-rw-r--r-- | packages/web-util/src/hooks/useLang.ts | 36 |
1 files changed, 31 insertions, 5 deletions
diff --git a/packages/web-util/src/hooks/useLang.ts b/packages/web-util/src/hooks/useLang.ts index 448cd8aba..e4e512388 100644 --- a/packages/web-util/src/hooks/useLang.ts +++ b/packages/web-util/src/hooks/useLang.ts @@ -20,16 +20,42 @@ import { useLocalStorage, } from "./useLocalStorage.js"; -function getBrowserLang(): string | undefined { +const MIN_LANG_COVERAGE_THRESHOLD = 90; +/** + * choose the best from the browser config based on the completeness + * on the translation + */ +function getBrowserLang(completness: Record<string, number>): string | undefined { if (typeof window === "undefined") return undefined; - if (window.navigator.languages) return window.navigator.languages[0]; - if (window.navigator.language) return window.navigator.language; + + if (window.navigator.language) { + if (completness[window.navigator.language] >= MIN_LANG_COVERAGE_THRESHOLD) { + return window.navigator.language + } + } + if (window.navigator.languages) { + const match = Object.entries(completness).filter(([code, value]) => { + if (value < MIN_LANG_COVERAGE_THRESHOLD) return false; //do not consider langs below 90% + return window.navigator.languages.findIndex(l => l.startsWith(code)) !== -1 + }).map(([code, value]) => ({ code, value })) + + if (match.length > 0) { + let max = match[0] + match.forEach(v => { + if (v.value > max.value) { + max = v + } + }) + return max.code + } + }; + return undefined; } const langPreferenceKey = buildStorageKey("lang-preference"); -export function useLang(initial?: string): Required<StorageState> { - const defaultValue = (getBrowserLang() || initial || "en").substring(0, 2); +export function useLang(initial: string | undefined, completness: Record<string, number>): Required<StorageState> { + const defaultValue = (getBrowserLang(completness) || initial || "en").substring(0, 2); return useLocalStorage(langPreferenceKey, defaultValue); } |