|
| 1 | +/** |
| 2 | + * Utility functions for language detection and handling |
| 3 | + */ |
| 4 | + |
| 5 | +function getPreferredLanguage(supportedLanguages = [], defaultLanguage = 'en') { |
| 6 | + if (typeof navigator === 'undefined') { |
| 7 | + return defaultLanguage; |
| 8 | + } |
| 9 | + |
| 10 | + const normalizeLanguage = (langCode) => langCode.toLowerCase().trim(); |
| 11 | + |
| 12 | + const normalizedSupported = supportedLanguages.map(normalizeLanguage); |
| 13 | + |
| 14 | + if (navigator.languages && navigator.languages.length) { |
| 15 | + const matchedLang = navigator.languages.find((browserLang) => { |
| 16 | + const normalizedBrowserLang = normalizeLanguage(browserLang); |
| 17 | + |
| 18 | + const hasExactMatch = |
| 19 | + normalizedSupported.findIndex( |
| 20 | + (lang) => lang === normalizedBrowserLang |
| 21 | + ) !== -1; |
| 22 | + |
| 23 | + if (hasExactMatch) { |
| 24 | + return true; |
| 25 | + } |
| 26 | + |
| 27 | + const languageOnly = normalizedBrowserLang.split('-')[0]; |
| 28 | + const hasLanguageOnlyMatch = |
| 29 | + normalizedSupported.findIndex( |
| 30 | + (lang) => lang === languageOnly || lang.startsWith(`${languageOnly}-`) |
| 31 | + ) !== -1; |
| 32 | + |
| 33 | + return hasLanguageOnlyMatch; |
| 34 | + }); |
| 35 | + |
| 36 | + if (matchedLang) { |
| 37 | + const normalizedMatchedLang = normalizeLanguage(matchedLang); |
| 38 | + const exactMatchIndex = normalizedSupported.findIndex( |
| 39 | + (lang) => lang === normalizedMatchedLang |
| 40 | + ); |
| 41 | + |
| 42 | + if (exactMatchIndex !== -1) { |
| 43 | + return supportedLanguages[exactMatchIndex]; |
| 44 | + } |
| 45 | + |
| 46 | + const languageOnly = normalizedMatchedLang.split('-')[0]; |
| 47 | + const languageOnlyMatchIndex = normalizedSupported.findIndex( |
| 48 | + (lang) => lang === languageOnly || lang.startsWith(`${languageOnly}-`) |
| 49 | + ); |
| 50 | + |
| 51 | + if (languageOnlyMatchIndex !== -1) { |
| 52 | + return supportedLanguages[languageOnlyMatchIndex]; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + if (navigator.language) { |
| 58 | + const normalizedNavLang = normalizeLanguage(navigator.language); |
| 59 | + const exactMatchIndex = normalizedSupported.findIndex( |
| 60 | + (lang) => lang === normalizedNavLang |
| 61 | + ); |
| 62 | + |
| 63 | + if (exactMatchIndex !== -1) { |
| 64 | + return supportedLanguages[exactMatchIndex]; |
| 65 | + } |
| 66 | + |
| 67 | + const languageOnly = normalizedNavLang.split('-')[0]; |
| 68 | + const languageOnlyMatchIndex = normalizedSupported.findIndex( |
| 69 | + (lang) => lang === languageOnly || lang.startsWith(`${languageOnly}-`) |
| 70 | + ); |
| 71 | + |
| 72 | + if (languageOnlyMatchIndex !== -1) { |
| 73 | + return supportedLanguages[languageOnlyMatchIndex]; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + return defaultLanguage; |
| 78 | +} |
| 79 | + |
| 80 | +export default getPreferredLanguage; |
0 commit comments