|
| 1 | +import { |
| 2 | + createContext, |
| 3 | + use, |
| 4 | + useContext, |
| 5 | + useMemo, |
| 6 | + type ReactNode, |
| 7 | +} from 'react'; |
| 8 | + |
| 9 | +interface LingoCompilerContextValue { |
| 10 | + locale: string; |
| 11 | + translations: Record<string, any>; |
| 12 | +} |
| 13 | + |
| 14 | +const LingoCompilerContext = createContext<LingoCompilerContextValue | null>(null); |
| 15 | + |
| 16 | +interface LingoCompilerProps { |
| 17 | + locale: string; |
| 18 | + children: ReactNode; |
| 19 | +} |
| 20 | + |
| 21 | +// Cache to prevent duplicate fetches |
| 22 | +const translationCache = new Map<string, Promise<Record<string, any>>>(); |
| 23 | + |
| 24 | +function fetchTranslations(locale: string): Promise<Record<string, any>> { |
| 25 | + if (translationCache.has(locale)) { |
| 26 | + return translationCache.get(locale)!; |
| 27 | + } |
| 28 | + |
| 29 | + const isDev = process.env.NODE_ENV === 'development'; |
| 30 | + const url = isDev |
| 31 | + ? `http://localhost:3001/i18n?locale=${locale}` |
| 32 | + : `/i18n/${locale}.json`; |
| 33 | + |
| 34 | + const promise = fetch(url).then((res) => { |
| 35 | + if (!res.ok) { |
| 36 | + throw new Error(`Failed to fetch translations for locale: ${locale}`); |
| 37 | + } |
| 38 | + return res.json(); |
| 39 | + }); |
| 40 | + |
| 41 | + translationCache.set(locale, promise); |
| 42 | + return promise; |
| 43 | +} |
| 44 | + |
| 45 | +export function LingoCompiler({ locale, children }: LingoCompilerProps) { |
| 46 | + const i18nPromise = useMemo(() => fetchTranslations(locale), [locale]); |
| 47 | + const translations = use(i18nPromise); |
| 48 | + |
| 49 | + return ( |
| 50 | + <LingoCompilerContext.Provider value={{ locale, translations }}> |
| 51 | + {children} |
| 52 | + </LingoCompilerContext.Provider> |
| 53 | + ); |
| 54 | +} |
| 55 | + |
| 56 | +export function useLingoCompiler() { |
| 57 | + const context = useContext(LingoCompilerContext); |
| 58 | + if (!context) { |
| 59 | + throw new Error('useLingoCompiler must be used within LingoCompiler'); |
| 60 | + } |
| 61 | + return context; |
| 62 | +} |
0 commit comments