react-intlayer
Version:
Easily internationalize i18n your React applications with type-safe multilingual content management.
58 lines (56 loc) • 1.77 kB
JavaScript
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
let react = require("react");
react = require_rolldown_runtime.__toESM(react);
//#region src/server/serverContext.tsx
/**
* Creates a new datastore for a given server context.
* Attempts to closely mimic the `createContext` API.
*
* @example
* const IntlayerServer = createServerContext<string | null>(null);
*
* <IntlayerServer value={locale}>
* {children}
* </IntlayerServer>
*/
const cacheFallback = () => () => ({ value: void 0 });
const createServerContext = (defaultValue) => {
throwInClient();
const getCache = (react.default.cache ?? cacheFallback)(() => ({ value: void 0 }));
const Provider = ({ children, value }) => {
getCache().value = value;
return children;
};
const ServerContext = Provider;
ServerContext.Provider = Provider;
ServerContext.Consumer = (props) => {
const store = getCache();
return props.children(store ? store.value : defaultValue);
};
ServerContext._storage = getCache;
ServerContext._defaultValue = defaultValue;
return ServerContext;
};
/**
* Fetches a value present in a given server context.
* Attempts to closely mimic the `useContext` API.
*
* @example
* getServerContext(IntlayerServer);
*/
const getServerContext = ({ _storage, _defaultValue }) => {
const store = _storage();
if (!store) return _defaultValue;
return store.value;
};
/**
* Throws if called within a client component environment.
* Useful to help prevent mistakes.
*/
const throwInClient = () => {
if (typeof window !== "undefined") throw new Error(`createServerContext only works in Server Components`);
};
//#endregion
exports.createServerContext = createServerContext;
exports.getServerContext = getServerContext;
//# sourceMappingURL=serverContext.cjs.map