dnd.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. /**
  2. * Copyright © Magento, Inc. All rights reserved.
  3. * See COPYING.txt for license details.
  4. */
  5. /**
  6. * @api
  7. */
  8. define([
  9. 'ko',
  10. 'Magento_Ui/js/lib/view/utils/async',
  11. 'underscore',
  12. 'uiRegistry',
  13. 'uiClass'
  14. ], function (ko, $, _, registry, Class) {
  15. 'use strict';
  16. var isTouchDevice = typeof document.ontouchstart !== 'undefined',
  17. transformProp;
  18. /**
  19. * Defines supported css 'transform' property.
  20. *
  21. * @returns {String|Undefined}
  22. */
  23. transformProp = (function () {
  24. var style = document.body.style,
  25. base = 'Transform',
  26. vendors = ['webkit', 'moz', 'ms', 'o'],
  27. vi = vendors.length,
  28. property;
  29. if (typeof style.transform != 'undefined') {
  30. return 'transform';
  31. }
  32. while (vi--) {
  33. property = vendors[vi] + base;
  34. if (typeof style[property] != 'undefined') {
  35. return property;
  36. }
  37. }
  38. })();
  39. /**
  40. * Returns first touch data if it's available.
  41. *
  42. * @param {(MouseEvent|TouchEvent)} e - Event object.
  43. * @returns {Object}
  44. */
  45. function getTouch(e) {
  46. return e.touches ? e.touches[0] : e;
  47. }
  48. /**
  49. * Moves specified DOM element to the x and y coordinates.
  50. *
  51. * @param {HTMLElement} elem - Element to be relocated.
  52. * @param {Number} x - X coordinate.
  53. * @param {Number} y - Y coordinate.
  54. */
  55. function locate(elem, x, y) {
  56. var value = 'translate(' + x + 'px,' + y + 'px)';
  57. elem.style[transformProp] = value;
  58. }
  59. /*eslint-disable no-extra-parens*/
  60. /**
  61. * Checks if specified coordinate is inside of the provided area.
  62. *
  63. * @param {Number} x - X coordinate.
  64. * @param {Number} y - Y coordinate.
  65. * @param {Object} area - Object which represents area.
  66. * @returns {Boolean}
  67. */
  68. function isInside(x, y, area) {
  69. return (
  70. area &&
  71. x >= area.left && x <= area.right &&
  72. y >= area.top && y <= area.bottom
  73. );
  74. }
  75. /*eslint-enable no-extra-parens*/
  76. /**
  77. * Calculates distance between two points.
  78. *
  79. * @param {Number} x1 - X coordinate of a first point.
  80. * @param {Number} y1 - Y coordinate of a first point.
  81. * @param {Number} x2 - X coordinate of a second point.
  82. * @param {Number} y2 - Y coordinate of a second point.
  83. * @returns {Number} Distance between points.
  84. */
  85. function distance(x1, y1, x2, y2) {
  86. var dx = x2 - x1,
  87. dy = y2 - y1;
  88. dx *= dx;
  89. dy *= dy;
  90. return Math.sqrt(dx + dy);
  91. }
  92. /**
  93. * Returns viewModel associated with a provided DOM element.
  94. *
  95. * @param {HTMLElement} elem
  96. * @returns {Object|Array}
  97. */
  98. function getModel(elem) {
  99. return ko.dataFor(elem);
  100. }
  101. /**
  102. * Checks whether cols are identical
  103. *
  104. * @param {HTMLElement} c1
  105. * @param {HTMLElement} c2
  106. * @returns {Boolean}
  107. */
  108. function compareCols(c1, c2) {
  109. return c1.cellIndex === c2.cellIndex;
  110. }
  111. return Class.extend({
  112. defaults: {
  113. rootSelector: '${ $.columnsProvider }:.admin__data-grid-wrap',
  114. tableSelector: '${ $.rootSelector } -> table.data-grid',
  115. mainTableSelector: '[data-role="grid"]',
  116. columnSelector: '${ $.tableSelector } thead tr th',
  117. noSelectClass: '_no-select',
  118. hiddenClass: '_hidden',
  119. fixedX: false,
  120. fixedY: true,
  121. minDistance: 2,
  122. columns: []
  123. },
  124. /**
  125. * Initializes Dnd component.
  126. *
  127. * @returns {Dnd} Chainable.
  128. */
  129. initialize: function () {
  130. _.bindAll(
  131. this,
  132. 'initTable',
  133. 'initColumn',
  134. 'removeColumn',
  135. 'onMouseMove',
  136. 'onMouseUp',
  137. 'onMouseDown'
  138. );
  139. this.$body = $('body');
  140. this._super()
  141. .initListeners();
  142. $.async(this.tableSelector, this.initTable);
  143. $.async(this.columnSelector, this.initColumn);
  144. return this;
  145. },
  146. /**
  147. * Binds necessary events listeners.
  148. *
  149. * @returns {Dnd} Chainbale.
  150. */
  151. initListeners: function () {
  152. if (isTouchDevice) {
  153. $(document).on({
  154. touchmove: this.onMouseMove,
  155. touchend: this.onMouseUp,
  156. touchleave: this.onMouseUp
  157. });
  158. } else {
  159. $(document).on({
  160. mousemove: this.onMouseMove,
  161. mouseup: this.onMouseUp
  162. });
  163. }
  164. return this;
  165. },
  166. /**
  167. * Defines specified table element as a main container.
  168. *
  169. * @param {HTMLTableElement} table
  170. * @returns {Dnd} Chainable.
  171. */
  172. initTable: function (table) {
  173. this.table = $(table).is(this.mainTableSelector) ? table : this.table;
  174. $(table).addClass('data-grid-draggable');
  175. return this;
  176. },
  177. /**
  178. * Sets specified column as a draggable element.
  179. *
  180. * @param {HTMLTableHeaderCellElement} column - Columns header element.
  181. * @returns {Dnd} Chainable.
  182. */
  183. initColumn: function (column) {
  184. var model = getModel(column),
  185. eventName;
  186. if (!model || !model.draggable) {
  187. return this;
  188. }
  189. if (!ko.es5.isTracked(model, 'dragover')) {
  190. model.track('dragover');
  191. }
  192. this.columns.push(column);
  193. $(column).bindings({
  194. css: {
  195. '_dragover-left': ko.computed(function () {
  196. return model.dragover === 'right';
  197. }),
  198. '_dragover-right': ko.computed(function () {
  199. return model.dragover === 'left';
  200. })
  201. }
  202. });
  203. eventName = isTouchDevice ?
  204. 'touchstart' :
  205. 'mousedown';
  206. $(column).on(eventName, this.onMouseDown);
  207. $.async.remove(column, this.removeColumn);
  208. return this;
  209. },
  210. /**
  211. * Removes specified column element from the columns array.
  212. *
  213. * @param {HTMLTableHeaderCellElement} column - Columns header element.
  214. * @returns {Dnd} Chainable.
  215. */
  216. removeColumn: function (column) {
  217. var columns = this.columns,
  218. index = columns.indexOf(column);
  219. if (~index) {
  220. columns.splice(index, 1);
  221. }
  222. return this;
  223. },
  224. /**
  225. * Returns index of column.
  226. *
  227. * @param {HTMLTableHeaderCellElement} elem
  228. * @returns {Number}
  229. */
  230. _getColumnIndex: function (elem) {
  231. return _.toArray(elem.parentNode.cells).indexOf(elem);
  232. },
  233. /**
  234. * Calculates coordinates of draggable elements.
  235. *
  236. * @returns {Dnd} Chainbale.
  237. */
  238. _cacheCoords: function () {
  239. var container = this.table.getBoundingClientRect(),
  240. bodyRect = document.body.getBoundingClientRect(),
  241. grabbed = this.grabbed,
  242. dragElem = grabbed.elem,
  243. cells = _.toArray(dragElem.parentNode.cells),
  244. rect;
  245. this.coords = this.columns.map(function (column) {
  246. var data,
  247. colIndex = _.findIndex(cells, function (cell) {
  248. return compareCols(cell, column);
  249. });
  250. rect = column.getBoundingClientRect();
  251. data = {
  252. index: colIndex,
  253. target: column,
  254. orig: rect,
  255. left: rect.left - bodyRect.left,
  256. right: rect.right - bodyRect.left,
  257. top: rect.top - bodyRect.top,
  258. bottom: container.bottom - bodyRect.top
  259. };
  260. if (column === dragElem) {
  261. this.dragArea = data;
  262. grabbed.shiftX = rect.left - grabbed.x;
  263. grabbed.shiftY = rect.top - grabbed.y;
  264. }
  265. return data;
  266. }, this);
  267. return this;
  268. },
  269. /**
  270. * Creates clone of a target table with only specified column visible.
  271. *
  272. * @param {HTMLTableHeaderCellElement} elem - Dragging column.
  273. * @returns {Dnd} Chainbale.
  274. */
  275. _cloneTable: function (elem) {
  276. var clone = this.table.cloneNode(true),
  277. columnIndex = this._getColumnIndex(elem),
  278. headRow = clone.tHead.firstElementChild,
  279. headCells = _.toArray(headRow.cells),
  280. tableBody = clone.tBodies[0],
  281. bodyRows = _.toArray(tableBody.children),
  282. origTrs = this.table.tBodies[0].children;
  283. clone.style.width = elem.offsetWidth + 'px';
  284. headCells.forEach(function (th, index) {
  285. if (index !== columnIndex) {
  286. headRow.removeChild(th);
  287. }
  288. });
  289. headRow.cells[0].style.height = elem.offsetHeight + 'px';
  290. bodyRows.forEach(function (row, rowIndex) {
  291. var cells = row.cells,
  292. cell;
  293. if (cells.length !== headCells.length) {
  294. tableBody.removeChild(row);
  295. return;
  296. }
  297. cell = row.cells[columnIndex].cloneNode(true);
  298. while (row.firstElementChild) {
  299. row.removeChild(row.firstElementChild);
  300. }
  301. cell.style.height = origTrs[rowIndex].cells[columnIndex].offsetHeight + 'px';
  302. row.appendChild(cell);
  303. });
  304. this.dragTable = clone;
  305. $(clone)
  306. .addClass('_dragging-copy')
  307. .appendTo('body');
  308. return this;
  309. },
  310. /**
  311. * Matches provided coordinates to available areas.
  312. *
  313. * @param {Number} x - X coordinate of a mouse pointer.
  314. * @param {Number} y - Y coordinate of a mouse pointer.
  315. * @returns {Object|Undefined} Matched area.
  316. */
  317. _getDropArea: function (x, y) {
  318. return _.find(this.coords, function (area) {
  319. return isInside(x, y, area);
  320. });
  321. },
  322. /**
  323. * Updates state of hovered areas.
  324. *
  325. * @param {Number} x - X coordinate of a mouse pointer.
  326. * @param {Number} y - Y coordinate of a mouse pointer.
  327. */
  328. _updateAreas: function (x, y) {
  329. var leavedArea = this.dropArea,
  330. area = this.dropArea = this._getDropArea(x, y);
  331. if (leavedArea) {
  332. this.dragleave(leavedArea);
  333. }
  334. if (area && !compareCols(area.target, this.dragArea.target)) {
  335. this.dragenter(area);
  336. }
  337. },
  338. /**
  339. * Grab action handler.
  340. *
  341. * @param {Number} x - X coordinate of a grabbed point.
  342. * @param {Number} y - Y coordinate of a grabbed point.
  343. * @param {HTMLElement} elem - Grabbed element.
  344. */
  345. grab: function (x, y, elem) {
  346. this.initDrag = true;
  347. this.grabbed = {
  348. x: x,
  349. y: y,
  350. elem: elem
  351. };
  352. this.$body.addClass(this.noSelectClass);
  353. },
  354. /**
  355. * Dragstart action handler.
  356. *
  357. * @param {HTMLTableHeaderCellElement} elem - Element which is dragging.
  358. */
  359. dragstart: function (elem) {
  360. this.initDrag = false;
  361. this.dropArea = false;
  362. this.dragging = true;
  363. getModel(elem).dragging(true);
  364. this._cacheCoords()
  365. ._cloneTable(elem);
  366. },
  367. /**
  368. * Drag action handler. Locates draggable
  369. * grid at a specified coordinates.
  370. *
  371. * @param {Number} x - X coordinate.
  372. * @param {Number} y - Y coordinate.
  373. */
  374. drag: function (x, y) {
  375. var grabbed = this.grabbed,
  376. dragArea = this.dragArea,
  377. posX = x + grabbed.shiftX,
  378. posY = y + grabbed.shiftY;
  379. if (this.fixedX) {
  380. x = dragArea.left;
  381. posX = dragArea.orig.left;
  382. }
  383. if (this.fixedY) {
  384. y = dragArea.top;
  385. posY = dragArea.orig.top;
  386. }
  387. locate(this.dragTable, posX, posY);
  388. if (!isInside(x, y, this.dropArea)) {
  389. this._updateAreas(x, y);
  390. }
  391. },
  392. /**
  393. * Dragenter action handler.
  394. *
  395. * @param {Object} dropArea
  396. */
  397. dragenter: function (dropArea) {
  398. var direction = this.dragArea.index < dropArea.index ?
  399. 'left' :
  400. 'right';
  401. getModel(dropArea.target).dragover = direction;
  402. },
  403. /**
  404. * Dragleave action handler.
  405. *
  406. * @param {Object} dropArea
  407. */
  408. dragleave: function (dropArea) {
  409. getModel(dropArea.target).dragover = false;
  410. },
  411. /**
  412. * Dragend action handler.
  413. *
  414. * @param {Object} dragArea
  415. */
  416. dragend: function (dragArea) {
  417. var dropArea = this.dropArea,
  418. dragElem = dragArea.target;
  419. this.dragging = false;
  420. document.body.removeChild(this.dragTable);
  421. getModel(dragElem).dragging(false);
  422. if (dropArea && !compareCols(dropArea.target, dragElem)) {
  423. this.drop(dropArea, dragArea);
  424. }
  425. },
  426. /**
  427. * Drop action handler.
  428. *
  429. * @param {Object} dropArea
  430. * @param {Object} dragArea
  431. */
  432. drop: function (dropArea, dragArea) {
  433. var dropModel = getModel(dropArea.target),
  434. dragModel = getModel(dragArea.target);
  435. getModel(this.table).insertChild(dragModel, dropModel);
  436. dropModel.dragover = false;
  437. },
  438. /**
  439. * Documents' 'mousemove' event handler.
  440. *
  441. * @param {(MouseEvent|TouchEvent)} e - Event object.
  442. */
  443. onMouseMove: function (e) {
  444. var grab = this.grabbed,
  445. touch = getTouch(e),
  446. x = touch.pageX,
  447. y = touch.pageY;
  448. if (this.initDrag || this.dragging) {
  449. e.preventDefault();
  450. }
  451. if (this.initDrag && distance(x, y, grab.x, grab.y) >= this.minDistance) {
  452. this.dragstart(grab.elem);
  453. }
  454. if (this.dragging) {
  455. this.drag(x, y);
  456. }
  457. },
  458. /**
  459. * Documents' 'mouseup' event handler.
  460. */
  461. onMouseUp: function () {
  462. if (this.initDrag || this.dragging) {
  463. this.initDrag = false;
  464. this.$body.removeClass(this.noSelectClass);
  465. }
  466. if (this.dragging) {
  467. this.dragend(this.dragArea);
  468. }
  469. },
  470. /**
  471. * Columns' 'mousedown' event handler.
  472. *
  473. * @param {(MouseEvent|TouchEvent)} e - Event object.
  474. */
  475. onMouseDown: function (e) {
  476. var touch = getTouch(e);
  477. this.grab(touch.pageX, touch.pageY, e.currentTarget);
  478. }
  479. });
  480. });