Files
open-webui/src/lib/utils/theme.ts
T
2026-12-02 03:58:13 +04:00

56 lines
1.8 KiB
TypeScript

import { theme } from '$lib/stores';
type Mode = 'light' | 'dark';
export type ThemeColors = Partial<Record<Mode, { bg: string; fg: string }>>;
// What the default greys are mixed from (see `--app-bg` / `--app-fg` in tailwind.css).
export const DEFAULT_THEME_COLORS: Record<Mode, { bg: string; fg: string }> = {
light: { bg: '#ffffff', fg: '#000000' },
dark: { bg: '#121212', fg: '#ffffff' }
};
export function getThemeColors(): ThemeColors {
try {
return JSON.parse(localStorage.themeColors ?? '{}');
} catch {
return {};
}
}
export function setThemeColors(colors: ThemeColors): void {
if (colors.light || colors.dark) localStorage.themeColors = JSON.stringify(colors);
else localStorage.removeItem('themeColors');
applyThemeColors();
}
// Keep in sync with the copy in app.html, which runs before first paint.
export function applyThemeColors(): void {
const root = document.documentElement;
const colors = getThemeColors()[root.classList.contains('dark') ? 'dark' : 'light'];
if (colors) {
root.style.setProperty('--app-bg', colors.bg);
root.style.setProperty('--app-fg', colors.fg);
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', colors.bg);
} else {
root.style.removeProperty('--app-bg');
root.style.removeProperty('--app-fg');
}
}
export function setTheme(value: string): void {
localStorage.setItem('theme', value);
theme.set(value);
const dark =
value === 'system'
? window.matchMedia('(prefers-color-scheme: dark)').matches
: value === 'dark';
const root = document.documentElement;
root.classList.remove(dark ? 'light' : 'dark');
root.classList.add(dark ? 'dark' : 'light');
document
.querySelector('meta[name="theme-color"]')
?.setAttribute('content', dark ? '#121212' : '#ffffff');
applyThemeColors();
window.applyTheme?.();
}