react-intlayer
Version:
Easily internationalize i18n your React applications with type-safe multilingual content management.
57 lines (54 loc) • 2.4 kB
JavaScript
'use client';
import { IntlayerEditorProvider } from "../editor/IntlayerEditorProvider.mjs";
import { localeInStorage, setLocaleInStorage as setLocaleInStorage$1 } from "./useLocaleStorage.mjs";
import { createContext, useContext } 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 { defaultLocale: defaultLocaleConfig, locales: availableLocales } = internationalization ?? {};
const defaultLocale = localeProp ?? localeInStorage ?? defaultLocaleProp ?? defaultLocaleConfig;
const [currentLocale, setCurrentLocale] = useCrossFrameState(MessageKey.INTLAYER_CURRENT_LOCALE, defaultLocale);
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(localeProp ?? 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