diff --git a/app/components/BookBuilder/Division.jsx b/app/components/BookBuilder/Division.jsx index a411be7f4b97e2f9c88da05a0ea7d90ea68b9a3b..a26075a45ca98c84c6b75c58ffef36eaa71f5459 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) }) }