Replaced localStorage-only hook with React Context Provider. Layout and page components now share the same state — switching language in the dropdown instantly updates all text on screen without requiring a page reload. NativeLanguageProvider added to root layout.tsx. useNativeLanguage() re-exported from Context for backward compat. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
62 lines
1.8 KiB
TypeScript
62 lines
1.8 KiB
TypeScript
'use client'
|
|
|
|
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
|
import { exerciseT, type ExerciseKey } from './exerciseTranslations'
|
|
|
|
const STORAGE_KEY = 'bp_native_language'
|
|
|
|
interface NativeLanguageState {
|
|
nativeLang: string
|
|
setNativeLang: (lang: string) => void
|
|
isThirdLanguage: boolean
|
|
t: (key: ExerciseKey) => string
|
|
wordInNative: (translations?: Record<string, any>) => string
|
|
}
|
|
|
|
const NativeLanguageContext = createContext<NativeLanguageState>({
|
|
nativeLang: 'de',
|
|
setNativeLang: () => {},
|
|
isThirdLanguage: false,
|
|
t: (key) => key,
|
|
wordInNative: () => '',
|
|
})
|
|
|
|
export function NativeLanguageProvider({ children }: { children: React.ReactNode }) {
|
|
const [nativeLang, setNativeLangState] = useState('de')
|
|
|
|
useEffect(() => {
|
|
const stored = localStorage.getItem(STORAGE_KEY)
|
|
if (stored) setNativeLangState(stored)
|
|
}, [])
|
|
|
|
const setNativeLang = useCallback((lang: string) => {
|
|
setNativeLangState(lang)
|
|
localStorage.setItem(STORAGE_KEY, lang)
|
|
}, [])
|
|
|
|
const isThirdLanguage = nativeLang !== 'de' && nativeLang !== 'en'
|
|
|
|
const t = useCallback((key: ExerciseKey): string => {
|
|
const entry = exerciseT[key]
|
|
if (!entry) return key
|
|
return (entry as Record<string, string>)[nativeLang] || entry.de || key
|
|
}, [nativeLang])
|
|
|
|
const wordInNative = useCallback((translations?: Record<string, any>): string => {
|
|
if (!translations || !isThirdLanguage) return ''
|
|
const entry = translations[nativeLang]
|
|
if (!entry) return ''
|
|
return typeof entry === 'string' ? entry : entry.text || ''
|
|
}, [nativeLang, isThirdLanguage])
|
|
|
|
return (
|
|
<NativeLanguageContext.Provider value={{ nativeLang, setNativeLang, isThirdLanguage, t, wordInNative }}>
|
|
{children}
|
|
</NativeLanguageContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useNativeLanguage() {
|
|
return useContext(NativeLanguageContext)
|
|
}
|