fix theme auto switching

This commit is contained in:
Matthias Kretschmann 2024-02-03 12:04:48 +00:00
parent db3a9525b9
commit 2dfbba4a0f
Signed by: m
GPG Key ID: 606EEEF3C479A91F
3 changed files with 18 additions and 10 deletions

View File

@ -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 };
}

View File

@ -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;

View File

@ -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,