22 lines
659 B
TypeScript
22 lines
659 B
TypeScript
import React from 'react';
|
|
import { translate, DEFAULT_LOCALE, type LocaleCode } from './messages';
|
|
import { useLocale } from './LocaleContext';
|
|
|
|
export type TranslateFn = (key: string, fallback?: string) => string;
|
|
|
|
function resolveTranslation(locale: LocaleCode, key: string, fallback?: string): string {
|
|
return translate(locale, key) ?? translate(DEFAULT_LOCALE, key) ?? fallback ?? key;
|
|
}
|
|
|
|
export function useTranslation() {
|
|
const { locale } = useLocale();
|
|
|
|
const t = React.useCallback<TranslateFn>(
|
|
(key, fallback) => resolveTranslation(locale, key, fallback),
|
|
[locale],
|
|
);
|
|
|
|
return React.useMemo(() => ({ t, locale }), [t, locale]);
|
|
}
|
|
|