diff --git a/src/common/hotbar-store.ts b/src/common/hotbar-store.ts index ce651dc66b..d81cc2b03a 100644 --- a/src/common/hotbar-store.ts +++ b/src/common/hotbar-store.ts @@ -158,17 +158,37 @@ export class HotbarStore extends BaseStore { hotbar.items[index] = null; } - swapItems(from: number, to: number): void { + findClosestEmptyIndex(from: number, direction = 1) { + let index = from; + + while(this.getActive().items[index] != null) { + index += direction; + } + + return index; + } + + restackItems(from: number, to: number): void { const { items } = this.getActive(); + const source = items[from]; + const moveDown = from < to; if (from < 0 || to < 0 || from >= items.length || to >= items.length || isNaN(from) || isNaN(to)) { throw new Error("Invalid 'from' or 'to' arguments"); } - if (from != to) { - const source = items.splice(from, 1); + if (from == to) { + return; + } - items.splice(to, 0, source[0]); + items.splice(from, 1, null); + + if (items[to] == null) { + items.splice(to, 1, source); + } else { + // Move cells up or down to closes empty cell + items.splice(this.findClosestEmptyIndex(to, moveDown ? -1 : 1), 1); + items.splice(to, 0, source); } } diff --git a/src/renderer/components/hotbar/hotbar-menu.tsx b/src/renderer/components/hotbar/hotbar-menu.tsx index fdbe4f70d4..29008f073c 100644 --- a/src/renderer/components/hotbar/hotbar-menu.tsx +++ b/src/renderer/components/hotbar/hotbar-menu.tsx @@ -45,7 +45,7 @@ export class HotbarMenu extends React.Component { const from = parseInt(source.droppableId); const to = parseInt(destination.droppableId); - HotbarStore.getInstance().swapItems(from, to); + HotbarStore.getInstance().restackItems(from, to); } renderGrid() {