From 6fcaeaafe22b76072a9ef1182f398e2dad14467a Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+Berry-13@users.noreply.github.com> Date: Sat, 9 Mar 2024 17:36:04 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20fix(ThemeContext):=20Listen=20fo?= =?UTF-8?q?r=20Theme=20Changes=20(#2037)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(ThemeContext): listen for changes * fix(Dropdown): theme auto-update not working --- client/src/components/ui/Dropdown.tsx | 26 ++++---------------------- client/src/hooks/ThemeContext.tsx | 13 +++++++++++++ 2 files changed, 17 insertions(+), 22 deletions(-) diff --git a/client/src/components/ui/Dropdown.tsx b/client/src/components/ui/Dropdown.tsx index 90d5b267e7..164b9f9bda 100644 --- a/client/src/components/ui/Dropdown.tsx +++ b/client/src/components/ui/Dropdown.tsx @@ -1,7 +1,6 @@ import React, { FC, useContext, useState } from 'react'; import { Listbox } from '@headlessui/react'; import { cn } from '~/utils/'; -import { ThemeContext } from '~/hooks'; type OptionType = { value: string; @@ -27,23 +26,8 @@ const Dropdown: FC = ({ width, testId = 'dropdown-menu', }) => { - const { theme } = useContext(ThemeContext); const [selectedValue, setSelectedValue] = useState(initialValue); - const themeStyles = { - light: 'bg-white text-gray-700 hover:bg-gray-50 border-gray-300', - dark: 'bg-gray-800 text-white hover:bg-gray-700 border-gray-600', - }; - - const isSystemDark = - window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; - const currentThemeStyle = - theme === 'system' - ? isSystemDark - ? themeStyles.dark - : themeStyles.light - : themeStyles[theme] || themeStyles.light; - return (
= ({ = ({ = ({ key={index} value={typeof item === 'string' ? item : item.value} className={cn( - 'relative cursor-pointer select-none py-1 pl-3 pr-6', - currentThemeStyle, + 'relative cursor-pointer select-none border-gray-300 bg-white py-1 pl-3 pr-6 text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-800 dark:text-white dark:hover:bg-gray-700', )} style={{ width: width ? `${width}px` : 'auto' }} data-theme={typeof item === 'string' ? item : (item as OptionType).value} diff --git a/client/src/hooks/ThemeContext.tsx b/client/src/hooks/ThemeContext.tsx index d7123bec86..397889f993 100644 --- a/client/src/hooks/ThemeContext.tsx +++ b/client/src/hooks/ThemeContext.tsx @@ -49,6 +49,19 @@ export const ThemeProvider = ({ initialTheme, children }) => { localStorage.setItem('color-theme', rawTheme); }; + useEffect(() => { + const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); + const changeThemeOnSystemChange = () => { + rawSetTheme(mediaQuery.matches ? 'dark' : 'light'); + }; + + mediaQuery.addEventListener('change', changeThemeOnSystemChange); + + return () => { + mediaQuery.removeEventListener('change', changeThemeOnSystemChange); + }; + }, []); + if (initialTheme) { rawSetTheme(initialTheme); }