|
1
|
import { |
|
2
|
CollisionDetection, |
|
3
|
DragEndEvent, |
|
4
|
DragOverEvent, |
|
5
|
DragStartEvent, |
|
6
|
KeyboardSensor, |
|
7
|
PointerSensor, |
|
8
|
closestCenter, |
|
9
|
pointerWithin, |
|
10
|
useSensor, |
|
11
|
useSensors, |
|
12
|
} from "@dnd-kit/core" |
|
13
|
import { arrayMove, sortableKeyboardCoordinates } from "@dnd-kit/sortable" |
|
14
|
import { Dispatch, SetStateAction, useRef, useState } from "react" |
|
15
|
import { DisplayEntry } from "../components/layout-composer/entries" |
|
16
|
import { |
|
17
|
getSectionIdFromTailId, |
|
18
|
isSectionTailId, |
|
19
|
} from "../components/layout-composer/entries" |
|
20
|
import type { LayoutPreference } from "../components/layout-composer/types" |
|
21
|
|
|
22
|
/** |
|
23
|
* Resolves the section a drop landed in. `overId` may be a section body, a |
|
24
|
* section's tail drop zone, or a specific entry. |
|
25
|
*/ |
|
26
|
function resolveOverSection( |
|
27
|
overId: string, |
|
28
|
sectionIds: Set<string>, |
|
29
|
widgetSectionMap: Record<string, string> |
|
30
|
): string | undefined { |
|
31
|
if (sectionIds.has(overId)) { |
|
32
|
return overId |
|
33
|
} |
|
34
|
if (isSectionTailId(overId)) { |
|
35
|
const sectionId = getSectionIdFromTailId(overId) |
|
36
|
return sectionIds.has(sectionId) ? sectionId : undefined |
|
37
|
} |
|
38
|
return widgetSectionMap[overId] |
|
39
|
} |
|
40
|
|
|
41
|
/** |
|
42
|
* Whether `id` targets a section container — its body or trailing drop zone — |
|
43
|
* rather than a specific entry. Used both to de-prioritize containers during |
|
44
|
* collision detection and to detect an "append to end" drop. |
|
45
|
*/ |
|
46
|
function isContainerTarget(id: string, sectionIds: Set<string>): boolean { |
|
47
|
return sectionIds.has(id) || isSectionTailId(id) |
|
48
|
} |
|
49
|
|
|
50
|
type UseLayoutDndOptions = { |
|
51
|
entriesBySection: Record<string, DisplayEntry[]> |
|
52
|
widgetSectionMap: Record<string, string> |
|
53
|
validSectionIds: Set<string> |
|
54
|
setDraft: Dispatch<SetStateAction<LayoutPreference | null>> |
|
55
|
} |
|
56
|
|
|
57
|
/** |
|
58
|
* Encapsulates the drag-and-drop behavior of the layout composer: sensors, |
|
59
|
* cursor-first collision detection, and the drag handlers that rewrite the |
|
60
|
* draft preference as entries are moved within and across sections. |
|
61
|
*/ |
|
62
|
export function useLayoutDnd({ |
|
63
|
entriesBySection, |
|
64
|
widgetSectionMap, |
|
65
|
validSectionIds, |
|
66
|
setDraft, |
|
67
|
}: UseLayoutDndOptions) { |
|
68
|
const [activeDragId, setActiveDragId] = useState<string | null>(null) |
|
69
|
// Last valid collision id during the current drag. Used to stabilize the |
|
70
|
// over-id when the cursor briefly leaves all droppables (column gutter, |
|
71
|
// padding, etc.) so the insertion slot doesn't flicker. |
|
72
|
const lastOverIdRef = useRef<string | null>(null) |
|
73
|
|
|
74
|
const sensors = useSensors( |
|
75
|
useSensor(PointerSensor), |
|
76
|
useSensor(KeyboardSensor, { |
|
77
|
coordinateGetter: sortableKeyboardCoordinates, |
|
78
|
}) |
|
79
|
) |
|
80
|
|
|
81
|
/** |
|
82
|
* Write sequential integer `order`s (0..n) for a section's entries into the |
|
83
|
* draft, pinning each to `sectionId`. Renumbering the whole section on every |
|
84
|
* move keeps orders as clean, collision-free integers. Pinning the absolute |
|
85
|
* section (rather than a delta against the natural section) means the stored |
|
86
|
* preference fully determines placement, so a later change to a widget's |
|
87
|
* registered zone can't drag a user-placed widget out from under it. |
|
88
|
*/ |
|
89
|
function reindexSection(sectionId: string, orderedWidgetIds: string[]) { |
|
90
|
setDraft((prev) => { |
|
91
|
if (!prev) { |
|
92
|
return prev |
|
93
|
} |
|
94
|
const widgets = { ...prev.widgets } |
|
95
|
orderedWidgetIds.forEach((id, index) => { |
|
96
|
widgets[id] = { ...widgets[id], section: sectionId, order: index } |
|
97
|
}) |
|
98
|
return { ...prev, widgets } |
|
99
|
}) |
|
100
|
} |
|
101
|
|
|
102
|
/** |
|
103
|
* Move a widget into `overSection`, inserting it just before `overId` — or at |
|
104
|
* the end when `overId` is the section body/tail (and thus not one of the |
|
105
|
* section's entries). |
|
106
|
*/ |
|
107
|
function moveToSection( |
|
108
|
activeWidgetId: string, |
|
109
|
overSection: string, |
|
110
|
overId: string |
|
111
|
) { |
|
112
|
const ids = (entriesBySection[overSection] ?? []).map((e) => e.widgetId) |
|
113
|
const overIndex = ids.indexOf(overId) |
|
114
|
ids.splice(overIndex === -1 ? ids.length : overIndex, 0, activeWidgetId) |
|
115
|
reindexSection(overSection, ids) |
|
116
|
} |
|
117
|
|
|
118
|
/** |
|
119
|
* Cursor-first collision detection with sticky fallback. |
|
120
|
* |
|
121
|
* 1. `pointerWithin` resolves the droppable the cursor is literally over — |
|
122
|
* immune to overlay-rect drift. |
|
123
|
* 2. If the cursor is in dead space (column gutter, padding) `pointerWithin` |
|
124
|
* returns nothing. Rather than letting `closestCenter` pick whichever |
|
125
|
* widget the overlay happens to mostly cover (which flickers with tiny |
|
126
|
* pointer movements), we reuse the last valid over-id from this drag. |
|
127
|
* 3. If we have no history yet (drag just started in dead space), fall back |
|
128
|
* to `closestCenter`. |
|
129
|
* |
|
130
|
* Section dropzones are de-prioritized in favor of widgets so the slot |
|
131
|
* anchors to a real entry whenever one is in range. |
|
132
|
*/ |
|
133
|
const collisionDetection: CollisionDetection = (args) => { |
|
134
|
// Section bodies and their tail drop zones are container targets — prefer a |
|
135
|
// real entry over them whenever one is in range so the insertion slot |
|
136
|
// anchors to a widget rather than the whole column or the end zone. |
|
137
|
const preferWidget = ( |
|
138
|
collisions: ReturnType<typeof closestCenter> |
|
139
|
): ReturnType<typeof closestCenter> => { |
|
140
|
const widget = collisions.find( |
|
141
|
(c) => !isContainerTarget(c.id as string, validSectionIds) |
|
142
|
) |
|
143
|
return widget ? [widget] : collisions |
|
144
|
} |
|
145
|
|
|
146
|
const pointer = pointerWithin(args) |
|
147
|
if (pointer.length > 0) { |
|
148
|
const chosen = preferWidget(pointer) |
|
149
|
if (chosen.length > 0) { |
|
150
|
lastOverIdRef.current = chosen[0].id as string |
|
151
|
} |
|
152
|
return chosen |
|
153
|
} |
|
154
|
|
|
155
|
if (lastOverIdRef.current !== null) { |
|
156
|
return [{ id: lastOverIdRef.current, data: { droppableContainer: null } }] |
|
157
|
} |
|
158
|
|
|
159
|
// No pointer hit and no history yet (drag just started in dead space) — |
|
160
|
// anchor to the closest entry so we still have a slot. |
|
161
|
const closest = preferWidget(closestCenter(args)) |
|
162
|
if (closest.length > 0) { |
|
163
|
lastOverIdRef.current = closest[0].id as string |
|
164
|
} |
|
165
|
return closest |
|
166
|
} |
|
167
|
|
|
168
|
/** |
|
169
|
* Resolves a drag event into the move it describes, or `null` when there's |
|
170
|
* nothing actionable: no drop target, dropped onto itself, or a target whose |
|
171
|
* section can't be resolved. Shared by the live `onDragOver` and the |
|
172
|
* `onDragEnd` fallback. |
|
173
|
*/ |
|
174
|
function resolveMove(event: DragOverEvent | DragEndEvent) { |
|
175
|
const { active, over } = event |
|
176
|
if (!over || active.id === over.id) { |
|
177
|
return null |
|
178
|
} |
|
179
|
|
|
180
|
const activeWidgetId = active.id as string |
|
181
|
const overId = over.id as string |
|
182
|
const activeSection = widgetSectionMap[activeWidgetId] |
|
183
|
const overSection = resolveOverSection( |
|
184
|
overId, |
|
185
|
validSectionIds, |
|
186
|
widgetSectionMap |
|
187
|
) |
|
188
|
if (!activeSection || !overSection) { |
|
189
|
return null |
|
190
|
} |
|
191
|
|
|
192
|
return { activeWidgetId, overId, activeSection, overSection } |
|
193
|
} |
|
194
|
|
|
195
|
function handleDragStart(event: DragStartEvent) { |
|
196
|
setActiveDragId(event.active.id as string) |
|
197
|
lastOverIdRef.current = null |
|
198
|
} |
|
199
|
|
|
200
|
/** |
|
201
|
* Fires continuously while dragging. When the cursor crosses into a |
|
202
|
* different section, we move the dragged item into that section's |
|
203
|
* `SortableContext` immediately so the items there shift to make room |
|
204
|
* *before* release. `handleDragEnd` still covers cross-section moves as a |
|
205
|
* fallback for keyboard-driven drags that never fire `onDragOver`. |
|
206
|
*/ |
|
207
|
function handleDragOver(event: DragOverEvent) { |
|
208
|
const move = resolveMove(event) |
|
209
|
if (!move || move.activeSection === move.overSection) { |
|
210
|
return |
|
211
|
} |
|
212
|
moveToSection(move.activeWidgetId, move.overSection, move.overId) |
|
213
|
} |
|
214
|
|
|
215
|
function handleDragEnd(event: DragEndEvent) { |
|
216
|
setActiveDragId(null) |
|
217
|
lastOverIdRef.current = null |
|
218
|
|
|
219
|
const move = resolveMove(event) |
|
220
|
if (!move) { |
|
221
|
return |
|
222
|
} |
|
223
|
const { activeWidgetId, overId, activeSection, overSection } = move |
|
224
|
|
|
225
|
// Cross-section moves are normally handled live by `handleDragOver`; this |
|
226
|
// covers keyboard-driven drags that never fire it. Pins the absolute |
|
227
|
// section the widget ends up in (see `moveToSection`). |
|
228
|
if (activeSection !== overSection) { |
|
229
|
moveToSection(activeWidgetId, overSection, overId) |
|
230
|
return |
|
231
|
} |
|
232
|
|
|
233
|
const ids = (entriesBySection[overSection] ?? []).map((e) => e.widgetId) |
|
234
|
const oldIndex = ids.indexOf(activeWidgetId) |
|
235
|
// Dropped on the section body/tail → move to the end; otherwise to the slot |
|
236
|
// of the entry under the cursor. |
|
237
|
const newIndex = isContainerTarget(overId, validSectionIds) |
|
238
|
? ids.length - 1 |
|
239
|
: ids.indexOf(overId) |
|
240
|
if (oldIndex === -1 || newIndex === -1) { |
|
241
|
return |
|
242
|
} |
|
243
|
|
|
244
|
reindexSection(activeSection, arrayMove(ids, oldIndex, newIndex)) |
|
245
|
} |
|
246
|
|
|
247
|
// Active drag entry, used by DragOverlay to render the moving ghost. |
|
248
|
const activeEntry = activeDragId |
|
249
|
? Object.values(entriesBySection) |
|
250
|
.flat() |
|
251
|
.find((e) => e.widgetId === activeDragId) |
|
252
|
: null |
|
253
|
|
|
254
|
return { |
|
255
|
sensors, |
|
256
|
collisionDetection, |
|
257
|
activeDragId, |
|
258
|
activeEntry, |
|
259
|
handleDragStart, |
|
260
|
handleDragOver, |
|
261
|
handleDragEnd, |
|
262
|
} |
|
263
|
} |