update theme handling and persist selection using Svelte store

This commit is contained in:
Danny Liu 2024-03-16 23:14:13 -07:00
parent 27153ddb03
commit 6f3acb347d
3 changed files with 59 additions and 41 deletions

View file

@ -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('');