2024-07-30 16:19:20 +08:00
|
|
|
import {
|
|
|
|
createContext,
|
|
|
|
useContext,
|
|
|
|
useRef,
|
|
|
|
} from 'react'
|
|
|
|
import {
|
2024-09-11 18:25:14 +08:00
|
|
|
create,
|
2024-07-30 16:19:20 +08:00
|
|
|
useStore as useZustandStore,
|
|
|
|
} from 'zustand'
|
2024-09-18 16:36:31 +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
|
|
|
}
|
|
|
|
|
2024-09-18 16:50:53 +08:00
|
|
|
export const createFileStore = (onChange?: (files: FileEntity[]) => void) => {
|
2024-09-11 18:25:14 +08:00
|
|
|
return create<Shape>(set => ({
|
2024-07-30 16:19:20 +08:00
|
|
|
files: [],
|
2024-09-11 18:25:14 +08:00
|
|
|
setFiles: (files) => {
|
|
|
|
set({ files })
|
2024-09-18 16:50:53 +08:00
|
|
|
onChange?.(files)
|
2024-09-11 18:25:14 +08:00
|
|
|
},
|
2024-07-30 16:19:20 +08:00
|
|
|
}))
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2024-09-18 16:50:53 +08:00
|
|
|
onChange?: (files: FileEntity[]) => void
|
2024-07-30 16:19:20 +08:00
|
|
|
}
|
2024-09-11 18:25:14 +08:00
|
|
|
export const FileContextProvider = ({
|
|
|
|
children,
|
2024-09-18 16:50:53 +08:00
|
|
|
onChange,
|
2024-09-11 18:25:14 +08:00
|
|
|
}: FileProviderProps) => {
|
2024-07-30 16:19:20 +08:00
|
|
|
const storeRef = useRef<FileStore>()
|
|
|
|
|
|
|
|
if (!storeRef.current)
|
2024-09-18 16:50:53 +08:00
|
|
|
storeRef.current = createFileStore(onChange)
|
2024-07-30 16:19:20 +08:00
|
|
|
|
|
|
|
return (
|
|
|
|
<FileContext.Provider value={storeRef.current}>
|
|
|
|
{children}
|
|
|
|
</FileContext.Provider>
|
|
|
|
)
|
|
|
|
}
|