All files / src/hooks connections.ts

67.71% Statements 86/127
53.84% Branches 21/39
50% Functions 18/36
70.29% Lines 71/101

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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346                                                              522x 522x   77x 77x   77x         60x         599x             1404x 505x 505x 170x 170x       170x 170x 170x   170x 873x 873x 873x 873x   417x   422x     873x 873x     170x 68x 68x 68x   30x   35x     68x     170x       845x             10681x 10681x           3x               3x                   10817x                                             951x 951x                     1109x                 951x 951x 951x 951x 951x     212x           26x           26x         212x 26x       1755x               429x 429x   3x         518x               10681x 10681x                                       10817x                 1601x 1601x   2x           1902x             10681x 10681x 10681x                                                               12657x             10681x   10681x 10681x                                                   12561x    
import { toast } from "sonner";
import {
  useFlowsheetPorts,
  useFlowsheetUnitOps,
  useObjectsPortsMap,
  useStreamType,
} from "@/hooks/flowsheetObjects";
import { useFlowsheetId } from "@/hooks/project";
import { useAppDispatch } from "@/store/hooks";
import {
  api,
  DirectionEnum,
  Port,
  PortRead,
  SimulationObjectRead,
  useUnitopsPortsAddStreamCreateMutation,
  useUnitopsPortsConvertToDnCreateMutation,
  useUnitopsPortsMergeStreamsCreateMutation,
  useUnitopsPortsPartialUpdateMutation,
  useUnitopsPortsSplitStreamCreateMutation,
  useUnitopsSimulationobjectsAddPortCreateMutation,
  useUnitopsSimulationobjectsMergeDecisionNodesCreateMutation,
} from "../api/apiStore.gen";
import { isStream } from "../lib/isStream";
import { useSearchParam } from "./searchParams";
 
/**
 * @returns Available ports for connection
 *   that is, those ports that are not connected to any stream or the connected stream is connected to only one port
 *   in the format of { availableInletPorts: [port1, port2, ...], availableOutletPorts: [port1, port2, ...] }
 */
export function useAvailablePortConnections() {
  const ports = useFlowsheetPorts();
 
  const availableInletPorts: PortRead[] = [];
  const availableOutletPorts: PortRead[] = [];
 
  ports?.forEach((port) => {
    if (!port.stream) {
      if (port.direction === DirectionEnum.Inlet) {
        availableInletPorts.push(port);
      } else {
        availableOutletPorts.push(port);
      }
    }
  });
 
  return { availableInletPorts, availableOutletPorts };
}
 
/**
 * @returns Available streams for connection
 *   in the format of { availableInletStreams: [stream1, stream2, ...], availableOutletStreams: [stream1, stream2, ...] }
 */
export function useAvailableStreamConnections() {
  const flowsheetObjects = useFlowsheetUnitOps();
  const objectsPortsMap = useObjectsPortsMap();
  const streams = flowsheetObjects?.filter((obj) => isStream(obj));
  const powerStreams = streams?.filter(
    (stream) => stream.objectType === "energy_stream",
  );
 
  const availableInletStreams: SimulationObjectRead[] = [];
  const availableOutletStreams: SimulationObjectRead[] = [];
  const availablePowerStreams: SimulationObjectRead[] = [];
 
  streams?.forEach((stream) => {
    const streamPorts = objectsPortsMap.get(stream.id)!;
    let newInlets = [stream];
    let newOutlets = [stream];
    streamPorts.forEach((port) => {
      if (port.direction === DirectionEnum.Inlet) {
        newInlets = [];
      } else {
        newOutlets = [];
      }
    });
    availableInletStreams.push(...newInlets);
    availableOutletStreams.push(...newOutlets);
  });
 
  powerStreams?.forEach((power) => {
    const powerStreamPorts = objectsPortsMap.get(power.id)!;
    let newPowerStreams = [power];
    powerStreamPorts.forEach((port) => {
      if (port.direction === DirectionEnum.Inlet) {
        newPowerStreams = [];
      } else {
        newPowerStreams = [];
      }
    });
    availablePowerStreams.push(...newPowerStreams);
  });
 
  return {
    availableInletStreams,
    availableOutletStreams,
    availablePowerStreams,
  };
}
 
/**
 * Connect two material streams together
 * @returns A function that connects two material streams
 */
export function useMergeStreams() {
  const [mergeStreamsMutation] = useUnitopsPortsMergeStreamsCreateMutation();
 
  return (
    activeObject: SimulationObjectRead,
    overObject: SimulationObjectRead,
  ) => {
    mergeStreamsMutation({
      mergeStreams: {
        stream1: activeObject.id,
        stream2: overObject.id,
      },
    })
      .unwrap()
      .then(() => {
        toast.success("Successfully connected material streams");
      })
      .catch((error) => {
        // Handle different error structures safely
        const errorMessage =
          error?.data?.message || error?.message || "Unknown error occurred";
        toast.error(`Failed to connect material streams: ${errorMessage}`);
        console.error("Merge streams error:", error);
        // Don't add to history if operation failed
      });
  };
}
 
/**
 * Splits an intermediate stream into two streams
 * @param objectId The ID of the stream to split
 * @returns A function that splits the stream
 */
export function useSplitStream() {
  const [splitStream] = useUnitopsPortsSplitStreamCreateMutation();
  return (objectId: number) => {
    splitStream({
      splitStream: {
        stream: objectId,
      },
    });
  };
}
 
/**
 * Splits an intermediate stream with undo/redo tracking
 * This captures the split operation information for proper undo functionality
 */
export function useSplitStreamWithHistory() {
  const [splitStreamMutation] = useUnitopsPortsSplitStreamCreateMutation();
 
  return async (streamId: number) => {
    try {
      return await splitStreamMutation({
        splitStream: { stream: streamId },
      }).unwrap();
    } catch (error) {
      console.error("Failed to split stream:", error);
      throw error;
    }
  };
}
 
/**
 * Disconnects or changes the connection of a port
 * @param portId The ID of the port to disconnect
 * @param patchedPort The new port data (eg. { stream: null} to disconnect)
 * @returns A function that disconnects the port
 */
export function useUpdatePort() {
  const [updatePort] = useUnitopsPortsPartialUpdateMutation();
  const dispatch = useAppDispatch();
  const flowsheetId = useFlowsheetId();
  const ports = useFlowsheetPorts();
 
  return (portId: number, patchedPort: Partial<Port>) => {
    const currentPort = ports?.find((p) => p.id === portId);
    if (!currentPort) {
      console.error("Port not found:", portId);
      return;
    }
 
    updatePort({
      id: portId,
      patchedPort: patchedPort,
    });
 
    // Update the cache optimistically
    dispatch(
      api.util.updateQueryData(
        "unitopsPortsList",
        { flowsheet: flowsheetId },
        (cachedPorts) => {
          const p = cachedPorts.find((p) => p.id === portId)!;
          Object.assign(p, patchedPort);
        },
      ),
    );
  };
}
 
/**
 * Adds a stream to a port
 * @param portId The ID of the port to add a stream to
 * @returns A function that adds a stream to a port
 */
export function useAddStream() {
  const [addStream] = useUnitopsPortsAddStreamCreateMutation();
  return (portId: number) => {
    addStream({
      addStream: {
        port: portId,
      },
    });
  };
}
 
/**
 * Converts a stream to a decision node
 * @param streamId The ID of the stream to convert
 * @returns A function that converts a stream to a decision node
 */
export function useConvertStreamToDn() {
  const [convertToDn] = useUnitopsPortsConvertToDnCreateMutation();
 
  return (streamId: number) => {
    convertToDn({
      convertToDn: {
        stream: streamId,
      },
      // stream: streamId
    })
      .unwrap()
      .then(() => {
        toast.success(
          "Successfully converted material stream to decision node",
        );
      })
      .catch((error) => {
        toast.error(
          `Failed to connect material streams: ${error.data.message}`,
        );
      });
  };
}
 
/**
 * Adds a port to a simulation object
 * @param simulationObjectId The ID of the simulation object to add a port to
 * @param key The key of the port to add
 * @returns A function that adds a port to a simulation object
 */
export function useAddPort() {
  const [addPort] = useUnitopsSimulationobjectsAddPortCreateMutation();
  return (simulationObjectId: number, key: string) => {
    addPort({
      addPort: {
        simulationObjectId: simulationObjectId,
        key: key,
      },
    });
  };
}
 
/**
 * Hook to add a port to a unit operation and connect a stream to it
 * @returns A function that adds a port and connects a stream
 */
export function useAddPortAndConnectStream() {
  const [addPort] = useUnitopsSimulationobjectsAddPortCreateMutation();
  const streamType = useStreamType();
 
  return (unitOp: SimulationObjectRead, stream: SimulationObjectRead) => {
    // Determine the port type based on the unit op type
    let portKey = "inlet"; // default
 
    if (unitOp.objectType === "decisionNode") {
      // For decision nodes, determine port based on stream type
      portKey = streamType(stream.id) === "feed" ? "outlet" : "inlet"; //feed streams are outlet and product streams are inlet
    } else if (unitOp.objectType === "mixer") {
      portKey = "inlet";
    } else if (unitOp.objectType === "splitter") {
      portKey = "outlet";
    }
 
    // Add the port with stream
    addPort({
      addPort: {
        simulationObjectId: unitOp.id,
        key: portKey,
        stream: stream.id,
      },
    })
      .unwrap()
      .then(() => {
        toast.success("Successfully added port and connected stream");
      })
      .catch((error) => {
        toast.error(
          `Failed to add port and connect stream: ${error.data?.message || "Unknown error"}`,
        );
      });
  };
}
 
/**
 * Merges two decision nodes
 * @returns A function that merges two decision nodes
 */
export function useMergeDecisionNodes() {
  const [mergeDecisionNodes] =
    useUnitopsSimulationobjectsMergeDecisionNodesCreateMutation();
  const [, setObjectId] = useSearchParam("object");
 
  return (
    decisionNodeActive: SimulationObjectRead,
    decisionNodeOver: SimulationObjectRead,
  ) => {
    // Switch selected object to the target node since active will be removed
    setObjectId(decisionNodeOver.id);
 
    //TODO: add optimistic updates for graphics and simulation objects in future
 
    mergeDecisionNodes({
      mergeDecisionNodes: {
        decisionNodeActive: decisionNodeActive.id,
        decisionNodeOver: decisionNodeOver.id,
      },
    })
      .unwrap()
      .then(() => {
        toast.success("Successfully merged decision nodes");
      })
      .catch((error) => {
        toast.error(
          `Failed to merge decision nodes: ${error.data?.message || "Unknown error"}`,
        );
      });
  };
}