2021-02-04 19:15:23 +01:00
|
|
|
import React, { Component, createContext, useMemo } from 'react';
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
import { useSelector } from 'react-redux';
|
2020-11-03 00:41:28 +01:00
|
|
|
import {
|
2022-12-21 18:31:06 +01:00
|
|
|
getCurrentLocale,
|
2020-11-03 00:41:28 +01:00
|
|
|
getCurrentLocaleMessages,
|
|
|
|
getEnLocaleMessages,
|
2021-02-04 19:15:23 +01:00
|
|
|
} from '../ducks/locale/locale';
|
2023-06-20 14:44:11 +02:00
|
|
|
import { getMessage } from '../helpers/utils/i18n-helper';
|
2020-03-23 18:07:05 +01:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
export const I18nContext = createContext((key) => `[${key}]`);
|
2020-03-23 18:07:05 +01:00
|
|
|
|
|
|
|
export const I18nProvider = (props) => {
|
2021-02-04 19:15:23 +01:00
|
|
|
const currentLocale = useSelector(getCurrentLocale);
|
|
|
|
const current = useSelector(getCurrentLocaleMessages);
|
|
|
|
const en = useSelector(getEnLocaleMessages);
|
2020-03-23 18:07:05 +01:00
|
|
|
|
|
|
|
const t = useMemo(() => {
|
2020-11-03 00:41:28 +01:00
|
|
|
return (key, ...args) =>
|
2020-03-23 18:07:05 +01:00
|
|
|
getMessage(currentLocale, current, key, ...args) ||
|
2021-02-04 19:15:23 +01:00
|
|
|
getMessage(currentLocale, en, key, ...args);
|
|
|
|
}, [currentLocale, current, en]);
|
2020-03-23 18:07:05 +01:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
return (
|
|
|
|
<I18nContext.Provider value={t}>{props.children}</I18nContext.Provider>
|
|
|
|
);
|
|
|
|
};
|
2020-03-23 18:07:05 +01:00
|
|
|
|
|
|
|
I18nProvider.propTypes = {
|
|
|
|
children: PropTypes.node,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-03-23 18:07:05 +01:00
|
|
|
|
|
|
|
I18nProvider.defaultProps = {
|
|
|
|
children: undefined,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-03-23 18:07:05 +01:00
|
|
|
|
|
|
|
export class LegacyI18nProvider extends Component {
|
|
|
|
static propTypes = {
|
|
|
|
children: PropTypes.node,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-03-23 18:07:05 +01:00
|
|
|
|
|
|
|
static defaultProps = {
|
|
|
|
children: undefined,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-03-23 18:07:05 +01:00
|
|
|
|
2021-02-04 19:15:23 +01:00
|
|
|
static contextType = I18nContext;
|
2020-03-23 18:07:05 +01:00
|
|
|
|
|
|
|
static childContextTypes = {
|
|
|
|
t: PropTypes.func,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-03-23 18:07:05 +01:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
getChildContext() {
|
2020-03-23 18:07:05 +01:00
|
|
|
return {
|
|
|
|
t: this.context,
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2020-03-23 18:07:05 +01:00
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
render() {
|
2021-02-04 19:15:23 +01:00
|
|
|
return this.props.children;
|
2020-03-23 18:07:05 +01:00
|
|
|
}
|
|
|
|
}
|