import { createContext, useContext, useRef, } from 'react' import { useStore as useZustandStore, } from 'zustand' import { createStore } from 'zustand/vanilla' import type { TFile } from './types' type Shape = { files: TFile[] setFiles: (files: TFile[]) => void } export const createFileStore = () => { return createStore(set => ({ files: [], setFiles: files => set({ files }), })) } type FileStore = ReturnType export const FileContext = createContext(null) export function useStore(selector: (state: Shape) => T): T { const store = useContext(FileContext) if (!store) throw new Error('Missing FileContext.Provider in the tree') return useZustandStore(store, selector) } export const useFileStore = () => { return useContext(FileContext)! } type FileProviderProps = { children: React.ReactNode } export const FileContextProvider = ({ children }: FileProviderProps) => { const storeRef = useRef() if (!storeRef.current) storeRef.current = createFileStore() return ( {children} ) }