2023-05-06 15:49:37 +08:00
|
|
|
import * as React from 'react';
|
2024-04-08 14:04:08 +08:00
|
|
|
|
2023-02-22 18:18:26 +08:00
|
|
|
import type { Locale } from '.';
|
|
|
|
import type { LocaleContextProps } from './context';
|
|
|
|
import LocaleContext from './context';
|
|
|
|
import defaultLocaleData from './en_US';
|
|
|
|
|
|
|
|
export type LocaleComponentName = Exclude<keyof Locale, 'locale'>;
|
|
|
|
|
|
|
|
const useLocale = <C extends LocaleComponentName = LocaleComponentName>(
|
|
|
|
componentName: C,
|
|
|
|
defaultLocale?: Locale[C] | (() => Locale[C]),
|
2023-02-24 10:51:59 +08:00
|
|
|
): readonly [NonNullable<Locale[C]>, string] => {
|
|
|
|
const fullLocale = React.useContext<LocaleContextProps | undefined>(LocaleContext);
|
|
|
|
|
|
|
|
const getLocale = React.useMemo<NonNullable<Locale[C]>>(() => {
|
2023-02-22 18:18:26 +08:00
|
|
|
const locale = defaultLocale || defaultLocaleData[componentName];
|
2023-02-24 10:51:59 +08:00
|
|
|
const localeFromContext = fullLocale?.[componentName] ?? {};
|
2023-02-22 18:18:26 +08:00
|
|
|
return {
|
|
|
|
...(typeof locale === 'function' ? locale() : locale),
|
|
|
|
...(localeFromContext || {}),
|
|
|
|
};
|
2023-02-24 10:51:59 +08:00
|
|
|
}, [componentName, defaultLocale, fullLocale]);
|
|
|
|
|
|
|
|
const getLocaleCode = React.useMemo<string>(() => {
|
|
|
|
const localeCode = fullLocale?.locale;
|
|
|
|
// Had use LocaleProvide but didn't set locale
|
|
|
|
if (fullLocale?.exist && !localeCode) {
|
|
|
|
return defaultLocaleData.locale;
|
|
|
|
}
|
|
|
|
return localeCode!;
|
|
|
|
}, [fullLocale]);
|
|
|
|
|
|
|
|
return [getLocale, getLocaleCode] as const;
|
2023-02-22 18:18:26 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
export default useLocale;
|