Files
5chan/src/stores/use-theme-store.ts
T

41 lines
1.3 KiB
TypeScript
Raw Normal View History

2024-05-31 20:14:32 +02:00
import { create, StoreApi } from 'zustand';
import localForageLru from '@plebbit/plebbit-react-hooks/dist/lib/localforage-lru/index.js';
2024-05-31 20:14:32 +02:00
interface ThemeState {
themes: Record<string, string>;
setTheme: (subplebbitAddress: string, theme: string) => void;
2024-06-17 15:39:49 +02:00
getTheme: (subplebbitAddress: string) => string | null;
loadThemes: () => void;
2024-05-31 20:14:32 +02:00
}
const themeStore = localForageLru.createInstance({
name: 'themeStore',
size: 1000,
});
const useThemeStore = create<ThemeState>((set: StoreApi<ThemeState>['setState'], get: StoreApi<ThemeState>['getState']) => ({
themes: {},
setTheme: async (subplebbitAddress: string, theme: string) => {
const currentThemes = get().themes;
const updatedThemes = { ...currentThemes, [subplebbitAddress]: theme };
await themeStore.setItem(subplebbitAddress, theme);
set({ themes: updatedThemes });
},
getTheme: (subplebbitAddress: string) => {
const currentThemes = get().themes;
2024-06-17 15:39:49 +02:00
return currentThemes[subplebbitAddress] || null;
},
loadThemes: async () => {
const entries: [string, string][] = await themeStore.entries();
const themes: Record<string, string> = {};
entries.forEach(([key, value]) => {
themes[key] = value;
});
set({ themes });
2024-05-31 20:14:32 +02:00
},
}));
useThemeStore.getState().loadThemes();
2024-05-31 20:14:32 +02:00
export default useThemeStore;