|
| 1 | +import { createContext, useContext, useRef } from "react"; |
| 2 | +import { createStore, StoreApi, useStore } from "zustand"; |
| 3 | +import { |
| 4 | + generateThemeBrowserStore, |
| 5 | + IThemeBrowserStore, |
| 6 | + ThemeBrowserStoreActions, |
| 7 | + ThemeBrowserStoreValues, |
| 8 | +} from "./theme-browser-store-factory"; |
| 9 | + |
| 10 | +const ThemeBrowserPersistenceStore = createStore< |
| 11 | + Record<string, StoreApi<IThemeBrowserStore> | undefined> |
| 12 | +>(() => ({})); |
| 13 | + |
| 14 | +const ThemeBrowserStoreContext = createContext<StoreApi<IThemeBrowserStore> | null>(null); |
| 15 | + |
| 16 | +export function ThemeBrowserStoreProvider({ |
| 17 | + pageId, |
| 18 | + children, |
| 19 | + filterPath, |
| 20 | + themePath, |
| 21 | + themeType, |
| 22 | + requiresAuth = false, |
| 23 | +}: { |
| 24 | + pageId: string; |
| 25 | + children: React.ReactNode; |
| 26 | + filterPath: string; |
| 27 | + themePath: string; |
| 28 | + themeType: "ALL" | "DESKTOP" | "BPM"; |
| 29 | + requiresAuth?: boolean; |
| 30 | +}) { |
| 31 | + const storeRef = useRef<StoreApi<IThemeBrowserStore> | null>(null); |
| 32 | + |
| 33 | + if (!storeRef.current) { |
| 34 | + let store: StoreApi<IThemeBrowserStore>; |
| 35 | + const existingStore = ThemeBrowserPersistenceStore.getState()[pageId]; |
| 36 | + |
| 37 | + if (existingStore) { |
| 38 | + store = existingStore; |
| 39 | + } else { |
| 40 | + store = generateThemeBrowserStore({ |
| 41 | + filterPath, |
| 42 | + themePath, |
| 43 | + themeType, |
| 44 | + requiresAuth, |
| 45 | + }); |
| 46 | + ThemeBrowserPersistenceStore.setState((state) => ({ |
| 47 | + ...state, |
| 48 | + [pageId]: store, |
| 49 | + })); |
| 50 | + } |
| 51 | + |
| 52 | + storeRef.current = store; |
| 53 | + } |
| 54 | + |
| 55 | + return ( |
| 56 | + <ThemeBrowserStoreContext.Provider value={storeRef.current}> |
| 57 | + {children} |
| 58 | + </ThemeBrowserStoreContext.Provider> |
| 59 | + ); |
| 60 | +} |
| 61 | + |
| 62 | +export const useThemeBrowserStore = <T,>(selector: (state: IThemeBrowserStore) => T) => { |
| 63 | + const store = useContext(ThemeBrowserStoreContext); |
| 64 | + if (!store) { |
| 65 | + throw new Error("Missing StoreProvider"); |
| 66 | + } |
| 67 | + return useStore(store, selector); |
| 68 | +}; |
| 69 | +export const useThemeBrowserStoreValue = <T extends keyof ThemeBrowserStoreValues>( |
| 70 | + key: T |
| 71 | +): IThemeBrowserStore[T] => useThemeBrowserStore((state) => state[key]); |
| 72 | + |
| 73 | +export const useThemeBrowserStoreAction = <T extends keyof ThemeBrowserStoreActions>( |
| 74 | + key: T |
| 75 | +): IThemeBrowserStore[T] => useThemeBrowserStore((state) => state[key]); |
0 commit comments