Skip to content

Commit 4c429ec

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

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

Diff for: packages/core/src/utils/general.ts

+16
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { GraphNode, SnapGrid, XYPosition } from '../types'
22
import type { UseDragEvent } from '../composables'
3+
import type { Dimensions, GraphNode, XYPosition } from '../types'
4+
import { clampPosition } from './graph'
35

46
export function isMouseEvent(event: MouseEvent | TouchEvent): event is MouseEvent {
57
return 'clientX' in event
@@ -36,3 +38,17 @@ export function snapPosition(position: XYPosition, snapGrid: SnapGrid = [1, 1]):
3638
y: snapGrid[1] * Math.round(position.y / snapGrid[1]),
3739
}
3840
}
41+
42+
export function clampPositionToParent(childPosition: XYPosition, childDimensions: Dimensions, parent: GraphNode) {
43+
const { width: parentWidth, height: parentHeight } = getNodeDimensions(parent)
44+
const { x: parentX, y: parentY } = parent.computedPosition
45+
46+
return clampPosition(
47+
childPosition,
48+
[
49+
[parentX, parentY],
50+
[parentX + parentWidth, parentY + parentHeight],
51+
],
52+
childDimensions,
53+
)
54+
}

Diff for: 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)