mirror of
https://github.com/utopia-os/utopia-ui.git
synced 2026-04-06 01:25:33 +00:00
fix auto theme
This commit is contained in:
parent
fba5fd9845
commit
69842003c9
@ -1,12 +1,38 @@
|
|||||||
import { useEffect } from 'react'
|
import { useEffect } from 'react'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply a theme based on the saved preference, a provided default theme, or the user's system preference.
|
||||||
|
* Falls back to the system dark/light preference when no theme is provided.
|
||||||
|
*/
|
||||||
export const useTheme = (defaultTheme = 'default') => {
|
export const useTheme = (defaultTheme = 'default') => {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const savedTheme = localStorage.getItem('theme')
|
const savedThemeRaw = localStorage.getItem('theme')
|
||||||
const initialTheme = savedTheme ? (JSON.parse(savedTheme) as string) : defaultTheme
|
const savedTheme = savedThemeRaw ? (JSON.parse(savedThemeRaw) as string) : undefined
|
||||||
if (initialTheme !== 'default') {
|
|
||||||
document.documentElement.setAttribute('data-theme', defaultTheme)
|
const prefersDark =
|
||||||
localStorage.setItem('theme', JSON.stringify(initialTheme))
|
typeof window !== 'undefined' && typeof window.matchMedia === 'function'
|
||||||
|
? window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||||
|
: false
|
||||||
|
|
||||||
|
const fallbackTheme =
|
||||||
|
defaultTheme && defaultTheme !== 'default'
|
||||||
|
? defaultTheme
|
||||||
|
: prefersDark
|
||||||
|
? 'dark'
|
||||||
|
: 'light'
|
||||||
|
|
||||||
|
const themeToApply = savedTheme ?? fallbackTheme
|
||||||
|
|
||||||
|
if (themeToApply === 'default') {
|
||||||
|
document.documentElement.removeAttribute('data-theme')
|
||||||
|
localStorage.removeItem('theme')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
document.documentElement.setAttribute('data-theme', themeToApply)
|
||||||
|
|
||||||
|
if (!savedTheme || savedTheme !== themeToApply) {
|
||||||
|
localStorage.setItem('theme', JSON.stringify(themeToApply))
|
||||||
}
|
}
|
||||||
}, [defaultTheme])
|
}, [defaultTheme])
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user