All files / src/hooks deleteObjects.ts

60.86% Statements 14/23
55.55% Branches 5/9
62.5% Functions 5/8
68.42% Lines 13/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                          21362x 21362x 21362x 21362x     4x           4x 19x   4x           4x           4x 32x   4x         22760x    
import {
  api,
  SimulationObjectRetrieveRead,
  useUnitopsSimulationobjectsDestroyMutation,
} from "@/api/apiStore.gen";
import { useFlowsheetId } from "@/hooks/project";
import { useAppDispatch } from "@/store/hooks";
import { useCurrentGroupId } from "./flowsheetObjects";
 
/** Delete one object while Django records the complete reversible batch. */
export const useDeleteSimulationObject = () => {
  const [deleteObject] = useUnitopsSimulationobjectsDestroyMutation();
  const optimisticallyDeleteSelection = useOptimisticallyDeleteSelection();
 
  return (simulationObject: SimulationObjectRetrieveRead) => {
    deleteObject({ id: simulationObject.id });
    optimisticallyDeleteSelection([simulationObject.id]);
  };
};
 
/** Remove deleted graphics immediately while the mutation refetches server state. */
export const useOptimisticallyDeleteSelection = () => {
  const flowsheetId = useFlowsheetId();
  const groupId = useCurrentGroupId();
  const dispatch = useAppDispatch();
 
  return (containedObjectIds: number[]) => {
    dispatch(
      api.util.updateQueryData(
        "graphicsObjectsList",
        { group: groupId },
        (previous) => {
          for (const simulationObjectId of containedObjectIds) {
            const index = previous.findIndex(
              (item) => item.simulationObject.id === simulationObjectId,
            );
            Iif (index !== -1) previous.splice(index, 1);
          }
        },
      ),
    );
 
    dispatch(
      api.util.updateQueryData(
        "unitopsSimulationobjectsList",
        { flowsheet: flowsheetId },
        (previous) => {
          for (const simulationObjectId of containedObjectIds) {
            const index = previous.findIndex(
              (item) => item.id === simulationObjectId,
            );
            Iif (index !== -1) previous.splice(index, 1);
          }
        },
      ),
    );
  };
};