You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

72 lines
2.1 KiB

import * as React from 'react';
import defaultLocaleData from './default';
import LocaleContext from './context';
import { Locale } from '.';
export interface LocaleReceiverProps {
componentName?: string;
defaultLocale?: object | Function;
children: (locale: object, localeCode?: string, fullLocale?: object) => React.ReactNode;
}
interface LocaleInterface {
[key: string]: any;
}
export interface LocaleReceiverContext {
antLocale?: LocaleInterface;
}
export default class LocaleReceiver extends React.Component<LocaleReceiverProps> {
static defaultProps = {
componentName: 'global',
};
static contextType = LocaleContext;
getLocale() {
const { componentName, defaultLocale } = this.props;
const locale: object | Function =
defaultLocale || (defaultLocaleData as LocaleInterface)[componentName || 'global'];
const antLocale = this.context;
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(typeof locale === 'function' ? locale() : locale),
...(localeFromContext || {}),
};
}
getLocaleCode() {
const antLocale = this.context;
const localeCode = antLocale && antLocale.locale;
// Had use LocaleProvide but didn't set locale
if (antLocale && antLocale.exist && !localeCode) {
return defaultLocaleData.locale;
}
return localeCode;
}
render() {
return this.props.children(this.getLocale(), this.getLocaleCode(), this.context);
}
}
type LocaleComponent = keyof Locale;
export function useLocaleReceiver<T extends LocaleComponent>(
componentName: T,
defaultLocale?: Locale[T] | Function,
): [Locale[T]] {
const antLocale = React.useContext(LocaleContext);
const componentLocale = React.useMemo(() => {
const locale = defaultLocale || defaultLocaleData[componentName || 'global'];
const localeFromContext = componentName && antLocale ? antLocale[componentName] : {};
return {
...(typeof locale === 'function' ? (locale as Function)() : locale),
...(localeFromContext || {}),
};
}, [componentName, defaultLocale, antLocale]);
return [componentLocale];
}