feat(utils): add vanilla drag and panzoom (#3108)

* refactor(panzoom): create vanilla helper

* feat(svelte): add interaction example

* refactor(panzoom): cleanup

* Update function-runner.ts

* refactor(panzoom): cleanup

* refactor(panzoom): rename functions

* feat(utils): add vanilla drag helper (#3107)

* feat(utils): add vanilla drag helper

* refactor(drag): cleanup

* refactor(drag): cleanup

* chore(packages): cleanup

* refactor(panzoom): cleanup and simplify
This commit is contained in:
Moritz Klack
2023-05-31 15:55:36 +02:00
committed by GitHub
parent d8ef041737
commit 1dab08f36e
59 changed files with 3258 additions and 4313 deletions
+53 -119
View File
@@ -1,136 +1,70 @@
import { get } from 'svelte/store';
import { drag as d3Drag, type D3DragEvent, type SubjectPosition } from 'd3-drag';
import { select } from 'd3-selection';
import type { XYPosition, CoordinateExtent } from '@reactflow/system';
import { XYDrag } from '@reactflow/utils';
import { getDragItems, hasSelector, calcNextPosition } from './utils';
import type { SvelteFlowStore } from '$lib/store/types';
export type UseDragData = { dx: number; dy: number };
export type UseDragEvent = D3DragEvent<HTMLDivElement, null, SubjectPosition>;
export type NodeDragItem = {
id: string;
position: XYPosition;
positionAbsolute: XYPosition;
// distance from the mouse cursor to the node when start dragging
distance: XYPosition;
width?: number | null;
height?: number | null;
extent?: 'parent' | CoordinateExtent;
parentNode?: string;
dragging?: boolean;
};
type UseDragParams = {
store: SvelteFlowStore;
disabled?: boolean;
noDragClassName?: string;
handleSelector?: string;
nodeId?: string;
updateNodePositions: (dragItems: NodeDragItem[], d: boolean, p: boolean) => void;
nodes: SvelteFlowStore['nodes'];
transform: SvelteFlowStore['transform'];
snapGrid: SvelteFlowStore['snapGrid'];
isSelectable?: boolean;
};
export default function drag(
nodeRef: Element,
{
handleSelector,
nodeId,
updateNodePositions,
nodes,
transform: transformStore,
snapGrid: snapGridStore
}: UseDragParams
) {
let dragging = false;
let dragItems: NodeDragItem[] = [];
let lastPos: { x: number | null; y: number | null } = { x: null, y: null };
export default function drag(domNode: Element, params: UseDragParams) {
const dragInstance = XYDrag({
domNode,
getStoreItems: () => {
const { store } = params;
const snapGrid = get(store.snapGrid);
const selection = select(nodeRef);
return {
nodes: get(store.nodes),
edges: get(store.edges),
nodeExtent: get(store.nodeExtent),
snapGrid: snapGrid ? snapGrid : [0, 0],
snapToGrid: !!snapGrid,
nodeOrigin: [0, 0],
multiSelectionActive: false,
domNode: get(store.domNode),
transform: get(store.transform),
autoPanOnNodeDrag: get(store.autoPanOnNodeDrag),
nodesDraggable: get(store.nodesDraggable),
selectNodesOnDrag: get(store.selectNodesOnDrag),
unselectNodesAndEdges: store.unselectNodesAndEdges,
updateNodePositions: store.updateNodePositions,
panBy: store.panBy
};
},
onNodeClick: () => {
console.log('node click');
}
});
const getPointerPosition = ({ sourceEvent }: UseDragEvent) => {
const x = sourceEvent.touches ? sourceEvent.touches[0].clientX : sourceEvent.clientX;
const y = sourceEvent.touches ? sourceEvent.touches[0].clientY : sourceEvent.clientY;
const transform = get(transformStore);
const snapGrid = get(snapGridStore);
const pointerPos = {
x: (x - transform[0]) / transform[2],
y: (y - transform[1]) / transform[2]
};
// we need the snapped position in order to be able to skip unnecessary drag events
return {
xSnapped: snapGrid ? snapGrid[0] * Math.round(pointerPos.x / snapGrid[0]) : pointerPos.x,
ySnapped: snapGrid ? snapGrid[1] * Math.round(pointerPos.y / snapGrid[1]) : pointerPos.y,
...pointerPos
};
};
const updateNodes = ({ x, y }: XYPosition) => {
let hasChange = false;
const snapGrid = get(snapGridStore);
dragItems = dragItems.map((n) => {
const nextPosition = { x: x - n.distance.x, y: y - n.distance.y };
if (snapGrid) {
nextPosition.x = snapGrid[0] * Math.round(nextPosition.x / snapGrid[0]);
nextPosition.y = snapGrid[1] * Math.round(nextPosition.y / snapGrid[1]);
}
const updatedPos = calcNextPosition(n, nextPosition, get(nodes));
// we want to make sure that we only fire a change event when there is a changes
hasChange =
hasChange ||
n.position.x !== updatedPos.position.x ||
n.position.y !== updatedPos.position.y;
n.position = updatedPos.position;
n.positionAbsolute = updatedPos.positionAbsolute;
return n;
});
if (!hasChange) {
function updateDrag(domNode: Element, params: UseDragParams) {
if (params.disabled) {
dragInstance.destroy();
return;
}
updateNodePositions(dragItems, true, true);
dragging = true;
};
const dragHandler = d3Drag()
.on('start', (event: UseDragEvent) => {
const pointerPos = getPointerPosition(event);
lastPos = pointerPos;
dragItems = getDragItems(get(nodes), pointerPos, nodeId);
})
.on('drag', (event: UseDragEvent) => {
const pointerPos = getPointerPosition(event);
// skip events without movement
if ((lastPos.x !== pointerPos.xSnapped || lastPos.y !== pointerPos.ySnapped) && dragItems) {
lastPos = pointerPos;
updateNodes(pointerPos);
}
})
.on('end', (event: UseDragEvent) => {
dragging = false;
if (dragItems) {
updateNodePositions(dragItems, false, false);
}
})
.filter((event: MouseEvent) => {
const target = event.target as HTMLDivElement;
const isDraggable =
!event.button &&
!hasSelector(target, '.nodrag', nodeRef) &&
(!handleSelector || hasSelector(target, handleSelector, nodeRef));
return isDraggable;
dragInstance.update({
domNode,
noDragClassName: params.noDragClassName,
handleSelector: params.handleSelector,
nodeId: params.nodeId,
isSelectable: params.isSelectable
});
}
selection.call(dragHandler);
updateDrag(domNode, params);
return {
update(params: UseDragParams) {
updateDrag(domNode, params);
},
destroy() {
dragInstance.destroy();
}
};
}
@@ -1,144 +0,0 @@
import {
errorMessages,
type CoordinateExtent,
type NodeDragItem,
type NodeOrigin,
type XYPosition
} from '@reactflow/system';
import { clampPosition, devWarn, getNodePositionWithOrigin, isNumeric } from '@reactflow/utils';
import type { Node } from '$lib/types';
export function isParentSelected(node: Node, nodes: Node[]): boolean {
if (!node.parentNode) {
return false;
}
const parentNode = nodes.find((n) => n.id === node.parentNode);
if (!parentNode) {
return false;
}
if (parentNode.selected) {
return true;
}
return isParentSelected(parentNode, nodes);
}
export function hasSelector(target: Element, selector: string, domNode: Element): boolean {
let current = target;
do {
if (current?.matches(selector)) return true;
if (current === domNode) return false;
current = current.parentElement as Element;
} while (current);
return false;
}
// looks for all selected nodes and created a NodeDragItem for each of them
export function getDragItems(nodes: Node[], mousePos: XYPosition, nodeId?: string): NodeDragItem[] {
return nodes
.filter(
(n) =>
(n.selected || n.id === nodeId) &&
(n.draggable || n.draggable === undefined) &&
(!n.parentNode || !isParentSelected(n, nodes))
)
.map((n) => ({
id: n.id,
position: n.position ? { ...n.position } : { x: 0, y: 0 },
positionAbsolute: n.positionAbsolute ? { ...n.positionAbsolute } : { x: 0, y: 0 },
distance: {
x: mousePos.x - (n.positionAbsolute?.x ?? 0),
y: mousePos.y - (n.positionAbsolute?.y ?? 0)
},
delta: {
x: 0,
y: 0
},
extent: n.extent,
parentNode: n.parentNode,
width: n.width,
height: n.height
}));
}
export function calcNextPosition(
node: NodeDragItem | Node,
nextPosition: XYPosition,
nodes: Node[],
nodeExtent?: CoordinateExtent
): { position: XYPosition; positionAbsolute: XYPosition } {
let currentExtent = node.extent || nodeExtent;
if (node.extent === 'parent') {
if (node.parentNode && node.width && node.height) {
const parent = nodes.find((n) => n.id === node.parentNode);
const parentOrigin = parent?.origin || [0, 0];
const nodeOrigin = node.origin || [0, 0];
const { x: parentX, y: parentY } = getNodePositionWithOrigin(
parent,
parentOrigin
).positionAbsolute;
console.log({
parentX,
parentY,
parentW: parent?.width,
parentH: parent?.height,
nodeW: node.width,
nodeH: node.height,
parentOrigin: parentOrigin[0]
});
currentExtent =
parent &&
isNumeric(parentX) &&
isNumeric(parentY) &&
isNumeric(parent.width) &&
isNumeric(parent.height)
? [
[parentX + node.width * nodeOrigin[0], parentY + node.height * nodeOrigin[1]],
[
parentX + parent.width - node.width + node.width * nodeOrigin[0],
parentY + parent.height - node.height + node.height * nodeOrigin[1]
]
]
: currentExtent;
} else {
devWarn('005', errorMessages['error005']());
currentExtent = nodeExtent;
}
} else if (node.extent && node.parentNode) {
const parent = nodes.find((n) => n.id === node.parentNode);
const { x: parentX, y: parentY } = getNodePositionWithOrigin(
parent,
parent?.origin || [0, 0]
).positionAbsolute;
currentExtent = [
[node.extent[0][0] + parentX, node.extent[0][1] + parentY],
[node.extent[1][0] + parentX, node.extent[1][1] + parentY]
];
}
let parentPosition = { x: 0, y: 0 };
if (node.parentNode) {
const parent = nodes.find((n) => n.id === node.parentNode);
parentPosition = getNodePositionWithOrigin(parent, parent?.origin || [0, 0]).positionAbsolute;
}
const positionAbsolute = currentExtent
? clampPosition(nextPosition, currentExtent as CoordinateExtent)
: nextPosition;
return {
position: {
x: positionAbsolute.x - parentPosition.x,
y: positionAbsolute.y - parentPosition.y
},
positionAbsolute
};
}