import { createContext, type PropsWithChildren, useContext, useRef, } from 'react' import type { StoreApi } from 'zustand' import { useShallow } from 'zustand/shallow' import type { UseBoundStoreWithEqualityFn } from 'zustand/traditional' import { createSettingsStore } from './createSettingsStore.js' import type { SettingsState, SettingsStoreProviderProps } from './types.js' type SettingsStore = UseBoundStoreWithEqualityFn> const SettingsStoreContext = createContext(null) export const SettingsStoreProvider = ({ children, config, }: PropsWithChildren) => { const storeRef = useRef(null) if (!storeRef.current) { storeRef.current = createSettingsStore(config) } return ( {children} ) } export function useSettingsStoreContext() { const useStore = useContext(SettingsStoreContext) if (!useStore) { throw new Error( 'You forgot to wrap your component in SettingsStoreContext.' ) } return useStore } export function useSettingsStore(selector: (state: SettingsState) => T): T { const useStore = useSettingsStoreContext() return useStore(useShallow(selector)) }