2024-07-17 18:54:46 +00:00
|
|
|
import { atom } from 'nanostores';
|
2024-12-13 00:11:35 +00:00
|
|
|
import { logStore } from './logs';
|
2024-07-17 18:54:46 +00:00
|
|
|
|
|
|
|
export type Theme = 'dark' | 'light';
|
|
|
|
|
|
|
|
export const kTheme = 'bolt_theme';
|
|
|
|
|
|
|
|
export function themeIsDark() {
|
|
|
|
return themeStore.get() === 'dark';
|
|
|
|
}
|
|
|
|
|
2024-07-29 12:37:23 +00:00
|
|
|
export const DEFAULT_THEME = 'light';
|
|
|
|
|
2024-07-17 18:54:46 +00:00
|
|
|
export const themeStore = atom<Theme>(initStore());
|
|
|
|
|
|
|
|
function initStore() {
|
|
|
|
if (!import.meta.env.SSR) {
|
|
|
|
const persistedTheme = localStorage.getItem(kTheme) as Theme | undefined;
|
|
|
|
const themeAttribute = document.querySelector('html')?.getAttribute('data-theme');
|
|
|
|
|
2024-07-29 12:37:23 +00:00
|
|
|
return persistedTheme ?? (themeAttribute as Theme) ?? DEFAULT_THEME;
|
2024-07-17 18:54:46 +00:00
|
|
|
}
|
|
|
|
|
2024-07-29 12:37:23 +00:00
|
|
|
return DEFAULT_THEME;
|
2024-07-17 18:54:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function toggleTheme() {
|
|
|
|
const currentTheme = themeStore.get();
|
|
|
|
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
2025-01-30 00:58:47 +00:00
|
|
|
|
|
|
|
// Update the theme store
|
2024-07-17 18:54:46 +00:00
|
|
|
themeStore.set(newTheme);
|
2025-01-30 00:58:47 +00:00
|
|
|
|
|
|
|
// Update localStorage
|
2024-07-17 18:54:46 +00:00
|
|
|
localStorage.setItem(kTheme, newTheme);
|
2025-01-30 00:58:47 +00:00
|
|
|
|
|
|
|
// Update the HTML attribute
|
2024-07-17 18:54:46 +00:00
|
|
|
document.querySelector('html')?.setAttribute('data-theme', newTheme);
|
2025-01-30 00:58:47 +00:00
|
|
|
|
|
|
|
// Update user profile if it exists
|
|
|
|
try {
|
|
|
|
const userProfile = localStorage.getItem('bolt_user_profile');
|
|
|
|
|
|
|
|
if (userProfile) {
|
|
|
|
const profile = JSON.parse(userProfile);
|
|
|
|
profile.theme = newTheme;
|
|
|
|
localStorage.setItem('bolt_user_profile', JSON.stringify(profile));
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
console.error('Error updating user profile theme:', error);
|
|
|
|
}
|
|
|
|
|
|
|
|
logStore.logSystem(`Theme changed to ${newTheme} mode`);
|
2024-07-17 18:54:46 +00:00
|
|
|
}
|