|
| 1 | +import { createContext, ReactElement, useRef, FC } from 'react'; |
| 2 | +import type { DraggableGroupProps } from './draggable.types'; |
| 3 | + |
| 4 | +const defaultProps = {} satisfies Partial<DraggableGroupProps>; |
| 5 | + |
| 6 | +/** |
| 7 | + * 在 dragstart 里生产,在 dragenter 消费,在 drop | dragend 销毁 |
| 8 | + */ |
| 9 | +export interface DraggableGroupContextProvider { |
| 10 | + readonly children: ReactElement; |
| 11 | + cancel?: (id: symbol) => void; |
| 12 | + enter?: (id: symbol) => void; |
| 13 | + drop?: (id: symbol) => void; |
| 14 | + readonly item: unknown; |
| 15 | + id: symbol; |
| 16 | +} |
| 17 | +export const draggableContext = createContext<{ |
| 18 | + fromRef: { current: DraggableGroupContextProvider | null }; |
| 19 | + toRef: { current: DraggableGroupContextProvider | null }; |
| 20 | + type: Exclude<DraggableGroupProps['type'], undefined>; |
| 21 | +}>({ |
| 22 | + fromRef: { current: null }, |
| 23 | + toRef: { current: null }, |
| 24 | + type: 'move', |
| 25 | +}); |
| 26 | + |
| 27 | +export const DraggableGroup: FC<DraggableGroupProps> = (props) => { |
| 28 | + const fromRef = useRef(null); |
| 29 | + const toRef = useRef(null); |
| 30 | + return ( |
| 31 | + <draggableContext.Provider |
| 32 | + value={{ |
| 33 | + type: props.type || 'move', |
| 34 | + fromRef, |
| 35 | + toRef, |
| 36 | + }} |
| 37 | + > |
| 38 | + {props.children} |
| 39 | + </draggableContext.Provider> |
| 40 | + ); |
| 41 | +}; |
| 42 | + |
| 43 | +DraggableGroup.defaultProps = defaultProps; |
| 44 | +DraggableGroup.displayName = 'DraggableGroup'; |
0 commit comments