Skip to content

Commit

Permalink
fix default theme selection
Browse files Browse the repository at this point in the history
  • Loading branch information
Abdenasser committed Nov 9, 2024
1 parent 250eb37 commit a4f2a5e
Showing 1 changed file with 26 additions and 12 deletions.
38 changes: 26 additions & 12 deletions src/lib/stores/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,49 @@ import { writable } from 'svelte/store';
import { themes, type Theme } from '$lib/styles';

function createThemeStore() {
// Get initial theme from localStorage or default to catppuccin
const storedTheme = typeof window !== 'undefined'
? localStorage.getItem('theme')
: 'catppuccin';

const { subscribe, set } = writable<Theme>(themes[storedTheme || 'catppuccin']);
// Default theme
const defaultTheme = themes.catppuccin;

// Initialize with default theme
const { subscribe, set } = writable<Theme>(defaultTheme);

// Initialize theme on client-side only
if (typeof window !== 'undefined') {
const storedTheme = localStorage.getItem('theme');
if (storedTheme && themes[storedTheme]) {
set(themes[storedTheme]);
}
}

return {
subscribe,
setTheme: (themeName: string) => {
const theme = themes[themeName];
if (theme) {
localStorage.setItem('theme', themeName);
if (typeof window !== 'undefined') {
localStorage.setItem('theme', themeName);
}
set(theme);
applyTheme(theme);
}
},
init: () => {
const theme = themes[storedTheme || 'catppuccin'];
const storedTheme = typeof window !== 'undefined'
? localStorage.getItem('theme')
: null;
const theme = (storedTheme && themes[storedTheme]) || defaultTheme;
applyTheme(theme);
}
};
}

function applyTheme(theme: Theme) {
const root = document.documentElement;
Object.entries(theme.colors).forEach(([key, value]) => {
root.style.setProperty(`--${key}`, value);
});
if (typeof window !== 'undefined') {
const root = document.documentElement;
Object.entries(theme.colors).forEach(([key, value]) => {
root.style.setProperty(`--${key}`, value);
});
}
}

export const themeStore = createThemeStore();

0 comments on commit a4f2a5e

Please sign in to comment.