2019-08-14 16:21:41 +00:00
|
|
|
import { LOCALE_URI } from "@saleor/config";
|
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-08-14 16:21:41 +00:00
|
|
|
import urlJoin from "url-join";
|
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
|
|
|
|
|
|
|
const { Consumer: LocaleConsumer, Provider } = LocaleContext;
|
|
|
|
|
|
|
|
const LocaleProvider = ({ children }) => {
|
2019-08-14 16:21:41 +00:00
|
|
|
const [localeIndex, setLocaleIndex] = React.useState(0);
|
|
|
|
const [messages, setMessages] = React.useState({});
|
|
|
|
|
|
|
|
const locale = navigator.languages[localeIndex];
|
|
|
|
|
|
|
|
React.useEffect(() => {
|
|
|
|
async function fetchLocale() {
|
|
|
|
if (locale) {
|
|
|
|
const res = await fetch(urlJoin(LOCALE_URI, `${locale}.json`), {
|
|
|
|
credentials: "same-origin",
|
|
|
|
mode: "cors"
|
|
|
|
});
|
|
|
|
if (res.ok) {
|
|
|
|
const localeData = await res.json();
|
|
|
|
setMessages(localeData);
|
|
|
|
} else {
|
|
|
|
setLocaleIndex(localeIndex + 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fetchLocale();
|
|
|
|
}, [localeIndex]);
|
2019-08-13 11:26:34 +00:00
|
|
|
|
|
|
|
return (
|
2019-08-14 16:21:41 +00:00
|
|
|
<IntlProvider locale={locale} messages={messages} key={locale}>
|
|
|
|
<Provider value={locale}>{children}</Provider>
|
2019-08-13 11:26:34 +00:00
|
|
|
</IntlProvider>
|
|
|
|
);
|
2019-06-19 14:40:52 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export { LocaleConsumer, LocaleProvider };
|