From 87102eb8c24bc7e21fa7aeaaf0dfa47ba2363967 Mon Sep 17 00:00:00 2001 From: braks <78412429+bcakmakoglu@users.noreply.github.com> Date: Wed, 14 Sep 2022 19:58:13 +0200 Subject: [PATCH] fix(nodes): align snap grid to 0,0 --- packages/vue-flow/src/composables/useDrag.ts | 13 +++++++++++-- packages/vue-flow/src/utils/drag.ts | 9 ++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/packages/vue-flow/src/composables/useDrag.ts b/packages/vue-flow/src/composables/useDrag.ts index 2b4865d5..7541d1d2 100644 --- a/packages/vue-flow/src/composables/useDrag.ts +++ b/packages/vue-flow/src/composables/useDrag.ts @@ -97,13 +97,22 @@ function useDrag(params: UseDragParams) { } }) .on('drag', (event: UseDragEvent) => { - const mousePos = getMousePosition(event, hasSnapGrid(node?.snapGrid) as SnapGrid) + const snapGrid = hasSnapGrid(node?.snapGrid) as SnapGrid + + const mousePos = getMousePosition(event, snapGrid) // skip events without movement if ((lastPos.x !== mousePos.x || lastPos.y !== mousePos.y) && dragItems) { lastPos = mousePos dragItems = dragItems.map((n) => - updatePosition(n, mousePos, n.parentNode ? getNode(n.parentNode) : undefined, nodeExtent), + updatePosition( + n, + mousePos, + !!snapGrid ?? snapToGrid, + snapGrid ?? globalSnapGrid, + n.parentNode ? getNode(n.parentNode) : undefined, + nodeExtent, + ), ) updateNodePositions(dragItems, true, true) diff --git a/packages/vue-flow/src/utils/drag.ts b/packages/vue-flow/src/utils/drag.ts index 78620fc4..ba179fea 100644 --- a/packages/vue-flow/src/utils/drag.ts +++ b/packages/vue-flow/src/utils/drag.ts @@ -1,6 +1,6 @@ import type { Ref } from 'vue' import { clampPosition, isParentSelected } from './graph' -import type { ComputedGetters, CoordinateExtent, Getters, GraphNode, NodeDragItem, XYPosition } from '~/types' +import type { ComputedGetters, CoordinateExtent, Getters, GraphNode, NodeDragItem, SnapGrid, XYPosition } from '~/types' export function hasSelector(target: Element, selector: string, node: Ref): boolean { let current = target @@ -59,10 +59,17 @@ export function getEventHandlerParams({ export function updatePosition( dragItem: NodeDragItem, mousePos: XYPosition, + snapToGrid?: boolean, + snapGrid?: SnapGrid, parent?: GraphNode, nodeExtent?: CoordinateExtent, ): NodeDragItem { const nextPosition = { x: mousePos.x - dragItem.distance.x, y: mousePos.y - dragItem.distance.y } + if (snapToGrid && snapGrid) { + const [snapX, snapY] = snapGrid + nextPosition.x = snapX * Math.round(nextPosition.x / snapX) + nextPosition.y = snapY * Math.round(nextPosition.y / snapY) + } const currentExtent = applyExtent(dragItem, nodeExtent, parent)