Skip to content

Commit

Permalink
feat(core): add clampPositionToParent util
Browse files Browse the repository at this point in the history
Signed-off-by: braks <[email protected]>
  • Loading branch information
bcakmakoglu committed Nov 1, 2024
1 parent e51f08c commit c7d80e3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
17 changes: 16 additions & 1 deletion packages/core/src/utils/general.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { GraphNode } from '../types'
import type { Dimensions, GraphNode, XYPosition } from '../types'
import { clampPosition } from './graph'

export function isMouseEvent(event: MouseEvent | TouchEvent): event is MouseEvent {
return 'clientX' in event
Expand All @@ -23,3 +24,17 @@ export function getNodeDimensions(node: GraphNode): { width: number; height: num
height: node.dimensions?.height ?? node.height ?? 0,
}
}

export function clampPositionToParent(childPosition: XYPosition, childDimensions: Dimensions, parent: GraphNode) {
const { width: parentWidth, height: parentHeight } = getNodeDimensions(parent)
const { x: parentX, y: parentY } = parent.computedPosition

return clampPosition(
childPosition,
[
[parentX, parentY],
[parentX + parentWidth, parentY + parentHeight],
],
childDimensions,
)
}
6 changes: 3 additions & 3 deletions packages/core/src/utils/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ export function clamp(val: number, min = 0, max = 1) {
return Math.min(Math.max(val, min), max)
}

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

Expand Down

0 comments on commit c7d80e3

Please sign in to comment.