All files / src/pages/flowsheet-page/flowsheet/Canvas RenderOperations.tsx

74.84% Statements 119/159
72.22% Branches 117/162
50% Functions 12/24
86.84% Lines 99/114

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 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363                                                                    8015x 8015x             750x 750x 3162x 16370x   3162x 3157x                                       3157x   750x                 750x                 1500x 2369x 2369x 2369x 2369x 2369x 2369x   2369x   2151x   2151x 2151x   2151x           2151x   2151x                                                 2151x       750x   750x 750x   750x   8015x                         5573x   2663x 2663x 2663x 2663x   2910x 2910x 2910x 2910x     159x                   5573x     44959x 44959x 44959x 44959x   45354x 44959x 44959x             44959x     2310x     15373x     1679x   11155x   39x   237x 27x     177x       51635x   44959x 3254x           45898x   44959x         2330x   1157x 2330x 2330x 3254x     2330x 2330x 2330x     2330x       2330x         2240x               90x                   51635x   44959x       1123x                   1196x                   46837x   44959x 1725x 1725x 1725x 1725x 2319x 2319x 2319x 2319x               7x 7x           1718x   4x           1725x   55309x   1725x     1725x   2330x                       48409x      
import { Edge, Handle, Node, Position } from "@xyflow/react";
import {
  CoreRecycledataListApiResponse,
  GetConnectionsList,
  GraphicObjectRead,
  ObjectTypeEnum,
  SimulationObjectRead,
  SimulationObjectRetrieveRead,
  useGraphicsgroupingsConnectionsRetrieveQuery,
} from "@/api/apiStore.gen";
import { useCurrentGroupId } from "@/hooks/flowsheetObjects";
import {
  useObjectRecycleData,
  useSimObjectConnectedToRecycle,
} from "@/hooks/recycleData";
import { isStream } from "../../../../lib/isStream";
import {
  collectTrackedConnectedUnitOpIds,
  trackedEdgeOpacity,
  trackedNodeOpacity,
} from "./renderTrackingStyles";
import { shouldStyleStreamEdges, streamEdgeStyle } from "./streamEdgeStyle";
 
interface RenderOperationProps {
  currentGroupObjects: SimulationObjectRead[];
  graphicsObjects: GraphicObjectRead[] | undefined;
  connectionGraphics: GetConnectionsList | undefined;
  recycleConnections: CoreRecycledataListApiResponse;
  objectsGraphicObjectsMap: Map<number, GraphicObjectRead>;
  streamPropertiesById: Map<number, SimulationObjectRetrieveRead>;
  trackedStreamIds?: Set<number>;
}
 
export const useRenderOperations = (props: RenderOperationProps) => {
  const { currentGroupObjects, graphicsObjects } = props;
  const trackedConnectedUnitOpIds = collectTrackedConnectedUnitOpIds(
    props.trackedStreamIds,
    props.connectionGraphics,
    props.recycleConnections,
  );
 
  function renderNodes(): Node[] {
    const nodes: Node[] = [];
    currentGroupObjects.map((unitop) => {
      const graphicObject = graphicsObjects?.find(
        (obj) => obj.simulationObject.id === unitop.id,
      );
      if (!graphicObject || !graphicObject.visible) return;
      const newNode: Node = {
        id: unitop.id.toString(),
        type: "simulationObjectGraphic",
        position: { x: +(graphicObject.x || 0), y: +(graphicObject.y || 0) },
        width: graphicObject.width,
        height: graphicObject.height,
        data: {
          simulationObject: unitop,
          graphicObject: graphicObject,
          label: unitop.componentName,
          hovered: props.trackedStreamIds?.has(unitop.id) ?? false,
        },
        style: {
          opacity: trackedNodeOpacity(
            unitop,
            props.trackedStreamIds,
            trackedConnectedUnitOpIds,
          ),
        },
      };
      nodes.push(newNode);
    });
    return nodes;
  }
 
  function renderEdges(): Edge[] {
    const {
      connectionGraphics,
      recycleConnections,
      objectsGraphicObjectsMap,
      streamPropertiesById,
    } = props;
 
    const mapConnectionsToEdges = (
      connectionGraphics:
        | GetConnectionsList
        | CoreRecycledataListApiResponse
        | undefined,
      isRecycle: boolean,
    ) => {
      connectionGraphics?.map((conn) => {
        const streamId = isRecycle ? conn.tearObject : conn.stream;
        const unitOpId = isRecycle ? conn.simulationObject : conn.unitOp;
        const unitopGraphic = objectsGraphicObjectsMap.get(unitOpId);
        const streamGraphic = objectsGraphicObjectsMap.get(streamId);
        const unitOpType = unitopGraphic?.simulationObject.objectType;
        const streamType = streamGraphic?.simulationObject.objectType;
 
        if (!unitopGraphic || !streamGraphic) return null; // couldn't find the graphic object, it is probably still being fetched
 
        const type = isRecycle ? "inlet" : conn.direction;
 
        const isEnergy = streamType === ObjectTypeEnum.EnergyStream;
        const isTracked = props.trackedStreamIds?.has(streamId) ?? false;
        const propertyStyle =
          !isRecycle && shouldStyleStreamEdges(streamType)
            ? streamEdgeStyle(streamPropertiesById.get(streamId), {
                tracked: isTracked,
              })
            : undefined;
        const strokeDasharray =
          propertyStyle?.strokeDasharray ?? (isRecycle ? "5,5" : undefined);
 
        const newEdge: Edge = {
          id:
            type === "inlet"
              ? `edge-${streamId}-${unitOpId}`
              : `edge-${unitOpId}-${streamId}`,
          source: type === "inlet" ? streamId.toString() : unitOpId.toString(),
          target: type === "outlet" ? streamId.toString() : unitOpId.toString(),
          sourceHandle:
            type === "inlet"
              ? `${streamType}-${streamId}-${unitOpId}`
              : `${unitOpType}-${unitOpId}-${streamId}`,
          targetHandle:
            type === "outlet"
              ? `${streamType}-${unitOpId}-${streamId}`
              : `${unitOpType}-${streamId}-${unitOpId}`,
          type: "step",
          style: {
            stroke: propertyStyle?.stroke ?? "#000000",
            strokeWidth: isTracked ? 5 : isRecycle ? 1 : 3,
            strokeDasharray,
            strokeLinecap: propertyStyle?.strokeLinecap,
            opacity: trackedEdgeOpacity(streamId, props.trackedStreamIds),
          },
          data: { isEnergyStream: isEnergy },
        };
        edges.push(newEdge);
      });
    };
 
    const edges: Edge[] = [];
 
    mapConnectionsToEdges(connectionGraphics, false);
    mapConnectionsToEdges(recycleConnections, true);
 
    return edges;
  }
  return { renderNodes: renderNodes, renderEdges: renderEdges };
};
 
interface DynamicHandlesProps {
  simulationObj: SimulationObjectRead;
  graphicObj: GraphicObjectRead;
}
 
const getHandlePositionRelativeToRotationAndFlip = (
  type: string,
  rotation: number,
  flipped: boolean,
): Position => {
  let handleOrientation = Position.Left;
  if (type === "target") {
    if (rotation === 0) handleOrientation = Position.Left;
    if (rotation === 90) handleOrientation = Position.Top;
    if (rotation === 180) handleOrientation = Position.Right;
    if (rotation === 270) handleOrientation = Position.Bottom;
  } else {
    if (rotation === 0) handleOrientation = Position.Right;
    if (rotation === 90) handleOrientation = Position.Bottom;
    if (rotation === 180) handleOrientation = Position.Left;
    if (rotation === 270) handleOrientation = Position.Top;
  }
  if (flipped) {
    handleOrientation === Position.Left
      ? (handleOrientation = Position.Right)
      : handleOrientation === Position.Right
        ? (handleOrientation = Position.Left)
        : handleOrientation === Position.Top
          ? (handleOrientation = Position.Bottom)
          : handleOrientation === Position.Bottom
            ? (handleOrientation = Position.Top)
            : console.log("Orientation not found!");
  }
  return handleOrientation;
};
 
export const DynamicHandles = (props: DynamicHandlesProps) => {
  const { simulationObj, graphicObj } = props;
  const groupId = useCurrentGroupId();
  const connQuery = useGraphicsgroupingsConnectionsRetrieveQuery({
    group: groupId,
  });
  const getRecycleConnection = useSimObjectConnectedToRecycle();
  const getRecycleData = useObjectRecycleData();
  type ConnectionHandle = {
    id: string;
    type: "source" | "target";
    position: Position;
  };
 
  const getConnectedObjects = () => {
    if (
      simulationObj.objectType === ObjectTypeEnum.Stream ||
      simulationObj.objectType === ObjectTypeEnum.EnergyStream
    ) {
      return connQuery.data
        ?.filter((obj) => obj.stream === simulationObj.id)
        .sort((a, b) => a.port - b.port);
    } else {
      if (graphicObj.rotation === 0) {
        return connQuery.data
          ?.filter((obj) => obj.unitOp === simulationObj.id)
          .sort((a, b) => a.port - b.port);
      } else if (graphicObj.rotation === 90 || graphicObj.rotation === 180) {
        return connQuery.data
          ?.filter((obj) => obj.unitOp === simulationObj.id)
          .sort((a, b) => b.port - a.port);
      } else {
        return connQuery.data
          ?.filter((obj) => obj.unitOp === simulationObj.id)
          .sort((b, a) => b.port - a.port);
      }
    }
  };
 
  const mapPortKeyToPosition = (direction: string): Position => {
    const type = direction === "inlet" ? "target" : "source";
    return getHandlePositionRelativeToRotationAndFlip(
      type,
      graphicObj.rotation || 0,
      graphicObj.flipped || false,
    );
  };
 
  const getHandlePlacement = (
    handles: ConnectionHandle[],
    handle: ConnectionHandle,
    index: number,
  ) => {
    const sameSideIndex = handles
      .slice(0, index)
      .filter((h) => h.position === handle.position).length;
    const connObjects = getConnectedObjects();
    const handlesOnSide = connObjects?.filter((obj) => {
      Iif (obj.unitOp !== simulationObj.id) return false;
      return mapPortKeyToPosition(obj.direction) === handle.position;
    });
    const handleCount = handlesOnSide?.length || 1;
    const nodeHeight = graphicObj.height!;
    const nodeWidth = graphicObj.width!;
 
    const offsetY =
      handle.position === Position.Left || handle.position === Position.Right
        ? ((sameSideIndex + 0.5) / handleCount) * nodeHeight
        : 0;
    const offsetX =
      handle.position === Position.Top || handle.position === Position.Bottom
        ? ((sameSideIndex + 0.5) / handleCount) * nodeWidth
        : 0;
    if (
      handle.position === Position.Left ||
      handle.position === Position.Right
    ) {
      return {
        top: offsetY,
        transform:
          handle.position === Position.Left
            ? "translate(50%, -50%)"
            : "translate(-50%, -50%)",
      };
    } else {
      return {
        left: offsetX,
        transform:
          handle.position === Position.Top
            ? "translate(-50%, 50%)"
            : "translate(-50%, -50%)",
      };
    }
  };
 
  const mapDirectionToHandle = (
    direction: string,
  ): { type: "target" | "source"; position: Position } => {
    if (isStream(simulationObj)) {
      const handleType = direction === "inlet" ? "source" : "target";
      return {
        type: handleType,
        position: getHandlePositionRelativeToRotationAndFlip(
          handleType,
          graphicObj.rotation || 0,
          graphicObj.flipped || false,
        ),
      };
    } else {
      const handleType = direction === "inlet" ? "target" : "source";
      return {
        type: handleType,
        position: getHandlePositionRelativeToRotationAndFlip(
          handleType,
          graphicObj.rotation || 0,
          graphicObj.flipped || false,
        ),
      };
    }
  };
 
  const getHandles = (): ConnectionHandle[] => {
    const handles: ConnectionHandle[] = [];
    const connObjects = getConnectedObjects();
    const objType = simulationObj.objectType;
    connObjects?.forEach((obj) => {
      const { type, position } = mapDirectionToHandle(obj.direction);
      const firstObjId = obj.direction === "inlet" ? obj.stream : obj.unitOp;
      const secondObjId = obj.direction === "inlet" ? obj.unitOp : obj.stream;
      handles.push({
        id: `${objType}-${firstObjId}-${secondObjId}`,
        type,
        position,
      });
    });
 
    if (simulationObj.objectType === ObjectTypeEnum.Recycle) {
      const recycleData = getRecycleData(+simulationObj.id!);
      handles.push({
        id: `${objType}-${recycleData?.tearObject}-${simulationObj.id}`,
        type: "target",
        position: Position.Top,
      });
    } else {
      const recycle = getRecycleConnection(+simulationObj.id!);
      if (recycle) {
        handles.push({
          id: `${objType}-${simulationObj.id}-${recycle.simulationObject}`,
          type: "source",
          position: Position.Bottom,
        });
      }
    }
    return handles;
  };
 
  const handles = getHandles();
 
  return (
    <>
      {handles.map((handle, index) => (
        <Handle
          key={handle.id}
          id={handle.id}
          type={handle.type}
          position={handle.position}
          isConnectable={false}
          style={{
            ...getHandlePlacement(handles, handle, index),
            opacity: 0,
          }}
        />
      ))}
    </>
  );
};