From c00a9ed241a4cbe08590a8987642560096c4fb53 Mon Sep 17 00:00:00 2001
From: john <johnbarlas39@gmail.com>
Date: Thu, 20 Apr 2017 01:55:56 +0300
Subject: [PATCH] implement chapters dnd with patches

---
 app/components/BookBuilder/Division.jsx | 50 +++++++++++++++++--------
 1 file changed, 35 insertions(+), 15 deletions(-)

diff --git a/app/components/BookBuilder/Division.jsx b/app/components/BookBuilder/Division.jsx
index a411be7..a26075a 100644
--- a/app/components/BookBuilder/Division.jsx
+++ b/app/components/BookBuilder/Division.jsx
@@ -80,32 +80,52 @@ export class Division extends React.Component {
 
     let toUpdate = []
 
+    // dragging upwards
     if (dragIndex > hoverIndex) {
-      const toModify = _.filter(chapters, function (c) {
+      // find the chapters that changed place
+      const toModify = _.filter(chapters, c => {
         return c.index >= hoverIndex && c.index < dragIndex
       })
-      _.forEach(toModify, function (c) {
-        c.index += 1
-        // update(book, c)
+
+      // build the patches for the chapters' updates
+      const patches = _.map(toModify, chapter => {
+        return {
+          id: chapter.id,
+          index: (chapter.index + 1)
+        }
       })
-      toUpdate = _.union(toUpdate, toModify)
-    } else if (dragIndex < hoverIndex) {
+
+      toUpdate = _.union(toUpdate, patches)
+    }
+
+    // dragging downwards
+    if (dragIndex < hoverIndex) {
+      // TODO -- refactor?
+      // do the same as above
       const toModify = _.filter(chapters, function (c) {
         return c.index <= hoverIndex && c.index > dragIndex
       })
-      _.forEach(toModify, function (c) {
-        c.index -= 1
-        // update(book, c)
+
+      const patches = _.map(toModify, chapter => {
+        return {
+          id: chapter.id,
+          index: (chapter.index - 1)
+        }
       })
-      toUpdate = _.union(toUpdate, toModify)
+
+      toUpdate = _.union(toUpdate, patches)
     }
 
-    dragChapter.index = hoverIndex
-    // update(book, dragChapter)
-    toUpdate.push(dragChapter)
+    // add the dragged chapter to the list of patches that are needed
+    const draggedPatch = {
+      id: dragChapter.id,
+      index: hoverIndex
+    }
+    toUpdate.push(draggedPatch)
 
-    _.forEach(toUpdate, function (chapter) {
-      update(book, chapter)
+    // perform all the updates
+    _.forEach(toUpdate, patch => {
+      update(book, patch)
     })
   }
 
-- 
GitLab