Skip to content

Commit

Permalink
fix: ensure site syncs with system theme changes (#49)
Browse files Browse the repository at this point in the history
* fix: tweaking theme provider

* formatting changes

* chore: disable eslint warning and update setter name

---------
Resolves #48
Co-authored-by: satnaing <[email protected]>
  • Loading branch information
kohinoor98 authored Nov 11, 2024
1 parent c5d163d commit 9a98533
Showing 1 changed file with 23 additions and 15 deletions.
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

0 comments on commit 9a98533

Please sign in to comment.