Canceling drag operation when using the closest center/corners collision detection #210
-
Is there a way to cancel drag operations when using this strategy? As far as I can see in the examples, How about introducing something like a max distance parameter to tell the algorithm to ignore the droppable if it's not close enough to the dragged element? I apologize if I've missed something, but couldn't find a way to achieve this with the existing API. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You can always "cancel" drag operations by not handling the As for collision detection, you can fork the import {min} from 'lodash';
import type {Coordinates, CollisionDetection, LayoutRect} from '@dnd-kit/core';
/**
* Returns the distance between two points
*/
function distanceBetween(p1: Coordinates, p2: Coordinates) {
return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
}
/**
* Returns the coordinates of the center of a given ClientRect
*/
function centerOfRectangle(
rect: LayoutRect,
left = rect.offsetLeft,
top = rect.offsetTop
): Coordinates {
return {
x: left + rect.width * 0.5,
y: top + rect.height * 0.5,
};
}
const MAX_DISTANCE = 200;
const customClosestCenter: CollisionDetection = (rects, rect) => {
const centerRect = centerOfRectangle(rect, rect.left, rect.top);
const distances = rects.reduce((acc, [_, rect]) => {
const distance = distanceBetween(centerOfRectangle(rect), centerRect);
// Do not match droppable if distance is greater than MAX_DISTANCE
return distance > MAX_DISTANCE ? acc : [...acc, distance];
}, []);
const minValue = min(distances);
const minValueIndex = distances.indexOf(minValue);
return rects[minValueIndex] ? rects[minValueIndex][0] : null;
}; |
Beta Was this translation helpful? Give feedback.
You can always "cancel" drag operations by not handling the
onDragEnd
event for a given operation.As for collision detection, you can fork the
closestCenter
collision detection and create your own custom collision detection algorithm that does not match droppables if they are further than a certain distance: