Files
blitzkit/packages/website/src/hooks/useLocale.tsx
T

39 lines
1010 B
TypeScript
Raw Normal View History

2025-01-14 19:22:41 -06:00
import { DEFAULT_LOCALE, unwrapper } from '@blitzkit/i18n';
2024-12-27 14:01:59 -06:00
import { createContext, useContext, type ReactNode } from 'react';
2025-01-06 20:09:11 -06:00
import { getStrings } from '../core/i18n/getStrings';
2024-12-27 14:01:59 -06:00
2025-01-06 20:09:11 -06:00
const LocaleContext = createContext<{
locale: string;
localeRaw: string | undefined;
} | null>(null);
2024-12-27 14:01:59 -06:00
2025-01-06 20:31:21 -06:00
interface LocaleProviderProps extends LocaleAcceptorProps {
2024-12-27 14:01:59 -06:00
children: ReactNode;
}
export function LocaleProvider({ locale, children }: LocaleProviderProps) {
return (
2025-01-06 20:09:11 -06:00
<LocaleContext.Provider
value={{ locale: locale ?? DEFAULT_LOCALE, localeRaw: locale }}
>
2024-12-27 14:01:59 -06:00
{children}
</LocaleContext.Provider>
);
}
export function useLocale() {
const context = useContext(LocaleContext);
if (!context) {
throw new Error('useLocale must be used within a LocaleProvider');
}
2025-01-06 20:09:11 -06:00
const strings = getStrings(context.locale);
2025-01-14 19:22:41 -06:00
const unwrap = unwrapper(context.locale);
2025-01-06 20:09:11 -06:00
2025-01-14 19:22:41 -06:00
return { locale: context.locale, strings, unwrap };
2024-12-27 14:01:59 -06:00
}
2025-01-06 20:31:21 -06:00
export interface LocaleAcceptorProps {
locale: string | undefined;
}