DragDropTouch.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. /*
  2. * Copyright (c) 2016 Bernardo Castilho
  3. *
  4. * Licensed under the MIT License (MIT)
  5. */
  6. var DragDropTouch;
  7. (function (DragDropTouch_1) {
  8. 'use strict';
  9. /**
  10. * Object used to hold the data that is being dragged during drag and drop operations.
  11. *
  12. * It may hold one or more data items of different types. For more information about
  13. * drag and drop operations and data transfer objects, see
  14. * <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer">HTML Drag and Drop API</a>.
  15. *
  16. * This object is created automatically by the @see:DragDropTouch singleton and is
  17. * accessible through the @see:dataTransfer property of all drag events.
  18. */
  19. var DataTransfer = (function () {
  20. function DataTransfer() {
  21. this._dropEffect = 'move';
  22. this._effectAllowed = 'all';
  23. this._data = {};
  24. }
  25. Object.defineProperty(DataTransfer.prototype, "dropEffect", {
  26. /**
  27. * Gets or sets the type of drag-and-drop operation currently selected.
  28. * The value must be 'none', 'copy', 'link', or 'move'.
  29. */
  30. get: function () {
  31. return this._dropEffect;
  32. },
  33. set: function (value) {
  34. this._dropEffect = value;
  35. },
  36. enumerable: true,
  37. configurable: true
  38. });
  39. Object.defineProperty(DataTransfer.prototype, "effectAllowed", {
  40. /**
  41. * Gets or sets the types of operations that are possible.
  42. * Must be one of 'none', 'copy', 'copyLink', 'copyMove', 'link',
  43. * 'linkMove', 'move', 'all' or 'uninitialized'.
  44. */
  45. get: function () {
  46. return this._effectAllowed;
  47. },
  48. set: function (value) {
  49. this._effectAllowed = value;
  50. },
  51. enumerable: true,
  52. configurable: true
  53. });
  54. Object.defineProperty(DataTransfer.prototype, "types", {
  55. /**
  56. * Gets an array of strings giving the formats that were set in the @see:dragstart event.
  57. */
  58. get: function () {
  59. return Object.keys(this._data);
  60. },
  61. enumerable: true,
  62. configurable: true
  63. });
  64. /**
  65. * Removes the data associated with a given type.
  66. *
  67. * The type argument is optional. If the type is empty or not specified, the data
  68. * associated with all types is removed. If data for the specified type does not exist,
  69. * or the data transfer contains no data, this method will have no effect.
  70. *
  71. * @param type Type of data to remove.
  72. */
  73. DataTransfer.prototype.clearData = function (type) {
  74. if (type != null) {
  75. delete this._data[type];
  76. }
  77. else {
  78. this._data = null;
  79. }
  80. };
  81. /**
  82. * Retrieves the data for a given type, or an empty string if data for that type does
  83. * not exist or the data transfer contains no data.
  84. *
  85. * @param type Type of data to retrieve.
  86. */
  87. DataTransfer.prototype.getData = function (type) {
  88. return this._data[type] || '';
  89. };
  90. /**
  91. * Set the data for a given type.
  92. *
  93. * For a list of recommended drag types, please see
  94. * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Recommended_Drag_Types.
  95. *
  96. * @param type Type of data to add.
  97. * @param value Data to add.
  98. */
  99. DataTransfer.prototype.setData = function (type, value) {
  100. this._data[type] = value;
  101. };
  102. /**
  103. * Set the image to be used for dragging if a custom one is desired.
  104. *
  105. * @param img An image element to use as the drag feedback image.
  106. * @param offsetX The horizontal offset within the image.
  107. * @param offsetY The vertical offset within the image.
  108. */
  109. DataTransfer.prototype.setDragImage = function (img, offsetX, offsetY) {
  110. var ddt = DragDropTouch._instance;
  111. ddt._imgCustom = img;
  112. ddt._imgOffset = { x: offsetX, y: offsetY };
  113. };
  114. return DataTransfer;
  115. }());
  116. DragDropTouch_1.DataTransfer = DataTransfer;
  117. /**
  118. * Defines a class that adds support for touch-based HTML5 drag/drop operations.
  119. *
  120. * The @see:DragDropTouch class listens to touch events and raises the
  121. * appropriate HTML5 drag/drop events as if the events had been caused
  122. * by mouse actions.
  123. *
  124. * The purpose of this class is to enable using existing, standard HTML5
  125. * drag/drop code on mobile devices running IOS or Android.
  126. *
  127. * To use, include the DragDropTouch.js file on the page. The class will
  128. * automatically start monitoring touch events and will raise the HTML5
  129. * drag drop events (dragstart, dragenter, dragleave, drop, dragend) which
  130. * should be handled by the application.
  131. *
  132. * For details and examples on HTML drag and drop, see
  133. * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations.
  134. */
  135. var DragDropTouch = (function () {
  136. /**
  137. * Initializes the single instance of the @see:DragDropTouch class.
  138. */
  139. function DragDropTouch() {
  140. this._lastClick = 0;
  141. // enforce singleton pattern
  142. if (DragDropTouch._instance) {
  143. throw 'DragDropTouch instance already created.';
  144. }
  145. // detect passive event support
  146. // https://github.com/Modernizr/Modernizr/issues/1894
  147. var supportsPassive = false;
  148. document.addEventListener('test', function () { }, {
  149. get passive() {
  150. supportsPassive = true;
  151. return true;
  152. }
  153. });
  154. // listen to touch events
  155. if ('ontouchstart' in document) {
  156. var d = document, ts = this._touchstart.bind(this), tm = this._touchmove.bind(this), te = this._touchend.bind(this), opt = supportsPassive ? { passive: false, capture: false } : false;
  157. d.addEventListener('touchstart', ts, opt);
  158. d.addEventListener('touchmove', tm, opt);
  159. d.addEventListener('touchend', te);
  160. d.addEventListener('touchcancel', te);
  161. }
  162. }
  163. /**
  164. * Gets a reference to the @see:DragDropTouch singleton.
  165. */
  166. DragDropTouch.getInstance = function () {
  167. return DragDropTouch._instance;
  168. };
  169. // ** event handlers
  170. DragDropTouch.prototype._touchstart = function (e) {
  171. var _this = this;
  172. if (this._shouldHandle(e)) {
  173. // raise double-click and prevent zooming
  174. if (Date.now() - this._lastClick < DragDropTouch._DBLCLICK) {
  175. if (this._dispatchEvent(e, 'dblclick', e.target)) {
  176. e.preventDefault();
  177. this._reset();
  178. return;
  179. }
  180. }
  181. // clear all variables
  182. this._reset();
  183. // get nearest draggable element
  184. var src = this._closestDraggable(e.target);
  185. if (src) {
  186. // give caller a chance to handle the hover/move events
  187. if (!this._dispatchEvent(e, 'mousemove', e.target) &&
  188. !this._dispatchEvent(e, 'mousedown', e.target)) {
  189. // get ready to start dragging
  190. this._dragSource = src;
  191. this._ptDown = this._getPoint(e);
  192. this._lastTouch = e;
  193. e.preventDefault();
  194. // show context menu if the user hasn't started dragging after a while
  195. setTimeout(function () {
  196. if (_this._dragSource == src && _this._img == null) {
  197. if (_this._dispatchEvent(e, 'contextmenu', src)) {
  198. _this._reset();
  199. }
  200. }
  201. }, DragDropTouch._CTXMENU);
  202. if (DragDropTouch._ISPRESSHOLDMODE) {
  203. this._pressHoldInterval = setTimeout(function () {
  204. _this._isDragEnabled = true;
  205. _this._touchmove(e);
  206. }, DragDropTouch._PRESSHOLDAWAIT);
  207. }
  208. }
  209. }
  210. }
  211. };
  212. DragDropTouch.prototype._touchmove = function (e) {
  213. if (this._shouldCancelPressHoldMove(e)) {
  214. this._reset();
  215. return;
  216. }
  217. if (this._shouldHandleMove(e) || this._shouldHandlePressHoldMove(e)) {
  218. // see if target wants to handle move
  219. var target = this._getTarget(e);
  220. if (this._dispatchEvent(e, 'mousemove', target)) {
  221. this._lastTouch = e;
  222. e.preventDefault();
  223. return;
  224. }
  225. // start dragging
  226. if (this._dragSource && !this._img && this._shouldStartDragging(e)) {
  227. this._dispatchEvent(e, 'dragstart', this._dragSource);
  228. this._createImage(e);
  229. this._dispatchEvent(e, 'dragenter', target);
  230. }
  231. // continue dragging
  232. if (this._img) {
  233. this._lastTouch = e;
  234. e.preventDefault(); // prevent scrolling
  235. if (target != this._lastTarget) {
  236. this._dispatchEvent(this._lastTouch, 'dragleave', this._lastTarget);
  237. this._dispatchEvent(e, 'dragenter', target);
  238. this._lastTarget = target;
  239. }
  240. this._moveImage(e);
  241. this._isDropZone = this._dispatchEvent(e, 'dragover', target);
  242. }
  243. }
  244. };
  245. DragDropTouch.prototype._touchend = function (e) {
  246. if (this._shouldHandle(e)) {
  247. // see if target wants to handle up
  248. if (this._dispatchEvent(this._lastTouch, 'mouseup', e.target)) {
  249. e.preventDefault();
  250. return;
  251. }
  252. // user clicked the element but didn't drag, so clear the source and simulate a click
  253. if (!this._img) {
  254. this._dragSource = null;
  255. this._dispatchEvent(this._lastTouch, 'click', e.target);
  256. this._lastClick = Date.now();
  257. }
  258. // finish dragging
  259. this._destroyImage();
  260. if (this._dragSource) {
  261. if (e.type.indexOf('cancel') < 0 && this._isDropZone) {
  262. this._dispatchEvent(this._lastTouch, 'drop', this._lastTarget);
  263. }
  264. this._dispatchEvent(this._lastTouch, 'dragend', this._dragSource);
  265. this._reset();
  266. }
  267. }
  268. };
  269. // ** utilities
  270. // ignore events that have been handled or that involve more than one touch
  271. DragDropTouch.prototype._shouldHandle = function (e) {
  272. return e &&
  273. !e.defaultPrevented &&
  274. e.touches && e.touches.length < 2;
  275. };
  276. // use regular condition outside of press & hold mode
  277. DragDropTouch.prototype._shouldHandleMove = function (e) {
  278. return !DragDropTouch._ISPRESSHOLDMODE && this._shouldHandle(e);
  279. };
  280. // allow to handle moves that involve many touches for press & hold
  281. DragDropTouch.prototype._shouldHandlePressHoldMove = function (e) {
  282. return DragDropTouch._ISPRESSHOLDMODE &&
  283. this._isDragEnabled && e && e.touches && e.touches.length;
  284. };
  285. // reset data if user drags without pressing & holding
  286. DragDropTouch.prototype._shouldCancelPressHoldMove = function (e) {
  287. return DragDropTouch._ISPRESSHOLDMODE && !this._isDragEnabled &&
  288. this._getDelta(e) > DragDropTouch._PRESSHOLDMARGIN;
  289. };
  290. // start dragging when specified delta is detected
  291. DragDropTouch.prototype._shouldStartDragging = function (e) {
  292. var delta = this._getDelta(e);
  293. return delta > DragDropTouch._THRESHOLD ||
  294. (DragDropTouch._ISPRESSHOLDMODE && delta >= DragDropTouch._PRESSHOLDTHRESHOLD);
  295. }
  296. // clear all members
  297. DragDropTouch.prototype._reset = function () {
  298. this._destroyImage();
  299. this._dragSource = null;
  300. this._lastTouch = null;
  301. this._lastTarget = null;
  302. this._ptDown = null;
  303. this._isDragEnabled = false;
  304. this._isDropZone = false;
  305. this._dataTransfer = new DataTransfer();
  306. clearInterval(this._pressHoldInterval);
  307. };
  308. // get point for a touch event
  309. DragDropTouch.prototype._getPoint = function (e, page) {
  310. if (e && e.touches) {
  311. e = e.touches[0];
  312. }
  313. return { x: page ? e.pageX : e.clientX, y: page ? e.pageY : e.clientY };
  314. };
  315. // get distance between the current touch event and the first one
  316. DragDropTouch.prototype._getDelta = function (e) {
  317. if (DragDropTouch._ISPRESSHOLDMODE && !this._ptDown) { return 0; }
  318. var p = this._getPoint(e);
  319. return Math.abs(p.x - this._ptDown.x) + Math.abs(p.y - this._ptDown.y);
  320. };
  321. // get the element at a given touch event
  322. DragDropTouch.prototype._getTarget = function (e) {
  323. var pt = this._getPoint(e), el = document.elementFromPoint(pt.x, pt.y);
  324. while (el && getComputedStyle(el).pointerEvents == 'none') {
  325. el = el.parentElement;
  326. }
  327. return el;
  328. };
  329. // create drag image from source element
  330. DragDropTouch.prototype._createImage = function (e) {
  331. // just in case...
  332. if (this._img) {
  333. this._destroyImage();
  334. }
  335. // create drag image from custom element or drag source
  336. var src = this._imgCustom || this._dragSource;
  337. this._img = src.cloneNode(true);
  338. this._copyStyle(src, this._img);
  339. this._img.style.top = this._img.style.left = '-9999px';
  340. // if creating from drag source, apply offset and opacity
  341. if (!this._imgCustom) {
  342. var rc = src.getBoundingClientRect(), pt = this._getPoint(e);
  343. this._imgOffset = { x: pt.x - rc.left, y: pt.y - rc.top };
  344. this._img.style.opacity = DragDropTouch._OPACITY.toString();
  345. }
  346. // add image to document
  347. this._moveImage(e);
  348. document.body.appendChild(this._img);
  349. };
  350. // dispose of drag image element
  351. DragDropTouch.prototype._destroyImage = function () {
  352. if (this._img && this._img.parentElement) {
  353. this._img.parentElement.removeChild(this._img);
  354. }
  355. this._img = null;
  356. this._imgCustom = null;
  357. };
  358. // move the drag image element
  359. DragDropTouch.prototype._moveImage = function (e) {
  360. var _this = this;
  361. requestAnimationFrame(function () {
  362. if (_this._img) {
  363. var pt = _this._getPoint(e, true), s = _this._img.style;
  364. s.position = 'absolute';
  365. s.pointerEvents = 'none';
  366. s.zIndex = '999999';
  367. s.left = Math.round(pt.x - _this._imgOffset.x) + 'px';
  368. s.top = Math.round(pt.y - _this._imgOffset.y) + 'px';
  369. }
  370. });
  371. };
  372. // copy properties from an object to another
  373. DragDropTouch.prototype._copyProps = function (dst, src, props) {
  374. for (var i = 0; i < props.length; i++) {
  375. var p = props[i];
  376. dst[p] = src[p];
  377. }
  378. };
  379. DragDropTouch.prototype._copyStyle = function (src, dst) {
  380. // remove potentially troublesome attributes
  381. DragDropTouch._rmvAtts.forEach(function (att) {
  382. dst.removeAttribute(att);
  383. });
  384. // copy canvas content
  385. if (src instanceof HTMLCanvasElement) {
  386. var cSrc = src, cDst = dst;
  387. cDst.width = cSrc.width;
  388. cDst.height = cSrc.height;
  389. cDst.getContext('2d').drawImage(cSrc, 0, 0);
  390. }
  391. // copy style (without transitions)
  392. var cs = getComputedStyle(src);
  393. for (var i = 0; i < cs.length; i++) {
  394. var key = cs[i];
  395. if (key.indexOf('transition') < 0) {
  396. dst.style[key] = cs[key];
  397. }
  398. }
  399. dst.style.pointerEvents = 'none';
  400. // and repeat for all children
  401. for (var i = 0; i < src.children.length; i++) {
  402. this._copyStyle(src.children[i], dst.children[i]);
  403. }
  404. };
  405. DragDropTouch.prototype._dispatchEvent = function (e, type, target) {
  406. if (e && target) {
  407. var evt = document.createEvent('Event'), t = e.touches ? e.touches[0] : e;
  408. evt.initEvent(type, true, true);
  409. evt.button = 0;
  410. evt.which = evt.buttons = 1;
  411. this._copyProps(evt, e, DragDropTouch._kbdProps);
  412. this._copyProps(evt, t, DragDropTouch._ptProps);
  413. evt.dataTransfer = this._dataTransfer;
  414. target.dispatchEvent(evt);
  415. return evt.defaultPrevented;
  416. }
  417. return false;
  418. };
  419. // gets an element's closest draggable ancestor
  420. DragDropTouch.prototype._closestDraggable = function (e) {
  421. for (; e; e = e.parentElement) {
  422. if (e.hasAttribute('draggable') && e.draggable) {
  423. return e;
  424. }
  425. }
  426. return null;
  427. };
  428. return DragDropTouch;
  429. }());
  430. /*private*/ DragDropTouch._instance = new DragDropTouch(); // singleton
  431. // constants
  432. DragDropTouch._THRESHOLD = 5; // pixels to move before drag starts
  433. DragDropTouch._OPACITY = 0.5; // drag image opacity
  434. DragDropTouch._DBLCLICK = 500; // max ms between clicks in a double click
  435. DragDropTouch._CTXMENU = 900; // ms to hold before raising 'contextmenu' event
  436. DragDropTouch._ISPRESSHOLDMODE = false; // decides of press & hold mode presence
  437. DragDropTouch._PRESSHOLDAWAIT = 400; // ms to wait before press & hold is detected
  438. DragDropTouch._PRESSHOLDMARGIN = 25; // pixels that finger might shiver while pressing
  439. DragDropTouch._PRESSHOLDTHRESHOLD = 0; // pixels to move before drag starts
  440. // copy styles/attributes from drag source to drag image element
  441. DragDropTouch._rmvAtts = 'id,class,style,draggable'.split(',');
  442. // synthesize and dispatch an event
  443. // returns true if the event has been handled (e.preventDefault == true)
  444. DragDropTouch._kbdProps = 'altKey,ctrlKey,metaKey,shiftKey'.split(',');
  445. DragDropTouch._ptProps = 'pageX,pageY,clientX,clientY,screenX,screenY,offsetX,offsetY'.split(',');
  446. DragDropTouch_1.DragDropTouch = DragDropTouch;
  447. })(DragDropTouch || (DragDropTouch = {}));