From 2dfbba4a0fe88d10224cbabc5772c7acca4334eb Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Sat, 3 Feb 2024 12:04:48 +0000 Subject: [PATCH] fix theme auto switching --- src/components/hooks/useTheme.ts | 22 +++++++++++++++------- src/lib/constants.ts | 2 +- src/store/app.ts | 4 ++-- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/src/components/hooks/useTheme.ts b/src/components/hooks/useTheme.ts index 099bf962..700fcd55 100644 --- a/src/components/hooks/useTheme.ts +++ b/src/components/hooks/useTheme.ts @@ -7,13 +7,9 @@ import { colord } from 'colord'; const selector = (state: { theme: string }) => state.theme; export function useTheme() { - const defaultTheme = - typeof window !== 'undefined' - ? window?.matchMedia('(prefers-color-scheme: dark)')?.matches - ? 'dark' - : 'light' - : 'light'; - const theme = useStore(selector) || getItem(THEME_CONFIG) || defaultTheme; + const isDark = window?.matchMedia('(prefers-color-scheme: dark)')?.matches; + const defaultTheme = typeof window !== 'undefined' ? (isDark ? 'dark' : 'light') : 'light'; + const theme = useStore(selector) || defaultTheme || getItem(THEME_CONFIG); const primaryColor = colord(THEME_COLORS[theme].primary); const colors = { @@ -62,6 +58,18 @@ export function useTheme() { } }, []); + useEffect(() => { + if (typeof window === 'undefined') return; + let theme: 'dark' | 'light'; + + window + .matchMedia('(prefers-color-scheme: dark)') + .addEventListener('change', ({ matches: isDark }) => { + theme = isDark ? 'dark' : 'light'; + saveTheme(theme); + }); + }, []); + return { theme, saveTheme, colors }; } diff --git a/src/lib/constants.ts b/src/lib/constants.ts index 0c894634..64feb968 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -14,7 +14,7 @@ export const UPDATES_URL = 'https://api.umami.is/v1/updates'; export const TELEMETRY_PIXEL = 'https://i.umami.is/a.png'; export const DEFAULT_LOCALE = process.env.defaultLocale || 'en-US'; -export const DEFAULT_THEME = 'light'; +// export const DEFAULT_THEME = 'light'; export const DEFAULT_ANIMATION_DURATION = 300; export const DEFAULT_DATE_RANGE = '24hour'; export const DEFAULT_WEBSITE_LIMIT = 10; diff --git a/src/store/app.ts b/src/store/app.ts index 53fdbd92..6ed62408 100644 --- a/src/store/app.ts +++ b/src/store/app.ts @@ -3,7 +3,7 @@ import { DATE_RANGE_CONFIG, DEFAULT_DATE_RANGE, DEFAULT_LOCALE, - DEFAULT_THEME, + // DEFAULT_THEME, LOCALE_CONFIG, THEME_CONFIG, } from 'lib/constants'; @@ -11,7 +11,7 @@ import { getItem } from 'next-basics'; const initialState = { locale: getItem(LOCALE_CONFIG) || DEFAULT_LOCALE, - theme: getItem(THEME_CONFIG) || DEFAULT_THEME, + theme: getItem(THEME_CONFIG), dateRange: getItem(DATE_RANGE_CONFIG) || DEFAULT_DATE_RANGE, shareToken: null, user: null,