-
Notifications
You must be signed in to change notification settings - Fork 45
/
useBorderChange.tsx
50 lines (46 loc) · 2.1 KB
/
useBorderChange.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*******************************************************************************
* Copyright (c) 2023 Obeo.
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
import { useCallback } from 'react';
import { Node, NodeChange, useReactFlow, XYPosition } from 'reactflow';
import { UseBorderChangeValue } from './useBorderChange.types';
const isNewPositionInsideIsParent = (newNodePosition: XYPosition, movedNode: Node, parentNode: Node): boolean => {
if (movedNode.width && movedNode.height && parentNode?.positionAbsolute && parentNode.width && parentNode.height) {
return (
parentNode.positionAbsolute.x < newNodePosition.x + movedNode.width &&
parentNode.positionAbsolute.x + parentNode.width > newNodePosition.x &&
parentNode.positionAbsolute.y < newNodePosition.y + movedNode.height &&
parentNode.positionAbsolute.y + parentNode.height > newNodePosition.y
);
}
return false;
};
export const useBorderChange = (): UseBorderChangeValue => {
const { getNodes } = useReactFlow();
const onBorderChange = useCallback((changes: NodeChange[]): NodeChange[] => {
return changes.map((change) => {
if (change.type === 'position' && change.positionAbsolute) {
const movedNode = getNodes().find((node) => change.id === node.id);
if (movedNode?.data.isBorderNode) {
const parentNode = getNodes().find((node) => movedNode?.parentNode === node.id);
if (parentNode && isNewPositionInsideIsParent(change.positionAbsolute, movedNode, parentNode)) {
//Invalid position, reset to the initial one
change.position = movedNode.position;
change.positionAbsolute = movedNode.positionAbsolute;
}
}
}
return change;
});
}, []);
return { onBorderChange };
};