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

71.57% Statements 136/190
67.43% Branches 147/218
40% Functions 12/30
85.07% Lines 114/134

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 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565                                                                                                                                                          103x                             5042x                     10681x 10681x           1729x 1729x 7519x 37875x   7519x 7504x                                         7504x   1729x                 1729x                 3458x 5451x 5451x 5451x 5451x 5451x 5451x 5451x 5451x   5451x   5079x   5079x 5079x                                                         5079x             5079x   5079x       5079x               5079x   5079x   5079x       5079x       5079x                   5079x                                       1729x   1729x 1729x   1729x   10681x                           21140x   10080x 10080x 10080x 10080x   11060x 11060x 11060x 11060x     1072x                   21140x     17830x 12940x 12940x 12940x   13525x 12940x 12940x                         17492x     111268x     4606x   28852x   201x   1167x 170x     1106x             2999x                           9129x         8301x     9529x   2015x 9529x 9529x 10318x     9529x 9529x 9529x     9529x       9529x         8879x               650x                                     8573x                   9129x                         12940x 12940x 12940x 12940x 17702x 17702x 17702x   17702x           17702x                     66x 66x           12874x   62x           12940x       12940x   12940x     12940x           17338x 12940x 12940x           12940x       12940x 907x 14058x               12940x 12940x 17830x                       12940x                                         15872x 38820x      
import {
  Edge,
  Handle,
  Node,
  Position,
  useUpdateNodeInternals,
} from "@xyflow/react";
import { useEffect } from "react";
import type { Connection } from "@/api/apiStore.gen";
import {
  CoreRecycledataListApiResponse,
  GetConnectionsList,
  GraphicObjectRead,
  ObjectTypeEnum,
  SimulationObjectRead,
  SimulationObjectRetrieveRead,
  useGraphicsgroupingsConnectionsRetrieveQuery,
} from "@/api/apiStore.gen";
import { useCurrentGroupId } from "@/hooks/flowsheetObjects";
import {
  useObjectRecycleData,
  useSimObjectConnectedToRecycle,
} from "@/hooks/recycleData";
import {
  ActivePortReconnect,
  getAnchorConnectionHandlePlacement,
  getAnchorHandlePlacement,
  getAnchorHandlePlacements,
  isPortAnchorOccupied,
  normaliseAnchorPosition,
} from "./connectionAnchors";
import { shouldStyleStreamEdges, streamEdgeStyle } from "./streamEdgeStyle";
import {
  collectTrackedConnectedUnitOpIds,
  trackedNodeOpacity,
} from "./streamTracking/renderTrackingStyles";
import { buildTrackedStreamConnectionEdges } from "./streamTracking/trackedEdges";
import type { TrackedStreamEdgeFlow } from "./streamTracking/types";
 
interface RenderOperationProps {
  currentGroupObjects: SimulationObjectRead[];
  graphicsObjects: GraphicObjectRead[] | undefined;
  connectionGraphics: GetConnectionsList | undefined;
  recycleConnections: CoreRecycledataListApiResponse;
  objectsGraphicObjectsMap: Map<number, GraphicObjectRead>;
  selectedStreamId: number | null;
  activeReconnect: ActivePortReconnect | null;
  canMutate: boolean;
  streamPropertiesById: Map<number, SimulationObjectRetrieveRead>;
  trackedStreamIds?: Set<number>;
  trackedFlowsByStreamId?: Map<number, TrackedStreamEdgeFlow[]>;
}
 
export type StreamConnectionEdgeData = Record<string, unknown> & {
  isEnergyStream: boolean;
  streamId: number;
  unitOpId: number;
  portId: number;
  direction: Connection["direction"];
  anchor_placement?: number | null;
  anchor_graphic_object?: number | null;
  anchor_endpoint_kind?: string | null;
  anchor_side?: string | null;
  anchor_index?: number | null;
  unitOpType?: ObjectTypeEnum;
  unitEndpoint: "source" | "target";
  unitGraphicObjectId: number;
  unitGraphic: {
    x: number;
    y: number;
    width: number;
    height: number;
    rotation: number;
    flipped: boolean;
  };
};
 
const portAnchorExcludedObjectTypes = new Set<ObjectTypeEnum>([
  ObjectTypeEnum.Header,
  ObjectTypeEnum.SimpleHeader,
  ObjectTypeEnum.Boiler,
  ObjectTypeEnum.Mixer,
  ObjectTypeEnum.EnergyMixer,
  ObjectTypeEnum.Splitter,
  ObjectTypeEnum.EnergySplitter,
]);
 
export function isPortAnchorReconnectableEdge(
  data: StreamConnectionEdgeData | undefined,
  selectedStreamId: number | null,
  canMutate: boolean,
): data is StreamConnectionEdgeData {
  return (
    !!data &&
    canMutate &&
    data.portId > 0 &&
    selectedStreamId === data.streamId &&
    data.unitOpType !== undefined &&
    !portAnchorExcludedObjectTypes.has(data.unitOpType)
  );
}
 
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,
          activeReconnect: props.activeReconnect,
          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 regularConnection = conn as Connection;
        const streamId = isRecycle ? conn.tearObject : conn.stream;
        const unitOpId = isRecycle ? conn.simulationObject : conn.unitOp;
        const portId = isRecycle ? -1 : regularConnection.port;
        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 data = {
          isEnergyStream: isEnergy,
          streamId,
          unitOpId,
          portId,
          direction: conn.direction,
          anchor_placement: isRecycle
            ? null
            : regularConnection.anchor_placement,
          anchor_graphic_object: isRecycle
            ? null
            : regularConnection.anchor_graphic_object,
          anchor_endpoint_kind: isRecycle
            ? null
            : regularConnection.anchor_endpoint_kind,
          anchor_side: isRecycle ? null : regularConnection.anchor_side,
          anchor_index: isRecycle ? null : regularConnection.anchor_index,
          unitOpType,
          unitEndpoint: type === "inlet" ? "target" : "source",
          unitGraphicObjectId: unitopGraphic.id,
          unitGraphic: {
            x: unitopGraphic.x || 0,
            y: unitopGraphic.y || 0,
            width: unitopGraphic.width || 0,
            height: unitopGraphic.height || 0,
            rotation: unitopGraphic.rotation || 0,
            flipped: !!unitopGraphic.flipped,
          },
        } satisfies StreamConnectionEdgeData;
        const isReconnectable = isRecycle
          ? false
          : isPortAnchorReconnectableEdge(
              data,
              props.selectedStreamId,
              props.canMutate,
            );
        const trackedFlows = props.trackedFlowsByStreamId?.get(streamId) ?? [];
        const propertyStyle =
          !isRecycle && shouldStyleStreamEdges(streamType)
            ? streamEdgeStyle(streamPropertiesById.get(streamId))
            : undefined;
        const edgeId =
          isRecycle && type === "inlet"
            ? `edge-${streamId}-${unitOpId}`
            : isRecycle
              ? `edge-${unitOpId}-${streamId}`
              : type === "inlet"
                ? `edge-${streamId}-${unitOpId}-${portId}`
                : `edge-${unitOpId}-${streamId}-${portId}`;
        const source =
          type === "inlet" ? streamId.toString() : unitOpId.toString();
        const target =
          type === "outlet" ? streamId.toString() : unitOpId.toString();
        const sourceHandle =
          type === "inlet"
            ? `${streamType}-${streamId}-${unitOpId}`
            : `${unitOpType}-${unitOpId}-${streamId}`;
        const targetHandle =
          type === "outlet"
            ? `${streamType}-${unitOpId}-${streamId}`
            : `${unitOpType}-${streamId}-${unitOpId}`;
        const unitEndpointPosition =
          getAnchorHandlePlacement(
            normaliseAnchorPosition(data.anchor_side, data.anchor_index),
            data.unitGraphic,
          )?.position ??
          getHandlePositionRelativeToRotationAndFlip(
            data.unitEndpoint,
            data.unitGraphic.rotation,
            data.unitGraphic.flipped,
          );
 
        edges.push(
          ...buildTrackedStreamConnectionEdges({
            edgeId,
            streamId,
            source,
            target,
            sourceHandle,
            targetHandle,
            isRecycle,
            propertyStyle,
            trackedFlows,
            trackedStreamIds: props.trackedStreamIds,
            data,
            reconnectable: isReconnectable ? data.unitEndpoint : false,
            reconnectableClassName: `stream-anchor-reconnectable stream-anchor-reconnect-${unitEndpointPosition}`,
          }),
        );
      });
    };
 
    const edges: Edge[] = [];
 
    mapConnectionsToEdges(connectionGraphics, false);
    mapConnectionsToEdges(recycleConnections, true);
 
    return edges;
  }
  return { renderNodes: renderNodes, renderEdges: renderEdges };
};
 
interface DynamicHandlesProps {
  simulationObj: SimulationObjectRead;
  graphicObj: GraphicObjectRead;
  activeReconnect?: ActivePortReconnect | null;
}
 
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, activeReconnect } = props;
  const groupId = useCurrentGroupId() || -1;
  const connQuery = useGraphicsgroupingsConnectionsRetrieveQuery({
    group: groupId,
  });
  const getRecycleConnection = useSimObjectConnectedToRecycle();
  const getRecycleData = useObjectRecycleData();
  type ConnectionHandle = {
    id: string;
    type: "source" | "target";
    position: Position;
    anchor_side?: string | null;
    anchor_index?: number | null;
    unitOpId?: number;
  };
 
  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,
  ) => {
    if (handle.unitOpId === simulationObj.id) {
      const anchorPlacement = getAnchorConnectionHandlePlacement(
        normaliseAnchorPosition(handle.anchor_side, handle.anchor_index),
        graphicObj,
      );
 
      Iif (anchorPlacement) return anchorPlacement.style;
    }
 
    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 (
      simulationObj.objectType === ObjectTypeEnum.Stream ||
      simulationObj.objectType === ObjectTypeEnum.EnergyStream
    ) {
      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;
      const anchorPlacement =
        obj.unitOp === simulationObj.id
          ? getAnchorHandlePlacement(
              normaliseAnchorPosition(obj.anchor_side, obj.anchor_index),
              graphicObj,
            )
          : null;
      handles.push({
        id: `${objType}-${firstObjId}-${secondObjId}`,
        type,
        position: anchorPlacement?.position || position,
        anchor_side: obj.anchor_side,
        anchor_index: obj.anchor_index,
        unitOpId: obj.unitOp,
      });
    });
 
    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();
  const anchorHandles =
    activeReconnect?.unitOpId === simulationObj.id
      ? getAnchorHandlePlacements(activeReconnect.portId, graphicObj)
      : [];
  const isAnchorOccupied = (anchor: { side: string; index: number }) =>
    isPortAnchorOccupied(
      connQuery.data,
      simulationObj.id,
      { anchor_side: anchor.side, anchor_index: anchor.index },
      activeReconnect?.portId,
    );
  const updateNodeInternals = useUpdateNodeInternals();
  const handlesSignature = handles
    .map(
      (handle) =>
        `${handle.id}:${handle.position}:${handle.anchor_side}:${handle.anchor_index}`,
    )
    .join("|");
  const anchorHandlesSignature = anchorHandles
    .map((handle) => `${handle.id}:${handle.position}`)
    .join("|");
 
  useEffect(() => {
    updateNodeInternals(simulationObj.id.toString());
  }, [
    anchorHandlesSignature,
    handlesSignature,
    simulationObj.id,
    updateNodeInternals,
  ]);
 
  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,
          }}
        />
      ))}
      {anchorHandles.map((handle) => {
        const isOccupied = isAnchorOccupied(handle);
        return (
          <Handle
            key={handle.id}
            id={handle.id}
            type={activeReconnect!.unitEndpoint}
            position={handle.position}
            isConnectable={!isOccupied}
            style={{
              ...handle.style,
              width: 9,
              height: 9,
              border: "2px solid #0369a1",
              background: isOccupied ? "#cbd5e1" : "#e0f2fe",
              opacity: isOccupied ? 0.35 : 1,
              pointerEvents: isOccupied ? "none" : "all",
              zIndex: 20,
            }}
          />
        );
      })}
    </>
  );
};