84 lines
2.3 KiB
TypeScript
84 lines
2.3 KiB
TypeScript
|
/**
|
|||
|
* Returns the user's locale
|
|||
|
*/
|
|||
|
export function getLocale(): string {
|
|||
|
return document.documentElement.dataset.locale || 'en'
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* Returns user's locale in canonical form
|
|||
|
* E.g. `en-US` instead of `en_US`
|
|||
|
*/
|
|||
|
export function getCanonicalLocale(): string {
|
|||
|
return getLocale().replace(/_/g, '-')
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* Returns the user's language
|
|||
|
*/
|
|||
|
export function getLanguage(): string {
|
|||
|
return document.documentElement.lang || 'en'
|
|||
|
}
|
|||
|
|
|||
|
/**
|
|||
|
* Check whether the current, or a given, language is read right-to-left
|
|||
|
*
|
|||
|
* @param language Language code to check, defaults to current language
|
|||
|
*/
|
|||
|
export function isRTL(language?: string): boolean {
|
|||
|
const languageCode = language || getLanguage()
|
|||
|
|
|||
|
// Source: https://meta.wikimedia.org/wiki/Template:List_of_language_names_ordered_by_code
|
|||
|
const rtlLanguages = [
|
|||
|
/* eslint-disable no-multi-spaces */
|
|||
|
'ae', // Avestan
|
|||
|
'ar', // 'العربية', Arabic
|
|||
|
'arc', // Aramaic
|
|||
|
'arz', // 'مصرى', Egyptian
|
|||
|
'bcc', // 'بلوچی مکرانی', Southern Balochi
|
|||
|
'bqi', // 'بختياري', Bakthiari
|
|||
|
'ckb', // 'Soranî / کوردی', Sorani
|
|||
|
'dv', // Dhivehi
|
|||
|
'fa', // 'فارسی', Persian
|
|||
|
'glk', // 'گیلکی', Gilaki
|
|||
|
'ha', // 'هَوُسَ', Hausa
|
|||
|
'he', // 'עברית', Hebrew
|
|||
|
'khw', // 'کھوار', Khowar
|
|||
|
'ks', // 'कॉशुर / کٲشُر', Kashmiri
|
|||
|
'ku', // 'Kurdî / كوردی', Kurdish
|
|||
|
'mzn', // 'مازِرونی', Mazanderani
|
|||
|
'nqo', // 'ߒߞߏ', N’Ko
|
|||
|
'pnb', // 'پنجابی', Western Punjabi
|
|||
|
'ps', // 'پښتو', Pashto,
|
|||
|
'sd', // 'سنڌي', Sindhi
|
|||
|
'ug', // 'Uyghurche / ئۇيغۇرچە', Uyghur
|
|||
|
'ur', // 'اردو', Urdu
|
|||
|
'uzs', // 'اوزبیکی', Uzbek Afghan
|
|||
|
'yi', // 'ייִדיש', Yiddish
|
|||
|
/* eslint-enable no-multi-spaces */
|
|||
|
]
|
|||
|
|
|||
|
// special case for Uzbek Afghan
|
|||
|
if ((language || getCanonicalLocale()).startsWith('uz-AF')) {
|
|||
|
return true
|
|||
|
}
|
|||
|
|
|||
|
return rtlLanguages.includes(languageCode)
|
|||
|
}
|
|||
|
|
|||
|
export function getBrowserLocale(options?: { languageCodeOnly: boolean }): string {
|
|||
|
const navigatorLocale = navigator.languages !== undefined
|
|||
|
? navigator.languages[0]
|
|||
|
: navigator.language;
|
|||
|
|
|||
|
if (!navigatorLocale) {
|
|||
|
return 'en'; // Fallback to 'en' if no locale is detected
|
|||
|
}
|
|||
|
|
|||
|
const locale = options?.languageCodeOnly
|
|||
|
? navigatorLocale.trim().split(/-|_/)[0]
|
|||
|
: navigatorLocale.trim();
|
|||
|
|
|||
|
return locale;
|
|||
|
}
|