From 5ea4cc13bb908cec98290069b74bdc11eb7a7f24 Mon Sep 17 00:00:00 2001 From: Matthew Holloway Date: Wed, 25 Sep 2024 03:53:08 +1200 Subject: [PATCH] feat: change theme dynamically when system preferences change (#7956) --- client/App.vue | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/client/App.vue b/client/App.vue index 2a6c5e6e98..7750674296 100644 --- a/client/App.vue +++ b/client/App.vue @@ -30,17 +30,24 @@ const appContainer = ref(null) // Set user theme // -------------------------------------------------------------------- -const desiredTheme = window.localStorage?.getItem('theme') -if (desiredTheme === 'dark') { - siteStore.theme = 'dark' -} else if (desiredTheme === 'light') { - siteStore.theme = 'light' -} else if (window.matchMedia("(prefers-color-scheme: dark)").matches) { - siteStore.theme = 'dark' -} else { - siteStore.theme = 'light' +function updateTheme() { + const desiredTheme = window.localStorage?.getItem('theme') + if (desiredTheme === 'dark') { + siteStore.theme = 'dark' + } else if (desiredTheme === 'light') { + siteStore.theme = 'light' + } else if (window.matchMedia("(prefers-color-scheme: dark)").matches) { + siteStore.theme = 'dark' + } else { + siteStore.theme = 'light' + } } +updateTheme() + +// this change event fires for either light or dark changes +window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateTheme) + // -------------------------------------------------------------------- // Handle browser resize // --------------------------------------------------------------------