Skip to content

Commit c7d80e3

Browse files
committed
feat(core): add clampPositionToParent util
Signed-off-by: braks <[email protected]>
1 parent e51f08c commit c7d80e3

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

packages/core/src/utils/general.ts

+16-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import type { GraphNode } from '../types'
1+
import type { Dimensions, GraphNode, XYPosition } from '../types'
2+
import { clampPosition } from './graph'
23

34
export function isMouseEvent(event: MouseEvent | TouchEvent): event is MouseEvent {
45
return 'clientX' in event
@@ -23,3 +24,17 @@ export function getNodeDimensions(node: GraphNode): { width: number; height: num
2324
height: node.dimensions?.height ?? node.height ?? 0,
2425
}
2526
}
27+
28+
export function clampPositionToParent(childPosition: XYPosition, childDimensions: Dimensions, parent: GraphNode) {
29+
const { width: parentWidth, height: parentHeight } = getNodeDimensions(parent)
30+
const { x: parentX, y: parentY } = parent.computedPosition
31+
32+
return clampPosition(
33+
childPosition,
34+
[
35+
[parentX, parentY],
36+
[parentX + parentWidth, parentY + parentHeight],
37+
],
38+
childDimensions,
39+
)
40+
}

packages/core/src/utils/graph.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,10 @@ export function clamp(val: number, min = 0, max = 1) {
4949
return Math.min(Math.max(val, min), max)
5050
}
5151

52-
export function clampPosition(position: XYPosition, extent: CoordinateExtent): XYPosition {
52+
export function clampPosition(position: XYPosition = { x: 0, y: 0 }, extent: CoordinateExtent, dimensions: Partial<Dimensions>) {
5353
return {
54-
x: clamp(position.x, extent[0][0], extent[1][0]),
55-
y: clamp(position.y, extent[0][1], extent[1][1]),
54+
x: clamp(position.x, extent[0][0], extent[1][0] - (dimensions?.width ?? 0)),
55+
y: clamp(position.y, extent[0][1], extent[1][1] - (dimensions?.height ?? 0)),
5656
}
5757
}
5858

0 commit comments

Comments
 (0)