import { internationalization } from '@intlayer/config/built'; import { registerAmbientLocaleResolver } from '@intlayer/core/interpreter'; import type { LocalesValues, ProviderVariant, } from '@intlayer/types/module_augmentation'; import type { FC, PropsWithChildren } from 'react'; import { createServerContext, getServerContext } from './serverContext'; const { defaultLocale } = internationalization ?? {}; /** * Context that store the current locale on the server side */ export const IntlayerServerContext = createServerContext(defaultLocale); // Lets a bare `getIntlayer` / `getDictionary` rendered on the server resolve to // the locale seeded by `IntlayerServerProvider` / `setLocale`. Read from the // store rather than `getServerContext`, whose default locale would shadow the // other resolvers. registerAmbientLocaleResolver(() => IntlayerServerContext._storage()?.value); /** * Context that stores the ambient variant on the server side. * * Kept separate from {@link IntlayerServerContext} so the locale context keeps * its plain `LocalesValues` shape for the packages already reading it. */ export const IntlayerServerVariantContext = createServerContext(undefined); /** * Hook that provides the current locale */ export const useIntlayer = () => getServerContext(IntlayerServerContext); /** * Get the current locale */ export const locale = getServerContext(IntlayerServerContext); /** * Seeds the request-scoped server context locale imperatively — the equivalent * of mounting {@link IntlayerServerProvider} without wrapping the tree. * * Useful in pages that must stay statically rendered while no ambient * request-derived locale source is static-safe (Next.js < 16): * * ```tsx * const Page = async ({ params }) => { * const { locale } = await params; * setLocale(locale); * return ; * }; * ``` */ export const setLocale = (locale: LocalesValues): void => { IntlayerServerContext._storage().value = locale; }; /** * Seeds the request-scoped ambient variant imperatively — the equivalent of * the `variant` prop of {@link IntlayerServerProvider} without wrapping the * tree. See that prop for the accepted shapes. */ export const setVariant = (variant: ProviderVariant): void => { IntlayerServerVariantContext._storage().value = variant; }; export type IntlayerServerProviderProps = PropsWithChildren & { locale?: LocalesValues; /** * Ambient variant applied to every dictionary read below this provider — for * a dimension resolved once per request (tenant, school type, plan tier…). * * Accepts a name (`'school1'`), an ordered preference chain * (`['school1', 'default']`), or a per-key map * (`{ key1: 'school1', default: 'base' }`). A call-site selector wins. */ variant?: ProviderVariant; }; /** * Provider that store the current locale on the server side */ export const IntlayerServerProvider: FC = ({ children, locale = defaultLocale, variant, }) => ( {children} );