mirror of
https://github.com/R0m1k3/Reviflow.git
synced 2026-10-21 22:18:07 +02:00
feat: implement dark mode with theme toggle and persistence
This commit is contained in:
1 parent
7a816c8230
commit
e7e5382de4
7 files changed
+163
-69
No files matched your search
@@ -0,0 +1,43 @@
|
||||
import { create } from 'zustand';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
interface ThemeState {
|
||||
isDark: boolean;
|
||||
toggleTheme: () => void;
|
||||
setTheme: (isDark: boolean) => void;
|
||||
}
|
||||
|
||||
export const useTheme = create<ThemeState>((set) => {
|
||||
// 1. Check local storage or system preference on initialization
|
||||
const stored = localStorage.getItem('theme-mode');
|
||||
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
|
||||
const initialIsDark = stored ? stored === 'dark' : systemPrefersDark;
|
||||
|
||||
return {
|
||||
isDark: initialIsDark,
|
||||
toggleTheme: () => set((state) => {
|
||||
const newIsDark = !state.isDark;
|
||||
localStorage.setItem('theme-mode', newIsDark ? 'dark' : 'light');
|
||||
return { isDark: newIsDark };
|
||||
}),
|
||||
setTheme: (isDark) => set(() => {
|
||||
localStorage.setItem('theme-mode', isDark ? 'dark' : 'light');
|
||||
return { isDark };
|
||||
})
|
||||
};
|
||||
});
|
||||
|
||||
// Hook to handle the side effect of applying the class to HTML/Body
|
||||
export function useThemeEffect() {
|
||||
const isDark = useTheme((state) => state.isDark);
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement;
|
||||
if (isDark) {
|
||||
root.classList.add('dark');
|
||||
} else {
|
||||
root.classList.remove('dark');
|
||||
}
|
||||
}, [isDark]);
|
||||
}
|
||||
Reference in new issue
Block a user