30 lines
1.1 KiB
TypeScript
30 lines
1.1 KiB
TypeScript
import { createContext, useMemo } from 'react';
|
|
import type { ReactNode } from 'react';
|
|
import type { I18nContextValue, InterpolationParams, TranslationMap } from './types';
|
|
import { interpolate, resolveKey } from './resolve';
|
|
|
|
export const I18nContext = createContext<I18nContextValue>({
|
|
t: (key: string) => key,
|
|
locale: 'en',
|
|
});
|
|
|
|
type I18nProviderProps = {
|
|
translations: TranslationMap;
|
|
locale: string;
|
|
/** The catalog `resolveKey` falls back to on a miss — a bug path, per D8, not a regional chain. */
|
|
fallbackLocale?: string;
|
|
children: ReactNode;
|
|
};
|
|
|
|
export const I18nProvider = ({ translations, locale, fallbackLocale = 'en', children }: I18nProviderProps) => {
|
|
const value = useMemo<I18nContextValue>(() => {
|
|
const t = (key: string, params?: InterpolationParams) => {
|
|
const count = typeof params?.count === 'number' ? params.count : undefined;
|
|
return interpolate(resolveKey(translations, locale, key, fallbackLocale, count), params);
|
|
};
|
|
return { t, locale };
|
|
}, [translations, locale, fallbackLocale]);
|
|
|
|
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
|
|
};
|