2026-10-06 11:42:11 +07:00
|
|
|
import { createContext, useContext, useEffect, useState, useCallback } from 'react'
|
|
|
|
|
|
2026-10-13 14:56:20 +07:00
|
|
|
type Theme = 'dark' | 'light'
|
2026-10-06 11:42:11 +07:00
|
|
|
|
|
|
|
|
interface ThemeContextValue {
|
|
|
|
|
theme: Theme
|
|
|
|
|
resolvedTheme: 'dark' | 'light'
|
|
|
|
|
setTheme: (theme: Theme) => void
|
|
|
|
|
cycleTheme: () => void
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined)
|
|
|
|
|
|
|
|
|
|
const STORAGE_KEY = 'portfolio-theme'
|
|
|
|
|
|
2026-10-13 14:56:20 +07:00
|
|
|
function getInitialTheme(): 'dark' | 'light' {
|
2026-10-06 11:42:11 +07:00
|
|
|
try {
|
|
|
|
|
const stored = localStorage.getItem(STORAGE_KEY)
|
2026-10-13 14:56:20 +07:00
|
|
|
if (stored === 'dark' || stored === 'light') {
|
2026-10-06 11:42:11 +07:00
|
|
|
return stored
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// localStorage unavailable
|
|
|
|
|
}
|
2026-10-13 14:56:20 +07:00
|
|
|
const prefersLight = window.matchMedia('(prefers-color-scheme: light)').matches
|
|
|
|
|
return prefersLight ? 'light' : 'dark'
|
2026-10-06 11:42:11 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function resolveTheme(theme: Theme): 'dark' | 'light' {
|
2026-10-13 14:56:20 +07:00
|
|
|
return theme
|
2026-10-06 11:42:11 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
2026-10-13 14:56:20 +07:00
|
|
|
const [theme, setThemeState] = useState<Theme>(getInitialTheme)
|
2026-10-06 11:42:11 +07:00
|
|
|
|
|
|
|
|
const resolvedTheme = resolveTheme(theme)
|
|
|
|
|
|
2026-10-13 15:57:16 +07:00
|
|
|
// Set data-theme during render so it's available before paint
|
|
|
|
|
document.documentElement.setAttribute('data-theme', resolvedTheme)
|
|
|
|
|
|
2026-10-06 11:42:11 +07:00
|
|
|
useEffect(() => {
|
|
|
|
|
try {
|
|
|
|
|
localStorage.setItem(STORAGE_KEY, theme)
|
|
|
|
|
} catch {
|
|
|
|
|
// localStorage unavailable
|
|
|
|
|
}
|
2026-10-13 15:57:16 +07:00
|
|
|
}, [theme])
|
|
|
|
|
|
2026-10-06 11:42:11 +07:00
|
|
|
|
|
|
|
|
const setTheme = useCallback((newTheme: Theme) => {
|
|
|
|
|
setThemeState(newTheme)
|
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
|
|
const cycleTheme = useCallback(() => {
|
2026-10-13 14:56:20 +07:00
|
|
|
setThemeState((prev) => (prev === 'dark' ? 'light' : 'dark'))
|
2026-10-06 11:42:11 +07:00
|
|
|
}, [])
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<ThemeContext.Provider value={{ theme, resolvedTheme, setTheme, cycleTheme }}>
|
|
|
|
|
{children}
|
|
|
|
|
</ThemeContext.Provider>
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useTheme() {
|
|
|
|
|
const context = useContext(ThemeContext)
|
|
|
|
|
if (!context) {
|
|
|
|
|
throw new Error('useTheme must be used within ThemeProvider')
|
|
|
|
|
}
|
|
|
|
|
return context
|
|
|
|
|
}
|