From e420713a6f68053c20e03e50cfcd9fe6c6fac287 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 28 Oct 2022 12:38:15 +0200 Subject: [PATCH] Add setting to toggle light/dark mode Signed-off-by: Thomas Citharel --- js/src/App.vue | 20 +++++++ js/src/assets/oruga-tailwindcss.css | 4 ++ js/src/i18n/en_US.json | 13 ++++- js/src/i18n/fr_FR.json | 11 +++- js/src/views/Settings/PreferencesView.vue | 70 ++++++++++++++++++++++- js/tailwind.config.js | 1 + lib/web/templates/page/index.html.heex | 7 +++ 7 files changed, 122 insertions(+), 4 deletions(-) diff --git a/js/src/App.vue b/js/src/App.vue index 0fe8e4987..108981bb3 100644 --- a/js/src/App.vue +++ b/js/src/App.vue @@ -54,6 +54,7 @@ import { defineAsyncComponent, computed, watch, + onBeforeUnmount, } from "vue"; import { LocationType } from "@/types/user-location.model"; import { useMutation, useQuery } from "@vue/apollo-composable"; @@ -155,6 +156,7 @@ onBeforeMount(async () => { }); const snackbar = inject("snackbar"); +const darkModePreference = window.matchMedia("(prefers-color-scheme: dark)"); onMounted(() => { online.value = window.navigator.onLine; @@ -187,6 +189,7 @@ onMounted(() => { }, }); }); + darkModePreference.addEventListener("change", changeTheme); }); onUnmounted(() => { @@ -289,6 +292,23 @@ watch(config, async (configWatched: IConfig | undefined) => { }); const isDemoMode = computed(() => config.value?.demoMode); + +const changeTheme = () => { + console.debug("changing theme"); + if ( + localStorage.getItem("theme") === "dark" || + (!("theme" in localStorage) && + window.matchMedia("(prefers-color-scheme: dark)").matches) + ) { + document.documentElement.classList.add("dark"); + } else { + document.documentElement.classList.remove("dark"); + } +}; + +onBeforeUnmount(() => { + darkModePreference.removeEventListener("change", changeTheme); +});