Cant drop external dragsource below tree
Hello, the following behaviour is, in my view, unfavourable. To move an element to the last position of the tree, you must first move the element to the penultimate position.
Is it somehow possible to change the behaviour to drag the source element to the last position in tree?
Can be reproduced on this example page: https://frontend-collective.github.io/react-sortable-tree/storybook/?selectedKind=Advanced&selectedStory=Drag%20from%20external%20source&full=0&addons=0&stories=1&panelRight=0
Oliver
Hi,
Were you able to find a solution to this issue?
Hello @CatLover94 , unfortunately not.
Anyone?
Up!, I face this issue too. In case of more complex tree data it's very uncomfortable, because hovering last element expands it and make it hard to drop new element as the last element in a tree.
What I did was have a custom drop target below the tree and on drop it updates the tree data.
But it's still a workaround and it's obvious bug, that element can't be dropped as the last element without hovering over tree. In my case it causes unwanted expand of other nodes (we are working on quite huge data trees).
I came up with a hacky solution by reworking the hover function in dnd-manager.js. It basically just detects whether the dragged item is below or above a node and adjusts the targetIndex accordingly.
hover: (dropTargetProps, monitor, component) => {
let targetIndex = 0;
const targetDepth = this.getTargetDepth(
dropTargetProps,
monitor,
component
);
const draggedNode = monitor.getItem().node;
const needsRedraw =
// Redraw if hovered above different nodes
dropTargetProps.node !== draggedNode ||
// Or hovered above the same node but at a different depth
targetDepth !== dropTargetProps.path.length - 1;
if (!needsRedraw) {
return;
}
// eslint-disable-next-line react/no-find-dom-node
const hoverBoundingRect = findDOMNode(
component
).getBoundingClientRect();
// Get vertical middle
const hoverMiddleY =
(hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
const clientOffset = monitor.getClientOffset();
// Get pixels to the top
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
// dragUp
if (hoverClientY <= hoverMiddleY) {
targetIndex = dropTargetProps.treeIndex;
}
// dragDown
if (hoverClientY >= hoverMiddleY) {
targetIndex = dropTargetProps.treeIndex + 1;
}
// throttle `dragHover` work to available animation frames
cancelAnimationFrame(this.rafId);
this.rafId = requestAnimationFrame(() => {
this.dragHover({
node: draggedNode,
path: monitor.getItem().path,
minimumTreeIndex: targetIndex,
depth: targetDepth,
});
});
},
I came up with a hacky solution by reworking the hover function in dnd-manager.js. It basically just detects whether the dragged item is below or above a node and adjusts the targetIndex accordingly.
hover: (dropTargetProps, monitor, component) => { let targetIndex = 0; const targetDepth = this.getTargetDepth( dropTargetProps, monitor, component ); const draggedNode = monitor.getItem().node; const needsRedraw = // Redraw if hovered above different nodes dropTargetProps.node !== draggedNode || // Or hovered above the same node but at a different depth targetDepth !== dropTargetProps.path.length - 1; if (!needsRedraw) { return; } // eslint-disable-next-line react/no-find-dom-node const hoverBoundingRect = findDOMNode( component ).getBoundingClientRect(); // Get vertical middle const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; const clientOffset = monitor.getClientOffset(); // Get pixels to the top const hoverClientY = clientOffset.y - hoverBoundingRect.top; // dragUp if (hoverClientY <= hoverMiddleY) { targetIndex = dropTargetProps.treeIndex; } // dragDown if (hoverClientY >= hoverMiddleY) { targetIndex = dropTargetProps.treeIndex + 1; } // throttle `dragHover` work to available animation frames cancelAnimationFrame(this.rafId); this.rafId = requestAnimationFrame(() => { this.dragHover({ node: draggedNode, path: monitor.getItem().path, minimumTreeIndex: targetIndex, depth: targetDepth, }); }); },
Amazing!!! Thank you so much for sharing this. Thank you for investigating the bug and providing a fix.
It did not work for me exactly as the code is. I removed cancelAnimationFrame and requestAnimationFrame and then it worked.
@HanaaAbbas
Awesome that it works for you. Could you point out where exactly you made these changes?
Did you patch this method? https://github.com/frontend-collective/react-sortable-tree/blob/v2.6.2/src/utils/dnd-manager.js#L227
Oliver
I made a quick and dirty workaround, this is NOT the react way to do. However I don't have much time to make a proper fix.
import { DragSource as dragSource, DropTarget as dropTarget } from 'react-dnd';
import { findDOMNode } from 'react-dom';
import { getDepth } from './tree-data-utils';
import { memoizedInsertNode } from './memoized-tree-data-utils';
export default class DndManager {
constructor(treeRef) {
this.treeRef = treeRef;
}
get startDrag() {
return this.treeRef.startDrag;
}
get dragHover() {
return this.treeRef.dragHover;
}
get endDrag() {
return this.treeRef.endDrag;
}
get drop() {
return this.treeRef.drop;
}
get treeId() {
return this.treeRef.treeId;
}
get dndType() {
return this.treeRef.dndType;
}
get treeData() {
return this.treeRef.state.draggingTreeData || this.treeRef.props.treeData;
}
get getNodeKey() {
return this.treeRef.props.getNodeKey;
}
get customCanDrop() {
return this.treeRef.props.canDrop;
}
get maxDepth() {
return this.treeRef.props.maxDepth;
}
getTargetDepth(dropTargetProps, monitor, component) {
let dropTargetDepth = 0;
const rowAbove = dropTargetProps.getPrevRow();
if (rowAbove) {
let { path } = rowAbove;
const aboveNodeCannotHaveChildren = !this.treeRef.canNodeHaveChildren(
rowAbove.node
);
if (aboveNodeCannotHaveChildren) {
path = path.slice(0, path.length - 1);
}
// Limit the length of the path to the deepest possible
dropTargetDepth = Math.min(path.length, dropTargetProps.path.length);
}
let blocksOffset;
let dragSourceInitialDepth = (monitor.getItem().path || []).length;
// When adding node from external source
if (monitor.getItem().treeId !== this.treeId) {
// Ignore the tree depth of the source, if it had any to begin with
dragSourceInitialDepth = 0;
if (component) {
const relativePosition = findDOMNode(component).getBoundingClientRect(); // eslint-disable-line react/no-find-dom-node
const leftShift =
monitor.getSourceClientOffset().x - relativePosition.left;
blocksOffset = Math.round(
leftShift / dropTargetProps.scaffoldBlockPxWidth
);
} else {
blocksOffset = dropTargetProps.path.length;
}
} else {
// handle row direction support
const direction = dropTargetProps.rowDirection === 'rtl' ? -1 : 1;
blocksOffset = Math.round(
(direction * monitor.getDifferenceFromInitialOffset().x) /
dropTargetProps.scaffoldBlockPxWidth
);
}
let targetDepth = Math.min(
dropTargetDepth,
Math.max(0, dragSourceInitialDepth + blocksOffset - 1)
);
// If a maxDepth is defined, constrain the target depth
if (typeof this.maxDepth !== 'undefined' && this.maxDepth !== null) {
const draggedNode = monitor.getItem().node;
const draggedChildDepth = getDepth(draggedNode);
targetDepth = Math.max(
0,
Math.min(targetDepth, this.maxDepth - draggedChildDepth - 1)
);
}
return targetDepth;
}
// eslint-disable-next-line class-methods-use-this
isOverLandingPad(monitor, landingPadEl) {
const landingPadRect = landingPadEl.getBoundingClientRect();
// rowWrapper padding: 10 10 10 0;
const landingPadTop = landingPadRect.top - 10;
const landingPadBottom = landingPadRect.bottom + 10;
const landingPadRight = landingPadRect.right + 10;
const landingPadLeft = landingPadRect.left;
const isOverPad =
monitor.getClientOffset().y > landingPadTop &&
monitor.getClientOffset().y < landingPadBottom &&
monitor.getClientOffset().x > landingPadLeft &&
monitor.getClientOffset().x < landingPadRight;
if (isOverPad) {
landingPadEl.classList.remove('rst__rowCancelPad');
} else if (!landingPadEl.classList.contains('rst__rowCancelPad')) {
landingPadEl.classList.add('rst__rowCancelPad');
}
return isOverPad;
}
canDrop(dropTargetProps, monitor) {
// eslint-disable-next-line react/no-find-dom-node
const landingPadEl = findDOMNode(this.treeRef)
.getElementsByClassName('rst__rowLandingPad')
.item(0);
if (landingPadEl) {
return this.isOverLandingPad(monitor, landingPadEl);
}
const rowAbove = dropTargetProps.getPrevRow();
const abovePath = rowAbove ? rowAbove.path : [];
const aboveNode = rowAbove ? rowAbove.node : {};
const targetDepth = this.getTargetDepth(dropTargetProps, monitor, null);
// Cannot drop if we're adding to the children of the row above and
// the row above is a function
if (
targetDepth >= abovePath.length &&
typeof aboveNode.children === 'function'
) {
return false;
}
if (typeof this.customCanDrop === 'function') {
const { node } = monitor.getItem();
const addedResult = memoizedInsertNode({
treeData: this.treeData,
newNode: node,
depth: targetDepth,
getNodeKey: this.getNodeKey,
minimumTreeIndex: dropTargetProps.listIndex,
expandParent: true,
});
return this.customCanDrop({
node,
prevPath: monitor.getItem().path,
prevParent: monitor.getItem().parentNode,
prevTreeIndex: monitor.getItem().treeIndex, // Equals -1 when dragged from external tree
nextPath: addedResult.path,
nextParent: addedResult.parentNode,
nextTreeIndex: addedResult.treeIndex,
});
}
return true;
}
wrapSource(el) {
const nodeDragSource = {
beginDrag: props => {
this.startDrag(props);
return {
node: props.node,
parentNode: props.parentNode,
path: props.path,
treeIndex: props.treeIndex,
treeId: props.treeId,
};
},
endDrag: (props, monitor) => {
this.endDrag(monitor.getDropResult());
},
isDragging: (props, monitor) => {
const dropTargetNode = monitor.getItem().node;
const draggedNode = props.node;
return draggedNode === dropTargetNode;
},
};
function nodeDragSourcePropInjection(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
connectDragPreview: connect.dragPreview(),
isDragging: monitor.isDragging(),
didDrop: monitor.didDrop(),
};
}
return dragSource(
this.dndType,
nodeDragSource,
nodeDragSourcePropInjection
)(el);
}
wrapTarget(el) {
const nodeDropTarget = {
drop: (dropTargetProps, monitor, component) => {
const result = {
node: monitor.getItem().node,
path: monitor.getItem().path,
treeIndex: monitor.getItem().treeIndex,
treeId: this.treeId,
minimumTreeIndex: dropTargetProps.treeIndex,
depth: this.getTargetDepth(dropTargetProps, monitor, component),
};
this.drop(result);
return result;
},
hover: (dropTargetProps, monitor, component) => {
let targetIndex = 0;
const targetDepth = this.getTargetDepth(
dropTargetProps,
monitor,
component
);
const draggedNode = monitor.getItem().node;
const needsRedraw =
// Redraw if hovered above different nodes
dropTargetProps.node !== draggedNode ||
// Or hovered above the same node but at a different depth
targetDepth !== dropTargetProps.path.length - 1;
if (!needsRedraw) {
return;
}
// eslint-disable-next-line react/no-find-dom-node
const hoverBoundingRect = findDOMNode(
component
).getBoundingClientRect();
// Get vertical middle
const hoverMiddleY =
(hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
const clientOffset = monitor.getClientOffset();
// Get pixels to the top
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
// dragUp
if (hoverClientY <= hoverMiddleY) {
targetIndex = dropTargetProps.treeIndex;
}
// dragDown
if (hoverClientY >= hoverMiddleY) {
targetIndex = dropTargetProps.treeIndex + 1;
}
// throttle `dragHover` work to available animation frames
cancelAnimationFrame(this.rafId);
this.rafId = requestAnimationFrame(() => {
this.dragHover({
node: draggedNode,
path: monitor.getItem().path,
minimumTreeIndex: targetIndex,
depth: targetDepth,
});
});
},
canDrop: this.canDrop.bind(this),
};
function nodeDropTargetPropInjection(connect, monitor) {
const dragged = monitor.getItem();
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop(),
draggedNode: dragged ? dragged.node : null,
};
}
return dropTarget(
this.dndType,
nodeDropTarget,
nodeDropTargetPropInjection
)(el);
}
wrapPlaceholder(el) {
const placeholderDropTarget = {
drop: (dropTargetProps, monitor) => {
const { node, path, treeIndex } = monitor.getItem();
const result = {
node,
path,
treeIndex,
treeId: this.treeId,
minimumTreeIndex: 0,
depth: 0,
};
this.drop(result);
return result;
},
};
function placeholderPropInjection(connect, monitor) {
const dragged = monitor.getItem();
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop(),
draggedNode: dragged ? dragged.node : null,
};
}
return dropTarget(
this.dndType,
placeholderDropTarget,
placeholderPropInjection
)(el);
}
}
I made changes to the canDrop and hover function and added isOverLandingPad.
The problem was that I couldn't figure out if the dropTarget was a landingpad or not. Maybe we could add another prop isLandingPad. The drag behaviour is acceptable for me right now. Maybe this helps to solve this issue.