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

92.34% Statements 181/196
76.25% Branches 61/80
89.28% Functions 25/28
94.17% Lines 178/189

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                                                                      45x             64x   64x   64x   64x                                   45x 45x 45x 45x 45x         64x   64x                 45x                                               45x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x   5533x 5533x   5533x   740x           48x 48x       5533x 26x   26x         26x     5533x       26x   26x 1x 1x       25x               25x     5533x         1x 1x               1x       1x             5533x     9x 9x   9x   6x 6x 6x   3x 3x 3x 3x   3x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x     3x 3x   3x 3x   3x   3x   3x     9x     5533x 148x     5533x       5533x                     5533x 25x 25x         25x 25x                 25x                       5533x     44x       44x                 5533x       44x       44x       5x 5x 28x 22x     5x                 5533x       44x 44x       23x 21x                     5533x           44x 44x 44x 44x 44x 8x       36x 15x       21x 15x       6x 6x         44x                 5533x       44x 44x 44x 44x 44x     44x 8x 36x 15x 21x   15x 15x   15x 6x   6x     6x   44x                   5533x           23x 23x 23x     23x 5x       5x 22x   5x       23x   45x       45x         22x 22x     44x               44x         44x 44x         44x               44x         44x   189x     44x 44x 44x 44x 44x 44x 44x           44x                                 5533x                    
import {
  api,
  GraphicObjectRead,
  ObjectTypeEnum,
  useGraphicsgroupingsUngroupCreateMutation,
  useGraphicsObjectsPartialUpdateMutation,
  useUnitopsSimulationobjectsCreateMutation,
} from "@/api/apiStore.gen";
import { useHasCommand } from "@/commands/commandHooks";
import { useConvertStreamToDn } from "@/hooks/connections";
import { useOptimisticallyDeleteSelection } from "@/hooks/deleteObjects";
import {
  useCurrentGroupId,
  useCurrentGroupObjects,
  useCurrentObject,
  useFlowsheetPorts,
  useFlowsheetUnitOps,
  useGraphicsObjects,
  useSimulationObjectGroup,
  useTrackCoordinates,
  useStreamType,
} from "@/hooks/flowsheetObjects";
import { useProjectId } from "@/hooks/project";
import { useCreateModuleFromTemplate } from "@/hooks/useTemplate";
import { useUndoRedoStore } from "@/hooks/useUndoRedoStore";
import { useAppDispatch } from "@/store/hooks";
import { PointerState } from "@/store/PointerSlice";
import { createAddCommand } from "@/utils/commandCreators";
import { useReactFlow } from "@xyflow/react";
import { useRunCommand } from "just-search-it";
import { useEffect, useState } from "react";
import { DropTargetMonitor } from "react-dnd";
import { toast } from "sonner";
import { SwitchGroup } from "../../../../commands/SwitchCurrentGroup";
 
export const snap = (
  x: number,
  y: number,
  width: number,
  height: number,
): { snapX: number; snapY: number } => {
  // snap to the centre of the object
  const SNAP_SIZE = 25;
 
  const snapX = Math.round((x + width / 2) / SNAP_SIZE) * SNAP_SIZE - width / 2;
  const snapY =
    Math.round((y + height / 2) / SNAP_SIZE) * SNAP_SIZE - height / 2;
 
  return {
    snapX,
    snapY,
  };
};
 
interface DragItem {
  unitOpType: ObjectTypeEnum | "template_module";
  templateId?: number;
  templateName?: string;
}
 
export interface FlowsheetSurfaceStateDef {
  scale: number;
  stageX: number;
  stageY: number;
}
 
export enum TransformOperation {
  Right = "right",
  Left = "left",
  Horizontal = "horizontal",
  Vertical = "vertical",
}
 
// Function to create the model
function createModel(x, y, unitOpType, flowsheetId, groupId) {
  const { snapX, snapY } = snap(x, y, 0, 0);
 
  return {
    x: snapX,
    y: snapY,
    objectType: unitOpType as ObjectTypeEnum,
    flowsheet: flowsheetId,
    parentGroup: groupId,
  };
}
 
const canvasToFlowsheetCoords = (x: number, stageX: number, scale: number) => {
  // converts the x coordinate from top left of canvas
  // to the x coordinate in the flowsheet (accounting for zoom and pan)
  // Works for x/stageX and y/stageY
  return (x - stageX) / scale;
};
 
export { canvasToFlowsheetCoords, createModel };
 
interface FlowsheetCanvasProps {
  canvasDiv: React.RefObject<HTMLDivElement>;
  pointerState: PointerState;
  FlowsheetSurfaceState: FlowsheetSurfaceStateDef;
  setFlowsheetSurfaceState: React.Dispatch<
    React.SetStateAction<{
      scale: number;
      stageX: number;
      stageY: number;
    }>
  >;
  canvasWidth: number;
  canvasHeight: number;
}
 
export const useFlowsheetCanvasFunctions = (props: FlowsheetCanvasProps) => {
  const dispatch = useAppDispatch();
  const { canvasDiv, FlowsheetSurfaceState } = props;
  const graphicsObjects = useGraphicsObjects();
  const currentObject = useCurrentObject();
  const currentGroupId = useCurrentGroupId();
  const currentGroupObjects = useCurrentGroupObjects();
  const flowsheetId = useProjectId();
  const flowsheetObjects = useFlowsheetUnitOps();
  const reactFlow = useReactFlow();
  const ports = useFlowsheetPorts();
  const streamType = useStreamType();
  const switchGroup = useRunCommand(SwitchGroup);
  const hasCommand = useHasCommand();
  const simulationObjectGroup = useSimulationObjectGroup();
  const [updateGraphicObject] = useGraphicsObjectsPartialUpdateMutation();
  const [createObject] = useUnitopsSimulationobjectsCreateMutation();
  const { createModuleFromTemplate } = useCreateModuleFromTemplate();
  const { addHistory } = useUndoRedoStore();
  const [ungroup] = useGraphicsgroupingsUngroupCreateMutation();
  const optimisticallyDeleteSelection = useOptimisticallyDeleteSelection();
  const convertStreamToDN = useConvertStreamToDn();
  const [loading, setLoading] = useState(true);
  useTrackCoordinates(FlowsheetSurfaceState, loading);
 
  const currentTab = currentGroupId;
  const canSwitchGroup = hasCommand(SwitchGroup, currentTab);
 
  useEffect(() => {
    // zoom to fit when the objects are first loaded
    if (
      loading &&
      graphicsObjects !== undefined &&
      flowsheetObjects !== undefined &&
      currentGroupId !== undefined
    ) {
      switchGroup(currentTab);
      setLoading(false);
    }
  }, [graphicsObjects, flowsheetObjects, currentGroupId, canSwitchGroup]);
 
  const getDropPosition = (monitor: DropTargetMonitor<DragItem, void>) => {
    const clientOffset = monitor.getClientOffset();
 
    const position = reactFlow.screenToFlowPosition({
      x: clientOffset?.x || 0,
      y: clientOffset?.y || 0,
    });
 
    return { x: position.x, y: position.y };
  };
 
  const handleDrop = (
    item: DragItem,
    monitor: DropTargetMonitor<DragItem, void>,
  ) => {
    const { x, y } = getDropPosition(monitor);
 
    if (item.unitOpType === "template_module") {
      handleTemplateModuleDrop(item, x, y);
      return;
    }
 
    //crerate the object with the current group id or use root if no group id is present
    const model = createModel(
      x,
      y,
      item.unitOpType,
      flowsheetId,
      currentGroupId,
    );
 
    handleObjectCreation(model);
  };
 
  const handleTemplateModuleDrop = async (
    item: { templateId: number; templateName: string },
    x?: number,
    y?: number,
  ) => {
    try {
      const created = await createModuleFromTemplate(
        item.templateId,
        flowsheetId,
        currentGroupId,
        x,
        y,
      );
 
      Iif (!created) {
        throw new Error("Backend did not return a created module id");
      }
 
      toast.success(`${item.templateName} module created successfully!`);
    } catch (error) {
      toast.error(`Failed to create ${item.templateName} module`);
      console.error("Template module creation error:", error);
    }
  };
 
  const zoomToFit = () => {
    let newStageX, newStageY, newScale;
 
    const canvasWidth = canvasDiv.current?.offsetWidth || 640;
    const canvasHeight = canvasDiv.current?.offsetHeight || 480;
 
    if (currentGroupObjects?.length === 0) {
      // No elements to fit, so just reset zoom
      newScale = 1;
      newStageX = 0;
      newStageY = 0;
    } else {
      let minX = Infinity,
        minY = Infinity,
        maxX = -Infinity,
        maxY = -Infinity;
 
      currentGroupObjects?.forEach((unitOp) => {
        const graphicObject = getGraphicsObject(unitOp.id);
        if (graphicObject) {
          const x = graphicObject.x ?? 0;
          const y = graphicObject.y ?? 0;
          const width = graphicObject.width ?? 0;
          const height = graphicObject.height ?? 0;
 
          minX = Math.min(minX, x); //left
          minY = Math.min(minY, y); //top
          maxX = Math.max(maxX, x + width); //right
          maxY = Math.max(maxY, y + height); //bottom
        }
      });
      const boundingWidth = maxX - minX;
      const boundingHeight = maxY - minY;
 
      const scaleX = canvasWidth / (boundingWidth + 500);
      const scaleY = canvasHeight / (boundingHeight + 500);
 
      newScale = Math.min(scaleX, scaleY) * 0.95; //  for padding
      // centreing
      newStageX =
        (canvasWidth - boundingWidth * newScale) / 2 - minX * newScale;
      newStageY =
        (canvasHeight - boundingHeight * newScale) / 2 - minY * newScale;
    }
    return { newScale, newStageX, newStageY };
  };
 
  const getGraphicsObject = (objID: number) => {
    return graphicsObjects?.find((obj) => obj.simulationObject.id === objID);
  };
 
  const convertStreamToDecisionNode = (streamID: number) => {
    convertStreamToDN(streamID);
  };
 
  const unGroupCurrentObject = () => {
    const group = simulationObjectGroup(currentObject.id);
    ungroup({
      ungroup: {
        parentGroup: group.id,
      },
    });
    optimisticallyDeleteSelection([currentObject.id]);
  };
 
  // After creating a new object, update its group
  const handleObjectCreation = async (objectData) => {
    try {
      const response = await createObject({
        simulationObject: objectData,
      }).unwrap();
 
      // Track the ADD command for undo/redo
      if (response?.id) {
        const addCommand = createAddCommand({
          objectId: response.id,
          graphicObjectId: response.graphics_object?.id || response.id,
          objectType: objectData.objectType,
          simulationObject: response,
          position: { x: objectData.x, y: objectData.y },
          groupId: objectData.parentGroup,
        });
 
        addHistory(addCommand);
      }
    } catch (error) {
      console.error("Failed to create object or update group:", error);
    }
  };
 
  /**
   * Get the centre/mid-point coordinates of a graphic object.
   * @param graphicObject - The graphic object to get the centre coordinates for.
   * @returns {x: number, y: number} - The x and y coordinates of the centre point.
   */
  const getCentredCoordinates = (
    graphicObject: GraphicObjectRead,
  ): { x: number; y: number } => {
    const centredCoord = {
      x: graphicObject?.x + graphicObject?.width / 2,
      y: graphicObject?.y + graphicObject?.height / 2,
    };
    return centredCoord;
  };
 
  /**
   * Get the distance between two points. Works better if centre point coordinates are used.
   * @param streamPoint - The XY coordinates of the stream object.
   * @param unitOpPoint - The XY coordinates of the unit operation it is connected to.
   * @returns {x: number, y: number} - The x and y distances between the two points.
   */
  const getDistanceBetweenPoints = (
    gObjPoint: { x: number; y: number },
    selectionCentre: { x: number; y: number },
  ): { x: number; y: number } => {
    const xyDistance = {
      x: selectionCentre.x - gObjPoint.x,
      y: selectionCentre.y - gObjPoint.y,
    };
    return xyDistance;
  };
 
  function getConnectedStreams(unitopId: number): number[] {
    const streams: number[] = [];
    ports?.forEach((port) => {
      if (port.unitOp === unitopId && port.stream != null) {
        streams.push(port.stream);
      }
    });
    return streams;
  }
 
  /**
   * Get the new dimensions of an object after a transformation operation (rotation or flip).
   * @param graphicObj - The graphic object being transformed.
   * @param operation - The type of transformation operation being performed (right, left, horizontal flip, vertical flip).
   * @returns {x: number, y: number} - The new width and height of the object after the transformation.
   */
  const getTransformedDimensions = (
    graphicObj: GraphicObjectRead,
    operation: string,
  ) => {
    Iif (!graphicObj) return;
    if (
      operation == TransformOperation.Right ||
      operation == TransformOperation.Left
    )
      return { newWidth: graphicObj.height, newHeight: graphicObj.width };
    return { newWidth: graphicObj.width, newHeight: graphicObj.height };
  };
 
  /**
   * Get the new coordinates of an object after a transformation operation (rotation or flip).
   * @param graphicObj - The graphic object being transformed.
   * @param operation - The type of transformation operation being performed (right, left, horizontal flip, vertical flip).
   * @param selectionCentre - The centre coordinates of the whole selection.
   * @param distance - The distance between the object and the selection centre.
   * @returns {x: number, y: number} - The new x and y coordinates of the object after the transformation.
   */
  const getTransformedPosition = (
    graphicObj: GraphicObjectRead,
    operation: string,
    selectionCentre: { x: number; y: number },
    distance: { x: number; y: number },
  ) => {
    Iif (!graphicObj) return;
    const currentWidth = graphicObj.width || 0;
    const currentHeight = graphicObj.height || 0;
    let newCoords = { x: graphicObj.x, y: graphicObj.y };
    if (operation == TransformOperation.Right) {
      newCoords = {
        x: selectionCentre.x + distance.y - currentHeight / 2,
        y: selectionCentre.y - distance.x - currentWidth / 2,
      };
    } else if (operation == TransformOperation.Left) {
      newCoords = {
        x: selectionCentre.x - distance.y - currentHeight / 2,
        y: selectionCentre.y + distance.x - currentWidth / 2,
      };
    } else if (operation == TransformOperation.Horizontal) {
      newCoords = {
        x: selectionCentre.x + distance.x - currentWidth / 2,
        y: graphicObj.y,
      };
    } else if (operation == TransformOperation.Vertical) {
      newCoords = {
        x: graphicObj.x,
        y: selectionCentre.y + distance.y - currentHeight / 2,
      };
    }
    return newCoords;
  };
 
  /**
   * Get the new rotation and flipped state of an object after a transformation operation (rotation or flip).
   * @param graphicObj - The graphic object being transformed.
   * @param operation - The type of transformation operation being performed (right, left, horizontal flip, vertical flip).
   * @returns {newRotation: number, newFlipped: boolean} - The new rotation and flipped state of the object after the transformation.
   */
  const getTransformationData = (
    graphicObj: GraphicObjectRead,
    operation: string,
  ) => {
    Iif (!graphicObj) return;
    const currentRotation = graphicObj?.rotation || 0;
    const currentFlipped = graphicObj?.flipped;
    let newRotation = currentRotation;
    let newFlipped = currentFlipped;
 
    // Rotate and Flip Operations
    if (operation == TransformOperation.Right) {
      newRotation = (currentRotation + 90) % 360;
    } else if (operation == TransformOperation.Left) {
      newRotation = (currentRotation - 90 + 360) % 360;
    } else if (operation == TransformOperation.Horizontal) {
      // Rotate twice only on certain current rotation conditions. This essentilly flips the group horizontally.
      if (currentRotation === 90 || currentRotation === 270) {
        newRotation = (currentRotation + 180) % 360;
      }
      newFlipped = !currentFlipped;
    } else if (operation == TransformOperation.Vertical) {
      // Rotate twice only on certain current rotation conditions. This essentially flips the group vertically.
      Iif (currentRotation === 0 || currentRotation === 180) {
        newRotation = (currentRotation + 180) % 360;
      }
      newFlipped = !currentFlipped;
    }
    return { newRotation, newFlipped };
  };
 
  /**
   * Rotate or flip the selected object and all its connected streams (if a single unit op is selected)
   * @param selectedGraphicObject - The main graphic object that is selected to be transformed.
   * @param operation - The type of transformation operation being performed (right, left, horizontal flip, vertical flip).
   * @param selectionCentre - The centre coordinates of the whole selection.
   * @param singleSelect - A boolean indicating whether only a single unit operation is selected (true) or multiple (false).
   */
  const rotateFlipSelectedObject = (
    selectedGraphicObject: GraphicObjectRead,
    operation: string,
    selectionCentre: { x: number; y: number },
    singleSelect: boolean,
  ) => {
    if (selectedGraphicObject) {
      const groupId = currentGroupId;
      const operationGroup = [selectedGraphicObject];
 
      // Add all connected streams to the operation group if a single unit op is selected
      if (singleSelect) {
        const connectedStreams = getConnectedStreams(
          selectedGraphicObject.simulationObject.id,
        ).map(getGraphicsObject);
        // filter out any undefined results from getGraphicsObject before pushing
        const connectedStreamsFiltered = connectedStreams.filter(
          (g): g is GraphicObjectRead => g !== undefined,
        );
        operationGroup.push(...connectedStreamsFiltered);
      }
 
      // Do operation on each object in the group (the selected object and its connected streams if single select)
      operationGroup.map((graphicObj) => {
        // Get centrepoint of the object then calculate its distance from the main unit's centrepoint
        Iif (!graphicObj) return;
 
        // Prevent intermediate streams from rotating
        // but still allow it to be rotated if it's the one selected to be rotated
        if (
          singleSelect &&
          graphicObj.simulationObject.objectType === "stream" &&
          operationGroup.length > 1
        ) {
          const sType = streamType(graphicObj.simulationObject.id);
          if (sType === "intermediate") return;
        }
 
        const { newRotation, newFlipped } = getTransformationData(
          graphicObj,
          operation,
        ) || {
          newRotation: graphicObj.rotation,
          newFlipped: graphicObj.flipped,
        };
 
        const { newWidth, newHeight } = getTransformedDimensions(
          graphicObj,
          operation,
        ) || { newWidth: graphicObj.width, newHeight: graphicObj.height };
 
        const centredCoordGobj = getCentredCoordinates(graphicObj);
        const distFromCentre = getDistanceBetweenPoints(
          centredCoordGobj,
          selectionCentre,
        );
 
        const newCoords = getTransformedPosition(
          graphicObj,
          operation,
          selectionCentre,
          distFromCentre,
        );
 
        // Optimistically update the rotation and flip status in the cache
        dispatch(
          api.util.updateQueryData(
            "graphicsObjectsList",
            { group: groupId },
            (cachedGraphicObjects) => {
              const gObj = cachedGraphicObjects?.find(
                (graphicObject) =>
                  graphicObject.simulationObject.id ===
                  graphicObj.simulationObject.id,
              );
              if (gObj) {
                gObj.x = newCoords?.x;
                gObj.y = newCoords?.y;
                gObj.rotation = newRotation;
                gObj.flipped = newFlipped;
                gObj.width = newWidth;
                gObj.height = newHeight;
              }
            },
          ),
        );
        // Update each object
        updateGraphicObject({
          id: graphicObj.id,
          patchedGraphicObject: {
            x: newCoords?.x,
            y: newCoords?.y,
            rotation: newRotation,
            flipped: newFlipped,
            width: newWidth,
            height: newHeight,
          },
        });
      });
    } else E{
      console.error(`No object selected`);
    }
  };
 
  return {
    FlowsheetSurfaceState: FlowsheetSurfaceState,
    handleDrop: handleDrop,
    zoomToFit: zoomToFit,
    convertStreamToDecisionNode,
    unGroupCurrentObject,
    rotateFlipSelectedObject: rotateFlipSelectedObject,
    loading,
  };
};