Add the existing application baseline and repository documentation/ignore rules. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
|
|
|
|
type Theme = 'light' | 'dark'
|
|
|
|
interface ThemeCtx {
|
|
theme: Theme
|
|
setTheme: (t: Theme) => void
|
|
}
|
|
|
|
const ThemeContext = createContext<ThemeCtx | null>(null)
|
|
|
|
export function ThemeProvider({ children }: { children: ReactNode }) {
|
|
const [theme, setThemeState] = useState<Theme>(() => {
|
|
const saved = localStorage.getItem('theme') as Theme | null
|
|
if (saved === 'light' || saved === 'dark') return saved
|
|
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
|
})
|
|
|
|
useEffect(() => {
|
|
const root = document.documentElement
|
|
root.classList.toggle('dark', theme === 'dark')
|
|
localStorage.setItem('theme', theme)
|
|
}, [theme])
|
|
|
|
function setTheme(t: Theme) {
|
|
setThemeState(t)
|
|
}
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, setTheme }}>
|
|
{children}
|
|
</ThemeContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useTheme() {
|
|
const ctx = useContext(ThemeContext)
|
|
if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
|
|
return ctx
|
|
}
|