Skip to content

Commit

Permalink
Apply optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
joel-jeremy committed Sep 27, 2024
1 parent a7a6f18 commit 38a6c02
Showing 1 changed file with 27 additions and 20 deletions.
47 changes: 27 additions & 20 deletions packages/desktop-client/src/style/theme.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @ts-strict-ignore
import { useLayoutEffect, useState } from 'react';
import { useCallback, useEffect, useLayoutEffect, useState } from 'react';

import { isNonProductionEnvironment } from 'loot-core/src/shared/environment';
import type { DarkTheme, Theme } from 'loot-core/src/types/prefs';
Expand Down Expand Up @@ -52,42 +52,49 @@ export function ThemeStyle() {
| undefined
>(undefined);

const darkThemeMediaQueryListener = useCallback(
(event: MediaQueryListEvent) => {
if (event.matches) {
setThemeColors(themes[darkThemePreference].colors);
} else {
setThemeColors(themes['light'].colors);
}
},
[darkThemePreference],
);

useLayoutEffect(() => {
if (theme === 'auto') {
const darkTheme = themes[darkThemePreference];

function darkThemeMediaQueryListener(event: MediaQueryListEvent) {
if (event.matches) {
setThemeColors(darkTheme.colors);
} else {
setThemeColors(themes['light'].colors);
}
}
const darkThemeMediaQuery = window.matchMedia(
'(prefers-color-scheme: dark)',
);

darkThemeMediaQuery.addEventListener(
'change',
darkThemeMediaQueryListener,
);

if (darkThemeMediaQuery.matches) {
setThemeColors(darkTheme.colors);
setThemeColors(themes[darkThemePreference].colors);
} else {
setThemeColors(themes['light'].colors);
}
} else {
setThemeColors(themes[theme].colors);
}
}, [theme, darkThemePreference]);

useEffect(() => {
if (theme === 'auto') {
const darkThemeMediaQuery = window.matchMedia(
'(prefers-color-scheme: dark)',
);
darkThemeMediaQuery.addEventListener(
'change',
darkThemeMediaQueryListener,
);
return () => {
darkThemeMediaQuery.removeEventListener(
'change',
darkThemeMediaQueryListener,
);
};
} else {
setThemeColors(themes[theme].colors);
}
}, [theme, darkThemePreference]);
}, [theme, darkThemeMediaQueryListener]);

if (!themeColors) return null;

Expand Down

0 comments on commit 38a6c02

Please sign in to comment.