fix(theme): detect system theme when theme cookie is not present
This commit is contained in:
parent
30c7d6ea4d
commit
7ded3aace4
2 changed files with 12 additions and 4 deletions
|
@ -12,14 +12,23 @@ type Props = {
|
|||
export const ThemeProvider = (props: Props) => {
|
||||
const { children, initialTheme } = props;
|
||||
const cookies = useCookies();
|
||||
const { theme } = useUIStore();
|
||||
const { theme, setDarkMode } = useUIStore();
|
||||
|
||||
useEffect(() => {
|
||||
if (theme) {
|
||||
cookies.set('theme', theme || initialTheme || 'light', { path: '/' });
|
||||
document.body.dataset.bsTheme = theme;
|
||||
} else if (!cookies.get('theme')) {
|
||||
// Detect system theme
|
||||
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
setDarkMode(systemTheme === 'dark');
|
||||
cookies.set('theme', systemTheme, { path: '/' });
|
||||
document.body.dataset.bsTheme = systemTheme;
|
||||
}
|
||||
}, [cookies, initialTheme, theme]);
|
||||
|
||||
const cookieTheme = cookies.get('theme');
|
||||
setDarkMode(cookieTheme === 'dark');
|
||||
}, [cookies, initialTheme, setDarkMode, theme]);
|
||||
|
||||
return children;
|
||||
};
|
||||
|
|
|
@ -25,8 +25,7 @@ export const useUIStore = create<UIStore>((set) => ({
|
|||
setDarkMode: (darkMode: boolean) => {
|
||||
if (darkMode) {
|
||||
set({ theme: 'dark' });
|
||||
}
|
||||
if (!darkMode) {
|
||||
} else {
|
||||
set({ theme: 'light' });
|
||||
}
|
||||
set({ darkMode });
|
||||
|
|
Loading…
Reference in a new issue