@@ -1477,21 +1477,48 @@ export default function TravelPlan() {
14771477
14781478 function handleComplete(parentId, childId) {
14791479 updatePlan(draft => {
1480- // Remove from the parent place ' s child IDs.
1480+ // remove child id from parent
14811481 const parent = draft[parentId];
1482- parent .childIds = parent .childIds
1483- .filter (id => id !== childId);
1482+ if (parent) {
1483+ parent.childIds = parent.childIds.filter(id => id !== childId);
1484+ }
14841485
1485- // Forget this place and all its subtree.
1486- deleteAllChildren (childId);
1486+ // recursively delete subtree
14871487 function deleteAllChildren(id) {
14881488 const place = draft[id];
1489+ if (!place) return;
14891490 place.childIds.forEach(deleteAllChildren);
14901491 delete draft[id];
14911492 }
1493+ deleteAllChildren(childId);
1494+
1495+ // If parent became empty (and isn' t root), delete it and cascade upward.
1496+ function tryDeleteEmptyParent (pId ) {
1497+ const p = draft[pId];
1498+ if (! p) return ;
1499+
1500+ if (p .childIds .length === 0 && pId !== 0 ) {
1501+ // find the grandparent that references pId
1502+ const grandParent = Object .values (draft).find (x => x .childIds ? .includes (pId));
1503+ const grandParentId = grandParent? .id ;
1504+
1505+ // If we found a grandparent, remove the reference to pId from it
1506+ if (grandParent) {
1507+ grandParent .childIds = grandParent .childIds .filter (cid => cid !== pId);
1508+ }
1509+
1510+ // delete this now-empty parent
1511+ delete draft[pId];
1512+
1513+ // if a grandparent exists, try deleting it too (recursive cascade)
1514+ if (grandParentId !== undefined ) {
1515+ tryDeleteEmptyParent (grandParentId);
1516+ }
1517+ }
1518+ }
1519+ tryDeleteEmptyParent (parentId);
14921520 });
14931521 }
1494-
14951522 const root = plan[0 ];
14961523 const planetIds = root .childIds ;
14971524 return (
0 commit comments