From f1716f45b9a9ce46aa8e98be9f414ff2c3d1cae4 Mon Sep 17 00:00:00 2001 From: Danny Liu Date: Sat, 16 Mar 2024 23:14:38 -0700 Subject: [PATCH] add event listener in app.html to handle system theme changes --- src/app.html | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/app.html b/src/app.html index 6216e56fa..931db8aa5 100644 --- a/src/app.html +++ b/src/app.html @@ -13,13 +13,29 @@ (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: light)').matches) ) { document.documentElement.classList.add('light'); - } else if (localStorage.theme) { + } else if (localStorage.theme && localStorage.theme !== 'system') { localStorage.theme.split(' ').forEach((e) => { document.documentElement.classList.add(e); }); - } else { + } else if (localStorage.theme && localStorage.theme === 'system') { + systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches; + document.documentElement.classList.add(systemTheme ? 'dark' : 'light'); + } + else { document.documentElement.classList.add('dark'); } + + window.matchMedia('(prefers-color-scheme: dark)').addListener((e) => { + if (localStorage.theme === 'system') { + if (e.matches) { + document.documentElement.classList.add('dark'); + document.documentElement.classList.remove('light'); + } else { + document.documentElement.classList.add('light'); + document.documentElement.classList.remove('dark'); + } + } + }); %sveltekit.head%