mirror of
https://github.com/stackblitz/bolt.new
synced 2024-11-27 22:42:21 +00:00
34 lines
833 B
TypeScript
34 lines
833 B
TypeScript
|
import { atom } from 'nanostores';
|
||
|
|
||
|
export type Theme = 'dark' | 'light';
|
||
|
|
||
|
export const kTheme = 'bolt_theme';
|
||
|
|
||
|
export function themeIsDark() {
|
||
|
return themeStore.get() === 'dark';
|
||
|
}
|
||
|
|
||
|
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');
|
||
|
|
||
|
return persistedTheme ?? (themeAttribute as Theme) ?? 'light';
|
||
|
}
|
||
|
|
||
|
return 'light';
|
||
|
}
|
||
|
|
||
|
export function toggleTheme() {
|
||
|
const currentTheme = themeStore.get();
|
||
|
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
|
||
|
|
||
|
themeStore.set(newTheme);
|
||
|
|
||
|
localStorage.setItem(kTheme, newTheme);
|
||
|
|
||
|
document.querySelector('html')?.setAttribute('data-theme', newTheme);
|
||
|
}
|