76 lines
1.8 KiB
TypeScript
76 lines
1.8 KiB
TypeScript
import { useIntl } from '@umijs/max';
|
|
|
|
/**
|
|
* Custom hook for easier internationalization usage
|
|
* Provides a simplified API for common i18n operations
|
|
*/
|
|
export const useTranslation = () => {
|
|
const intl = useIntl();
|
|
|
|
/**
|
|
* Simple translation function
|
|
* @param id - Translation key
|
|
* @param values - Values to interpolate into the translation
|
|
* @returns Translated string
|
|
*/
|
|
const t = (id: string, values?: Record<string, any>): string => {
|
|
return intl.formatMessage({ id }, values);
|
|
};
|
|
|
|
/**
|
|
* Check if current locale is the specified one
|
|
* @param locale - Locale code (e.g., 'vi-VN', 'en-US')
|
|
* @returns boolean
|
|
*/
|
|
const isLocale = (locale: string): boolean => {
|
|
return intl.locale === locale;
|
|
};
|
|
|
|
/**
|
|
* Get current locale code
|
|
* @returns Current locale string
|
|
*/
|
|
const getCurrentLocale = (): string => {
|
|
return intl.locale;
|
|
};
|
|
|
|
/**
|
|
* Format date with locale consideration
|
|
* @param date - Date to format
|
|
* @param options - Intl.DateTimeFormatOptions
|
|
* @returns Formatted date string
|
|
*/
|
|
const formatDate = (
|
|
date: Date | number,
|
|
options?: Intl.DateTimeFormatOptions
|
|
): string => {
|
|
return new Intl.DateTimeFormat(intl.locale, options).format(
|
|
typeof date === 'number' ? new Date(date) : date
|
|
);
|
|
};
|
|
|
|
/**
|
|
* Format number with locale consideration
|
|
* @param number - Number to format
|
|
* @param options - Intl.NumberFormatOptions
|
|
* @returns Formatted number string
|
|
*/
|
|
const formatNumber = (
|
|
number: number,
|
|
options?: Intl.NumberFormatOptions
|
|
): string => {
|
|
return new Intl.NumberFormat(intl.locale, options).format(number);
|
|
};
|
|
|
|
return {
|
|
t,
|
|
isLocale,
|
|
getCurrentLocale,
|
|
formatDate,
|
|
formatNumber,
|
|
// Expose original intl object for advanced usage
|
|
intl,
|
|
};
|
|
};
|
|
|
|
export default useTranslation; |