Skip to content

Commit

Permalink
feat[closes #84]: add system theme preference
Browse files Browse the repository at this point in the history
  • Loading branch information
GabsEdits committed Jul 21, 2024
1 parent d1b585b commit f53e008
Showing 1 changed file with 34 additions and 21 deletions.
55 changes: 34 additions & 21 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,11 @@
</div>
</div>

<button @click="toggleDarkMode"
<button @click="toggleThemeMode"
class="flex items-center p-2 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white">
<i class="material-icons" v-if="isDarkMode">light_mode</i>
<i class="material-icons" v-else>dark_mode</i>
<i class="material-icons" v-if="theme === 'light'">light_mode</i>
<i class="material-icons" v-if="theme === 'system'">computer</i>
<i class="material-icons" v-if="theme === 'dark'">dark_mode</i>
</button>

<div class="hidden sm:flex items-center space-x-4">
Expand Down Expand Up @@ -102,7 +103,7 @@ export default defineComponent({
search: "",
chronosConfig: {} as ChronosConfig,
collectionShortName: "",
isDarkMode: false,
theme: "system",
};
},
computed: {
Expand All @@ -117,6 +118,9 @@ export default defineComponent({
$route(to, from) {
this.fetchLanguages();
},
theme() {
this.applyTheme();
},
},
async mounted() {
try {
Expand All @@ -133,17 +137,9 @@ export default defineComponent({
state.prefLang = "en";
});
// Dark mode
const userPrefersDark =
localStorage.getItem("darkMode") === "true" ||
(!("darkMode" in localStorage) &&
window.matchMedia("(prefers-color-scheme: dark)").matches);
this.isDarkMode = userPrefersDark;
if (userPrefersDark) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
// Theme
this.theme = localStorage.getItem("theme") || "system";
this.applyTheme();
},
methods: {
setLang(lang: string) {
Expand Down Expand Up @@ -196,12 +192,29 @@ export default defineComponent({
}
}
},
toggleDarkMode() {
document.documentElement.classList.toggle("dark");
const isDarkMode = document.documentElement.classList.contains("dark");
localStorage.setItem("darkMode", isDarkMode ? "true" : "false");
this.isDarkMode = isDarkMode;
applyTheme() {
if (this.theme === "system") {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
} else if (this.theme === "dark") {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
},
toggleThemeMode() {
if (this.theme === "system") {
this.theme = "dark";
} else if (this.theme === "dark") {
this.theme = "light";
} else {
this.theme = "system";
}
localStorage.setItem("theme", this.theme);
this.applyTheme();
},
emptySearch() {
this.searchResponse = [];
Expand Down

0 comments on commit f53e008

Please sign in to comment.