phanpy/src/utils/localeCode2Text.jsx

43 lines
966 B
React
Raw Normal View History

2024-08-13 09:26:23 +02:00
import { i18n } from '@lingui/core';
import mem from './mem';
2024-08-13 09:26:23 +02:00
// Some codes are not supported by Intl.DisplayNames
// These are mapped to other codes as fallback
const codeMappings = {
'zh-YUE': 'YUE',
zh_HANT: 'zh-Hant',
};
const IntlDN = mem(
(locale) =>
new Intl.DisplayNames(locale || undefined, {
type: 'language',
}),
);
function _localeCode2Text(code) {
2024-08-13 09:26:23 +02:00
let locale;
let fallback;
if (typeof code === 'object') {
({ code, locale, fallback } = code);
}
try {
2024-08-13 09:26:23 +02:00
const text = IntlDN(locale || i18n.locale).of(code);
if (text !== code) return text;
return fallback || '';
} catch (e) {
2024-08-13 09:26:23 +02:00
if (codeMappings[code]) {
try {
const text = IntlDN(locale || i18n.locale).of(codeMappings[code]);
if (text !== codeMappings[code]) return text;
return fallback || '';
} catch (e) {}
}
console.warn(code, e);
return fallback || '';
}
}
export default mem(_localeCode2Text);