react-intlayer
Version:
Easily internationalize i18n your React applications with type-safe multilingual content management.
60 lines (57 loc) • 2.51 kB
JavaScript
'use client';
import { IntlayerEditorProvider } from "../editor/IntlayerEditorProvider.mjs";
import { localeInStorage, setLocaleInStorage as setLocaleInStorage$1 } from "./useLocaleStorage.mjs";
import { createContext, useContext, useEffect } from "react";
import { jsx } from "react/jsx-runtime";
import { localeResolver } from "@intlayer/core";
import { MessageKey, useCrossFrameState } from "@intlayer/editor-react";
import configuration from "@intlayer/config/built";
//#region src/client/IntlayerProvider.tsx
/**
* Context that store the current locale on the client side
*/
const IntlayerClientContext = createContext({
locale: localeInStorage ?? configuration?.internationalization?.defaultLocale,
setLocale: () => null,
isCookieEnabled: true,
disableEditor: false
});
/**
* Hook that provides the current locale
*/
const useIntlayerContext = () => useContext(IntlayerClientContext);
/**
* Provider that store the current locale on the client side
*/
const IntlayerProviderContent = ({ locale: localeProp, defaultLocale: defaultLocaleProp, children, setLocale: setLocaleProp, disableEditor, isCookieEnabled }) => {
const { internationalization } = configuration ?? {};
const { locales: availableLocales, defaultLocale: defaultLocaleConfig } = internationalization ?? {};
const initialLocale = localeProp ?? localeInStorage ?? defaultLocaleProp ?? defaultLocaleConfig;
const [currentLocale, setCurrentLocale] = useCrossFrameState(MessageKey.INTLAYER_CURRENT_LOCALE, initialLocale);
useEffect(() => {
if (localeProp && localeProp !== currentLocale) setCurrentLocale(localeProp);
}, [localeProp]);
const setLocaleBase = (newLocale) => {
if (currentLocale.toString() === newLocale.toString()) return;
if (!availableLocales?.map(String).includes(newLocale)) {
console.error(`Locale ${newLocale} is not available`);
return;
}
setCurrentLocale(newLocale);
setLocaleInStorage$1(newLocale, isCookieEnabled);
};
const setLocale = setLocaleProp ?? setLocaleBase;
const resolvedLocale = localeResolver(currentLocale);
return /* @__PURE__ */ jsx(IntlayerClientContext.Provider, {
value: {
locale: resolvedLocale,
setLocale,
disableEditor
},
children
});
};
const IntlayerProvider = (props) => /* @__PURE__ */ jsx(IntlayerEditorProvider, { children: /* @__PURE__ */ jsx(IntlayerProviderContent, { ...props }) });
//#endregion
export { IntlayerClientContext, IntlayerProvider, IntlayerProviderContent, useIntlayerContext };
//# sourceMappingURL=IntlayerProvider.mjs.map