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-17 12:17:36 +02:00
|
|
|
themes: Record<string, string>;
|
|
|
|
|
setTheme: (subplebbitAddress: string, theme: string) => void;
|
2024-06-17 15:39:49 +02:00
|
|
|
getTheme: (subplebbitAddress: string) => string | null;
|
2024-06-17 12:17:36 +02:00
|
|
|
loadThemes: () => 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']) => ({
|
|
|
|
|
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;
|
2024-06-17 12:17:36 +02:00
|
|
|
},
|
|
|
|
|
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
|
|
|
},
|
|
|
|
|
}));
|
|
|
|
|
|
2024-06-17 12:17:36 +02:00
|
|
|
useThemeStore.getState().loadThemes();
|
|
|
|
|
|
2024-05-31 20:14:32 +02:00
|
|
|
export default useThemeStore;
|