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