refactor: theme manager (#17976)
This commit is contained in:
@@ -2,39 +2,12 @@ import { browser } from '$app/environment';
|
||||
import { Theme, defaultLang } from '$lib/constants';
|
||||
import { getPreferredLocale } from '$lib/utils/i18n';
|
||||
import { persisted } from 'svelte-persisted-store';
|
||||
import { get } from 'svelte/store';
|
||||
|
||||
export interface ThemeSetting {
|
||||
value: Theme;
|
||||
system: boolean;
|
||||
}
|
||||
|
||||
export const handleToggleTheme = () => {
|
||||
const theme = get(colorTheme);
|
||||
theme.value = theme.value === Theme.DARK ? Theme.LIGHT : Theme.DARK;
|
||||
colorTheme.set(theme);
|
||||
};
|
||||
|
||||
const initTheme = (): ThemeSetting => {
|
||||
if (browser && globalThis.matchMedia && !globalThis.matchMedia('(prefers-color-scheme: dark)').matches) {
|
||||
return { value: Theme.LIGHT, system: false };
|
||||
}
|
||||
return { value: Theme.DARK, system: false };
|
||||
};
|
||||
|
||||
const initialTheme = initTheme();
|
||||
|
||||
// The 'color-theme' key is also used by app.html to prevent FOUC on page load.
|
||||
export const colorTheme = persisted<ThemeSetting>('color-theme', initialTheme, {
|
||||
serializer: {
|
||||
parse: (text: string): ThemeSetting => {
|
||||
const parsedText: ThemeSetting = JSON.parse(text);
|
||||
return Object.values(Theme).includes(parsedText.value) ? parsedText : initTheme();
|
||||
},
|
||||
stringify: (object) => JSON.stringify(object),
|
||||
},
|
||||
});
|
||||
|
||||
// Locale to use for formatting dates, numbers, etc.
|
||||
export const locale = persisted<string | undefined>('locale', undefined, {
|
||||
serializer: {
|
||||
|
||||
Reference in New Issue
Block a user