Skip to content

Commit

Permalink
feat: automatically switch theme when system color preference changes (
Browse files Browse the repository at this point in the history
  • Loading branch information
abereghici authored Nov 3, 2021
1 parent b94d95a commit 3255e47
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
2 changes: 1 addition & 1 deletion apps/blog/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"scripts": {
"dev": "prisma generate && next dev",
"build": "prisma generate && next build",
"start": "next start",
"start": "prisma generate && next start",
"lint": "bereghici-scripts lint './src/**/*.{js,jsx,ts,tsx}'",
"pre-commit": "bereghici-scripts pre-commit",
"typecheck": "bereghici-scripts typecheck",
Expand Down
25 changes: 20 additions & 5 deletions packages/design-system/theme/src/theme-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,6 @@ const ThemeContext =
function ThemeProvider({ children }: { children: React.ReactNode }) {
const [themeName, setThemeName] = React.useState<ThemeTypes>('light');

React.useEffect(() => {
const colorMode = window.document.body.getAttribute(THEME_DATA_ATTRIBUTE);
setThemeName(colorMode === 'dark' ? 'dark' : 'light');
}, []);

const setTheme = React.useCallback((newThemeName: ThemeTypes) => {
localStorage.set(THEME_STORAGE_KEY, newThemeName);
document.body.setAttribute(THEME_DATA_ATTRIBUTE, newThemeName);
Expand All @@ -38,6 +33,26 @@ function ThemeProvider({ children }: { children: React.ReactNode }) {
[themeName, setTheme]
);

React.useEffect(() => {
const colorMode = window.document.body.getAttribute(THEME_DATA_ATTRIBUTE);
setThemeName(colorMode === 'dark' ? 'dark' : 'light');
}, []);

React.useEffect(() => {
const onThemeChange = (e: MediaQueryListEvent) => {
const colorPreference = e.matches ? 'dark' : 'light';

setTheme(colorPreference);
};

const mql = window.matchMedia('(prefers-color-scheme: dark)');
mql.addEventListener('change', onThemeChange);

return () => {
mql.removeEventListener('change', onThemeChange);
};
}, [setTheme]);

return (
<>
<Global
Expand Down

0 comments on commit 3255e47

Please sign in to comment.