/cms/static/cms/js/plugins/jquery.ui.nestedsortable.js

http://github.com/divio/django-cms · JavaScript · 613 lines · 437 code · 120 blank · 56 comment · 198 complexity · 52dfa9df48477437c4a156279c75b8dc MD5 · raw file

  1. /*
  2. * jQuery UI Nested Sortable
  3. * v 2.0 / 29 oct 2012
  4. * http://mjsarfatti.com/sandbox/nestedSortable
  5. *
  6. * Depends on:
  7. * jquery.ui.sortable.js 1.10+
  8. *
  9. * Copyright (c) 2010-2013 Manuele J Sarfatti
  10. * Licensed under the MIT License
  11. * http://www.opensource.org/licenses/mit-license.php
  12. */
  13. (function($) {
  14. function isOverAxis( x, reference, size ) {
  15. return ( x > reference ) && ( x < ( reference + size ) );
  16. }
  17. $.widget("mjs.nestedSortable", $.extend({}, $.ui.sortable.prototype, {
  18. options: {
  19. doNotClear: false,
  20. expandOnHover: 700,
  21. isAllowed: function(placeholder, placeholderParent, originalItem) { return true; },
  22. isTree: false,
  23. listType: 'ol',
  24. maxLevels: 0,
  25. protectRoot: false,
  26. rootID: null,
  27. rtl: false,
  28. startCollapsed: false,
  29. tabSize: 20,
  30. branchClass: 'mjs-nestedSortable-branch',
  31. collapsedClass: 'mjs-nestedSortable-collapsed',
  32. disableNestingClass: 'mjs-nestedSortable-no-nesting',
  33. errorClass: 'mjs-nestedSortable-error',
  34. expandedClass: 'mjs-nestedSortable-expanded',
  35. hoveringClass: 'mjs-nestedSortable-hovering',
  36. leafClass: 'mjs-nestedSortable-leaf'
  37. },
  38. _create: function() {
  39. this.element.data('ui-sortable', this.element.data('mjs-nestedSortable'));
  40. // mjs - prevent browser from freezing if the HTML is not correct
  41. if (!this.element.is(this.options.listType))
  42. throw new Error('nestedSortable: Please check that the listType option is set to your actual list type');
  43. // mjs - force 'intersect' tolerance method if we have a tree with expanding/collapsing functionality
  44. if (this.options.isTree && this.options.expandOnHover) {
  45. this.options.tolerance = 'intersect';
  46. }
  47. $.ui.sortable.prototype._create.apply(this, arguments);
  48. // mjs - prepare the tree by applying the right classes (the CSS is responsible for actual hide/show functionality)
  49. if (this.options.isTree) {
  50. var self = this;
  51. $(this.items).each(function() {
  52. var $li = this.item;
  53. if ($li.children(self.options.listType).length) {
  54. $li.addClass(self.options.branchClass);
  55. // expand/collapse class only if they have children
  56. if (self.options.startCollapsed) $li.addClass(self.options.collapsedClass);
  57. else $li.addClass(self.options.expandedClass);
  58. } else {
  59. $li.addClass(self.options.leafClass);
  60. }
  61. })
  62. }
  63. },
  64. _destroy: function() {
  65. this.element
  66. .removeData("mjs-nestedSortable")
  67. .removeData("ui-sortable");
  68. return $.ui.sortable.prototype._destroy.apply(this, arguments);
  69. },
  70. _mouseDrag: function(event) {
  71. var i, item, itemElement, intersection,
  72. o = this.options,
  73. scrolled = false;
  74. //Compute the helpers position
  75. this.position = this._generatePosition(event);
  76. this.positionAbs = this._convertPositionTo("absolute");
  77. if (!this.lastPositionAbs) {
  78. this.lastPositionAbs = this.positionAbs;
  79. }
  80. //Do scrolling
  81. if(this.options.scroll) {
  82. if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {
  83. if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
  84. this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
  85. } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
  86. this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
  87. }
  88. if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
  89. this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
  90. } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
  91. this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
  92. }
  93. } else {
  94. if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
  95. scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
  96. } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
  97. scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
  98. }
  99. if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
  100. scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
  101. } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
  102. scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
  103. }
  104. }
  105. if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
  106. $.ui.ddmanager.prepareOffsets(this, event);
  107. }
  108. //Regenerate the absolute position used for position checks
  109. this.positionAbs = this._convertPositionTo("absolute");
  110. // mjs - find the top offset before rearrangement,
  111. var previousTopOffset = this.placeholder.offset().top;
  112. //Set the helper position
  113. if(!this.options.axis || this.options.axis !== "y") {
  114. this.helper[0].style.left = this.position.left+"px";
  115. }
  116. if(!this.options.axis || this.options.axis !== "x") {
  117. this.helper[0].style.top = this.position.top+"px";
  118. }
  119. // mjs - check and reset hovering state at each cycle
  120. this.hovering = this.hovering ? this.hovering : null;
  121. this.mouseentered = this.mouseentered ? this.mouseentered : false;
  122. // mjs - let's start caching some variables
  123. var parentItem = (this.placeholder[0].parentNode.parentNode &&
  124. $(this.placeholder[0].parentNode.parentNode).closest('.ui-sortable').length)
  125. ? $(this.placeholder[0].parentNode.parentNode)
  126. : null,
  127. level = this._getLevel(this.placeholder),
  128. childLevels = this._getChildLevels(this.helper);
  129. var newList = document.createElement(o.listType);
  130. //Rearrange
  131. for (i = this.items.length - 1; i >= 0; i--) {
  132. //Cache variables and intersection, continue if no intersection
  133. item = this.items[i];
  134. itemElement = item.item[0];
  135. intersection = this._intersectsWithPointer(item);
  136. if (!intersection) {
  137. continue;
  138. }
  139. // Only put the placeholder inside the current Container, skip all
  140. // items form other containers. This works because when moving
  141. // an item from one container to another the
  142. // currentContainer is switched before the placeholder is moved.
  143. //
  144. // Without this moving items in "sub-sortables" can cause the placeholder to jitter
  145. // beetween the outer and inner container.
  146. if (item.instance !== this.currentContainer) {
  147. continue;
  148. }
  149. // cannot intersect with itself
  150. // no useless actions that have been done before
  151. // no action if the item moved is the parent of the item checked
  152. if (itemElement !== this.currentItem[0] &&
  153. this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
  154. !$.contains(this.placeholder[0], itemElement) &&
  155. (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
  156. ) {
  157. // mjs - we are intersecting an element: trigger the mouseenter event and store this state
  158. if (!this.mouseentered) {
  159. $(itemElement).mouseenter();
  160. this.mouseentered = true;
  161. }
  162. // mjs - if the element has children and they are hidden, show them after a delay (CSS responsible)
  163. if (o.isTree && $(itemElement).hasClass(o.collapsedClass) && o.expandOnHover) {
  164. if (!this.hovering) {
  165. $(itemElement).addClass(o.hoveringClass);
  166. var self = this;
  167. this.hovering = window.setTimeout(function() {
  168. $(itemElement).removeClass(o.collapsedClass).addClass(o.expandedClass);
  169. self.refreshPositions();
  170. self._trigger("expand", event, self._uiHash());
  171. }, o.expandOnHover);
  172. }
  173. }
  174. this.direction = intersection == 1 ? "down" : "up";
  175. // mjs - rearrange the elements and reset timeouts and hovering state
  176. if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
  177. $(itemElement).mouseleave();
  178. this.mouseentered = false;
  179. $(itemElement).removeClass(o.hoveringClass);
  180. this.hovering && window.clearTimeout(this.hovering);
  181. this.hovering = null;
  182. // mjs - do not switch container if it's a root item and 'protectRoot' is true
  183. // or if it's not a root item but we are trying to make it root
  184. if (o.protectRoot
  185. && ! (this.currentItem[0].parentNode == this.element[0] // it's a root item
  186. && itemElement.parentNode != this.element[0]) // it's intersecting a non-root item
  187. ) {
  188. if (this.currentItem[0].parentNode != this.element[0]
  189. && itemElement.parentNode == this.element[0]
  190. ) {
  191. if ( ! $(itemElement).children(o.listType).length) {
  192. itemElement.appendChild(newList);
  193. o.isTree && $(itemElement).removeClass(o.leafClass).addClass(o.branchClass + ' ' + o.expandedClass);
  194. }
  195. var a = this.direction === "down" ? $(itemElement).prev().children(o.listType) : $(itemElement).children(o.listType);
  196. if (a[0] !== undefined) {
  197. this._rearrange(event, null, a);
  198. }
  199. } else {
  200. this._rearrange(event, item);
  201. }
  202. } else if ( ! o.protectRoot) {
  203. this._rearrange(event, item);
  204. }
  205. } else {
  206. break;
  207. }
  208. // Clear emtpy ul's/ol's
  209. this._clearEmpty(itemElement);
  210. this._trigger("change", event, this._uiHash());
  211. break;
  212. }
  213. }
  214. // mjs - to find the previous sibling in the list, keep backtracking until we hit a valid list item.
  215. var previousItem = this.placeholder[0].previousSibling ? $(this.placeholder[0].previousSibling) : null;
  216. if (previousItem != null) {
  217. while (previousItem[0].nodeName.toLowerCase() != $(o.listType)[0].nodeName.toLowerCase() || previousItem[0] == this.currentItem[0] || previousItem[0] == this.helper[0]) {
  218. if (previousItem[0].previousSibling) {
  219. previousItem = $(previousItem[0].previousSibling);
  220. } else {
  221. previousItem = null;
  222. break;
  223. }
  224. }
  225. }
  226. // mjs - to find the next sibling in the list, keep stepping forward until we hit a valid list item.
  227. var nextItem = this.placeholder[0].nextSibling ? $(this.placeholder[0].nextSibling) : null;
  228. if (nextItem != null) {
  229. while (nextItem[0].nodeName.toLowerCase() != $(o.listType)[0].nodeName.toLowerCase() || nextItem[0] == this.currentItem[0] || nextItem[0] == this.helper[0]) {
  230. if (nextItem[0].nextSibling) {
  231. nextItem = $(nextItem[0].nextSibling);
  232. } else {
  233. nextItem = null;
  234. break;
  235. }
  236. }
  237. }
  238. this.beyondMaxLevels = 0;
  239. // mjs - if the item is moved to the left, send it one level up but only if it's at the bottom of the list
  240. if (parentItem != null
  241. && nextItem == null
  242. && ! (o.protectRoot && parentItem[0].parentNode == this.element[0])
  243. &&
  244. (o.rtl && (this.positionAbs.left + this.helper.outerWidth() > parentItem.offset().left + parentItem.outerWidth())
  245. || ! o.rtl && (this.positionAbs.left < parentItem.offset().left))
  246. ) {
  247. parentItem.after(this.placeholder[0]);
  248. if (o.isTree && parentItem.children(o.listItem).children(o.listItem + ':visible:not(.ui-sortable-helper)').length < 1) {
  249. parentItem.removeClass(this.options.branchClass + ' ' + this.options.expandedClass)
  250. .addClass(this.options.leafClass);
  251. }
  252. this._clearEmpty(parentItem[0]);
  253. this._trigger("change", event, this._uiHash());
  254. }
  255. // mjs - if the item is below a sibling and is moved to the right, make it a child of that sibling
  256. else if (previousItem != null
  257. && ! previousItem.hasClass(o.disableNestingClass)
  258. &&
  259. (previousItem.children(o.listType).length && previousItem.children(o.listType).is(':visible')
  260. || ! previousItem.children(o.listType).length)
  261. && ! (o.protectRoot && this.currentItem[0].parentNode == this.element[0])
  262. &&
  263. (o.rtl && (this.positionAbs.left + this.helper.outerWidth() < previousItem.offset().left + previousItem.outerWidth() - o.tabSize)
  264. || ! o.rtl && (this.positionAbs.left > previousItem.offset().left + o.tabSize))
  265. ) {
  266. this._isAllowed(previousItem, level, level+childLevels+1);
  267. if (!previousItem.children(o.listType).length) {
  268. previousItem[0].appendChild(newList);
  269. o.isTree && previousItem.removeClass(o.leafClass).addClass(o.branchClass + ' ' + o.expandedClass);
  270. }
  271. // mjs - if this item is being moved from the top, add it to the top of the list.
  272. if (previousTopOffset && (previousTopOffset <= previousItem.offset().top)) {
  273. previousItem.children(o.listType).prepend(this.placeholder);
  274. }
  275. // mjs - otherwise, add it to the bottom of the list.
  276. else if(previousItem.children(o.listType).length) {
  277. previousItem.children(o.listType)[0].appendChild(this.placeholder[0]);
  278. }
  279. this._trigger("change", event, this._uiHash());
  280. }
  281. else {
  282. this._isAllowed(parentItem, level, level+childLevels);
  283. }
  284. //Post events to containers
  285. this._contactContainers(event);
  286. //Interconnect with droppables
  287. if($.ui.ddmanager) {
  288. $.ui.ddmanager.drag(this, event);
  289. }
  290. //Call callbacks
  291. this._trigger('sort', event, this._uiHash());
  292. this.lastPositionAbs = this.positionAbs;
  293. return false;
  294. },
  295. _mouseStop: function(event, noPropagation) {
  296. // mjs - if the item is in a position not allowed, send it back
  297. if (this.beyondMaxLevels) {
  298. this.placeholder.removeClass(this.options.errorClass);
  299. if (this.domPosition.prev) {
  300. $(this.domPosition.prev).after(this.placeholder);
  301. } else {
  302. $(this.domPosition.parent).prepend(this.placeholder);
  303. }
  304. this._trigger("revert", event, this._uiHash());
  305. }
  306. // mjs - clear the hovering timeout, just to be sure
  307. $('.'+this.options.hoveringClass).mouseleave().removeClass(this.options.hoveringClass);
  308. this.mouseentered = false;
  309. this.hovering && window.clearTimeout(this.hovering);
  310. this.hovering = null;
  311. $.ui.sortable.prototype._mouseStop.apply(this, arguments);
  312. },
  313. // mjs - this function is slightly modified to make it easier to hover over a collapsed element and have it expand
  314. _intersectsWithSides: function(item) {
  315. var half = this.options.isTree ? .8 : .5;
  316. var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height*half), item.height),
  317. isOverTopHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top - (item.height*half), item.height),
  318. isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
  319. verticalDirection = this._getDragVerticalDirection(),
  320. horizontalDirection = this._getDragHorizontalDirection();
  321. if (this.floating && horizontalDirection) {
  322. return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
  323. } else {
  324. return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && isOverTopHalf));
  325. }
  326. },
  327. _contactContainers: function(event) {
  328. if (this.options.protectRoot && this.currentItem[0].parentNode == this.element[0] ) {
  329. return;
  330. }
  331. $.ui.sortable.prototype._contactContainers.apply(this, arguments);
  332. },
  333. _clear: function(event, noPropagation) {
  334. $.ui.sortable.prototype._clear.apply(this, arguments);
  335. // mjs - clean last empty ul/ol
  336. for (var i = this.items.length - 1; i >= 0; i--) {
  337. var item = this.items[i].item[0];
  338. this._clearEmpty(item);
  339. }
  340. },
  341. serialize: function(options) {
  342. var o = $.extend({}, this.options, options),
  343. items = this._getItemsAsjQuery(o && o.connected),
  344. str = [];
  345. $(items).each(function() {
  346. var res = ($(o.item || this).attr(o.attribute || 'id') || '')
  347. .match(o.expression || (/(.+)[-=_](.+)/)),
  348. pid = ($(o.item || this).parent(o.listType)
  349. .parent(o.items)
  350. .attr(o.attribute || 'id') || '')
  351. .match(o.expression || (/(.+)[-=_](.+)/));
  352. if (res) {
  353. str.push(((o.key || res[1]) + '[' + (o.key && o.expression ? res[1] : res[2]) + ']')
  354. + '='
  355. + (pid ? (o.key && o.expression ? pid[1] : pid[2]) : o.rootID));
  356. }
  357. });
  358. if(!str.length && o.key) {
  359. str.push(o.key + '=');
  360. }
  361. return str.join('&');
  362. },
  363. toHierarchy: function(options) {
  364. var o = $.extend({}, this.options, options),
  365. sDepth = o.startDepthCount || 0,
  366. ret = [];
  367. $(this.element).children(o.items).each(function () {
  368. var level = _recursiveItems(this);
  369. ret.push(level);
  370. });
  371. return ret;
  372. function _recursiveItems(item) {
  373. var id = ($(item).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
  374. if (id) {
  375. var currentItem = {"id" : id[2]};
  376. if ($(item).children(o.listType).children(o.items).length > 0) {
  377. currentItem.children = [];
  378. $(item).children(o.listType).children(o.items).each(function() {
  379. var level = _recursiveItems(this);
  380. currentItem.children.push(level);
  381. });
  382. }
  383. return currentItem;
  384. }
  385. }
  386. },
  387. toArray: function(options) {
  388. var o = $.extend({}, this.options, options),
  389. sDepth = o.startDepthCount || 0,
  390. ret = [],
  391. left = 1;
  392. if (!o.excludeRoot) {
  393. ret.push({
  394. "item_id": o.rootID,
  395. "parent_id": null,
  396. "depth": sDepth,
  397. "left": left,
  398. "right": ($(o.items, this.element).length + 1) * 2
  399. });
  400. left++
  401. }
  402. $(this.element).children(o.items).each(function () {
  403. left = _recursiveArray(this, sDepth + 1, left);
  404. });
  405. ret = ret.sort(function(a,b){ return (a.left - b.left); });
  406. return ret;
  407. function _recursiveArray(item, depth, left) {
  408. var right = left + 1,
  409. id,
  410. pid;
  411. if ($(item).children(o.listType).children(o.items).length > 0) {
  412. depth ++;
  413. $(item).children(o.listType).children(o.items).each(function () {
  414. right = _recursiveArray($(this), depth, right);
  415. });
  416. depth --;
  417. }
  418. id = ($(item).attr(o.attribute || 'id')).match(o.expression || (/(.+)[-=_](.+)/));
  419. if (depth === sDepth + 1) {
  420. pid = o.rootID;
  421. } else {
  422. var parentItem = ($(item).parent(o.listType)
  423. .parent(o.items)
  424. .attr(o.attribute || 'id'))
  425. .match(o.expression || (/(.+)[-=_](.+)/));
  426. pid = parentItem[2];
  427. }
  428. if (id) {
  429. ret.push({"item_id": id[2], "parent_id": pid, "depth": depth, "left": left, "right": right});
  430. }
  431. left = right + 1;
  432. return left;
  433. }
  434. },
  435. _clearEmpty: function(item) {
  436. var o = this.options;
  437. var emptyList = $(item).children(o.listType);
  438. if (emptyList.length && !emptyList.children().length && !o.doNotClear) {
  439. o.isTree && $(item).removeClass(o.branchClass + ' ' + o.expandedClass).addClass(o.leafClass);
  440. emptyList.remove();
  441. } else if (o.isTree && emptyList.length && emptyList.children().length && emptyList.is(':visible')) {
  442. $(item).removeClass(o.leafClass).addClass(o.branchClass + ' ' + o.expandedClass);
  443. } else if (o.isTree && emptyList.length && emptyList.children().length && !emptyList.is(':visible')) {
  444. $(item).removeClass(o.leafClass).addClass(o.branchClass + ' ' + o.collapsedClass);
  445. }
  446. },
  447. _getLevel: function(item) {
  448. var level = 1;
  449. if (this.options.listType) {
  450. var list = item.closest(this.options.listType);
  451. while (list && list.length > 0 &&
  452. !list.is('.ui-sortable')) {
  453. level++;
  454. list = list.parent().closest(this.options.listType);
  455. }
  456. }
  457. return level;
  458. },
  459. _getChildLevels: function(parent, depth) {
  460. var self = this,
  461. o = this.options,
  462. result = 0;
  463. depth = depth || 0;
  464. $(parent).children(o.listType).children(o.items).each(function (index, child) {
  465. result = Math.max(self._getChildLevels(child, depth + 1), result);
  466. });
  467. return depth ? result + 1 : result;
  468. },
  469. _isAllowed: function(parentItem, level, levels) {
  470. var o = this.options,
  471. maxLevels = this.placeholder.closest('.ui-sortable').nestedSortable('option', 'maxLevels'); // this takes into account the maxLevels set to the recipient list
  472. // mjs - is the root protected?
  473. // mjs - are we nesting too deep?
  474. if ( ! o.isAllowed(this.placeholder, parentItem, this.currentItem)) {
  475. this.placeholder.addClass(o.errorClass);
  476. if (maxLevels < levels && maxLevels != 0) {
  477. this.beyondMaxLevels = levels - maxLevels;
  478. } else {
  479. this.beyondMaxLevels = 1;
  480. }
  481. } else {
  482. if (maxLevels < levels && maxLevels != 0) {
  483. this.placeholder.addClass(o.errorClass);
  484. this.beyondMaxLevels = levels - maxLevels;
  485. } else {
  486. this.placeholder.removeClass(o.errorClass);
  487. this.beyondMaxLevels = 0;
  488. }
  489. }
  490. }
  491. }));
  492. $.mjs.nestedSortable.prototype.options = $.extend({}, $.ui.sortable.prototype.options, $.mjs.nestedSortable.prototype.options);
  493. })(jQuery);