From b28896db1222c87c00e5948122e9f6cb164c40e0 Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Thu, 1 Jul 2021 11:24:55 +1000 Subject: [PATCH] Fix bug with groups not being removed when deleting --- src/contexts/GroupContext.js | 11 ++++++++++- src/contexts/TileDragContext.js | 5 ----- src/helpers/group.js | 8 +++++++- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/contexts/GroupContext.js b/src/contexts/GroupContext.js index fa123d9..3b2138d 100644 --- a/src/contexts/GroupContext.js +++ b/src/contexts/GroupContext.js @@ -29,7 +29,16 @@ export function GroupProvider({ const [openGroupItems, setOpenGroupItems] = useState([]); useEffect(() => { if (openGroupId) { - setOpenGroupItems(getGroupItems(groupsFromIds([openGroupId], groups)[0])); + const openGroups = groupsFromIds([openGroupId], groups); + if (openGroups.length === 1) { + const openGroup = openGroups[0]; + setOpenGroupItems(getGroupItems(openGroup)); + } else { + // Close group if we can't find it + // This can happen if it was deleted or all it's items were deleted + setOpenGroupItems([]); + setOpenGroupId(); + } } else { setOpenGroupItems([]); } diff --git a/src/contexts/TileDragContext.js b/src/contexts/TileDragContext.js index 3663f5a..3a0f52f 100644 --- a/src/contexts/TileDragContext.js +++ b/src/contexts/TileDragContext.js @@ -58,7 +58,6 @@ export function TileDragProvider({ selectedGroupIds, onGroupsChange, onGroupSelect, - onGroupClose, filter, } = useGroup(); @@ -147,10 +146,6 @@ export function TileDragProvider({ onGroupSelect(); // Handle tile ungroup const newGroups = ungroup(groups, openGroupId, selectedIndices); - // Close group if it was removed - if (!newGroups.find((group) => group.id === openGroupId)) { - onGroupClose(); - } onGroupsChange(newGroups); } else if (over.id === ADD_TO_MAP_ID) { onDragAdd && diff --git a/src/helpers/group.js b/src/helpers/group.js index ba62aa4..dd8571b 100644 --- a/src/helpers/group.js +++ b/src/helpers/group.js @@ -31,7 +31,9 @@ export function groupsFromIds(groupIds, groups) { const groupsByIds = keyBy(groups, "id"); const filteredGroups = []; for (let groupId of groupIds) { - filteredGroups.push(groupsByIds[groupId]); + if (groupId in groupsByIds) { + filteredGroups.push(groupsByIds[groupId]); + } } return filteredGroups; } @@ -259,6 +261,10 @@ export function removeGroupsItems(groups, itemIds) { newGroups[i].items.splice(j, 1); } } + // Remove group if no items are left + if (newGroups[i].items.length === 0) { + newGroups.splice(i, 1); + } } }