Files
ea-chatbot-lg/frontend/src/components/theme-provider.tsx
Yunxiao Xu 7be24d8884 fix(frontend): resolve build errors
- Fix undefined loadHistory in App.tsx
- Use type-only import for Theme in theme-provider.tsx
- Update auth.ts to import Theme from theme-context
2026-02-21 08:30:27 -08:00

54 lines
1.3 KiB
TypeScript

import { useEffect, useState, useCallback, useMemo } from "react"
import { AuthService } from "@/services/auth"
import { type Theme, ThemeContext } from "./theme-context"
export function ThemeProvider({
children,
initialTheme = "light",
isAuthenticated = false,
}: {
children: React.ReactNode
initialTheme?: Theme
isAuthenticated?: boolean
}) {
const [theme, setThemeState] = useState<Theme>(initialTheme)
useEffect(() => {
const root = window.document.documentElement
root.classList.remove("light", "dark")
root.classList.add(theme)
}, [theme])
const setTheme = useCallback(async (newTheme: Theme) => {
setThemeState(newTheme)
if (isAuthenticated) {
try {
await AuthService.updateTheme(newTheme)
} catch (error) {
console.error("Failed to sync theme to backend:", error)
}
}
}, [isAuthenticated])
const setThemeLocal = useCallback((newTheme: Theme) => {
setThemeState(newTheme)
}, [])
const toggleTheme = useCallback(() => {
setTheme(theme === "light" ? "dark" : "light")
}, [theme, setTheme])
const value = useMemo(() => ({
theme,
setTheme,
setThemeLocal,
toggleTheme
}), [theme, setTheme, setThemeLocal, toggleTheme])
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
)
}