2024-05-31 20:14:32 +02:00
|
|
|
import { create, StoreApi } from 'zustand';
|
2024-06-17 12:17:36 +02:00
|
|
|
import localForageLru from '@plebbit/plebbit-react-hooks/dist/lib/localforage-lru/index.js';
|
2024-05-31 20:14:32 +02:00
|
|
|
|
|
|
|
|
interface ThemeState {
|
2024-06-30 21:50:50 +02:00
|
|
|
themes: {
|
|
|
|
|
nsfw: string;
|
|
|
|
|
sfw: string;
|
|
|
|
|
all: string;
|
|
|
|
|
subscriptions: string;
|
|
|
|
|
};
|
2024-07-10 12:36:44 +02:00
|
|
|
currentTheme: string | null;
|
2024-06-30 21:50:50 +02:00
|
|
|
setTheme: (category: keyof ThemeState['themes'], theme: string) => void;
|
|
|
|
|
getTheme: (category: keyof ThemeState['themes']) => string | null;
|
2024-06-22 12:36:38 +02:00
|
|
|
loadThemes: () => Promise<void>;
|
2024-05-31 20:14:32 +02:00
|
|
|
}
|
|
|
|
|
|
2024-06-17 12:17:36 +02:00
|
|
|
const themeStore = localForageLru.createInstance({
|
|
|
|
|
name: 'themeStore',
|
|
|
|
|
size: 1000,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const useThemeStore = create<ThemeState>((set: StoreApi<ThemeState>['setState'], get: StoreApi<ThemeState>['getState']) => ({
|
2024-06-30 21:50:50 +02:00
|
|
|
themes: {
|
|
|
|
|
nsfw: 'yotsuba',
|
|
|
|
|
sfw: 'yotsuba-b',
|
|
|
|
|
all: 'yotsuba-b',
|
|
|
|
|
subscriptions: 'yotsuba-b',
|
|
|
|
|
},
|
2024-07-10 12:36:44 +02:00
|
|
|
currentTheme: null,
|
2024-06-30 21:50:50 +02:00
|
|
|
setTheme: async (category, theme) => {
|
2024-06-17 12:17:36 +02:00
|
|
|
const currentThemes = get().themes;
|
2024-06-30 21:50:50 +02:00
|
|
|
const updatedThemes = { ...currentThemes, [category]: theme };
|
|
|
|
|
await themeStore.setItem(category, theme);
|
2024-07-10 12:36:44 +02:00
|
|
|
set({ themes: updatedThemes, currentTheme: theme });
|
2024-06-17 12:17:36 +02:00
|
|
|
},
|
2024-06-30 21:50:50 +02:00
|
|
|
getTheme: (category) => {
|
2024-06-17 12:17:36 +02:00
|
|
|
const currentThemes = get().themes;
|
2024-07-10 12:36:44 +02:00
|
|
|
const theme = currentThemes[category] || null;
|
|
|
|
|
set({ currentTheme: theme });
|
|
|
|
|
return theme;
|
2024-06-17 12:17:36 +02:00
|
|
|
},
|
|
|
|
|
loadThemes: async () => {
|
2024-06-30 21:50:50 +02:00
|
|
|
const entries: [keyof ThemeState['themes'], string][] = await themeStore.entries();
|
|
|
|
|
const themes: Record<keyof ThemeState['themes'], string> = {
|
|
|
|
|
nsfw: 'yotsuba',
|
|
|
|
|
sfw: 'yotsuba-b',
|
|
|
|
|
all: 'yotsuba-b',
|
|
|
|
|
subscriptions: 'yotsuba-b',
|
|
|
|
|
};
|
2024-06-17 12:17:36 +02:00
|
|
|
entries.forEach(([key, value]) => {
|
|
|
|
|
themes[key] = value;
|
|
|
|
|
});
|
2024-07-10 12:36:44 +02:00
|
|
|
set({ themes, currentTheme: null });
|
2024-05-31 20:14:32 +02:00
|
|
|
},
|
|
|
|
|
}));
|
|
|
|
|
|
2024-06-22 12:36:38 +02:00
|
|
|
// Load themes on store initialization
|
2024-06-17 12:17:36 +02:00
|
|
|
useThemeStore.getState().loadThemes();
|
|
|
|
|
|
2024-05-31 20:14:32 +02:00
|
|
|
export default useThemeStore;
|