import * as React from 'react'; import type { Locale } from '.'; import type { LocaleContextProps } from './context'; import LocaleContext from './context'; import defaultLocaleData from '../locale/en_US'; export type LocaleComponentName = Exclude; export interface LocaleReceiverProps { componentName?: C; defaultLocale?: Locale[C] | (() => Locale[C]); children: ( locale: NonNullable, localeCode: string, fullLocale: Locale, ) => React.ReactElement; } const LocaleReceiver = ( props: LocaleReceiverProps, ) => { const { componentName = 'global' as C, defaultLocale, children } = props; const antLocale = React.useContext(LocaleContext); const getLocale = React.useMemo>(() => { const locale = defaultLocale || defaultLocaleData[componentName]; const localeFromContext = antLocale?.[componentName] ?? {}; return { ...(locale instanceof Function ? locale() : locale), ...(localeFromContext || {}), }; }, [componentName, defaultLocale, antLocale]); const getLocaleCode = React.useMemo(() => { const localeCode = antLocale && antLocale.locale; // Had use LocaleProvide but didn't set locale if (antLocale && antLocale.exist && !localeCode) { return defaultLocaleData.locale; } return localeCode!; }, [antLocale]); return children(getLocale, getLocaleCode, antLocale!); }; export default LocaleReceiver; export const useLocaleReceiver = ( componentName: C, defaultLocale?: Locale[C] | (() => Locale[C]), ): [Locale[C]] => { const antLocale = React.useContext(LocaleContext); const getLocale = React.useMemo>(() => { const locale = defaultLocale || defaultLocaleData[componentName]; const localeFromContext = antLocale?.[componentName] ?? {}; return { ...(typeof locale === 'function' ? locale() : locale), ...(localeFromContext || {}), }; }, [componentName, defaultLocale, antLocale]); return [getLocale]; };