2021-06-30 03:41:34 +02:00
|
|
|
import { useEffect } from 'react';
|
|
|
|
import { useRouter } from 'next/router';
|
2023-06-03 08:10:59 +02:00
|
|
|
import { httpGet, setItem } from 'next-basics';
|
2020-09-19 19:35:05 +02:00
|
|
|
import { LOCALE_CONFIG } from 'lib/constants';
|
2021-11-21 02:18:25 +01:00
|
|
|
import { getDateLocale, getTextDirection } from 'lib/lang';
|
2022-02-23 07:47:59 +01:00
|
|
|
import useStore, { setLocale } from 'store/app';
|
2021-06-30 03:41:34 +02:00
|
|
|
import useForceUpdate from 'hooks/useForceUpdate';
|
2022-03-19 03:17:23 +01:00
|
|
|
import enUS from 'public/intl/messages/en-US.json';
|
2021-06-30 03:41:34 +02:00
|
|
|
|
|
|
|
const messages = {
|
|
|
|
'en-US': enUS,
|
|
|
|
};
|
2020-09-09 05:46:31 +02:00
|
|
|
|
2022-02-23 07:47:59 +01:00
|
|
|
const selector = state => state.locale;
|
|
|
|
|
2023-05-18 08:20:06 +02:00
|
|
|
export function useLocale() {
|
2022-02-23 07:47:59 +01:00
|
|
|
const locale = useStore(selector);
|
2021-06-30 03:41:34 +02:00
|
|
|
const { basePath } = useRouter();
|
|
|
|
const forceUpdate = useForceUpdate();
|
2021-11-21 02:18:25 +01:00
|
|
|
const dir = getTextDirection(locale);
|
|
|
|
const dateLocale = getDateLocale(locale);
|
2021-06-30 03:41:34 +02:00
|
|
|
|
|
|
|
async function loadMessages(locale) {
|
2023-06-03 08:10:59 +02:00
|
|
|
const { ok, data } = await httpGet(`${basePath}/intl/messages/${locale}.json`);
|
2021-06-30 03:41:34 +02:00
|
|
|
|
2023-01-11 23:47:38 +01:00
|
|
|
if (ok) {
|
2021-06-30 03:41:34 +02:00
|
|
|
messages[locale] = data;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function saveLocale(value) {
|
|
|
|
if (!messages[value]) {
|
|
|
|
await loadMessages(value);
|
|
|
|
}
|
2020-09-09 05:46:31 +02:00
|
|
|
|
2020-09-19 19:35:05 +02:00
|
|
|
setItem(LOCALE_CONFIG, value);
|
2021-06-30 03:41:34 +02:00
|
|
|
|
2023-01-19 00:05:39 +01:00
|
|
|
document.getElementById('__next')?.setAttribute('dir', getTextDirection(value));
|
|
|
|
|
2021-06-30 03:41:34 +02:00
|
|
|
if (locale !== value) {
|
2022-02-23 07:47:59 +01:00
|
|
|
setLocale(value);
|
2021-06-30 03:41:34 +02:00
|
|
|
} else {
|
|
|
|
forceUpdate();
|
|
|
|
}
|
2020-09-09 05:46:31 +02:00
|
|
|
}
|
|
|
|
|
2021-06-30 03:41:34 +02:00
|
|
|
useEffect(() => {
|
|
|
|
if (!messages[locale]) {
|
|
|
|
saveLocale(locale);
|
|
|
|
}
|
|
|
|
}, [locale]);
|
|
|
|
|
2022-08-21 13:30:40 +02:00
|
|
|
useEffect(() => {
|
2023-02-15 11:27:18 +01:00
|
|
|
const url = new URL(window?.location?.href);
|
2022-08-21 13:30:40 +02:00
|
|
|
const locale = url.searchParams.get('locale');
|
|
|
|
|
|
|
|
if (locale) {
|
|
|
|
saveLocale(locale);
|
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
2021-11-21 02:18:25 +01:00
|
|
|
return { locale, saveLocale, messages, dir, dateLocale };
|
2020-09-09 05:46:31 +02:00
|
|
|
}
|
2023-05-18 08:20:06 +02:00
|
|
|
|
|
|
|
export default useLocale;
|