From 6f3acb347d76068b12c653e035566773e19ea7e7 Mon Sep 17 00:00:00 2001 From: Danny Liu Date: Sat, 16 Mar 2024 23:14:13 -0700 Subject: [PATCH] update theme handling and persist selection using Svelte store --- .../components/chat/Settings/General.svelte | 72 +++++++++---------- src/lib/stores/index.ts | 24 ++++++- src/routes/+layout.svelte | 4 +- 3 files changed, 59 insertions(+), 41 deletions(-) diff --git a/src/lib/components/chat/Settings/General.svelte b/src/lib/components/chat/Settings/General.svelte index 6c8bca130..8dca7c613 100644 --- a/src/lib/components/chat/Settings/General.svelte +++ b/src/lib/components/chat/Settings/General.svelte @@ -1,10 +1,11 @@
@@ -127,7 +125,7 @@
Theme
- {#if theme === 'dark'} + {#if actualTheme === 'dark'} - {:else if theme === 'light'} + {:else if actualTheme === 'light'} diff --git a/src/lib/stores/index.ts b/src/lib/stores/index.ts index e25cd33ed..7b15cf1d9 100644 --- a/src/lib/stores/index.ts +++ b/src/lib/stores/index.ts @@ -1,5 +1,5 @@ import { APP_NAME } from '$lib/constants'; -import { writable } from 'svelte/store'; +import { writable, derived } from 'svelte/store'; // Backend export const WEBUI_NAME = writable(APP_NAME); @@ -7,7 +7,27 @@ export const config = writable(undefined); export const user = writable(undefined); // Frontend -export const theme = writable('dark'); +const rawThemeSetting = writable('system'); +export const theme = derived(rawThemeSetting, ($rawThemeSetting) => { + if ($rawThemeSetting === 'system') { + return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; + } + return $rawThemeSetting; +}); + +window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => { + rawThemeSetting.update((currentTheme) => { + if (currentTheme === 'system') { + return e.matches ? 'dark' : 'light'; + } + return currentTheme; + }); +}); + +export function setTheme(theme){ + rawThemeSetting.set(theme); + localStorage.setItem('theme', theme); +} export const chatId = writable(''); diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index d604f901a..6e19f263a 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -1,6 +1,6 @@