@@ -18,18 +18,30 @@ const defaultThemes = getDefaultThemes();
18
18
// used for event
19
19
const darkModePreference = window.matchMedia('(prefers-color-scheme: dark)');
20
20
21
- // light is default
22
- // const getMode = (themeMode) => (themeMode === MODES.dark ? MODES.dark : MODES.light);
23
-
24
21
const getDefaultTheme = (themeMode) => defaultThemes[themeMode];
25
22
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);
28
31
29
- if (!storedTheme) return getDefaultTheme(themeMode);
32
+ const isModeMatch = theme.mode === themeMode;
33
+ const isThemeNameMatch =
34
+ themePrefix && currentThemePrefix && themePrefix === currentThemePrefix;
30
35
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;
33
45
};
34
46
35
47
/** 'dark' | 'light' | null */
@@ -151,10 +163,7 @@ const defaultThemes = getDefaultThemes();
151
163
// listen for prefers-color-scheme change
152
164
darkModePreference.addEventListener('change', (event) => {
153
165
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);
158
167
setTheme(newTheme);
159
168
});
160
169
</script >
0 commit comments