Skip to content

Commit b967e4c

Browse files
committed
theme dark mode preference onChange mostly works
1 parent 05ded58 commit b967e4c

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

src/components/ThemeScript.astro

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,30 @@ const defaultThemes = getDefaultThemes();
1818
// used for event
1919
const darkModePreference = window.matchMedia('(prefers-color-scheme: dark)');
2020

21-
// light is default
22-
// const getMode = (themeMode) => (themeMode === MODES.dark ? MODES.dark : MODES.light);
23-
2421
const getDefaultTheme = (themeMode) => defaultThemes[themeMode];
2522

26-
const setMode = (themeMode) => {
27-
const storedTheme = getStoredTheme();
23+
const getThemeNamePrefix = (themeName) => themeName.split('-')?.[0];
24+
25+
const getThemeFromMode = (themeMode) => {
26+
const currentTheme = getTheme();
27+
28+
const newTheme = THEMES.find((theme) => {
29+
const currentThemePrefix = getThemeNamePrefix(currentTheme.name);
30+
const themePrefix = getThemeNamePrefix(theme.name);
2831

29-
if (!storedTheme) return getDefaultTheme(themeMode);
32+
const isModeMatch = theme.mode === themeMode;
33+
const isThemeNameMatch =
34+
themePrefix && currentThemePrefix && themePrefix === currentThemePrefix;
3035

31-
const newTheme = { ...storedTheme, mode: themeMode };
32-
return newTheme;
36+
const isFound = isModeMatch && isThemeNameMatch;
37+
38+
return isFound;
39+
});
40+
41+
const defaultTheme = getDefaultTheme(themeMode);
42+
const resultTheme = newTheme ?? defaultTheme;
43+
44+
return resultTheme;
3345
};
3446

3547
/** 'dark' | 'light' | null */
@@ -151,10 +163,7 @@ const defaultThemes = getDefaultThemes();
151163
// listen for prefers-color-scheme change
152164
darkModePreference.addEventListener('change', (event) => {
153165
const newMode = event.matches ? MODES.dark : MODES.light;
154-
const newTheme = setMode(newMode);
155-
156-
console.log('newMode', newMode, 'newTheme', newTheme);
157-
// has bug: { mode: "dark", name: "default-light" }
166+
const newTheme = getThemeFromMode(newMode);
158167
setTheme(newTheme);
159168
});
160169
</script>

0 commit comments

Comments
 (0)