Skip to content

Commit

Permalink
Restore system theme change event handler
Browse files Browse the repository at this point in the history
  • Loading branch information
mathjazz committed Oct 26, 2023
1 parent e53e89c commit ed5d06b
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions translate/src/context/Theme.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createContext, useState } from 'react';
import { createContext, useEffect, useState } from 'react';
import { useTheme } from '~/hooks/useTheme';

export const ThemeContext = createContext({
Expand All @@ -9,9 +9,26 @@ export function ThemeProvider({ children }: { children: React.ReactElement }) {
const [theme] = useState(
() => document.body.getAttribute('data-theme') || 'dark',
);

const applyTheme = useTheme();

applyTheme(theme);
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

function handleThemeChange(e: MediaQueryListEvent) {
let userThemeSetting = document.body.getAttribute('data-theme') || 'dark';

if (userThemeSetting === 'system') {
applyTheme(e.matches ? 'dark' : 'light');
}
}

mediaQuery.addEventListener('change', handleThemeChange);

return () => {
mediaQuery.removeEventListener('change', handleThemeChange);
};
}, [theme]);

return (
<ThemeContext.Provider value={{ theme }}>{children}</ThemeContext.Provider>
Expand Down

0 comments on commit ed5d06b

Please sign in to comment.