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; const selector = (state: { theme: string }) => state.theme;
export function useTheme() { export function useTheme() {
const defaultTheme = const isDark = window?.matchMedia('(prefers-color-scheme: dark)')?.matches;
typeof window !== 'undefined' const defaultTheme = typeof window !== 'undefined' ? (isDark ? 'dark' : 'light') : 'light';
? window?.matchMedia('(prefers-color-scheme: dark)')?.matches const theme = useStore(selector) || defaultTheme || getItem(THEME_CONFIG);
? 'dark'
: 'light'
: 'light';
const theme = useStore(selector) || getItem(THEME_CONFIG) || defaultTheme;
const primaryColor = colord(THEME_COLORS[theme].primary); const primaryColor = colord(THEME_COLORS[theme].primary);
const colors = { 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 }; 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 TELEMETRY_PIXEL = 'https://i.umami.is/a.png';
export const DEFAULT_LOCALE = process.env.defaultLocale || 'en-US'; 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_ANIMATION_DURATION = 300;
export const DEFAULT_DATE_RANGE = '24hour'; export const DEFAULT_DATE_RANGE = '24hour';
export const DEFAULT_WEBSITE_LIMIT = 10; export const DEFAULT_WEBSITE_LIMIT = 10;

View File

@ -3,7 +3,7 @@ import {
DATE_RANGE_CONFIG, DATE_RANGE_CONFIG,
DEFAULT_DATE_RANGE, DEFAULT_DATE_RANGE,
DEFAULT_LOCALE, DEFAULT_LOCALE,
DEFAULT_THEME, // DEFAULT_THEME,
LOCALE_CONFIG, LOCALE_CONFIG,
THEME_CONFIG, THEME_CONFIG,
} from 'lib/constants'; } from 'lib/constants';
@ -11,7 +11,7 @@ import { getItem } from 'next-basics';
const initialState = { const initialState = {
locale: getItem(LOCALE_CONFIG) || DEFAULT_LOCALE, locale: getItem(LOCALE_CONFIG) || DEFAULT_LOCALE,
theme: getItem(THEME_CONFIG) || DEFAULT_THEME, theme: getItem(THEME_CONFIG),
dateRange: getItem(DATE_RANGE_CONFIG) || DEFAULT_DATE_RANGE, dateRange: getItem(DATE_RANGE_CONFIG) || DEFAULT_DATE_RANGE,
shareToken: null, shareToken: null,
user: null, user: null,