fix(theme): detect system theme when theme cookie is not present

This commit is contained in:
Nicolas Meienberger 2023-10-21 13:54:06 +02:00 committed by Nicolas Meienberger
parent 30c7d6ea4d
commit 7ded3aace4
2 changed files with 12 additions and 4 deletions

View file

@ -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;
};

View file

@ -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 });