-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathDragDropContainer.tsx
More file actions
312 lines (274 loc) · 10.2 KB
/
DragDropContainer.tsx
File metadata and controls
312 lines (274 loc) · 10.2 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import { useCallback, useEffect, useRef, useState } from 'react';
import * as ReactDOM from 'react-dom';
import { css } from '@patternfly/react-styles';
import {
DndContext,
closestCenter,
DragOverlay,
DndContextProps,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragEndEvent,
DragStartEvent,
UniqueIdentifier,
DragOverEvent,
CollisionDetection,
pointerWithin,
rectIntersection,
getFirstCollision,
DragCancelEvent
} from '@dnd-kit/core';
import { arrayMove, sortableKeyboardCoordinates } from '@dnd-kit/sortable';
import { Draggable } from './Draggable';
import { DraggableDataListItem } from './DraggableDataListItem';
import { DraggableDualListSelectorListItem } from './DraggableDualListSelectorListItem';
import styles from '@patternfly/react-styles/css/components/DragDrop/drag-drop';
import { DataList } from '@patternfly/react-core/dist/esm/components/DataList/DataList';
import { canUseDOM } from '@patternfly/react-core/dist/esm/helpers/util';
export type DragDropContainerDragStartEvent = DragStartEvent;
export type DragDropContainerDragOverEvent = DragOverEvent;
export type DragDropContainerDragEndEvent = DragEndEvent;
export type DragDropContainerDragCancelEvent = DragCancelEvent;
export interface DraggableObject {
/** Unique id of the draggable object */
id: string | number;
/** Content rendered in the draggable object */
content: React.ReactNode;
/** Props spread to the rendered wrapper of the draggable object */
props?: any;
}
/**
* DragDropSortProps extends dnd-kit's props which may be viewed at https://docs.dndkit.com/api-documentation/context-provider#props.
*/
export interface DragDropContainerProps extends DndContextProps {
/** Content containing one or more Droppable zones. */
children?: React.ReactNode;
/** Set of records of all child droppables - their zone IDs and their draggable items. */
items: Record<string, DraggableObject[]>;
/** Callback when use begins dragging a draggable object */
onDrag?: (event: DragDropContainerDragStartEvent) => void;
/** Callback when an item is dragged to another container */
onContainerMove?: (event: DragDropContainerDragOverEvent, items: Record<string, DraggableObject[]>) => void;
/** Callback when user drops a draggable object */
onDrop: (event: DragDropContainerDragEndEvent, items: Record<string, DraggableObject[]>) => void;
/** Callback when drag is cancelled */
onCancel?: (event: DragDropContainerDragCancelEvent, items: Record<string, DraggableObject[]>) => void;
/** The variant determines which component wraps the draggable object.
* Default variant wraps the draggable object in a div.
* DataList variant wraps the draggable object in a DataListItem
* DualListSelectorList variant wraps the draggable objects in a DualListSelectorListItem and a div.pf-c-dual-list-selector__item-text element
* */
variant?: 'default' | 'DataList' | 'DualListSelectorList';
/** Additional classes to apply to the drag overlay */
overlayProps?: any;
/** The parent container to append the drag overlay to. Defaults to document.body. */
appendTo?: HTMLElement | (() => HTMLElement);
}
export const DragDropContainer: React.FunctionComponent<DragDropContainerProps> = ({
children,
items,
onDrag = () => {},
onContainerMove = () => {},
onDrop = () => {},
onCancel = () => {},
variant = 'default',
overlayProps,
appendTo = () => document.body,
...props
}: DragDropContainerProps) => {
const itemsCopy = useRef<Record<string, DraggableObject[]> | null>(null);
const hasRecentlyMovedContainer = useRef(false);
const [activeId, setActiveId] = useState<UniqueIdentifier>(null);
const lastOverId = useRef<UniqueIdentifier | null>(null);
const findItem = useCallback(
(id: UniqueIdentifier, containerId: UniqueIdentifier) => items[containerId].find((item) => item.id === id),
[items]
);
const findContainer = useCallback(
(id: UniqueIdentifier) => {
if (id in items) {
return id;
}
return Object.keys(items).find((key) => items[key].find((obj) => obj.id === id));
},
[items]
);
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates
})
);
const collisionDetectionStrategy: CollisionDetection = useCallback(
(args) => {
if (activeId && activeId in items) {
return closestCenter({
...args,
droppableContainers: args.droppableContainers.filter((container) => container.id in items)
});
}
const pointerIntersections = pointerWithin(args);
const intersections = pointerIntersections.length > 0 ? pointerIntersections : rectIntersection(args);
let overId = getFirstCollision(intersections, 'id');
if (overId != null) {
if (overId in items) {
const containerItems = items[overId];
if (containerItems.length > 0) {
overId = closestCenter({
...args,
droppableContainers: args.droppableContainers.filter(
(container) => container.id !== overId && containerItems.find((obj) => obj.id === container.id)
)
})[0]?.id;
}
}
lastOverId.current = overId;
return [{ id: overId }];
}
if (hasRecentlyMovedContainer.current) {
lastOverId.current = activeId;
}
return lastOverId.current ? [{ id: lastOverId.current }] : [];
},
[activeId, items]
);
useEffect(() => {
requestAnimationFrame(() => {
hasRecentlyMovedContainer.current = false;
});
}, [items]);
const handleDragStart = (event: DragStartEvent) => {
const { active } = event;
itemsCopy.current = { ...items };
setActiveId(active.id);
onDrag(event);
};
const handleDragOver = (event: DragOverEvent) => {
const { active, over } = event;
const { id: activeId } = active;
const { id: overId } = over;
if (!overId || activeId in items) {
return;
}
const activeContainer = findContainer(activeId);
const overContainer = findContainer(overId);
if (!overContainer || !activeContainer) {
return;
}
if (activeContainer !== overContainer) {
const activeItems = items[activeContainer];
const overItems = items[overContainer];
const overIndex = overItems.findIndex((draggableItem) => draggableItem.id === overId);
const activeIndex = activeItems.findIndex((draggableItem) => draggableItem.id === activeId);
const isBelowOverItem =
over && active.rect.current.translated && active.rect.current.translated.top > over.rect.top + over.rect.height;
const modifier = isBelowOverItem ? 1 : 0;
const newIndex = overIndex >= 0 ? overIndex + modifier : overItems.length + 1;
const newItems = {
...items,
[activeContainer]: items[activeContainer].filter((item) => item.id !== active.id),
[overContainer]: [
...items[overContainer].slice(0, newIndex),
items[activeContainer][activeIndex],
...items[overContainer].slice(newIndex, items[overContainer].length)
]
};
hasRecentlyMovedContainer.current = true;
onContainerMove(event, newItems);
}
};
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
const { id: activeId } = active;
const { id: overId } = over;
const activeContainer = findContainer(activeId);
if (!over || !activeContainer) {
setActiveId(null);
return;
}
const overContainer = findContainer(overId);
if (!overContainer) {
setActiveId(null);
return;
}
const activeIndex = items[activeContainer].findIndex((draggableItem) => draggableItem.id === activeId);
const overIndex = items[overContainer].findIndex((draggableItem) => draggableItem.id === overId);
if (activeIndex !== overIndex) {
const newItems = { ...items, [overContainer]: arrayMove(items[overContainer], activeIndex, overIndex) };
onDrop(event, newItems);
}
setActiveId(null);
};
const handleDragCancel = (event: DragCancelEvent) => {
onCancel(event, itemsCopy.current);
itemsCopy.current = null;
setActiveId(null);
};
const getDragOverlay = () => {
if (!activeId) {
return;
}
const item = findItem(activeId, findContainer(activeId));
let content;
switch (variant) {
case 'DualListSelectorList':
content = (
<DraggableDualListSelectorListItem key={item.id} id={item.id} {...item.props}>
{item.content}
</DraggableDualListSelectorListItem>
);
break;
case 'DataList':
content = (
<DraggableDataListItem key={item.id} id={item.id} {...item.props}>
{item.content}
</DraggableDataListItem>
);
break;
default:
content = (
<Draggable useDragButton={variant === 'default'} key={item.id} id={item.id} {...item.props}>
{item.content}
</Draggable>
);
}
return (
<div
className={css(styles.draggable, styles.modifiers.dragging)}
style={
{
'--pf-v6-c-draggable--m-dragging--BackgroundColor':
'var(--pf-t--global--background--color--floating--default)'
} as React.CSSProperties
}
>
{variant === 'DualListSelectorList' && <ul className="pf-v6-c-dual-list-selector">{content}</ul>}
{variant === 'DataList' && (
<DataList aria-label="draggable overlay" {...overlayProps}>
{content}
</DataList>
)}
{variant !== 'DualListSelectorList' && variant !== 'DataList' && content}
</div>
);
};
const dragOverlay = <DragOverlay>{activeId && getDragOverlay()}</DragOverlay>;
const portalTarget = typeof appendTo === 'function' ? appendTo() : appendTo || document.body;
return (
<DndContext
sensors={sensors}
collisionDetection={collisionDetectionStrategy}
onDragEnd={handleDragEnd}
onDragOver={handleDragOver}
onDragStart={handleDragStart}
onDragCancel={handleDragCancel}
{...props}
>
{children}
{canUseDOM && portalTarget ? ReactDOM.createPortal(dragOverlay, portalTarget) : dragOverlay}
</DndContext>
);
};
DragDropContainer.displayName = 'DragDropContainer';