Swap.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import {
  2. toggleClass,
  3. index
  4. } from '../../src/utils.js';
  5. let lastSwapEl;
  6. function SwapPlugin() {
  7. function Swap() {
  8. this.defaults = {
  9. swapClass: 'sortable-swap-highlight'
  10. };
  11. }
  12. Swap.prototype = {
  13. dragStart({ dragEl }) {
  14. lastSwapEl = dragEl;
  15. },
  16. dragOverValid({ completed, target, onMove, activeSortable, changed, cancel }) {
  17. if (!activeSortable.options.swap) return;
  18. let el = this.sortable.el,
  19. options = this.options;
  20. if (target && target !== el) {
  21. let prevSwapEl = lastSwapEl;
  22. if (onMove(target) !== false) {
  23. toggleClass(target, options.swapClass, true);
  24. lastSwapEl = target;
  25. } else {
  26. lastSwapEl = null;
  27. }
  28. if (prevSwapEl && prevSwapEl !== lastSwapEl) {
  29. toggleClass(prevSwapEl, options.swapClass, false);
  30. }
  31. }
  32. changed();
  33. completed(true);
  34. cancel();
  35. },
  36. drop({ activeSortable, putSortable, dragEl }) {
  37. let toSortable = (putSortable || this.sortable);
  38. let options = this.options;
  39. lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false);
  40. if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) {
  41. if (dragEl !== lastSwapEl) {
  42. toSortable.captureAnimationState();
  43. if (toSortable !== activeSortable) activeSortable.captureAnimationState();
  44. swapNodes(dragEl, lastSwapEl);
  45. toSortable.animateAll();
  46. if (toSortable !== activeSortable) activeSortable.animateAll();
  47. }
  48. }
  49. },
  50. nulling() {
  51. lastSwapEl = null;
  52. }
  53. };
  54. return Object.assign(Swap, {
  55. pluginName: 'swap',
  56. eventProperties() {
  57. return {
  58. swapItem: lastSwapEl
  59. };
  60. }
  61. });
  62. }
  63. function swapNodes(n1, n2) {
  64. let p1 = n1.parentNode,
  65. p2 = n2.parentNode,
  66. i1, i2;
  67. if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return;
  68. i1 = index(n1);
  69. i2 = index(n2);
  70. if (p1.isEqualNode(p2) && i1 < i2) {
  71. i2++;
  72. }
  73. p1.insertBefore(n2, p1.children[i1]);
  74. p2.insertBefore(n1, p2.children[i2]);
  75. }
  76. export default SwapPlugin;