this repo has no description
1import { i18n } from '@lingui/core';
2
3import translangLanguagesNative from '../data/translang-languages-native';
4
5import mem from './mem';
6
7// Some codes are not supported by Intl.DisplayNames
8// These are mapped to other codes as fallback
9const codeMappings = {
10 'zh-YUE': 'YUE',
11 zh_HANT: 'zh-Hant',
12};
13
14const IntlDN = mem(
15 (locale) =>
16 new Intl.DisplayNames(locale || undefined, {
17 type: 'language',
18 }),
19);
20
21function _localeCode2Text(code) {
22 let locale;
23 let fallback;
24 if (typeof code === 'object') {
25 ({ code, locale, fallback } = code);
26 }
27 try {
28 const text = IntlDN(locale || i18n.locale).of(code);
29 if (text !== code) return text;
30 if (!fallback) {
31 const anotherText = IntlDN(code).of(code);
32 if (anotherText !== code) return anotherText;
33 const yetAnotherText = translangLanguagesNative?.[locale];
34 if (yetAnotherText !== code) return yetAnotherText;
35 }
36 return fallback || '';
37 } catch (e) {
38 if (codeMappings[code]) {
39 try {
40 const text = IntlDN(codeMappings[locale] || locale || i18n.locale).of(
41 codeMappings[code],
42 );
43 if (text !== codeMappings[code]) return text;
44 return fallback || '';
45 } catch (e2) {
46 console.warn(code, e2);
47 }
48 }
49 return fallback || '';
50 }
51}
52
53export default mem(_localeCode2Text);