forked from Shopify/draggable
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Sortable.ts
314 lines (258 loc) · 8.31 KB
/
Sortable.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
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
313
314
import Draggable, {
DragOverContainerEvent,
DragOverEvent,
DragStartEvent,
DragStopEvent,
DraggableOptions,
} from '../Draggable';
import { DraggableEmitterMap } from '../Draggable/Draggable';
import {
SortableStartEvent,
SortableSortEvent,
SortableSortedEvent,
SortableStopEvent,
SortableEvent,
SortableEventMap,
} from './SortableEvent';
const onDragStart = Symbol('onDragStart');
const onDragOverContainer = Symbol('onDragOverContainer');
const onDragOver = Symbol('onDragOver');
const onDragStop = Symbol('onDragStop');
/**
* Returns announcement message when a Draggable element has been sorted with another Draggable element
* or moved into a new container
*/
const onSortableSortedDefaultAnnouncement = ({
dragEvent,
}: SortableSortedEvent) => {
const sourceText =
dragEvent.source.textContent?.trim() ??
dragEvent.source.id ??
'sortable element';
if (dragEvent.over) {
const overText =
dragEvent.over.textContent?.trim() ??
dragEvent.over.id ??
'sortable element';
const isFollowing =
dragEvent.source.compareDocumentPosition(dragEvent.over) &
Node.DOCUMENT_POSITION_FOLLOWING;
if (isFollowing) return `Placed ${sourceText} after ${overText}`;
else return `Placed ${sourceText} before ${overText}`;
} else {
// need to figure out how to compute container name
return `Placed ${sourceText} into a different container`;
}
};
const index = (element: HTMLElement) =>
Array.prototype.indexOf.call(element.parentElement?.children, element);
const moveInsideEmptyContainer = (
source: HTMLElement,
overContainer: HTMLElement
) => {
const oldContainer = source.parentElement;
overContainer.appendChild(source);
return { oldContainer, newContainer: overContainer };
};
const moveWithinContainer = (source: HTMLElement, over: HTMLElement) => {
const oldIndex = index(source);
const newIndex = index(over);
if (oldIndex < newIndex)
source.parentElement?.insertBefore(source, over.nextElementSibling);
else source.parentElement?.insertBefore(source, over);
return {
oldContainer: source.parentElement,
newContainer: source.parentElement,
};
};
const moveOutsideContainer = (
source: HTMLElement,
over: HTMLElement,
overContainer: HTMLElement
) => {
const oldContainer = source.parentElement;
if (over) over.parentElement?.insertBefore(source, over);
else overContainer.appendChild(source);
return { oldContainer, newContainer: source.parentElement };
};
const move = ({
source,
over,
overContainer,
children,
}: {
source: HTMLElement;
over: HTMLElement;
overContainer: HTMLElement;
children: HTMLElement[];
}) => {
const emptyOverContainer = !children.length;
const differentContainer = source.parentElement !== overContainer;
const sameContainer = over && source.parentElement === over.parentElement;
if (emptyOverContainer)
return moveInsideEmptyContainer(source, overContainer);
else if (sameContainer) return moveWithinContainer(source, over);
else if (differentContainer)
return moveOutsideContainer(source, over, overContainer);
else return null;
};
const defaultAnnouncements = {
'sortable:sorted': onSortableSortedDefaultAnnouncement,
};
interface SortableOptions extends Omit<DraggableOptions, 'announcements'> {
announcements: Record<
string,
(event: SortableEvent | CustomEvent) => unknown
>;
}
export interface SortableEmitterMap
extends DraggableEmitterMap,
SortableEventMap {}
/**
* Sortable is built on top of Draggable and allows sorting of draggable elements. Sortable will keep
* track of the original index and emits the new index as you drag over draggable elements.
*/
export default class Sortable extends Draggable {
startIndex: number | null;
startContainer: HTMLElement | null;
declare on: <
K extends keyof SortableEmitterMap,
E extends SortableEmitterMap[K]
>(
type: K,
...callbacks: Array<(event: E) => void>
) => this;
declare off: <
K extends keyof SortableEmitterMap,
E extends SortableEmitterMap[K]
>(
type: K,
callback: (event: E) => void
) => this;
constructor(
containers: NodeList | HTMLElement[] | HTMLElement = [document.body],
options: Partial<SortableOptions> = {}
) {
super(containers, {
...options,
announcements: {
...defaultAnnouncements,
...(options.announcements ?? {}),
},
});
this.on('drag:start', this[onDragStart])
.on('drag:over:container', this[onDragOverContainer])
.on('drag:over', this[onDragOver])
.on('drag:stop', this[onDragStop]);
}
/**
* Destroys Sortable instance.
*/
destroy() {
super.destroy();
this.off('drag:start', this[onDragStart])
.off('drag:over:container', this[onDragOverContainer])
.off('drag:over', this[onDragOver])
.off('drag:stop', this[onDragStop]);
}
/**
* Returns true index of element within its container during drag operation, i.e. excluding mirror and original source
*/
index(element: HTMLElement): number {
return this.getSortableElementsForContainer(element.parentElement).indexOf(
element
);
}
/**
* Returns sortable elements for a given container, excluding the mirror and
* original source element if present
*/
getSortableElementsForContainer(container: HTMLElement): HTMLElement[] {
const allSortableElements = <HTMLElement[]>[
...container.querySelectorAll(this.options.draggable),
];
return [...allSortableElements].filter(
(childElement) =>
childElement !== this.originalSource &&
childElement !== this.mirror &&
childElement.parentElement === container
);
}
private [onDragStart] = (event: DragStartEvent) => {
this.startContainer = event.source.parentElement;
this.startIndex = this.index(event.source);
const sortableStartEvent = new SortableStartEvent({
dragEvent: event,
startIndex: this.startIndex,
startContainer: this.startContainer,
});
this.trigger(sortableStartEvent);
if (sortableStartEvent.defaultPrevented) event.preventDefault();
};
private [onDragOverContainer] = (event: DragOverContainerEvent) => {
if (event.defaultPrevented) return;
const { source, overContainer } = event;
const oldIndex = this.index(source);
const sortableSortEvent = new SortableSortEvent({
dragEvent: event,
currentIndex: oldIndex,
source,
overContainer: event.overContainer,
});
this.trigger(sortableSortEvent);
if (sortableSortEvent.defaultPrevented) return;
const children = this.getSortableElementsForContainer(overContainer);
const moves = move({ source, over: event.over, overContainer, children });
if (!moves) return;
const { oldContainer, newContainer } = moves;
const newIndex = this.index(event.source);
const sortableSortedEvent = new SortableSortedEvent({
dragEvent: event,
oldIndex,
newIndex,
oldContainer,
newContainer,
});
this.trigger(sortableSortedEvent);
};
private [onDragOver] = (event: DragOverEvent) => {
if (event.over === event.originalSource || event.over === event.source)
return;
const { source, over, overContainer } = event;
const oldIndex = this.index(source);
const sortableSortEvent = new SortableSortEvent({
dragEvent: event,
currentIndex: oldIndex,
overContainer,
over,
source,
});
this.trigger(sortableSortEvent);
if (sortableSortEvent.defaultPrevented) return;
const children = this.getDraggableElementsForContainer(overContainer);
const moves = move({ source, over, overContainer, children });
if (!moves) return;
const { oldContainer, newContainer } = moves;
const newIndex = this.index(source);
const sortableSortedEvent = new SortableSortedEvent({
dragEvent: event,
oldIndex,
newIndex,
oldContainer,
newContainer,
});
this.trigger(sortableSortedEvent);
};
private [onDragStop] = (event: DragStopEvent) => {
const sortableStopEvent = new SortableStopEvent({
dragEvent: event,
oldIndex: this.startIndex,
newIndex: this.index(event.source),
oldContainer: this.startContainer,
newContainer: event.source.parentElement,
});
this.trigger(sortableStopEvent);
this.startIndex = null;
this.startContainer = null;
};
}