-
Notifications
You must be signed in to change notification settings - Fork 389
/
restrictToParentElementWithMargins.ts
45 lines (37 loc) · 1.3 KB
/
restrictToParentElementWithMargins.ts
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
import type {ClientRect, Modifier} from '@dnd-kit/core'
import type {Transform} from '@dnd-kit/utilities'
function restrictToBoundingRect(
transform: Transform,
rect: ClientRect,
boundingRect: ClientRect,
margins: Margins
): Transform {
const value = {
...transform,
}
const marginY = margins.y || 0
const marginX = margins.x || 0
if (rect.top + value.y <= boundingRect.top + marginY) {
value.y = boundingRect.top - rect.top + marginY
} else if (rect.bottom + value.y >= boundingRect.top + boundingRect.height - marginY) {
value.y = boundingRect.top + boundingRect.height - rect.bottom - marginY
}
if (rect.left + value.x <= boundingRect.left - marginX) {
value.x = boundingRect.left - rect.left + marginX
} else if (rect.right + value.x >= boundingRect.left + boundingRect.width + marginX) {
value.x = boundingRect.left + boundingRect.width - rect.right + marginX
}
return value
}
interface Margins {
x?: number
y?: number
}
export const restrictToParentElementWithMargins: (margins: Margins) => Modifier =
(margins: Margins) =>
({containerNodeRect, draggingNodeRect, transform}) => {
if (!draggingNodeRect || !containerNodeRect) {
return transform
}
return restrictToBoundingRect(transform, draggingNodeRect, containerNodeRect, margins)
}