-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdraggable.mjs
552 lines (527 loc) · 16.1 KB
/
draggable.mjs
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// CONSTANTS BLOCK
export const dragSymbol = Symbol("draggable");
const EventConstructor = 'DragEvent' in window ? window.DragEvent : window.MouseEvent;
// END CONSTANTS BLOCK
/// SETTABLES BLOCK
// These variables and functions set up two
// settable items with side effects when they are set.
// isDragging is true when a drag is happening, false otherwise
let _isDragging = false;
const isDragging = function(setVal) {
if(arguments.length > 0) {
if (!setVal) {
dragFloater(null);
}
_isDragging = setVal;
} else {
return _isDragging;
}
};
// dragFloater is the DOM elements that appear near the pointer
// when a drag is happening. They can be configured or even turned
// off by event listeners.
let _dragFloater = null;
const dragFloater = function(setVal) {
if(arguments.length > 0) {
if (_dragFloater) {
document.body.removeChild(_dragFloater);
}
if (setVal) {
document.body.appendChild(setVal);
}
_dragFloater = setVal;
} else {
return _dragFloater;
}
};
let activeDraggable = null;
/// END SETTABLES BLOCK
function assignMouseEventProperties(toEvent, fromEvent) {
[MouseEvent, UIEvent, Event].forEach(cls => {
Object.getOwnPropertyNames(cls.prototype).forEach(key => {
if(typeof fromEvent[key] !== "function" && !(key in toEvent)) {
toEvent[key] = fromEvent[key];
}
});
});
return toEvent;
}
function left(node) {
let offset = 0;
while(node) {
offset += node.offsetLeft || 0;
node = node.parentNode;
}
return offset;
}
function top(node) {
let offset = 0;
while(node) {
offset += node.offsetTop || 0;
node = node.parentNode;
}
return offset;
}
// GLOBAL LISTENERS BLOCK
// these listeners need to always be listening on the document, and in capture
// phase to ensure they always run despite a possible stopPropagation() elsewhere.
/**
* No matter where in the document it happens,
* mouseup ends a drag.
*/
document.addEventListener(
"mouseup",
function endDragOnMouseUp() {
isDragging(false);
dragFloater(null);
if (activeDraggable) {
activeDraggable.isMouseDown = false;
activeDraggable = null;
}
},
true
);
/**
* This handler is for the case when the user releases the mouse button outside
* the document, then re-enters with the button up.
*/
document.addEventListener(
"mouseenter",
function cancelDragReenteringDocumentWithMouseUp(ev) {
if (!ev.buttons && ev.target === ev.currentTarget) {
if (activeDraggable) {
activeDraggable.cleanupDocumentEvents();
activeDraggable.isMouseDown = false;
activeDraggable = null;
}
isDragging(false);
dragFloater(null);
}
},
true
);
// END GLOBAL LISTENERS
// PROPERTY UTILS
// These are used to set up automatic coercions and settables in the options object for dispatching synthetic events.
function booleanProperty(key) {
return {
set(val) {
this._data[key] = !!val;
},
get() {
return this._data[key];
}
};
}
function numberProperty(key) {
return {
set(val) {
this._data[key] = +val;
},
get() {
return this._data[key];
}
};
}
function setterProperty(settable) {
return {
set(val) {
settable(val);
},
get() {
return settable();
}
};
}
// END PROPERTY UTILS
const DraggableVMProperties = {
/**
* Whether to enable dragging for this item.
* This is much more convenient in usage when some items
* might not be draggable (like if a product list wants
* one type of product to be draggable but not another).
*/
enabled: booleanProperty("enabled"),
/**
* The draggable element itself is accessible from the view model.
* This is set during connectedCallback
*/
element: {
writable: true,
value: undefined
},
/**
* Data is expected to be passed through binding to the draggable
* view model. It defaults to an empty observable object for
* convenience.
*/
data: {
writable: true,
value: {}
},
/**
* Whether a mouse down happened over the draggable element. Used
* for determining when to start a drag which requires mouse down
* and some movement away from initialX/initialY
*/
isMouseDown: booleanProperty("isMouseDown"),
/**
* The X position where mouse down happened.
*/
initialX: numberProperty("initialX"),
/**
* The Y position where mouse down happend.
*/
initialY: numberProperty("initialY"),
/**
* Whether to allow mouseup events when drop happens. Only needed
* if drop cannot be handled by the drop target.
*/
propagateMouseUp: booleanProperty("propagateMouseUp"),
/**
* Whether to allow mouseenter events when dragenter happens. Only needed
* if dragenter cannot be handled by the dragover target but the event
* is still required.
*/
propagateMouseEnter: booleanProperty("propagateMouseEnter"),
/**
* Whether to allow mouseleave events when dragleave happens. Only needed
* if dragleave cannot be handled by the dragover target but the event
* is still required.
*/
propagateMouseLeave: booleanProperty("propagateMouseLeave"),
/**
* Whether to allow mousemove events when dragmove happens. Only needed
* if dragmove cannot be handled by the dragover target but the event
* is still required.
*/
propagateMouseMove: booleanProperty("propagateMouseMove"),
/**
* isDragging is a gettable/settable proxy to the "global" boolean value
*/
isDragging: setterProperty(isDragging),
/**
* dragFloater is a gettable/settable proxy to the "global" boolean value
*/
dragFloater: setterProperty(dragFloater),
};
export function DraggableVM(opts) {
Object.defineProperties(
this,
Object.assign(DraggableVMProperties, {
_data: {
enumerable: false,
writable: false,
value: {
enabled: true,
isMouseDown: false,
initialX: 0,
initialY: 0,
propagateMouseUp: false,
propagateMouseEnter: false,
propagateMouseLeave: false,
propagateMouseMove: false
}
}
})
);
/**
* all draggable view models can read and set the values of isDragging
* and dragFloater
*/
Object.assign(this, opts);
/**
* Once the element is connected, reference it in the view model, then
* set all images contained within to not be natively draggable. If the
* draggable is removed from the DOM while dragging, unbind its events.
*/
this.connectedCallback = el => {
this.element = el;
el.querySelectorAll("img").forEach(img => {
img.setAttribute("draggable", false);
});
return () => {
this.cleanupDocumentEvents();
};
},
/**
* On init, set up the document event functions to be bound to the current
* view model, for convenient binding an unbinding as event listeners.
*/
[
/**
* Mousemove triggers dragover, and moves the floater
* to the current mouse position. Unlike native drag,
* this drag places the floater's top left at the pointer's
* position.
*/
["Move", "dragover", (event) => {
const _dragFloater = dragFloater();
if(_dragFloater) {
_dragFloater.style.top = event.clientY + "px";
_dragFloater.style.left = event.clientX + "px";
}
}],
/**
* mouseenter triggers dragenter
*/
["Enter", "dragenter"],
/**
* mouseleave triggers dragleave
*/
["Leave", "dragleave"],
/**
* mouseup triggers drop on the drop target and dragend on the
* draggable. It also cleans up the mousedown state on the view
* model, and the global isDragging and floater compute values.
*/
["Up", "drop", () => {
this.cleanupDocumentEvents();
Object.assign(this, {
isMouseDown: false,
initialX: NaN,
initialY: NaN,
});
dragFloater(null);
activeDraggable = null;
isDragging(false);
}, (event) => {
const endEvent = new EventConstructor("draggable-dragend", assignMouseEventProperties({
relatedTarget: this.element,
bubbles: true
}, event));
Object.assign(endEvent, {
data: this.data,
draggable: this
});
this.element.dispatchEvent(endEvent);
}]
].forEach(([name, eventName, preHook, postHook]) => {
this["documentMouse" + name] = event => {
if (!this["propagateMouse" + name]) {
event.stopPropagation();
event.preventDefault();
}
preHook && preHook(event);
const target = event.target;
const dragEvent = new EventConstructor("draggable-" + eventName, assignMouseEventProperties({
relatedTarget: this.element,
bubbles: name === "Move" || name === "Up" // bubble for move and drop
}, event));
Object.assign(dragEvent, {
data: this.data,
draggable: this
});
target.dispatchEvent(dragEvent);
postHook && postHook(event);
};
});
this.documentTouchMove = ev => {
ev.preventDefault();
var newTarget = document.elementFromPoint(ev.targetTouches[0].clientX, ev.targetTouches[0].clientY);
if(newTarget === null) {
// stop dragging if the touch event leaves the document
document.dispatchEvent(new MouseEvent("mouseleave", ev.changedTouches[0]));
isDragging(false);
this.lastTarget = document;
} else {
if(this.lastTarget !== newTarget) {
// generate synthetic leave and enter events.
const range = document.createRange();
range.setStart(this.lastTarget, 0);
range.setEnd(newTarget, 0);
const rangeAncestor = range.commonAncestorContainer;
const nodeChainLeave = [];
const nodeChainEnter = [];
let currentNode = this.lastTarget;
while (currentNode && currentNode !== rangeAncestor) {
nodeChainLeave.push(currentNode);
currentNode = currentNode.parentNode;
}
currentNode = newTarget;
while (currentNode && currentNode !== rangeAncestor) {
nodeChainEnter.push(currentNode);
currentNode = currentNode.parentNode;
}
nodeChainEnter.reverse();
nodeChainLeave.forEach(node => {
node.dispatchEvent(new MouseEvent("mouseleave"), { bubbles: false, cancelBubble: true });
});
nodeChainEnter.forEach(node => {
node.dispatchEvent(new MouseEvent("mouseenter"), { bubbles: false, cancelBubble: true });
});
}
newTarget.dispatchEvent(new MouseEvent(
"mousemove", {
clientX: ev.changedTouches[0].clientX,
clientY: ev.changedTouches[0].clientY,
screenX: ev.changedTouches[0].screenX,
screenY: ev.changedTouches[0].screenY,
pageX: ev.changedTouches[0].pageX,
pageY: ev.changedTouches[0].pageY,
offsetX: ev.changedTouches[0].pageX - left(newTarget),
offsetY: ev.changedTouches[0].pageY - top(newTarget)
}
));
this.lastTarget = newTarget;
}
};
this.documentTouchUp = ev => {
if(ev.touches.length === 0) {
ev.stopPropagation();
ev.target.dispatchEvent(new MouseEvent("mouseup", ev.changedTouches[0]));
}
};
}
DraggableVM.prototype.setupDocumentEvents = function() {
/**
* During a drag, capture-phase mouse events are set up on the
* document to intercept mouse movement and transform it into drag
* events.
*/
document.addEventListener("mousemove", this.documentMouseMove, true);
document.addEventListener("mouseup", this.documentMouseUp, true);
document.addEventListener("mouseenter", this.documentMouseEnter, true);
document.addEventListener("mouseleave", this.documentMouseLeave, true);
/**
* Also do the same for touch events;
*/
document.addEventListener("touchmove", this.documentTouchMove, {passive: false, capture: true});
document.addEventListener("touchend", this.documentTouchUp, true);
};
/**
* Once a drag is ended, remove these events from the document.
*/
DraggableVM.prototype.cleanupDocumentEvents = function() {
document.removeEventListener("mousemove", this.documentMouseMove, true);
document.removeEventListener("mouseup", this.documentMouseUp, true);
document.removeEventListener("mouseenter", this.documentMouseEnter, true);
document.removeEventListener("mouseleave", this.documentMouseLeave, true);
document.removeEventListener("touchmove", this.documentTouchMove, {passive: false, capture: true});
document.removeEventListener("touchend", this.documentTouchUp, true);
};
export default function Draggable(el, data = {}) {
const viewModel = el[dragSymbol] = new DraggableVM({
data
});
/**
* Mousedown starts the process of listening for a drag.
* For a drag to start, the user must also move the pointer
* 5px away from the location of this mousedown, so record
* the initial x and y coords.
*/
const mousedownHandler = ev => {
if (viewModel.enabled) {
Object.assign(viewModel, {
isMouseDown: true,
initialX: ev.clientX,
initialY: ev.clientY,
});
activeDraggable = viewModel;
}
};
el.addEventListener("mousedown", mousedownHandler, false);
el.addEventListener("touchstart", ev => {
if(ev.touches.length === 1) {
ev.preventDefault();
viewModel.lastTarget = ev.target;
mousedownHandler(ev.targetTouches[0]);
}
}, false);
/**
* moving the mouse on the element more than the 5px tolerance,
* or leaving the element, causes the drag to start.
*/
const mousemoveHandler = ev => {
const eventX = ev.clientX;
const eventY = ev.clientY;
const deltaEventX = Math.abs(eventX - viewModel.initialX);
const deltaEventY = Math.abs(eventY - viewModel.initialY);
if (
viewModel.enabled &&
viewModel.isMouseDown &&
!isDragging() &&
(deltaEventX >= 5 || deltaEventY >= 5)
) {
startDragging(ev);
}
};
el.addEventListener("mousemove", mousemoveHandler, false);
el.addEventListener("touchmove", ev => {
ev.preventDefault();
mousemoveHandler(ev.targetTouches[0]);
}, false);
el.addEventListener("mouseleave", function(ev) {
if (
viewModel.enabled &&
viewModel.isMouseDown &&
!isDragging()
) {
startDragging(ev);
}
}, false);
/**
* Begin the drag by signalling that drag is in effect,
* then set up the bound events for this view model on the document,
* then create a floater to follow the mouse around,
* then dispatch dragstart.
*/
function startDragging (ev) {
// start dragging!
isDragging(true);
viewModel.setupDocumentEvents();
var div = document.createElement("div");
div.innerHTML = el.innerHTML;
Object.assign(div.style, {
"pointer-events": "none",
opacity: 0.8,
position: "fixed",
top: ev.clientY,
left: ev.clientX,
height: el.clientHeight,
width: el.clientWidth,
"z-index": 10000,
});
dragFloater(div);
var event = new EventConstructor("draggable-dragstart", assignMouseEventProperties({
bubbles: true
}, ev));
Object.assign(event, {
data: viewModel.data,
draggable: viewModel
});
el.dispatchEvent(event);
}
/**
* For any images which are added after this component is instantiated,
* ensure their native drag handling does not interfere with the drag operation.
*/
var imgObserver = new MutationObserver(function(observations) {
observations.forEach(function(obs) {
obs.addedNodes.forEach(function(node) {
if(node.tagName === "IMG") {
node.setAttribute("draggable", false);
}
});
});
});
imgObserver.observe(el, {
childList: true,
subtree: true
});
// Sane teardown. When element is removed from document, remove bindings.
var disconnectedCallback = viewModel.connectedCallback(el);
var draggableObserver = new MutationObserver(function(observations) {
observations.forEach(function(obs) {
obs.removedNodes.forEach(function(node) {
if(node === el) {
disconnectedCallback();
imgObserver.disconnect();
draggableObserver.disconnect();
node[dragSymbol] = null;
}
});
});
});
draggableObserver.observe(el.parentNode, { childList: true });
}