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

59.66% Statements 213/357
40.97% Branches 59/144
62% Functions 31/50
60.23% Lines 209/347

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 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989                                                                                                          33x               42x   42x   42x   42x                                   41x   41x                 33x       86x                                       33x           3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x   3763x 3763x 7430x   3763x 3763x 3763x 3763x 3763x 3763x   3763x   3763x   3763x   595x           40x 40x                         3763x     3763x             78x       78x               78x             3763x 23x   23x           23x             23x     3763x       23x   23x 1x 1x       22x               22x     3763x         1x 1x               1x       1x             3763x 3x     3x           3x           3x         3x                   3x                   3x   3x     3763x 10x 10x 10x 10x       3763x             3763x 4x       4x 4x             4x 1x 1x 1x 1x 1x 1x     3x     4x       3763x 111x               3763x                               3763x                                     3763x                                                 3763x                                                 3763x                                                 3763x                                 3763x                                                                                                                                                                                                                       3763x     54x 54x   54x   47x 47x 47x   7x 7x 7x 7x   7x 31x 31x 31x 31x 31x 31x   31x 31x 31x 31x     7x 7x   7x 7x   7x   7x   7x     54x             54x     3763x 3x 3x 3x             3763x 35x 35x           35x 22x   16x 16x   22x             3763x 123x   69x       3763x 27x 16x   27x               3763x 9x   6x       6x 6x 6x 6x 6x       3763x                                                                     3763x 1x                 3763x 285x 285x 285x 285x 285x   3763x 285x   285x     285x   285x 285x   285x       285x       285x     3763x                                       3763x 291x 291x         3763x       3763x 5x     3763x                       3763x 22x   22x         22x 22x                 22x                                 3763x 1x 1x                   1x     3763x 1x       1x 1x         1x         1x                                                                           3763x                                                    
import {
  api,
  GraphicObjectRead,
  ObjectTypeEnum,
  useGraphicsgroupingsDestroyMutation,
  useGraphicsgroupingsUngroupCreateMutation,
  useGraphicsObjectsPartialUpdateMutation,
  useUnitopsSimulationobjectsCreateMutation,
  useUnitopsSimulationobjectsDuplicateSimulationObjectCreateMutation,
} from "@/api/apiStore.gen";
import { useHasCommand } from "@/commands/commandHooks";
import {
  useConvertStreamToDn,
  useSplitStreamWithHistory,
} from "@/hooks/connections";
import {
  useDeleteSimulationObject,
  useOptimisticallyDeleteSelection,
} from "@/hooks/deleteObjects";
import {
  useCurrentGroupId,
  useCurrentGroupObjects,
  useCurrentObject,
  useFlowsheetPorts,
  useFlowsheetUnitOps,
  useGraphicsObjects,
  useGroup,
  useGroupObjects,
  useObjectsGraphicObjectsMap,
  useSimulationObjectGroup,
  useStreamType,
  useTrackCoordinates,
} from "@/hooks/flowsheetObjects";
import { useProjectId } from "@/hooks/project";
import { useSearchParam } from "@/hooks/searchParams";
import { setCopiedObject } from "@/store/CopySlice";
import { useAppDispatch } from "@/store/hooks";
import { PointerState, setPointerState } from "@/store/PointerSlice";
import { RootState } from "@/store/store";
import { useRunCommand } from "just-search-it";
import { useEffect, useState } from "react";
import { DropTargetMonitor } from "react-dnd";
import { useSelector } from "react-redux";
import { useSearchParams } from "react-router-dom";
import { toast } from "sonner";
import { SwitchGroup } from "../../../../commands/SwitchCurrentGroup";
import { isStream } from "../../../../lib/isStream";
import { useSelectionRect } from "./SelectionRect";
import { useUndoRedoStore } from "@/hooks/useUndoRedoStore";
import { createAddCommand } from "@/utils/commandCreators";
import { ContentTypes } from "../LeftSideBar/LeftSideBarTabDefinitions";
import { useCreateModuleFromTemplate } from "@/hooks/useTemplate";
 
export const snap = (
  x: number,
  y: number,
  width: number,
  height: number
): { snapX: number; snapY: number } => {
  // snap to the center 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;
}
// 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 {
    canvasDiv,
    pointerState,
    FlowsheetSurfaceState,
    setFlowsheetSurfaceState,
  } = props;
  const dispatch = useAppDispatch();
  const objectsGraphicObjectsMap = useObjectsGraphicObjectsMap();
  const flowsheetId = useProjectId();
  const deleteSimulationObject = useDeleteSimulationObject();
  const graphicsObjects = useGraphicsObjects();
  const currentGroupObjects = useCurrentGroupObjects();
  const [createObject] = useUnitopsSimulationobjectsCreateMutation();
  const { addHistory } = useUndoRedoStore();
  const splitStreamWithHistory = useSplitStreamWithHistory();
  const streamType = useStreamType();
  const [objectId] = useSearchParam("object");
  const [searchParams, setSearchParams] = useSearchParams();
  const [deleteGroup] = useGraphicsgroupingsDestroyMutation();
  const simulationObjectGroup = useSimulationObjectGroup();
  const currentObject = useCurrentObject();
  const [updateGraphicObject] = useGraphicsObjectsPartialUpdateMutation();
  const convertStreamToDN = useConvertStreamToDn();
  const optimisticallyDeleteSelection = useOptimisticallyDeleteSelection();
  const currentGroupId = useCurrentGroupId();
  const getGroup = useGroup();
  const [ungroup] = useGraphicsgroupingsUngroupCreateMutation();
  const flowsheetObjects = useFlowsheetUnitOps();
  const groupObjects = useGroupObjects();
  const [duplicateObject] =
    useUnitopsSimulationobjectsDuplicateSimulationObjectCreateMutation();
  const copiedObjects = useSelector(
    (state: RootState) => state.copiedObject.ids
  );
  const [loading, setLoading] = useState(true);
  const switchGroup = useRunCommand(SwitchGroup);
  const hasCommand = useHasCommand();
  const ports = useFlowsheetPorts();
  useTrackCoordinates(FlowsheetSurfaceState, loading);
  const { createModuleFromTemplate } = useCreateModuleFromTemplate();
 
  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 {
    selectionRect,
    onSelectionRemoved,
    onSelectionStart,
    onResizeSelectionRect,
    onSelectionRectResizeEnd,
    setSelectionRect,
    makeGroup,
    deleteSelectedObjects,
  } = useSelectionRect(FlowsheetSurfaceState);
 
  // Change current zoom of the canvas
  const changeZoom = (
    towardX: number,
    towardY: number,
    amount: number,
    newStageX?: number,
    newStageY?: number
  ) => {
    const newScale = Math.min(
      1.5,
      Math.max(0.25, FlowsheetSurfaceState.scale * amount)
    ); //Zoom value must be within the range of 25% to 150%
    const mousePointTo = {
      x:
        towardX / FlowsheetSurfaceState.scale -
        FlowsheetSurfaceState.stageX / FlowsheetSurfaceState.scale,
      y:
        towardY / FlowsheetSurfaceState.scale -
        FlowsheetSurfaceState.stageY / FlowsheetSurfaceState.scale,
    };
    setFlowsheetSurfaceState({
      scale: newScale,
      stageX: newStageX ?? (towardX / newScale - mousePointTo.x) * newScale,
      stageY: newStageY ?? (towardY / newScale - mousePointTo.y) * newScale,
    });
  };
 
  const getDropPosition = (monitor: DropTargetMonitor<DragItem, void>) => {
    const clientOffset = monitor.getClientOffset();
 
    const x = canvasToFlowsheetCoords(
      (clientOffset?.x || 0) -
        (canvasDiv.current?.parentElement?.offsetLeft || 0),
      FlowsheetSurfaceState.stageX,
      FlowsheetSurfaceState.scale
    );
    const y = canvasToFlowsheetCoords(
      (clientOffset?.y || 0) -
        (canvasDiv.current?.parentElement?.offsetTop || 0),
      FlowsheetSurfaceState.stageY,
      FlowsheetSurfaceState.scale
    );
 
    return { x, 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 onKeyDown = (e) => {
    const zoomBy = 1.25;
 
    // TODO: move all these to the command system?
    Iif (e.ctrlKey && e.key === "c") {
      e.preventDefault();
      handleObjectCopy();
      return;
    }
 
    Iif (e.ctrlKey && e.key === "v") {
      e.preventDefault();
      handleControlVPaste();
      return;
    }
 
    Iif (e.key === "M" || e.key === "m") {
      dispatch(setPointerState("move"));
      return;
    }
 
    Iif (e.ctrlKey && e.key === "=") {
      e.preventDefault();
      Iif (!canvasDiv.current) return;
      changeZoom(
        canvasDiv.current.offsetWidth / 2,
        canvasDiv.current.offsetHeight / 2,
        zoomBy
      );
    }
 
    Iif (e.ctrlKey && e.key === "-") {
      e.preventDefault();
      Iif (!canvasDiv.current) return;
      changeZoom(
        canvasDiv.current.offsetWidth / 2,
        canvasDiv.current.offsetHeight / 2,
        1 / zoomBy
      );
    }
 
    Iif (e.key !== "Delete" && e.key !== "Backspace") return;
 
    deleteSelectedObject();
  };
 
  const clearObjectSelection = () => {
    setSearchParams((prev) => {
      const newSearchParams = new URLSearchParams(prev);
      newSearchParams.delete("object");
      return newSearchParams;
    });
  };
 
  const deleteSelectedObjectsMultiple = () => {
    deleteSelectedObjects();
    clearObjectSelection();
    // disable the selection rectangle
    onSelectionRemoved();
  };
 
  const deleteSelectedObject = () => {
    Iif (selectionRect.selectVisible) {
      deleteSelectedObjectsMultiple();
      return;
    }
    if (currentObject) {
      Iif (
        isStream(currentObject.objectType) &&
        streamType(currentObject.id) == "intermediate"
      ) {
        // deleting an intermediate stream, perform a split
        splitStream(currentObject.id);
      } else {
        if (currentObject.objectType === "group") {
          const group = simulationObjectGroup(currentObject.id);
          if (group) {
            deleteGroup({ id: group.id });
            const objectsToDelete = groupObjects(group.id).map((obj) => obj.id);
            objectsToDelete.push(currentObject.id);
            optimisticallyDeleteSelection(objectsToDelete);
          }
        } else {
          deleteSimulationObject(currentObject);
        }
      }
      clearObjectSelection();
    }
  };
 
  const getGraphicsObject = (objID: number) => {
    return graphicsObjects?.find((obj) => obj.simulationObject.id === objID);
  };
 
  /**
   * 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 = (
    streamPoint: { x: number; y: number },
    unitOpPoint: { x: number; y: number }
  ): { x: number; y: number } => {
    const xyDistance = {
      x: streamPoint.x - unitOpPoint.x,
      y: streamPoint.y - unitOpPoint.y,
    };
    return xyDistance;
  };
 
  /**
   * Get the coordinates of the position of an object after a clockwise rotation around a selected object.
   * @param selectedObject - The object being rotated around.
   * @param objectToMove - The object being moved.
   * @param unitCoords - The centre coordinates of the selected object.
   * @param distance - The distance between the object and the selected object.
   * @returns {x: number, y: number} - The new x and y coordinates of the object after rotation.
   */
  const getCoordsClockwiseRotation = (
    selectedObject: GraphicObjectRead,
    objectToMove: GraphicObjectRead,
    unitCoords: { x: number; y: number },
    distance: { x: number; y: number }
  ): { x: number; y: number } => {
    let newCoords = { x: objectToMove.x, y: objectToMove.y };
    Iif (selectedObject.id !== objectToMove.id) {
      // CW rotation - x distance becomes -y, y distance becomes x; offset with object dimensions
      newCoords = {
        x: unitCoords.x - distance.y - objectToMove.height / 2,
        y: unitCoords.y + distance.x - objectToMove.height / 2,
      };
    }
    return newCoords;
  };
 
  /**
   * Get the coordinates of the position of an object after an anti-clockwise rotation around a selected object.
   * @param selectedObject - The object being rotated around.
   * @param objectToMove - The object being moved.
   * @param unitCoords - The centre coordinates of the selected object.
   * @param distance - The distance between the object and the selected object.
   * @returns {x: number, y: number} - The new x and y coordinates of the object after rotation.
   */
  const getCoordsAntiClockwiseRotation = (
    selectedObject: GraphicObjectRead,
    objectToMove: GraphicObjectRead,
    unitCoords: { x: number; y: number },
    distance: { x: number; y: number }
  ): { x: number; y: number } => {
    let newCoords = { x: objectToMove.x, y: objectToMove.y };
    Iif (selectedObject.id !== objectToMove.id) {
      // ACW rotation - x distance becomes y, y distance becomes -x; offset with object dimensions
      newCoords = {
        x: unitCoords.x + distance.y - objectToMove.width / 2,
        y: unitCoords.y - distance.x - objectToMove.width / 2,
      };
    }
    return newCoords;
  };
 
  /**
   * Get the coordinates of the position of an object after a horizontal flip.
   * @param selectedObject - The object being flipped.
   * @param objectToMove - The object being moved.
   * @param unitCoords - The centre coordinates of the selected object (the one being flipped).
   * @param distance - The distance between the object and the selected object.
   * @returns {x: number, y: number} - The new x and y coordinates of the object after the flip.
   */
  const getCoordsFlipH = (
    selectedObject: GraphicObjectRead,
    objectToMove: GraphicObjectRead,
    unitCoords: { x: number; y: number },
    distance: { x: number; y: number }
  ): { x: number; y: number } => {
    let newCoords = { x: objectToMove.x, y: objectToMove.y };
    Iif (selectedObject.id !== objectToMove.id) {
      // Flip units horizontally - x distance becomes -x; offset with object dimensions
      newCoords = {
        x: unitCoords.x - distance.x - objectToMove.width / 2,
        y: unitCoords.y + distance.y - objectToMove.height / 2,
      };
    }
    return newCoords;
  };
 
  /**
   * Get the coordinates of the position of an object after a vertical flip.
   * @param selectedObject - The object being flipped.
   * @param objectToMove - The object being moved.
   * @param unitCoords - The centre coordinates of the selected object (the one being flipped).
   * @param distance - The distance between the object and the selected object.
   * @returns {x: number, y: number} - The new x and y coordinates of the object after the flip.
   */
  const getCoordsFlipV = (
    selectedObject: GraphicObjectRead,
    objectToMove: GraphicObjectRead,
    unitCoords: { x: number; y: number },
    distance: { x: number; y: number }
  ): { x: number; y: number } => {
    let newCoords = { x: objectToMove.x, y: objectToMove.y };
    Iif (selectedObject.id !== objectToMove.id) {
      // Flip units vertically - y distance becomes -y; offset with object dimensions
      newCoords = {
        x: unitCoords.x + distance.x - objectToMove.width / 2,
        y: unitCoords.y - distance.y - objectToMove.height / 2,
      };
    }
    return newCoords;
  };
 
  const rotateFlipSelectedObject = (operation: string) => {
    const objID = +objectId!;
    const selectedGraphicObject = getGraphicsObject(objID);
    const groupId = currentGroupId;
 
    if (selectedGraphicObject) {
      const currentRotation = Number(selectedGraphicObject?.rotation) || 0;
      const currentFlipped = selectedGraphicObject?.flipped;
      const connectedStreams = getConnectedStreams(
        selectedGraphicObject.simulationObject.id
      );
      const operationGroup = [
        selectedGraphicObject.simulationObject.id,
        ...connectedStreams,
      ];
      let newRotation = currentRotation;
      let newFlipped = currentFlipped;
 
      // Do operation on the selected unit and all connected streams
      operationGroup.map((simulationObjectId) => {
        // Get centrepoint of the object then calculate its distance from the main unit's centrepoint
        const graphicObj = getGraphicsObject(simulationObjectId);
        Iif (!graphicObj) return; // Skip if no graphic object found
        const centredCoordStream = getCentredCoordinates(graphicObj);
        const centredCoordUnit = getCentredCoordinates(selectedGraphicObject);
        const distFromMainUnit = getDistanceBetweenPoints(
          centredCoordStream,
          centredCoordUnit
        );
        let newCoords = { x: graphicObj.x, y: graphicObj.y };
 
        // Rotate and Flip Operations
        if (operation == "right") {
          newRotation = (currentRotation + 90) % 360;
          newCoords = getCoordsClockwiseRotation(
            selectedGraphicObject,
            graphicObj,
            centredCoordUnit,
            distFromMainUnit
          );
        } else if (operation == "left") {
          newRotation = (currentRotation - 90 + 360) % 360;
          newCoords = getCoordsAntiClockwiseRotation(
            selectedGraphicObject,
            graphicObj,
            centredCoordUnit,
            distFromMainUnit
          );
        } else if (operation == "horizontal") {
          // Rotate twice only on certain current rotation conditions. This essentilly flips the group horizontally.
          Iif (currentRotation === 90 || currentRotation === 270) {
            newRotation = (currentRotation + 180) % 360;
          }
          newFlipped = !currentFlipped;
          newCoords = getCoordsFlipH(
            selectedGraphicObject,
            graphicObj,
            centredCoordUnit,
            distFromMainUnit
          );
        I} else if (operation == "vertical") {
          // Rotate twice only on certain current rotation conditions. This essentilly flips the group vertically.
          Iif (currentRotation === 0 || currentRotation === 180) {
            newRotation = (currentRotation + 180) % 360;
          }
          newFlipped = !currentFlipped;
          newCoords = getCoordsFlipV(
            selectedGraphicObject,
            graphicObj,
            centredCoordUnit,
            distFromMainUnit
          );
        }
        // Update each object
        updateGraphicObject({
          id: graphicObj.id,
          patchedGraphicObject: {
            x: newCoords.x,
            y: newCoords.y,
            rotation: newRotation,
            flipped: newFlipped,
          },
        });
        // 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 === simulationObjectId
              );
              Iif (gObj) {
                gObj.x = newCoords.x;
                gObj.y = newCoords.y;
                gObj.rotation = newRotation;
                gObj.flipped = newFlipped;
              }
            }
          )
        );
      });
    } else {
      console.error(`No object selected`, objID);
    }
  };
 
  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
      // centering
      newStageX =
        (canvasWidth - boundingWidth * newScale) / 2 - minX * newScale;
      newStageY =
        (canvasHeight - boundingHeight * newScale) / 2 - minY * newScale;
    }
    changeZoom(
      canvasWidth / 2,
      canvasHeight / 2,
      newScale / FlowsheetSurfaceState.scale,
      newStageX,
      newStageY
    );
    return { newScale, newStageX, newStageY };
  };
 
  const resetZoom = () => {
    const canvasWidth = canvasDiv.current?.offsetWidth || 640;
    const canvasHeight = canvasDiv.current?.offsetHeight || 480;
    changeZoom(
      canvasWidth / 2,
      canvasHeight / 2,
      1 / FlowsheetSurfaceState.scale
    );
  };
 
  const onMouseDown = (e) => {
    const stage = e.target.getStage();
    Iif (pointerState.state === "move") {
      Iif (e.evt.button == 0 || e.evt.button == 1) {
        stage.draggable(true); // Enable dragging for panning
        return; // Return early, disabling other interactions
      }
    }
    if (e.currentTarget != e.target) return; // dragging a unit op
    if (e.evt.button == 0) {
      // left mouse button, selection rectangle
      stage.draggable(false);
      onSelectionStart(e);
    }
    Iif (e.evt.button == 1) {
      // middle mouse button, enable dragging
      stage.draggable(true);
      return;
    }
  };
 
  const onMouseMove = (e) => {
    if (selectionRect.selectEnabled) {
      // update selection rectangle
      onResizeSelectionRect(e);
    }
  };
 
  const onMouseUp = (e) => {
    if (selectionRect.selectEnabled) {
      onSelectionRectResizeEnd(e);
    }
    Iif (e.evt.button == 1) {
      // middle mouse button, disable dragging
      const stage = e.target.getStage();
      stage.draggable(false);
      return;
    }
  };
 
  const onDoubleClick = (e) => {
    if (e.currentTarget != e.target) return; // skip if the stage is not clicked
    // clear the object selection
    clearObjectSelection();
 
    // Bring up the flowsheet details on the right side-bar
    // const group = getGroup;
    const newSearchParams = new URLSearchParams(searchParams);
    const id = getGroup(currentGroupId).simulationObject;
    newSearchParams.set("object", id.toString());
    newSearchParams.set("content", ContentTypes.objectDetails);
    setSearchParams(newSearchParams);
  };
 
  // Manages zoom and scrolling behaviours with mousewheel actions
  const onScroll = (e) => {
    // stop default scrolling
    e.evt.preventDefault();
    if (e.evt.ctrlKey) {
      // zoom in and out
      const scaleBy = 1.1;
      const stage = e.target.getStage();
      const scaleMultiplier = e.evt.deltaY < 0 ? scaleBy : 1 / scaleBy;
      changeZoom(
        stage.getPointerPosition().x,
        stage.getPointerPosition().y,
        scaleMultiplier
      );
    } else if (e.evt.shiftKey) {
      // shift + scroll is horizontal scroll
      setFlowsheetSurfaceState({
        ...FlowsheetSurfaceState,
        stageX: FlowsheetSurfaceState.stageX - e.evt.deltaY * 0.3,
      });
    } else if (Math.abs(e.evt.deltaX) > Math.abs(e.evt.deltaY)) {
      // horizontal scroll in touchpad
      setFlowsheetSurfaceState({
        ...FlowsheetSurfaceState,
        stageX: FlowsheetSurfaceState.stageX - e.evt.deltaX * 0.3,
      });
    } else {
      // Handle vertical scrolling logic here
      setFlowsheetSurfaceState({
        ...FlowsheetSurfaceState,
        stageY: FlowsheetSurfaceState.stageY - e.evt.deltaY * 0.3,
      });
    }
  };
 
  //Dragging the canvas using mouse
  const onStageDrag = (e) => {
    if (e.currentTarget != e.target) return; // dragging a unit op
    e.evt.preventDefault();
    setFlowsheetSurfaceState({
      ...FlowsheetSurfaceState,
      stageX: e.target.x(),
      stageY: e.target.y(),
    });
  };
 
  const extractGraphicObject = (graphicObject) => {
    const objectX = +graphicObject.x;
    const objectY = +graphicObject.y;
    const objectWidth = +graphicObject.width;
    const objectHeight = +graphicObject.height;
    return { objectX, objectY, objectWidth, objectHeight };
  };
  const isObjectVisible = (graphicObject) => {
    Iif (!graphicObject) return false;
    const { objectX, objectY, objectWidth, objectHeight } =
      extractGraphicObject(graphicObject);
 
    const visibleX =
      (FlowsheetSurfaceState.stageX / FlowsheetSurfaceState.scale) * -1;
    const visibleY =
      (FlowsheetSurfaceState.stageY / FlowsheetSurfaceState.scale) * -1;
    const visibleWidth =
      (canvasDiv.current?.offsetWidth || 640) / FlowsheetSurfaceState.scale;
    const visibleHeight =
      (canvasDiv.current?.offsetHeight || 480) / FlowsheetSurfaceState.scale;
 
    const isVisible =
      objectX + objectWidth >= visibleX &&
      objectX <= visibleX + visibleWidth &&
      objectY + objectHeight >= visibleY &&
      objectY <= visibleY + visibleHeight;
    return isVisible;
  };
 
  const moveCanvasToObject = (graphicObject) => {
    const { objectX, objectY, objectWidth, objectHeight } =
      extractGraphicObject(graphicObject);
    const canvasWidth = canvasDiv.current?.offsetWidth || 640;
    const canvasHeight = canvasDiv.current?.offsetHeight || 480;
 
    const newStageX =
      canvasWidth / 2 -
      (objectX + objectWidth / 2) * FlowsheetSurfaceState.scale;
    const newStageY =
      canvasHeight / 2 -
      (objectY + objectHeight / 2) * FlowsheetSurfaceState.scale;
 
    setFlowsheetSurfaceState({
      ...FlowsheetSurfaceState,
      stageX: newStageX,
      stageY: newStageY,
    });
  };
 
  const onObjectSelect = (objectId: number) => {
    const graphicObject = objectsGraphicObjectsMap.get(objectId);
    Iif (graphicObject && !isObjectVisible(graphicObject)) {
      moveCanvasToObject(graphicObject);
    }
  };
 
  const convertStreamToDecisionNode = (streamID: number) => {
    convertStreamToDN(streamID);
  };
 
  const groupSelectedObjects = () => {
    makeGroup();
  };
 
  const unGroupCurrentObject = () => {
    const group = simulationObjectGroup(currentObject.id);
    ungroup({
      ungroup: {
        parentGroup: group.id,
      },
    });
    optimisticallyDeleteSelection([currentObject.id]);
    clearObjectSelection();
  };
 
  // After creating a new object, update its group
  const handleObjectCreation = async (objectData) => {
    try {
      // CRITICAL FIX: Track ADD operations for undo/redo in drag-and-drop
      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);
    }
  };
 
  function getConnectedStreams(unitopId: number): number[] {
    const streams: number[] = [];
    ports?.forEach((port) => {
      Iif (port.unitOp === unitopId && port.stream != null) {
        streams.push(port.stream);
      }
    });
    return streams;
  }
 
  const handleObjectCopy = () => {
    if (selectionRect.selectVisible) {
      dispatch(setCopiedObject(selectionRect.containedObjects));
    E} else if (currentObject && currentObject.id) {
      // Get connected streams
      const connectedStreams = getConnectedStreams(currentObject.id);
      // Include the unitop and its connected streams
      const objectsToCopy = [currentObject.id, ...connectedStreams];
      dispatch(setCopiedObject(objectsToCopy));
    } else {
      toast.error("No object selected to copy.");
    }
    return;
  };
 
  const handleObjectPaste = (position: { x: number; y: number }) => {
    const pos = position || {
      x: props.canvasWidth / 2,
      y: props.canvasHeight / 2,
    };
    if (copiedObjects) {
      const flowsheetX = canvasToFlowsheetCoords(
        pos.x,
        FlowsheetSurfaceState.stageX,
        FlowsheetSurfaceState.scale
      );
      const flowsheetY = canvasToFlowsheetCoords(
        pos.y,
        FlowsheetSurfaceState.stageY,
        FlowsheetSurfaceState.scale
      );
      duplicateObject({
        duplicateSimulationObject: {
          objectIDs: copiedObjects,
          x: flowsheetX,
          y: flowsheetY,
        },
      }).unwrap();
    } else E{
      toast.error("No object copied to paste.");
    }
  };
 
  function handleControlVPaste() {
    const canvasWidth = canvasDiv.current.offsetWidth;
    const canvasHeight = canvasDiv.current.offsetHeight;
    if (copiedObjects) {
      const flowsheetX = canvasToFlowsheetCoords(
        canvasWidth / 2,
        FlowsheetSurfaceState.stageX,
        FlowsheetSurfaceState.scale
      );
      const flowsheetY = canvasToFlowsheetCoords(
        canvasHeight / 2,
        FlowsheetSurfaceState.stageY,
        FlowsheetSurfaceState.scale
      );
      duplicateObject({
        duplicateSimulationObject: {
          objectIDs: copiedObjects,
          x: flowsheetX,
          y: flowsheetY,
        },
      }).unwrap();
    } else {
      toast.error("No object copied to paste.");
    }
  }
 
  return {
    FlowsheetSurfaceState: FlowsheetSurfaceState,
    changeZoom: changeZoom,
    handleDrop: handleDrop,
    onKeyDown: onKeyDown,
    onMouseDown: onMouseDown,
    onMouseUp: onMouseUp,
    onMouseMove: onMouseMove,
    onDoubleClick: onDoubleClick,
    onScroll: onScroll,
    onStageDrag: onStageDrag,
    zoomToFit: zoomToFit,
    resetZoom: resetZoom,
    deleteSelectedObject: deleteSelectedObject,
    rotateFlipSelectedObject: rotateFlipSelectedObject,
    onObjectSelect,
    convertStreamToDecisionNode,
    groupSelectedObjects,
    unGroupCurrentObject,
    handleObjectCopy,
    handleObjectPaste,
    selectionRect,
    loading,
    setSelectionRect,
  };
};