Skip to content

Commit c2bad0b

Browse files
committed
Add auto dark/light theme switch based on OS preference
Related to #825 Add automatic theme switching based on OS preference * Add logic in `src/mixins/ThemingMixin.js` to detect OS theme preference using `window.matchMedia`. * Update `initializeTheme` method in `src/mixins/ThemingMixin.js` to set theme based on OS preference. * Modify `applyLocalTheme` method in `src/mixins/ThemingMixin.js` to apply the detected theme dynamically. * Include logic in `src/App.vue` to detect and apply theme based on OS preference during app initialization.
1 parent 85f8425 commit c2bad0b

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/App.vue

+10
Original file line numberDiff line numberDiff line change
@@ -155,11 +155,21 @@ export default {
155155
e.preventDefault();
156156
return 'You may have unsaved edits. Are you sure you want to exit the page?';
157157
},
158+
/* Detect and apply theme based on OS preference */
159+
applyThemeBasedOnOSPreference() {
160+
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
161+
const osTheme = prefersDark ? this.appConfig.nightTheme : this.appConfig.dayTheme;
162+
if (osTheme) {
163+
this.$store.commit(Keys.SET_THEME, osTheme);
164+
this.updateTheme(osTheme);
165+
}
166+
},
158167
},
159168
/* Basic initialization tasks on app load */
160169
async mounted() {
161170
await this.$store.dispatch(Keys.INITIALIZE_CONFIG); // Initialize config before moving on
162171
this.applyLanguage(); // Apply users local language
172+
this.applyThemeBasedOnOSPreference(); // Apply theme based on OS preference
163173
this.hideSplash(); // Hide the splash screen, if visible
164174
if (this.appConfig.customCss) { // Inject users custom CSS, if present
165175
const cleanedCss = this.appConfig.customCss.replace(/<\/?[^>]+(>|$)/g, '');

src/mixins/ThemingMixin.js

+8
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,14 @@ const ThemingMixin = {
136136
} else if (hasExternal) {
137137
this.applyRemoteTheme(this.externalThemes[initialTheme]);
138138
}
139+
140+
// Detect OS theme preference and apply the corresponding theme
141+
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
142+
const osTheme = prefersDark ? this.appConfig.nightTheme : this.appConfig.dayTheme;
143+
if (osTheme) {
144+
this.$store.commit(Keys.SET_THEME, osTheme);
145+
this.updateTheme(osTheme);
146+
}
139147
},
140148
},
141149
};

0 commit comments

Comments
 (0)