-
Notifications
You must be signed in to change notification settings - Fork 0
/
draggable.directive.ts
300 lines (261 loc) · 9.13 KB
/
draggable.directive.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
import {
Directive,
ElementRef,
EmbeddedViewRef,
EventEmitter,
HostListener,
Input,
OnDestroy,
Output,
Renderer2,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
export type ListDragReordering = { oldIndex: number; newIndex: number };
@Directive({
selector: '[appDraggable]',
standalone: true,
})
export class appDraggableDirective implements OnDestroy {
private isDragging: boolean = false;
private initialX: number = 0;
private initialY: number = 0;
private initialWidth!: CSSStyleDeclaration;
private prevX: number = 0;
private prevY: number = 0;
private rowPlaceholderViewRef: EmbeddedViewRef<HTMLElement> | null = null;
private rowPlaceholderElement!: HTMLElement | null;
private oldIndex: number = -1;
private mouseMoveListener!:
| undefined
| OmitThisParameter<(event: MouseEvent) => void>;
@Input() blockedAxis!: 'x' | 'y' | undefined;
@Input() zIndex!: number;
@Input() dragBy!: string;
@Input() rowPlaceholder!: TemplateRef<HTMLElement>;
@Output() changeCurrentElIndex: EventEmitter<{
oldIndex: number;
newIndex: number;
}> = new EventEmitter<ListDragReordering>();
constructor(
private elementRef: ElementRef,
private renderer: Renderer2,
private viewContainerRef: ViewContainerRef
) {
this.initialX = this.elementRef.nativeElement.offsetLeft;
this.initialY = this.elementRef.nativeElement.offsetTop;
this.initialWidth = window.getComputedStyle(this.elementRef.nativeElement);
this.mouseMoveListener = this.onMouseMove.bind(this); // Bound method for proper removal
}
ngOnDestroy(): void {
this.cleanupListeners();
}
@HostListener('mousedown', ['$event'])
onMouseDown(event: MouseEvent) {
let dragHandler: HTMLElement | null = null;
if (this.dragBy) {
dragHandler = this.elementRef.nativeElement.querySelector(
`.${this.dragBy}`
);
}
// Check if the mousedown event occurred on the drag handle, or on the element itself if no handle is specified
if (
!this.dragBy ||
(dragHandler && dragHandler.contains(event.target as Node))
) {
// Reset styles and position before starting new drag
this.renderer.removeAttribute(this.elementRef.nativeElement, 'style');
this.renderer.removeClass(
this.elementRef.nativeElement,
'app-draggable-dragging'
);
this.isDragging = true;
this.initialX = event.clientX + window.scrollX;
this.initialY = event.clientY + window.scrollY;
this.prevX = this.initialX;
this.prevY = this.initialY;
this.renderer.setStyle(
this.elementRef.nativeElement,
'width',
this.initialWidth
);
this.renderer.setStyle(
this.elementRef.nativeElement,
'position',
'fixed'
);
this.renderer.setStyle(this.elementRef.nativeElement, 'z-index', '11');
this.renderer.setStyle(
this.elementRef.nativeElement,
'cursor',
'grabbing'
);
this.renderer.setStyle(
this.elementRef.nativeElement,
'transition',
'top left .15s ease-in'
);
this.renderer.setStyle(
this.elementRef.nativeElement,
'user-select',
'none'
);
this.renderer.addClass(
this.elementRef.nativeElement,
'app-draggable-dragging'
);
// Create placeholder element
if (this.rowPlaceholder) {
this.createRowPlaceholderElement(this.rowPlaceholder);
}
}
}
@HostListener('document:mouseup')
onMouseUp() {
if (this.isDragging) {
this.isDragging = false;
this.cleanupListeners();
// Remove all styles from the draggable element
this.renderer.removeAttribute(this.elementRef.nativeElement, 'style');
this.renderer.removeClass(
this.elementRef.nativeElement,
'app-draggable-dragging'
);
// Set initial values
this.initialX = this.elementRef.nativeElement.offsetLeft;
this.initialY = this.elementRef.nativeElement.offsetTop;
// Remove placeholder elements
this.removeRowPlaceholderElement();
this.removeRowPlaceholderElement();
// Emit the old and new indexes
this.changeCurrentElIndex.emit({
oldIndex: this.oldIndex,
newIndex: this.elementRef.nativeElement.oldIndex,
});
}
}
@HostListener('document:mousemove', ['$event'])
onMouseMove(event: MouseEvent) {
if (this.isDragging) {
const offsetX = event.clientX - this.prevX;
const offsetY = event.clientY - this.prevY;
const newLeft = this.elementRef.nativeElement.offsetLeft + offsetX;
const newTop = this.elementRef.nativeElement.offsetTop + offsetY;
// dragging horizontally
if (this.blockedAxis !== 'x') {
this.renderer.setStyle(
this.elementRef.nativeElement,
'left',
newLeft + 'px'
);
}
// dragging vertically, ex: the element in the list
if (this.blockedAxis !== 'y') {
this.renderer.setStyle(
this.elementRef.nativeElement,
'top',
newTop + 'px'
);
// Get an element under the cursor
const elementUnderCursor = document.elementFromPoint(
event.clientX,
event.clientY
);
if (elementUnderCursor instanceof HTMLElement) {
// Check if the element is a child of the parent list
const parentElement = this.elementRef.nativeElement.parentElement;
// Filter out placeholder elements
const items = Array.from(parentElement.children).filter(
child => child !== this.rowPlaceholderElement
);
const itemsNumber = items.length;
// Calculate the index of the target element
let newIndex = items.indexOf(elementUnderCursor) + 1;
newIndex = newIndex < 0 ? 0 : newIndex;
// If newIndex is greater than oldIndex (dragging down in the list),
// decrease or increase newIndex by 1 to accurately reflect the position
if (newIndex > this.oldIndex) {
newIndex--;
newIndex = newIndex < 0 ? 0 : newIndex;
}
if (newIndex < this.oldIndex) {
newIndex++;
newIndex = newIndex > itemsNumber ? itemsNumber - 1 : newIndex;
}
// If newIndex is equal to oldIndex, check if the mouse movement indicates a return
// to the original position
if (newIndex === this.oldIndex && event.clientY < this.prevY) {
newIndex--; // Adjust newIndex to reflect the return to the original position
}
// Create placeholder
if (this.rowPlaceholder) {
this.changeRowPlaceholderIndex(this.rowPlaceholder, newIndex);
}
this.oldIndex = newIndex; // Update old index
}
}
this.prevX = event.clientX;
this.prevY = event.clientY;
}
}
private createRowPlaceholderElement(tpl: TemplateRef<HTMLElement>): void {
// Remove any existing placeholder
this.removeRowPlaceholderElement();
// Create the placeholder using TemplateRef and ViewContainerRef
this.rowPlaceholderViewRef = this.viewContainerRef.createEmbeddedView(tpl);
// Get the root element of the created view
this.rowPlaceholderElement = this.rowPlaceholderViewRef
.rootNodes[0] as HTMLElement;
// Insert the placeholder after the current element
this.renderer.insertBefore(
this.elementRef.nativeElement.parentNode,
this.rowPlaceholderElement,
this.elementRef.nativeElement.nextSibling
);
}
private changeRowPlaceholderIndex(
tpl: TemplateRef<HTMLElement>,
index: number
): void {
this.removeRowPlaceholderElement();
this.rowPlaceholderViewRef = this.viewContainerRef.createEmbeddedView(tpl);
this.rowPlaceholderElement = this.rowPlaceholderViewRef
.rootNodes[0] as HTMLElement;
// Check if rowPlaceholderElement is not null before inserting
if (this.rowPlaceholderElement) {
const parentElement = this.elementRef.nativeElement.parentNode;
const children = parentElement.children;
const childCount = children.length;
// If dragging below the list (index is the last child), insert after the last child
if (index === childCount) {
this.renderer.appendChild(parentElement, this.rowPlaceholderElement);
}
// Otherwise, insert before the element at the calculated index
else {
this.renderer.insertBefore(
parentElement,
this.rowPlaceholderElement,
children[index]
);
}
}
}
private removeRowPlaceholderElement(): void {
if (this.rowPlaceholderViewRef) {
this.rowPlaceholderViewRef.destroy(); // Clean up the view ref
this.rowPlaceholderViewRef = null;
}
if (this.rowPlaceholderElement && this.rowPlaceholderElement.parentNode) {
this.rowPlaceholderElement.parentNode.removeChild(
this.rowPlaceholderElement
);
this.rowPlaceholderElement = null;
}
}
private cleanupListeners(): void {
if (this.mouseMoveListener) {
document.removeEventListener('mousemove', this.mouseMoveListener);
this.mouseMoveListener = undefined;
}
}
}