phanpy/src/utils/lang.js

73 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-08-13 15:26:23 +08:00
import { i18n } from '@lingui/core';
import {
detect,
fromNavigator,
fromStorage,
fromUrl,
} from '@lingui/detect-locale';
import Locale from 'intl-locale-textinfo-polyfill';
import { DEFAULT_LANG, LOCALES } from '../locales';
2024-08-13 15:26:23 +08:00
import { messages } from '../locales/en.po';
import localeMatch from '../utils/locale-match';
const { PHANPY_DEFAULT_LANG } = import.meta.env;
2024-08-20 20:00:33 +08:00
const langFileMaps = {
2024-08-20 20:18:16 +08:00
// kab: 'kab-KAB',
2024-08-20 20:00:33 +08:00
};
i18n.load(DEFAULT_LANG, messages);
2024-08-13 15:26:23 +08:00
i18n.on('change', () => {
const lang = i18n.locale;
if (lang) {
2024-08-15 15:33:15 +08:00
// lang
document.documentElement.lang = lang;
2024-08-13 15:26:23 +08:00
// LTR or RTL
2024-08-20 19:58:50 +08:00
try {
const { direction } = new Locale(lang).textInfo;
document.documentElement.dir = direction;
} catch (e) {
console.error(e);
}
2024-08-13 15:26:23 +08:00
}
});
export async function activateLang(lang) {
if (!lang || lang === DEFAULT_LANG) {
i18n.activate(DEFAULT_LANG);
console.log('💬 ACTIVATE LANG', DEFAULT_LANG, lang);
} else {
try {
2024-08-20 20:00:33 +08:00
const { messages } = await import(
`../locales/${langFileMaps[lang] || lang}.po`
);
i18n.loadAndActivate({ locale: lang, messages });
console.log('💬 ACTIVATE LANG', lang, messages);
} catch (e) {
2024-08-20 20:00:33 +08:00
console.error(e);
// Fallback to default language
i18n.activate(DEFAULT_LANG);
console.log('💬 ACTIVATE LANG', DEFAULT_LANG, lang);
}
}
}
2024-08-13 15:26:23 +08:00
export function initActivateLang() {
const lang = detect(
fromUrl('lang'),
fromStorage('lang'),
fromNavigator(),
PHANPY_DEFAULT_LANG,
2024-08-13 15:26:23 +08:00
DEFAULT_LANG,
);
2024-08-20 20:00:33 +08:00
const matchedLang =
LOCALES.find((l) => l === lang) || localeMatch(lang, LOCALES);
2024-08-13 15:26:23 +08:00
activateLang(matchedLang);
// const yes = confirm(t`Reload to apply language setting?`);
// if (yes) {
// window.location.reload();
// }
}