dify/web/app/components/base/file-uploader/store.tsx

54 lines
1.2 KiB
TypeScript
Raw Normal View History

2024-07-30 16:19:20 +08:00
import {
createContext,
useContext,
useRef,
} from 'react'
import {
useStore as useZustandStore,
} from 'zustand'
import { createStore } from 'zustand/vanilla'
2024-09-10 14:17:29 +08:00
import type { FileEntity } from './types'
2024-07-30 16:19:20 +08:00
type Shape = {
2024-09-10 14:17:29 +08:00
files: FileEntity[]
setFiles: (files: FileEntity[]) => void
2024-07-30 16:19:20 +08:00
}
export const createFileStore = () => {
return createStore<Shape>(set => ({
files: [],
setFiles: files => set({ files }),
}))
}
type FileStore = ReturnType<typeof createFileStore>
export const FileContext = createContext<FileStore | null>(null)
export function useStore<T>(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<FileStore>()
if (!storeRef.current)
storeRef.current = createFileStore()
return (
<FileContext.Provider value={storeRef.current}>
{children}
</FileContext.Provider>
)
}