Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: tweaking theme provider #49

Merged
merged 3 commits into from
Nov 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions src/components/theme-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,34 +26,42 @@ export function ThemeProvider({
storageKey = 'vite-ui-theme',
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(
const [theme, _setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
)

useEffect(() => {
const root = window.document.documentElement
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

root.classList.remove('light', 'dark')

if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)')
.matches
? 'dark'
: 'light'
const applyTheme = (theme: Theme) => {
root.classList.remove('light', 'dark') // Remove existing theme classes
const systemTheme = mediaQuery.matches ? 'dark' : 'light'
const effectiveTheme = theme === 'system' ? systemTheme : theme
root.classList.add(effectiveTheme) // Add the new theme class
}

root.classList.add(systemTheme)
return
const handleChange = () => {
if (theme === 'system') {
applyTheme('system')
}
}

root.classList.add(theme)
applyTheme(theme)

mediaQuery.addEventListener('change', handleChange)

return () => mediaQuery.removeEventListener('change', handleChange)
}, [theme])

const setTheme = (theme: Theme) => {
localStorage.setItem(storageKey, theme)
_setTheme(theme)
}

const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme)
setTheme(theme)
},
setTheme,
}

return (
Expand Down