|
| 1 | +import * as React from 'react'; |
| 2 | +import { useRef } from 'react'; |
| 3 | +import { findDOMNode } from 'react-dom'; |
| 4 | +import { |
| 5 | + DragSourceMonitor, |
| 6 | + DropTargetMonitor, |
| 7 | + useDrag, |
| 8 | + useDrop, |
| 9 | +} from 'react-dnd'; |
| 10 | + |
| 11 | +interface ITabProps { |
| 12 | + active?: string; |
| 13 | + content?: React.ReactNode; |
| 14 | + index?: number; |
| 15 | + id?: number | string; |
| 16 | + name?: any; |
| 17 | + moveTab: (dragIndex?: number, hoverIndex?: number | string) => void; |
| 18 | +} |
| 19 | + |
| 20 | +const WrapTabNode: React.FC<ITabProps> = (props) => { |
| 21 | + const { id, index, moveTab, children } = props; |
| 22 | + const ref = useRef<HTMLDivElement>(null); |
| 23 | + |
| 24 | + const [, drag] = useDrag({ |
| 25 | + collect: (monitor: DragSourceMonitor) => ({ |
| 26 | + isDragging: monitor.isDragging(), |
| 27 | + }), |
| 28 | + item: { type: 'DND_NODE', id, index }, |
| 29 | + }); |
| 30 | + |
| 31 | + const [, drop] = useDrop({ |
| 32 | + accept: 'DND_NODE', |
| 33 | + hover( |
| 34 | + item: { type: string; index: number }, |
| 35 | + monitor: DropTargetMonitor |
| 36 | + ) { |
| 37 | + debugger; |
| 38 | + if (!ref.current) return; |
| 39 | + let hoverIndex; |
| 40 | + const component = ref.current; |
| 41 | + const dragIndex = monitor.getItem().index; |
| 42 | + hoverIndex = index; |
| 43 | + // Don't replace items with themselves |
| 44 | + if (dragIndex === hoverIndex) { |
| 45 | + return; |
| 46 | + } |
| 47 | + const hoverBoundingRect = (findDOMNode( |
| 48 | + component |
| 49 | + ) as Element)?.getBoundingClientRect(); |
| 50 | + const hoverMiddleX = |
| 51 | + (hoverBoundingRect.right - hoverBoundingRect.left) / 2; |
| 52 | + const clientOffset = monitor.getClientOffset(); |
| 53 | + const hoverClientX = |
| 54 | + (clientOffset as { x: number; y: number }).x - |
| 55 | + hoverBoundingRect.left; |
| 56 | + // 往下拖动 |
| 57 | + if (dragIndex < hoverIndex && hoverClientX < hoverMiddleX) { |
| 58 | + return; |
| 59 | + } |
| 60 | + // 往上拖动 |
| 61 | + if (dragIndex > hoverIndex && hoverClientX > hoverMiddleX) { |
| 62 | + return; |
| 63 | + } |
| 64 | + moveTab(dragIndex, hoverIndex); |
| 65 | + monitor.getItem().index = hoverIndex; |
| 66 | + }, |
| 67 | + }); |
| 68 | + drag(drop(ref)); |
| 69 | + |
| 70 | + return <div ref={ref}>{children}</div>; |
| 71 | +}; |
| 72 | + |
| 73 | +export default WrapTabNode; |
0 commit comments