From 1e7fa988da5a969212848d26c189adaf7a390c56 Mon Sep 17 00:00:00 2001 From: Sahil Silare Date: Tue, 1 Oct 2024 10:02:51 +0530 Subject: [PATCH] feat: added theme check unless already set --- frontend/src/hooks/index.ts | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/frontend/src/hooks/index.ts b/frontend/src/hooks/index.ts index a8bfe1da7..dfb9cb467 100644 --- a/frontend/src/hooks/index.ts +++ b/frontend/src/hooks/index.ts @@ -66,9 +66,34 @@ export function useMediaQuery() { } export function useDarkTheme() { - const [isDarkTheme, setIsDarkTheme] = useState( - localStorage.getItem('selectedTheme') === 'Dark' || false, - ); + const getSystemThemePreference = () => { + return ( + window.matchMedia && + window.matchMedia('(prefers-color-scheme: dark)').matches + ); + }; + + const getInitialTheme = () => { + const storedTheme = localStorage.getItem('selectedTheme'); + if (storedTheme === 'Dark' || storedTheme === 'Light') { + return storedTheme === 'Dark'; + } + return getSystemThemePreference(); + }; + + const [isDarkTheme, setIsDarkTheme] = useState(getInitialTheme()); + + useEffect(() => { + const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); + const handleChange = () => { + if (localStorage.getItem('selectedTheme') === null) { + setIsDarkTheme(mediaQuery.matches); + } + }; + + mediaQuery.addListener(handleChange); + return () => mediaQuery.removeListener(handleChange); + }, []); useEffect(() => { localStorage.setItem('selectedTheme', isDarkTheme ? 'Dark' : 'Light'); @@ -79,9 +104,9 @@ export function useDarkTheme() { } }, [isDarkTheme]); - const toggleTheme: any = () => { + const toggleTheme = () => { setIsDarkTheme(!isDarkTheme); }; - return [isDarkTheme, toggleTheme]; + return [isDarkTheme, toggleTheme] as const; }