lib/amd/src/sortable_list.js

  1. // This file is part of Moodle - http://moodle.org/
  2. //
  3. // Moodle is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // Moodle is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  15. /**
  16. * A javascript module to handle list items drag and drop
  17. *
  18. * Example of usage:
  19. *
  20. * Create a list (for example `<ul>` or `<tbody>`) where each draggable element has a drag handle.
  21. * The best practice is to use the template core/drag_handle:
  22. * $OUTPUT->render_from_template('core/drag_handle', ['movetitle' => get_string('movecontent', 'moodle', ELEMENTNAME)]);
  23. *
  24. * Attach this JS module to this list:
  25. *
  26. * Space between define and ( critical in comment but not allowed in code in order to function
  27. * correctly with Moodle's requirejs.php
  28. *
  29. * For the full list of possible parameters see var defaultParameters below.
  30. *
  31. * The following jQuery events are fired:
  32. * - SortableList.EVENTS.DRAGSTART : when user started dragging a list element
  33. * - SortableList.EVENTS.DRAG : when user dragged a list element to a new position
  34. * - SortableList.EVENTS.DROP : when user dropped a list element
  35. * - SortableList.EVENTS.DROPEND : when user finished dragging - either fired right after dropping or
  36. * if "Esc" was pressed during dragging
  37. *
  38. * @example
  39. * define (['jquery', 'core/sortable_list'], function($, SortableList) {
  40. * var list = new SortableList('ul.my-awesome-list'); // source list (usually <ul> or <tbody>) - selector or element
  41. *
  42. * // Listen to the events when element is dragged.
  43. * $('ul.my-awesome-list > *').on(SortableList.EVENTS.DROP, function(evt, info) {
  44. * console.log(info);
  45. * });
  46. *
  47. * // Advanced usage. Overwrite methods getElementName, getDestinationName, moveDialogueTitle, for example:
  48. * list.getElementName = function(element) {
  49. * return $.Deferred().resolve(element.attr('data-name'));
  50. * }
  51. * });
  52. *
  53. * @module core/sortable_list
  54. * @class core/sortable_list
  55. * @copyright 2018 Marina Glancy
  56. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  57. */
  58. define(['jquery', 'core/log', 'core/autoscroll', 'core/str', 'core/modal_factory', 'core/modal_events', 'core/notification'],
  59. function($, log, autoScroll, str, ModalFactory, ModalEvents, Notification) {
  60. /**
  61. * Default parameters
  62. *
  63. * @private
  64. * @type {Object}
  65. */
  66. var defaultParameters = {
  67. targetListSelector: null,
  68. moveHandlerSelector: '[data-drag-type=move]',
  69. isHorizontal: false,
  70. autoScroll: true
  71. };
  72. /**
  73. * Class names for different elements that may be changed during sorting
  74. *
  75. * @private
  76. * @type {Object}
  77. */
  78. var CSS = {
  79. keyboardDragClass: 'dragdrop-keyboard-drag',
  80. isDraggedClass: 'sortable-list-is-dragged',
  81. currentPositionClass: 'sortable-list-current-position',
  82. sourceListClass: 'sortable-list-source',
  83. targetListClass: 'sortable-list-target',
  84. overElementClass: 'sortable-list-over-element'
  85. };
  86. /**
  87. * Test the browser support for options objects on event listeners.
  88. * @return {Boolean}
  89. */
  90. var eventListenerOptionsSupported = function() {
  91. var passivesupported = false,
  92. options,
  93. testeventname = "testpassiveeventoptions";
  94. // Options support testing example from:
  95. // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
  96. try {
  97. options = Object.defineProperty({}, "passive", {
  98. // eslint-disable-next-line getter-return
  99. get: function() {
  100. passivesupported = true;
  101. }
  102. });
  103. // We use an event name that is not likely to conflict with any real event.
  104. document.addEventListener(testeventname, options, options);
  105. // We remove the event listener as we have tested the options already.
  106. document.removeEventListener(testeventname, options, options);
  107. } catch (err) {
  108. // It's already false.
  109. passivesupported = false;
  110. }
  111. return passivesupported;
  112. };
  113. /**
  114. * Allow to create non-passive touchstart listeners and prevent page scrolling when dragging
  115. * From: https://stackoverflow.com/a/48098097
  116. *
  117. * @param {string} eventname
  118. * @returns {object}
  119. */
  120. var registerNotPassiveListeners = function(eventname) {
  121. return {
  122. setup: function(x, ns, handle) {
  123. if (ns.includes('notPassive')) {
  124. this.addEventListener(eventname, handle, {passive: false});
  125. return true;
  126. } else {
  127. return false;
  128. }
  129. }
  130. };
  131. };
  132. if (eventListenerOptionsSupported) {
  133. $.event.special.touchstart = registerNotPassiveListeners('touchstart');
  134. $.event.special.touchmove = registerNotPassiveListeners('touchmove');
  135. $.event.special.touchend = registerNotPassiveListeners('touchend');
  136. }
  137. /**
  138. * Initialise sortable list.
  139. *
  140. * @param {(String|jQuery|Element)} root JQuery/DOM element representing sortable list (i.e. <ul>, <tbody>) or CSS selector
  141. * @param {Object} config Parameters for the list. See defaultParameters above for examples.
  142. * @param {(String|jQuery|Element)} config.targetListSelector target lists, by default same as root
  143. * @param {String} config.moveHandlerSelector CSS selector for a drag handle. By default '[data-drag-type=move]'
  144. * @param {String} config.listSelector CSS selector for target lists. By default the same as root
  145. * @param {(Boolean|Function)} config.isHorizontal Set to true if the list is horizontal (can also be a callback
  146. * with list as an argument)
  147. * @param {Boolean} config.autoScroll Engages autoscroll module for automatic vertical scrolling of the whole page,
  148. * by default true
  149. */
  150. var SortableList = function(root, config) {
  151. this.info = null;
  152. this.proxy = null;
  153. this.proxyDelta = null;
  154. this.dragCounter = 0;
  155. this.lastEvent = null;
  156. this.config = $.extend({}, defaultParameters, config || {});
  157. this.config.listSelector = root;
  158. if (!this.config.targetListSelector) {
  159. this.config.targetListSelector = root;
  160. }
  161. if (typeof this.config.listSelector === 'object') {
  162. // The root is an element on the page. Register a listener for this element.
  163. $(this.config.listSelector).on('mousedown touchstart.notPassive', $.proxy(this.dragStartHandler, this));
  164. } else {
  165. // The root is a CSS selector. Register a listener that picks up the element dynamically.
  166. $('body').on('mousedown touchstart.notPassive', this.config.listSelector, $.proxy(this.dragStartHandler, this));
  167. }
  168. if (this.config.moveHandlerSelector !== null) {
  169. $('body').on('click keypress', this.config.moveHandlerSelector, $.proxy(this.clickHandler, this));
  170. }
  171. };
  172. /**
  173. * Events fired by this entity
  174. *
  175. * @public
  176. * @type {Object}
  177. */
  178. SortableList.EVENTS = {
  179. DRAGSTART: 'sortablelist-dragstart',
  180. DRAG: 'sortablelist-drag',
  181. DROP: 'sortablelist-drop',
  182. DRAGEND: 'sortablelist-dragend'
  183. };
  184. /**
  185. * Resets the temporary classes assigned during dragging
  186. * @private
  187. */
  188. SortableList.prototype.resetDraggedClasses = function() {
  189. var classes = [
  190. CSS.isDraggedClass,
  191. CSS.currentPositionClass,
  192. CSS.overElementClass,
  193. CSS.targetListClass,
  194. ];
  195. for (var i in classes) {
  196. $('.' + classes[i]).removeClass(classes[i]);
  197. }
  198. if (this.proxy) {
  199. this.proxy.remove();
  200. this.proxy = $();
  201. }
  202. };
  203. /**
  204. * Calculates evt.pageX, evt.pageY, evt.clientX and evt.clientY
  205. *
  206. * For touch events pageX and pageY are taken from the first touch;
  207. * For the emulated mousemove event they are taken from the last real event.
  208. *
  209. * @private
  210. * @param {Event} evt
  211. */
  212. SortableList.prototype.calculatePositionOnPage = function(evt) {
  213. if (evt.originalEvent && evt.originalEvent.touches && evt.originalEvent.touches[0] !== undefined) {
  214. // This is a touchmove or touchstart event, get position from the first touch position.
  215. var touch = evt.originalEvent.touches[0];
  216. evt.pageX = touch.pageX;
  217. evt.pageY = touch.pageY;
  218. }
  219. if (evt.pageX === undefined) {
  220. // Information is not present in case of touchend or when event was emulated by autoScroll.
  221. // Take the absolute mouse position from the last event.
  222. evt.pageX = this.lastEvent.pageX;
  223. evt.pageY = this.lastEvent.pageY;
  224. } else {
  225. this.lastEvent = evt;
  226. }
  227. if (evt.clientX === undefined) {
  228. // If not provided in event calculate relative mouse position.
  229. evt.clientX = Math.round(evt.pageX - $(window).scrollLeft());
  230. evt.clientY = Math.round(evt.pageY - $(window).scrollTop());
  231. }
  232. };
  233. /**
  234. * Handler from dragstart event
  235. *
  236. * @private
  237. * @param {Event} evt
  238. */
  239. SortableList.prototype.dragStartHandler = function(evt) {
  240. if (this.info !== null) {
  241. if (this.info.type === 'click' || this.info.type === 'touchend') {
  242. // Ignore double click.
  243. return;
  244. }
  245. // Mouse down or touch while already dragging, cancel previous dragging.
  246. this.moveElement(this.info.sourceList, this.info.sourceNextElement);
  247. this.finishDragging();
  248. }
  249. if (evt.type === 'mousedown' && evt.which !== 1) {
  250. // We only need left mouse click. If this is a mousedown event with right/middle click ignore it.
  251. return;
  252. }
  253. this.calculatePositionOnPage(evt);
  254. var movedElement = $(evt.target).closest($(evt.currentTarget).children());
  255. if (!movedElement.length) {
  256. // Can't find the element user wants to drag. They clicked on the list but outside of any element of the list.
  257. return;
  258. }
  259. // Check that we grabbed the element by the handle.
  260. if (this.config.moveHandlerSelector !== null) {
  261. if (!$(evt.target).closest(this.config.moveHandlerSelector, movedElement).length) {
  262. return;
  263. }
  264. }
  265. evt.stopPropagation();
  266. evt.preventDefault();
  267. // Information about moved element with original location.
  268. // This object is passed to event observers.
  269. this.dragCounter++;
  270. this.info = {
  271. element: movedElement,
  272. sourceNextElement: movedElement.next(),
  273. sourceList: movedElement.parent(),
  274. targetNextElement: movedElement.next(),
  275. targetList: movedElement.parent(),
  276. type: evt.type,
  277. dropped: false,
  278. startX: evt.pageX,
  279. startY: evt.pageY,
  280. startTime: new Date().getTime()
  281. };
  282. $(this.config.targetListSelector).addClass(CSS.targetListClass);
  283. var offset = movedElement.offset();
  284. movedElement.addClass(CSS.currentPositionClass);
  285. this.proxyDelta = {x: offset.left - evt.pageX, y: offset.top - evt.pageY};
  286. this.proxy = $();
  287. var thisDragCounter = this.dragCounter;
  288. setTimeout($.proxy(function() {
  289. // This mousedown event may in fact be a beginning of a 'click' event. Use timeout before showing the
  290. // dragged object so we can catch click event. When timeout finishes make sure that click event
  291. // has not happened during this half a second.
  292. // Verify dragcounter to make sure the user did not manage to do two very fast drag actions one after another.
  293. if (this.info === null || this.info.type === 'click' || this.info.type === 'keypress'
  294. || this.dragCounter !== thisDragCounter) {
  295. return;
  296. }
  297. // Create a proxy - the copy of the dragged element that moves together with a mouse.
  298. this.createProxy();
  299. }, this), 500);
  300. // Start drag.
  301. $(window).on('mousemove touchmove.notPassive mouseup touchend.notPassive', $.proxy(this.dragHandler, this));
  302. $(window).on('keypress', $.proxy(this.dragcancelHandler, this));
  303. // Start autoscrolling. Every time the page is scrolled emulate the mousemove event.
  304. if (this.config.autoScroll) {
  305. autoScroll.start(function() {
  306. $(window).trigger('mousemove');
  307. });
  308. }
  309. this.executeCallback(SortableList.EVENTS.DRAGSTART);
  310. };
  311. /**
  312. * Creates a "proxy" object - a copy of the element that is being moved that always follows the mouse
  313. * @private
  314. */
  315. SortableList.prototype.createProxy = function() {
  316. this.proxy = this.info.element.clone();
  317. this.info.sourceList.append(this.proxy);
  318. this.proxy.removeAttr('id').removeClass(CSS.currentPositionClass)
  319. .addClass(CSS.isDraggedClass).css({position: 'fixed'});
  320. this.proxy.offset({top: this.proxyDelta.y + this.lastEvent.pageY, left: this.proxyDelta.x + this.lastEvent.pageX});
  321. };
  322. /**
  323. * Handler for click event - when user clicks on the drag handler or presses Enter on keyboard
  324. *
  325. * @private
  326. * @param {Event} evt
  327. */
  328. SortableList.prototype.clickHandler = function(evt) {
  329. if (evt.type === 'keypress' && evt.originalEvent.keyCode !== 13 && evt.originalEvent.keyCode !== 32) {
  330. return;
  331. }
  332. if (this.info !== null) {
  333. // Ignore double click.
  334. return;
  335. }
  336. // Find the element that this draghandle belongs to.
  337. var clickedElement = $(evt.target).closest(this.config.moveHandlerSelector),
  338. sourceList = clickedElement.closest(this.config.listSelector),
  339. movedElement = clickedElement.closest(sourceList.children());
  340. if (!movedElement.length) {
  341. return;
  342. }
  343. evt.preventDefault();
  344. evt.stopPropagation();
  345. // Store information about moved element with original location.
  346. this.dragCounter++;
  347. this.info = {
  348. element: movedElement,
  349. sourceNextElement: movedElement.next(),
  350. sourceList: sourceList,
  351. targetNextElement: movedElement.next(),
  352. targetList: sourceList,
  353. dropped: false,
  354. type: evt.type,
  355. startTime: new Date().getTime()
  356. };
  357. this.executeCallback(SortableList.EVENTS.DRAGSTART);
  358. this.displayMoveDialogue(clickedElement);
  359. };
  360. /**
  361. * Finds the position of the mouse inside the element - on the top, on the bottom, on the right or on the left\
  362. *
  363. * Used to determine if the moved element should be moved after or before the current element
  364. *
  365. * @private
  366. * @param {Number} pageX
  367. * @param {Number} pageY
  368. * @param {jQuery} element
  369. * @returns {(Object|null)}
  370. */
  371. SortableList.prototype.getPositionInNode = function(pageX, pageY, element) {
  372. if (!element.length) {
  373. return null;
  374. }
  375. var node = element[0],
  376. offset = 0,
  377. rect = node.getBoundingClientRect(),
  378. y = pageY - (rect.top + window.scrollY),
  379. x = pageX - (rect.left + window.scrollX);
  380. if (x >= -offset && x <= rect.width + offset && y >= -offset && y <= rect.height + offset) {
  381. return {
  382. x: x,
  383. y: y,
  384. xRatio: rect.width ? (x / rect.width) : 0,
  385. yRatio: rect.height ? (y / rect.height) : 0
  386. };
  387. }
  388. return null;
  389. };
  390. /**
  391. * Check if list is horizontal
  392. *
  393. * @param {jQuery} element
  394. * @return {Boolean}
  395. */
  396. SortableList.prototype.isListHorizontal = function(element) {
  397. var isHorizontal = this.config.isHorizontal;
  398. if (isHorizontal === true || isHorizontal === false) {
  399. return isHorizontal;
  400. }
  401. return isHorizontal(element);
  402. };
  403. /**
  404. * Handler for events mousemove touchmove mouseup touchend
  405. *
  406. * @private
  407. * @param {Event} evt
  408. */
  409. SortableList.prototype.dragHandler = function(evt) {
  410. evt.preventDefault();
  411. evt.stopPropagation();
  412. this.calculatePositionOnPage(evt);
  413. // We can not use evt.target here because it will most likely be our proxy.
  414. // Move the proxy out of the way so we can find the element at the current mouse position.
  415. this.proxy.offset({top: -1000, left: -1000});
  416. // Find the element at the current mouse position.
  417. var element = $(document.elementFromPoint(evt.clientX, evt.clientY));
  418. // Find the list element and the list over the mouse position.
  419. var mainElement = this.info.element[0],
  420. isNotSelf = function() {
  421. return this !== mainElement;
  422. },
  423. current = element.closest('.' + CSS.targetListClass + ' > :not(.' + CSS.isDraggedClass + ')').filter(isNotSelf),
  424. currentList = element.closest('.' + CSS.targetListClass),
  425. proxy = this.proxy,
  426. isNotProxy = function() {
  427. return !proxy || !proxy.length || this !== proxy[0];
  428. };
  429. // Add the specified class to the list element we are hovering.
  430. $('.' + CSS.overElementClass).removeClass(CSS.overElementClass);
  431. current.addClass(CSS.overElementClass);
  432. // Move proxy to the current position.
  433. this.proxy.offset({top: this.proxyDelta.y + evt.pageY, left: this.proxyDelta.x + evt.pageX});
  434. if (currentList.length && !currentList.children().filter(isNotProxy).length) {
  435. // Mouse is over an empty list.
  436. this.moveElement(currentList, $());
  437. } else if (current.length === 1 && !this.info.element.find(current[0]).length) {
  438. // Mouse is over an element in a list - find whether we should move the current position
  439. // above or below this element.
  440. var coordinates = this.getPositionInNode(evt.pageX, evt.pageY, current);
  441. if (coordinates) {
  442. var parent = current.parent(),
  443. ratio = this.isListHorizontal(parent) ? coordinates.xRatio : coordinates.yRatio,
  444. subList = current.find('.' + CSS.targetListClass),
  445. subListEmpty = !subList.children().filter(isNotProxy).filter(isNotSelf).length;
  446. if (subList.length && subListEmpty && ratio > 0.2 && ratio < 0.8) {
  447. // This is an element that is a parent of an empty list and we are around the middle of this element.
  448. // Treat it as if we are over this empty list.
  449. this.moveElement(subList, $());
  450. } else if (ratio > 0.5) {
  451. // Insert after this element.
  452. this.moveElement(parent, current.next().filter(isNotProxy));
  453. } else {
  454. // Insert before this element.
  455. this.moveElement(parent, current);
  456. }
  457. }
  458. }
  459. if (evt.type === 'mouseup' || evt.type === 'touchend') {
  460. // Drop the moved element.
  461. this.info.endX = evt.pageX;
  462. this.info.endY = evt.pageY;
  463. this.info.endTime = new Date().getTime();
  464. this.info.dropped = true;
  465. this.info.positionChanged = this.hasPositionChanged(this.info);
  466. var oldinfo = this.info;
  467. this.executeCallback(SortableList.EVENTS.DROP);
  468. this.finishDragging();
  469. if (evt.type === 'touchend'
  470. && this.config.moveHandlerSelector !== null
  471. && (oldinfo.endTime - oldinfo.startTime < 500)
  472. && !oldinfo.positionChanged) {
  473. // The click event is not triggered on touch screens because we call preventDefault in touchstart handler.
  474. // If the touchend quickly followed touchstart without moving, consider it a "click".
  475. this.clickHandler(evt);
  476. }
  477. }
  478. };
  479. /**
  480. * Checks if the position of the dragged element in the list has changed
  481. *
  482. * @private
  483. * @param {Object} info
  484. * @return {Boolean}
  485. */
  486. SortableList.prototype.hasPositionChanged = function(info) {
  487. return info.sourceList[0] !== info.targetList[0] ||
  488. info.sourceNextElement.length !== info.targetNextElement.length ||
  489. (info.sourceNextElement.length && info.sourceNextElement[0] !== info.targetNextElement[0]);
  490. };
  491. /**
  492. * Moves the current position of the dragged element
  493. *
  494. * @private
  495. * @param {jQuery} parentElement
  496. * @param {jQuery} beforeElement
  497. */
  498. SortableList.prototype.moveElement = function(parentElement, beforeElement) {
  499. var dragEl = this.info.element;
  500. if (beforeElement.length && beforeElement[0] === dragEl[0]) {
  501. // Insert before the current position of the dragged element - nothing to do.
  502. return;
  503. }
  504. if (parentElement[0] === this.info.targetList[0] &&
  505. beforeElement.length === this.info.targetNextElement.length &&
  506. beforeElement[0] === this.info.targetNextElement[0]) {
  507. // Insert in the same location as the current position - nothing to do.
  508. return;
  509. }
  510. if (beforeElement.length) {
  511. // Move the dragged element before the specified element.
  512. parentElement[0].insertBefore(dragEl[0], beforeElement[0]);
  513. } else if (this.proxy && this.proxy.parent().length && this.proxy.parent()[0] === parentElement[0]) {
  514. // We need to move to the end of the list but the last element in this list is a proxy.
  515. // Always leave the proxy in the end of the list.
  516. parentElement[0].insertBefore(dragEl[0], this.proxy[0]);
  517. } else {
  518. // Insert in the end of a list (when proxy is in another list).
  519. parentElement[0].appendChild(dragEl[0]);
  520. }
  521. // Save the current position of the dragged element in the list.
  522. this.info.targetList = parentElement;
  523. this.info.targetNextElement = beforeElement;
  524. this.executeCallback(SortableList.EVENTS.DRAG);
  525. };
  526. /**
  527. * Finish dragging (when dropped or cancelled).
  528. * @private
  529. */
  530. SortableList.prototype.finishDragging = function() {
  531. this.resetDraggedClasses();
  532. if (this.config.autoScroll) {
  533. autoScroll.stop();
  534. }
  535. $(window).off('mousemove touchmove.notPassive mouseup touchend.notPassive', $.proxy(this.dragHandler, this));
  536. $(window).off('keypress', $.proxy(this.dragcancelHandler, this));
  537. this.executeCallback(SortableList.EVENTS.DRAGEND);
  538. this.info = null;
  539. };
  540. /**
  541. * Executes callback specified in sortable list parameters
  542. *
  543. * @private
  544. * @param {String} eventName
  545. */
  546. SortableList.prototype.executeCallback = function(eventName) {
  547. this.info.element.trigger(eventName, this.info);
  548. };
  549. /**
  550. * Handler from keypress event (cancel dragging when Esc is pressed)
  551. *
  552. * @private
  553. * @param {Event} evt
  554. */
  555. SortableList.prototype.dragcancelHandler = function(evt) {
  556. if (evt.type !== 'keypress' || evt.originalEvent.keyCode !== 27) {
  557. // Only cancel dragging when Esc was pressed.
  558. return;
  559. }
  560. // Dragging was cancelled. Return item to the original position.
  561. this.moveElement(this.info.sourceList, this.info.sourceNextElement);
  562. this.finishDragging();
  563. };
  564. /**
  565. * Returns the name of the current element to be used in the move dialogue
  566. *
  567. * @public
  568. * @param {jQuery} element
  569. * @return {Promise}
  570. */
  571. SortableList.prototype.getElementName = function(element) {
  572. return $.Deferred().resolve(element.text());
  573. };
  574. /**
  575. * Returns the label for the potential move destination, i.e. "After ElementX" or "To the top of the list"
  576. *
  577. * Note that we use "after" in the label for better UX
  578. *
  579. * @public
  580. * @param {jQuery} parentElement
  581. * @param {jQuery} afterElement
  582. * @return {Promise}
  583. */
  584. SortableList.prototype.getDestinationName = function(parentElement, afterElement) {
  585. if (!afterElement.length) {
  586. return str.get_string('movecontenttothetop', 'moodle');
  587. } else {
  588. return this.getElementName(afterElement)
  589. .then(function(name) {
  590. return str.get_string('movecontentafter', 'moodle', name);
  591. });
  592. }
  593. };
  594. /**
  595. * Returns the title for the move dialogue ("Move elementY")
  596. *
  597. * @public
  598. * @param {jQuery} element
  599. * @param {jQuery} handler
  600. * @return {Promise}
  601. */
  602. SortableList.prototype.getMoveDialogueTitle = function(element, handler) {
  603. if (handler.attr('title')) {
  604. return $.Deferred().resolve(handler.attr('title'));
  605. }
  606. return this.getElementName(element).then(function(name) {
  607. return str.get_string('movecontent', 'moodle', name);
  608. });
  609. };
  610. /**
  611. * Returns the list of possible move destinations
  612. *
  613. * @private
  614. * @return {Promise}
  615. */
  616. SortableList.prototype.getDestinationsList = function() {
  617. var addedLists = [],
  618. targets = $(this.config.targetListSelector),
  619. destinations = $('<ul/>').addClass(CSS.keyboardDragClass),
  620. result = $.when().then(function() {
  621. return destinations;
  622. }),
  623. createLink = $.proxy(function(parentElement, beforeElement, afterElement) {
  624. if (beforeElement.is(this.info.element) || afterElement.is(this.info.element)) {
  625. // Can not move before or after itself.
  626. return;
  627. }
  628. if ($.contains(this.info.element[0], parentElement[0])) {
  629. // Can not move to its own child.
  630. return;
  631. }
  632. result = result
  633. .then($.proxy(function() {
  634. return this.getDestinationName(parentElement, afterElement);
  635. }, this))
  636. .then(function(txt) {
  637. var li = $('<li/>').appendTo(destinations);
  638. var a = $('<a href="#"/>').attr('data-core_sortable_list-quickmove', 1).appendTo(li);
  639. a.data('parent-element', parentElement).data('before-element', beforeElement).text(txt);
  640. return destinations;
  641. });
  642. }, this),
  643. addList = function() {
  644. // Destination lists may be nested. We want to add all move destinations in the same
  645. // order they appear on the screen for the user.
  646. if ($.inArray(this, addedLists) !== -1) {
  647. return;
  648. }
  649. addedLists.push(this);
  650. var list = $(this),
  651. children = list.children();
  652. children.each(function() {
  653. var element = $(this);
  654. createLink(list, element, element.prev());
  655. // Add all nested lists.
  656. element.find(targets).each(addList);
  657. });
  658. createLink(list, $(), children.last());
  659. };
  660. targets.each(addList);
  661. return result;
  662. };
  663. /**
  664. * Displays the dialogue to move element.
  665. * @param {jQuery} clickedElement element to return focus to after the modal is closed
  666. * @private
  667. */
  668. SortableList.prototype.displayMoveDialogue = function(clickedElement) {
  669. ModalFactory.create({
  670. type: ModalFactory.types.CANCEL,
  671. title: this.getMoveDialogueTitle(this.info.element, clickedElement),
  672. body: this.getDestinationsList()
  673. }).then($.proxy(function(modal) {
  674. var quickMoveHandler = $.proxy(function(e) {
  675. e.preventDefault();
  676. e.stopPropagation();
  677. this.moveElement($(e.currentTarget).data('parent-element'), $(e.currentTarget).data('before-element'));
  678. this.info.endTime = new Date().getTime();
  679. this.info.positionChanged = this.hasPositionChanged(this.info);
  680. this.info.dropped = true;
  681. clickedElement.focus();
  682. this.executeCallback(SortableList.EVENTS.DROP);
  683. modal.hide();
  684. }, this);
  685. modal.getRoot().on('click', '[data-core_sortable_list-quickmove]', quickMoveHandler);
  686. modal.getRoot().on(ModalEvents.hidden, $.proxy(function() {
  687. // Always destroy when hidden, it is generated dynamically each time.
  688. modal.getRoot().off('click', '[data-core_sortable_list-quickmove]', quickMoveHandler);
  689. modal.destroy();
  690. this.finishDragging();
  691. }, this));
  692. modal.setLarge();
  693. modal.show();
  694. return modal;
  695. }, this)).catch(Notification.exception);
  696. };
  697. return SortableList;
  698. });