-
-
Notifications
You must be signed in to change notification settings - Fork 595
/
sortableKeyboardCoordinates.ts
85 lines (71 loc) · 2.04 KB
/
sortableKeyboardCoordinates.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import {
closestCorners,
getViewRect,
KeyboardCode,
RectEntry,
KeyboardCoordinateGetter,
} from '@dnd-kit/core';
import {subtract as getCoordinatesDelta} from '@dnd-kit/utilities';
const directions: string[] = [
KeyboardCode.Down,
KeyboardCode.Right,
KeyboardCode.Up,
KeyboardCode.Left,
];
export const sortableKeyboardCoordinates: KeyboardCoordinateGetter = (
event,
{context: {translatedRect, droppableContainers}}
) => {
if (directions.includes(event.code)) {
event.preventDefault();
if (!translatedRect) {
return;
}
const layoutRects: RectEntry[] = [];
Object.entries(droppableContainers).forEach(([id, container]) => {
if (container?.disabled) {
return;
}
const node = container?.node.current;
if (!node) {
return;
}
const rect = getViewRect(node);
switch (event.code) {
case KeyboardCode.Down:
if (translatedRect.top + translatedRect.height <= rect.top) {
layoutRects.push([id, rect]);
}
break;
case KeyboardCode.Up:
if (translatedRect.top >= rect.top + rect.height) {
layoutRects.push([id, rect]);
}
break;
case KeyboardCode.Left:
if (translatedRect.left >= rect.left + rect.width) {
layoutRects.push([id, rect]);
}
break;
case KeyboardCode.Right:
if (translatedRect.left + translatedRect.width <= rect.left) {
layoutRects.push([id, rect]);
}
break;
}
});
const closestId = closestCorners(layoutRects, translatedRect);
if (closestId) {
const newNode = droppableContainers[closestId]?.node.current;
if (newNode) {
const newRect = getViewRect(newNode);
const newCoordinates = getCoordinatesDelta({
x: newRect.left - (translatedRect.width - newRect.width),
y: newRect.top - (translatedRect.height - newRect.height),
});
return newCoordinates;
}
}
}
return undefined;
};