| 1 |
import { cloneElement, Fragment, useContext, useState } from 'react'; |
| 2 |
import { css } from '@patternfly/react-styles'; |
| 3 |
import styles from '@patternfly/react-styles/css/components/DragDrop/drag-drop'; |
| 4 |
import { DroppableContext } from './DroppableContext'; |
| 5 |
import { DragDropContext } from './DragDrop'; |
| 6 |
// import cssDraggingBackgroundColor from '@patternfly/react-tokens/dist/esm/c_draggable_m_dragging_BackgroundColor'; |
| 7 |
const cssDraggingBackgroundColor = { name: `--${styles.draggable}--m-dragging--BackgroundColor` }; |
| 8 |
|
| 9 |
export interface DraggableProps extends React.HTMLProps<HTMLDivElement> { |
| 10 |
/** Content rendered inside DragDrop */ |
| 11 |
children?: React.ReactNode; |
| 12 |
/** Don't wrap the component in a div. Requires passing a single child. */ |
| 13 |
hasNoWrapper?: boolean; |
| 14 |
/** Class to add to outer div */ |
| 15 |
className?: string; |
| 16 |
} |
| 17 |
|
| 18 |
// Browsers really like being different from each other. |
| 19 |
function getDefaultBackground() { |
| 20 |
const div = document.createElement('div'); |
| 21 |
document.head.appendChild(div); |
| 22 |
const bg = window.getComputedStyle(div).backgroundColor; |
| 23 |
document.head.removeChild(div); |
| 24 |
return bg; |
| 25 |
} |
| 26 |
|
| 27 |
function getInheritedBackgroundColor(el: HTMLElement): string { |
| 28 |
const defaultStyle = getDefaultBackground(); |
| 29 |
const backgroundColor = window.getComputedStyle(el).backgroundColor; |
| 30 |
|
| 31 |
if (backgroundColor !== defaultStyle) { |
| 32 |
return backgroundColor; |
| 33 |
} else if (!el.parentElement) { |
| 34 |
return defaultStyle; |
| 35 |
} |
| 36 |
|
| 37 |
return getInheritedBackgroundColor(el.parentElement); |
| 38 |
} |
| 39 |
|
| 40 |
function removeBlankDiv(node: HTMLElement) { |
| 41 |
if (node.getAttribute('blankDiv') === 'true') { |
| 42 |
// eslint-disable-next-line @typescript-eslint/prefer-for-of |
| 43 |
for (let i = 0; i < node.children.length; i++) { |
| 44 |
const child = node.children[i]; |
| 45 |
if (child.getAttribute('blankDiv') === 'true') { |
| 46 |
node.removeChild(child); |
| 47 |
node.setAttribute('blankDiv', 'false'); |
| 48 |
break; |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
interface DroppableItem { |
| 55 |
node: HTMLElement; |
| 56 |
rect: DOMRect; |
| 57 |
isDraggingHost: boolean; |
| 58 |
draggableNodes: HTMLElement[]; |
| 59 |
draggableNodesRects: DOMRect[]; |
| 60 |
} |
| 61 |
|
| 62 |
// Reset per-element state |
| 63 |
function resetDroppableItem(droppableItem: DroppableItem) { |
| 64 |
removeBlankDiv(droppableItem.node); |
| 65 |
droppableItem.node.classList.remove(styles.modifiers.dragging); |
| 66 |
droppableItem.node.classList.remove(styles.modifiers.dragOutside); |
| 67 |
droppableItem.draggableNodes.forEach((n, i) => { |
| 68 |
n.style.transform = ''; |
| 69 |
n.style.transition = ''; |
| 70 |
droppableItem.draggableNodesRects[i] = n.getBoundingClientRect(); |
| 71 |
}); |
| 72 |
} |
| 73 |
|
| 74 |
function overlaps(ev: MouseEvent, rect: DOMRect) { |
| 75 |
return ( |
| 76 |
ev.clientX > rect.x && ev.clientX < rect.x + rect.width && ev.clientY > rect.y && ev.clientY < rect.y + rect.height |
| 77 |
); |
| 78 |
} |
| 79 |
|
| 80 |
export const Draggable: React.FunctionComponent<DraggableProps> = ({ |
| 81 |
className, |
| 82 |
children, |
| 83 |
style: styleProp = {}, |
| 84 |
hasNoWrapper = false, |
| 85 |
...props |
| 86 |
}: DraggableProps) => { |
| 87 |
/* eslint-disable prefer-const */ |
| 88 |
let [style, setStyle] = useState(styleProp); |
| 89 |
/* eslint-enable prefer-const */ |
| 90 |
const [isDragging, setIsDragging] = useState(false); |
| 91 |
const [isValidDrag, setIsValidDrag] = useState(true); |
| 92 |
const { zone, droppableId } = useContext(DroppableContext); |
| 93 |
const { onDrag, onDragMove, onDrop } = useContext(DragDropContext); |
| 94 |
// Some state is better just to leave as vars passed around between various callbacks |
| 95 |
// You can only drag around one item at a time anyways... |
| 96 |
let startX = 0; |
| 97 |
let startY = 0; |
| 98 |
let index: number = null; // Index of this draggable |
| 99 |
let hoveringDroppable: HTMLElement; |
| 100 |
let hoveringIndex: number = null; |
| 101 |
let mouseMoveListener: EventListener; |
| 102 |
let mouseUpListener: EventListener; |
| 103 |
// Makes it so dragging the _bottom_ of the item over the halfway of another moves it |
| 104 |
let startYOffset = 0; |
| 105 |
|
| 106 |
// After item returning to where it started animation completes |
| 107 |
const onTransitionEnd = (_ev: React.TransitionEvent<HTMLElement>) => { |
| 108 |
if (isDragging) { |
| 109 |
setIsDragging(false); |
| 110 |
setStyle(styleProp); |
| 111 |
} |
| 112 |
}; |
| 113 |
|
| 114 |
function getSourceAndDest() { |
| 115 |
const hoveringDroppableId = hoveringDroppable ? hoveringDroppable.getAttribute('data-pf-droppableid') : null; |
| 116 |
const source = { |
| 117 |
droppableId, |
| 118 |
index |
| 119 |
}; |
| 120 |
const dest = |
| 121 |
hoveringDroppableId !== null |
| 122 |
? { |
| 123 |
droppableId: hoveringDroppableId, |
| 124 |
index: hoveringIndex |
| 125 |
} |
| 126 |
: undefined; |
| 127 |
return { source, dest, hoveringDroppableId }; |
| 128 |
} |
| 129 |
|
| 130 |
const onMouseUpWhileDragging = (droppableItems: DroppableItem[]) => { |
| 131 |
droppableItems.forEach(resetDroppableItem); |
| 132 |
document.removeEventListener('mousemove', mouseMoveListener); |
| 133 |
document.removeEventListener('mouseup', mouseUpListener); |
| 134 |
document.removeEventListener('contextmenu', mouseUpListener); |
| 135 |
const { source, dest, hoveringDroppableId } = getSourceAndDest(); |
| 136 |
const consumerReordered = onDrop(source, dest); |
| 137 |
if (consumerReordered && droppableId === hoveringDroppableId) { |
| 138 |
setIsDragging(false); |
| 139 |
setStyle(styleProp); |
| 140 |
} else if (!consumerReordered) { |
| 141 |
// Animate item returning to where it started |
| 142 |
setStyle({ |
| 143 |
...style, |
| 144 |
transition: 'transform 0.5s cubic-bezier(0.2, 1, 0.1, 1) 0s', |
| 145 |
transform: '', |
| 146 |
background: styleProp.background, |
| 147 |
boxShadow: styleProp.boxShadow |
| 148 |
}); |
| 149 |
} |
| 150 |
}; |
| 151 |
|
| 152 |
// This is where the magic happens |
| 153 |
const onMouseMoveWhileDragging = (ev: MouseEvent, droppableItems: DroppableItem[], blankDivRect: DOMRect) => { |
| 154 |
// Compute each time what droppable node we are hovering over |
| 155 |
hoveringDroppable = null; |
| 156 |
droppableItems.forEach((droppableItem) => { |
| 157 |
const { node, rect, isDraggingHost, draggableNodes, draggableNodesRects } = droppableItem; |
| 158 |
if (overlaps(ev, rect)) { |
| 159 |
// Add valid dropzone style |
| 160 |
node.classList.remove(styles.modifiers.dragOutside); |
| 161 |
hoveringDroppable = node; |
| 162 |
// Check if we need to add a blank div row |
| 163 |
if (node.getAttribute('blankDiv') !== 'true' && !isDraggingHost) { |
| 164 |
const blankDiv = document.createElement('div'); |
| 165 |
blankDiv.setAttribute('blankDiv', 'true'); // Makes removing easier |
| 166 |
let blankDivPos = -1; |
| 167 |
for (let i = 0; i < draggableNodes.length; i++) { |
| 168 |
const childRect = draggableNodesRects[i]; |
| 169 |
const isLast = i === draggableNodes.length - 1; |
| 170 |
const startOverlaps = childRect.y >= startY - startYOffset; |
| 171 |
if ((startOverlaps || isLast) && blankDivPos === -1) { |
| 172 |
if (isLast && !startOverlaps) { |
| 173 |
draggableNodes[i].after(blankDiv); |
| 174 |
} else { |
| 175 |
draggableNodes[i].before(blankDiv); |
| 176 |
} |
| 177 |
blankDiv.style.height = `${blankDivRect.height}px`; |
| 178 |
blankDiv.style.width = `${blankDivRect.width}px`; |
| 179 |
node.setAttribute('blankDiv', 'true'); // Makes removing easier |
| 180 |
blankDivPos = i; |
| 181 |
} |
| 182 |
if (blankDivPos !== -1) { |
| 183 |
childRect.y += blankDivRect.height; |
| 184 |
} |
| 185 |
} |
| 186 |
// Insert so drag + drop behavior matches single-list case |
| 187 |
draggableNodes.splice(blankDivPos, 0, blankDiv); |
| 188 |
draggableNodesRects.splice(blankDivPos, 0, blankDivRect); |
| 189 |
// Extend hitbox of droppable zone |
| 190 |
rect.height += blankDivRect.height; |
| 191 |
} |
| 192 |
} else { |
| 193 |
resetDroppableItem(droppableItem); |
| 194 |
node.classList.add(styles.modifiers.dragging); |
| 195 |
node.classList.add(styles.modifiers.dragOutside); |
| 196 |
} |
| 197 |
}); |
| 198 |
|
| 199 |
// Move hovering draggable and style it based on cursor position |
| 200 |
setStyle({ |
| 201 |
...style, |
| 202 |
transform: `translate(${ev.pageX - startX}px, ${ev.pageY - startY}px)` |
| 203 |
}); |
| 204 |
setIsValidDrag(Boolean(hoveringDroppable)); |
| 205 |
|
| 206 |
// Iterate through sibling draggable nodes to reposition them and store correct hoveringIndex for onDrop |
| 207 |
hoveringIndex = null; |
| 208 |
if (hoveringDroppable) { |
| 209 |
const { draggableNodes, draggableNodesRects } = droppableItems.find((item) => item.node === hoveringDroppable); |
| 210 |
let lastTranslate = 0; |
| 211 |
draggableNodes.forEach((n, i) => { |
| 212 |
n.style.transition = 'transform 0.5s cubic-bezier(0.2, 1, 0.1, 1) 0s'; |
| 213 |
const rect = draggableNodesRects[i]; |
| 214 |
const halfway = rect.y + rect.height / 2; |
| 215 |
let translateY = 0; |
| 216 |
// Use offset for more interactive translations |
| 217 |
if (startY < halfway && ev.pageY + (blankDivRect.height - startYOffset) > halfway) { |
| 218 |
translateY -= blankDivRect.height; |
| 219 |
} else if (startY >= halfway && ev.pageY - startYOffset <= halfway) { |
| 220 |
translateY += blankDivRect.height; |
| 221 |
} |
| 222 |
// Clever way to find item currently hovering over |
| 223 |
if ((translateY <= lastTranslate && translateY < 0) || (translateY > lastTranslate && translateY > 0)) { |
| 224 |
hoveringIndex = i; |
| 225 |
} |
| 226 |
n.style.transform = `translate(0, ${translateY}px`; |
| 227 |
lastTranslate = translateY; |
| 228 |
}); |
| 229 |
} |
| 230 |
|
| 231 |
const { source, dest } = getSourceAndDest(); |
| 232 |
onDragMove(source, dest); |
| 233 |
}; |
| 234 |
|
| 235 |
const onDragStart = (ev: React.DragEvent<HTMLElement>) => { |
| 236 |
// Default HTML drag and drop doesn't allow us to change what the thing |
| 237 |
// being dragged looks like. Because of this we'll use prevent the default |
| 238 |
// and use `mouseMove` and `mouseUp` instead |
| 239 |
ev.preventDefault(); |
| 240 |
if (isDragging) { |
| 241 |
// still in animation |
| 242 |
return; |
| 243 |
} |
| 244 |
|
| 245 |
// Cache droppable and draggable nodes and their bounding rects |
| 246 |
const dragging = ev.target as HTMLElement; |
| 247 |
const rect = dragging.getBoundingClientRect(); |
| 248 |
const droppableNodes = Array.from(document.querySelectorAll(`[data-pf-droppable="${zone}"]`)) as HTMLElement[]; |
| 249 |
const droppableItems = droppableNodes.reduce((acc, cur) => { |
| 250 |
cur.classList.add(styles.modifiers.dragging); |
| 251 |
const draggableNodes = Array.from(cur.querySelectorAll(`[data-pf-draggable-zone="${zone}"]`)) as HTMLElement[]; |
| 252 |
const isDraggingHost = cur.contains(dragging); |
| 253 |
if (isDraggingHost) { |
| 254 |
index = draggableNodes.indexOf(dragging); |
| 255 |
} |
| 256 |
const droppableItem = { |
| 257 |
node: cur, |
| 258 |
rect: cur.getBoundingClientRect(), |
| 259 |
isDraggingHost, |
| 260 |
// We don't want styles to apply to the left behind div in onMouseMoveWhileDragging |
| 261 |
draggableNodes: draggableNodes.map((node) => (node === dragging ? node.cloneNode(false) : node)), |
| 262 |
draggableNodesRects: draggableNodes.map((node) => node.getBoundingClientRect()) |
| 263 |
}; |
| 264 |
acc.push(droppableItem); |
| 265 |
return acc; |
| 266 |
}, []); |
| 267 |
|
| 268 |
if (!onDrag({ droppableId, index })) { |
| 269 |
// Consumer disallowed drag |
| 270 |
droppableItems.forEach((item) => resetDroppableItem(item)); |
| 271 |
return; |
| 272 |
} |
| 273 |
|
| 274 |
// Set initial style so future style mods take effect |
| 275 |
style = { |
| 276 |
...style, |
| 277 |
top: rect.y, |
| 278 |
left: rect.x, |
| 279 |
width: rect.width, |
| 280 |
height: rect.height, |
| 281 |
[cssDraggingBackgroundColor.name]: getInheritedBackgroundColor(dragging), |
| 282 |
position: 'fixed', |
| 283 |
zIndex: 5000 |
| 284 |
} as any; |
| 285 |
setStyle(style); |
| 286 |
// Store event details |
| 287 |
startX = ev.pageX; |
| 288 |
startY = ev.pageY; |
| 289 |
startYOffset = startY - rect.y; |
| 290 |
setIsDragging(true); |
| 291 |
mouseMoveListener = (ev) => onMouseMoveWhileDragging(ev as MouseEvent, droppableItems, rect); |
| 292 |
mouseUpListener = () => onMouseUpWhileDragging(droppableItems); |
| 293 |
document.addEventListener('mousemove', mouseMoveListener); |
| 294 |
document.addEventListener('mouseup', mouseUpListener); |
| 295 |
// Comment out this line to debug while dragging by right clicking |
| 296 |
// document.addEventListener('contextmenu', mouseUpListener); |
| 297 |
}; |
| 298 |
|
| 299 |
const childProps = { |
| 300 |
'data-pf-draggable-zone': isDragging ? null : zone, |
| 301 |
draggable: true, |
| 302 |
className: css( |
| 303 |
styles.draggable, |
| 304 |
isDragging && styles.modifiers.dragging, |
| 305 |
!isValidDrag && styles.modifiers.dragOutside, |
| 306 |
className |
| 307 |
), |
| 308 |
onDragStart, |
| 309 |
onTransitionEnd, |
| 310 |
style, |
| 311 |
...props |
| 312 |
}; |
| 313 |
|
| 314 |
return ( |
| 315 |
<Fragment> |
| 316 |
{/* Leave behind blank spot per-design */} |
| 317 |
{isDragging && ( |
| 318 |
<div draggable {...props} style={{ ...styleProp, visibility: 'hidden' }}> |
| 319 |
{children} |
| 320 |
</div> |
| 321 |
)} |
| 322 |
{hasNoWrapper ? ( |
| 323 |
cloneElement(children as React.ReactElement<any>, childProps) |
| 324 |
) : ( |
| 325 |
<div {...childProps}>{children}</div> |
| 326 |
)} |
| 327 |
</Fragment> |
| 328 |
); |
| 329 |
}; |
| 330 |
Draggable.displayName = 'Draggable'; |