2019-08-09 10:26:22 +00:00
|
|
|
import React from "react";
|
2019-08-13 11:26:34 +00:00
|
|
|
import { IntlProvider } from "react-intl";
|
2019-06-19 14:40:52 +00:00
|
|
|
|
2019-08-13 11:26:34 +00:00
|
|
|
export type LocaleContextType = string;
|
|
|
|
export const LocaleContext = React.createContext<LocaleContextType>("en");
|
2019-06-19 14:40:52 +00:00
|
|
|
|
2019-08-16 13:55:04 +00:00
|
|
|
const { Consumer: LocaleConsumer, Provider: RawLocaleProvider } = LocaleContext;
|
2019-06-19 14:40:52 +00:00
|
|
|
|
2019-08-27 12:05:53 +00:00
|
|
|
enum Locale {
|
|
|
|
EN = "en",
|
|
|
|
EN_GB = "en-gb",
|
|
|
|
EN_US = "en-us"
|
|
|
|
}
|
|
|
|
|
|
|
|
type LocaleMessages = Record<string, string>;
|
|
|
|
const localeData: Record<Locale, LocaleMessages> = {
|
|
|
|
[Locale.EN]: {},
|
|
|
|
[Locale.EN_GB]: {},
|
|
|
|
[Locale.EN_US]: {}
|
|
|
|
};
|
|
|
|
|
|
|
|
function getMatchingLocale(): Locale {
|
|
|
|
const localeEntries = Object.entries(Locale);
|
|
|
|
|
|
|
|
for (const preferredLocale of navigator.languages) {
|
|
|
|
for (const localeEntry of localeEntries) {
|
|
|
|
if (localeEntry[1].toLowerCase() === preferredLocale.toLowerCase()) {
|
|
|
|
return Locale[localeEntry[0]];
|
2019-08-14 16:21:41 +00:00
|
|
|
}
|
|
|
|
}
|
2019-08-27 12:05:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const LocaleProvider: React.FC = ({ children }) => {
|
|
|
|
const [locale] = React.useState(getMatchingLocale());
|
2019-08-13 11:26:34 +00:00
|
|
|
|
|
|
|
return (
|
2019-08-27 12:05:53 +00:00
|
|
|
<IntlProvider locale={locale} messages={localeData[locale]} key={locale}>
|
2019-08-16 13:55:04 +00:00
|
|
|
<RawLocaleProvider value={locale}>{children}</RawLocaleProvider>
|
2019-08-13 11:26:34 +00:00
|
|
|
</IntlProvider>
|
|
|
|
);
|
2019-06-19 14:40:52 +00:00
|
|
|
};
|
|
|
|
|
2019-08-16 13:55:04 +00:00
|
|
|
export { LocaleConsumer, LocaleProvider, RawLocaleProvider };
|