index.js (3518B)
1 import L from "leaflet"; 2 3 const DragEvents = L.Evented.extend({ 4 options: { 5 dragTolerance: 2, 6 dragButtons: [0], 7 stopOnLeave: false, 8 }, 9 10 initialize: function(element, options) { 11 L.setOptions(this, options); 12 this.element = element; 13 14 this.dragButton = null; 15 this.startEvent = null; 16 this.prevEvent = null; 17 this.isDragging = false; 18 19 L.DomEvent.on(element, 'mousedown', this.onMouseDown, this); 20 }, 21 22 onMouseDown: function(e) { 23 if (this.dragButton === null && this.options.dragButtons.includes(e.button)) { 24 this.dragButton = e.button; 25 this.startEvent = e; 26 this.prevEvent = e; 27 L.DomUtil.disableImageDrag(); 28 L.DomUtil.disableTextSelection(); 29 this._moveHandler = this.onMouseMove.bind(this); 30 document.addEventListener('mousemove', this._moveHandler, true); 31 L.DomEvent.on(document, 'mouseup', this.onMouseUp, this); 32 if (this.options.stopOnLeave) { 33 L.DomEvent.on(this.element, 'mouseleave', this.onMouseLeave, this); 34 } 35 } 36 }, 37 38 onMouseUp: function(e) { 39 if (this.dragButton === e.button) { 40 if (this.isDragging) { 41 this.fireDragEvent('dragend', e); 42 } else { 43 this.fire('click', {originalEvent: e, target: this.element}); 44 } 45 this.finishDrag(); 46 } 47 }, 48 49 onMouseMove: function(e) { 50 var that = this; 51 function exceedsTolerance() { 52 var tolerance = that.options.dragTolerance; 53 return Math.abs(e.clientX - that.startEvent.clientX) > tolerance || 54 Math.abs(e.clientY - that.startEvent.clientY) > tolerance; 55 } 56 57 if (this.isDragging) { 58 this.fireDragEvent('drag', e); 59 this.prevEvent = e; 60 } else if (this.dragButton !== null && exceedsTolerance()) { 61 this.isDragging = true; 62 this.fireDragEvent('dragstart', this.startEvent); 63 this.fireDragEvent('drag', e); 64 this.prevEvent = e; 65 } 66 }, 67 68 onMouseLeave: function(e) { 69 if (this.isDragging) { 70 this.fireDragEvent('dragend', e); 71 this.finishDrag(); 72 } 73 }, 74 75 fireDragEvent: function(type, originalEvent) { 76 const prevPos = L.point(this.prevEvent.clientX, this.prevEvent.clientY); 77 const pos = L.point(originalEvent.clientX, originalEvent.clientY); 78 const data = { 79 dragButton: this.dragButton, 80 originalEvent, 81 dragMovement: pos.subtract(prevPos) // e.movementX is not available in Safari 82 }; 83 this.fire(type, data); 84 }, 85 86 finishDrag: function() { 87 this.isDragging = false; 88 this.dragButton = null; 89 L.DomUtil.enableImageDrag(); 90 L.DomUtil.enableTextSelection(); 91 document.removeEventListener('mousemove', this._moveHandler, true); 92 L.DomEvent.off(document, 'mouseup', this.onMouseUp, this); 93 L.DomEvent.off(this.element, 'mouseleave', this.onMouseLeave, this); 94 } 95 } 96 ); 97 98 export {DragEvents};