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

83.24% Statements 318/382
58.65% Branches 61/104
90.36% Functions 75/83
87.89% Lines 305/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 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190                                                                                                                                                                                                                    76x                                 76x       8015x 8015x 16940x 8015x 8015x 8015x 8015x     8015x           8015x               8015x 8015x 8015x 8015x     8015x 8015x 8015x 8015x 8015x 8015x 8015x 8015x 8015x 8015x 8015x 8015x 1057x   1057x 4879x   4712x       1057x     8015x   8015x   8015x       8015x       8015x 165x     8015x 8015x 8015x 8015x 8015x 8015x 8015x   8015x   8015x 8015x 8015x 8015x 81x     8015x                             8015x   8015x 8015x 16940x   8015x 8015x 8015x     8015x 8015x 8015x 8015x 8015x 8015x 8015x       8015x                               8015x 8015x         8015x     8015x     8015x   19x 19x   19x   19x         19x   55x       19x 19x           19x                       8015x   10x 10x                                     3x 3x                                                             7x         7x   73x     7x 7x           7x                                         8015x 44x 44x 44x 44x         8015x   4x   4x 27x     4x     4x   4x 4x                 4x         4x   4x         4x                             8015x 149x     8186x                             3x   18x   3x               8015x   1x 1x   2x     1x         8015x 1665x 1665x   148x 148x             8015x 149x 149x   148x 148x                       8015x   781x         8015x   18x 18x         8015x           8015x   15x 15x 15x 15x 15x           8015x   20x 20x 20x 20x 20x 20x       3x 9x                   20x                 20x               8015x 20x 20x 20x     8015x   178x     69x 69x     69x   13x   13x 13x 77x   13x 13x         13x       109x   109x   4x 4x 4x 19x   4x 4x         4x             8015x   20x 20x     20x     10x 10x   10x 10x     10x 10x         8015x 182x         3x 3x 9x   3x     8015x   3x 3x 9x           8015x   2x   2x       2x 1x 1x   1x 1x           19x 19x     19x       19x       8015x 18x     8x   10x     18x 18x     8015x 1x 1x 1x     8015x                                                 8015x       8015x   40x 40x 40x         8015x         5x 5x 5x 5x 5x         8015x 3x 3x 3x 3x   3x 3x     8015x 2x 2x 6x     1x     1x   1x 1x       8015x   2x   2x 2x           2x 2x                               1x 1x 1x                               8015x 5x 5x 5x       14x           8015x                                       8015x                             8015x   1377x 1377x             7x     1370x                 8015x   7x 7x 7x       7x 7x 23x                       8015x   663x 3622x   663x           8015x 81x     8015x   74x   74x   74x         8015x   53x   53x 53x         8015x   69x           8015x 1736x   265x 1729x       2x         8015x 750x   750x     750x   750x 2794x       3157x             750x 750x                                                                                                                                                                                                                                                                              
import {
  addEdge,
  applyEdgeChanges,
  applyNodeChanges,
  Background,
  BackgroundVariant,
  Controls,
  Edge,
  MiniMap,
  Node,
  ReactFlow,
  Node as RFNode,
  SelectionMode,
  useEdgesState,
  useNodesState,
  useReactFlow,
  Viewport,
} from "@xyflow/react";
import {
  api,
  GraphicObjectRead,
  GroupingRead,
  MonitoringTableRead,
  ObjectTypeEnum,
  SimulationObjectRead,
  SimulationObjectRetrieveRead,
  useCoreRecycledataListQuery,
  useGraphicsgroupingsConnectionsRetrieveQuery,
  useGraphicsgroupingsDeleteSelectedObjectsCreateMutation,
  useGraphicsgroupingsMakeGroupCreateMutation,
  useGraphicsgroupingsPartialUpdateMutation,
  useGraphicsgroupingsUngroupCreateMutation,
  useGraphicsObjectsPartialUpdateMutation,
  useLazyUnitopsSimulationobjectsTrackedStreamFlowRetrieveQuery,
  useUnitopsSimulationobjectsDuplicateSimulationObjectCreateMutation,
} from "@/api/apiStore.gen";
import { SwitchGroupCommands } from "@/commands/SwitchCurrentGroup";
import {
  useAddPortAndConnectStream,
  useMergeDecisionNodes,
  useMergeStreams,
} from "@/hooks/connections";
import {
  useCaptureDeletionConnections,
  useOptimisticallyDeleteSelection,
} from "@/hooks/deleteObjects";
import { useFlowsheetAccess } from "@/hooks/flowsheetAccess";
import {
  useCurrentGroupId,
  useCurrentGroupObjects,
  useCurrentObject,
  useFlowsheetObjectsIdMap,
  useFlowsheetPorts,
  useGraphicsObjects,
  useGroup,
  useObjectsGraphicObjectsMap,
  useSimulationObjectGroup,
} from "@/hooks/flowsheetObjects";
import {
  useFlowsheetTabFromGroupId,
  useSwitchToGroup,
} from "@/hooks/projectTabs";
import { useUndoRedoStore } from "@/hooks/useUndoRedoStore";
import { setCopiedObject } from "@/store/CopySlice";
import { useAppDispatch } from "@/store/hooks";
import { setPointerState } from "@/store/PointerSlice";
import { RootState } from "@/store/store";
import {
  createDeleteCommand,
  createMoveCommand,
} from "@/utils/commandCreators";
import "@xyflow/react/dist/style.css";
import React, {
  createContext,
  memo,
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useDrop } from "react-dnd";
import { useSelector } from "react-redux";
import { useSearchParams } from "react-router-dom";
import { toast } from "sonner";
import { useResizeObserver } from "usehooks-ts";
import { UnitOpCommands } from "../../../../commands/AddUnitOp";
import { isStream } from "../../../../lib/isStream";
import { DownloadFlowsheetTagMappingsCommand } from "../../export/DownloadFlowsheetTagMappings";
import { ConnectToExcelCommand } from "../../multi-steady-state/ConnectToExcelCommand";
import { DownloadTagMappingsCommand } from "../../multi-steady-state/DownloadTagMappings";
import { ExportMSSRResultsCommand } from "../../multi-steady-state/ExportMSSResultsCommand";
import { ContentTypes } from "../LeftSideBar/LeftSideBarTabDefinitions";
import BreadCrumbs from "./BreadCrumbs";
import { ContextMenu, Coordinates } from "./ContextMenu";
import { FlowsheetCommands } from "./FlowsheetCommands";
import FlowsheetControls from "./FlowsheetControls";
import { useFlowsheetCanvasFunctions } from "./FlowsheetFunctions";
import MonitoringTablesContainer from "./MonitoringTablesContainer";
import PropertyHover from "./PropertyHover";
import { useRenderOperations } from "./RenderOperations";
import { SimulationObjectGraphic } from "./SimulationObjectGraphic";
import { TemperatureScale } from "./TemperatureScale";
import { useAutoSortCanvas } from "./useAutoSortCanvas";
import { useHoveredObject } from "./useHoveredObject";
 
const nodeTypes = {
  simulationObjectGraphic: SimulationObjectGraphic,
};
 
interface FlowsheetProps {
  width: number;
  monitoringTables?: MonitoringTableRead[];
  onHideTable?: (tableId: number) => void;
  onRenameTable?: (tableId: number, newName: string) => void;
}
 
type TrackedStreamState = {
  sourceStreamId: number;
  sourceName: string;
  streamIds: number[];
};
 
export const IndicatorVisibilityContext = createContext<boolean>(true);
 
const FlowsheetSurface: React.FC<FlowsheetProps> = (props) => {
  // Flowsheet/Canvas
  const canvasDiv = useRef(null);
  const hoverRef = useRef<string | null>(null);
  const pointerState = useSelector((state: RootState) => state.pointer);
  const { height = 480 } = useResizeObserver({ ref: canvasDiv });
  const canvasWidth = Math.floor(props.width);
  const canvasHeight = Math.floor(height);
  const [flowsheetSurface, setFlowsheetSurface] = useState<
    Record<string, Viewport>
  >({});
  const [FlowsheetSurfaceState, setFlowsheetSurfaceState] = useState({
    scale: 1,
    stageX: canvasWidth,
    stageY: canvasHeight,
  });
  const { handleDrop, zoomToFit, rotateFlipSelectedObject } =
    useFlowsheetCanvasFunctions({
      canvasDiv,
      pointerState,
      FlowsheetSurfaceState,
      setFlowsheetSurfaceState,
      canvasWidth,
      canvasHeight,
    });
  const [indicatorsVisible, setIndicatorsVisible] = useState(true);
  const [searchParams, setParams] = useSearchParams();
  const access = useFlowsheetAccess();
  const canMutate = access?.can_edit ?? true;
 
  // Hooks
  const dispatch = useAppDispatch();
  const rootGroup = useCurrentGroupId();
  const graphicsObjects = useGraphicsObjects();
  const currentGroupObjects = useCurrentGroupObjects();
  const flowsheetObjectIdMap = useFlowsheetObjectsIdMap();
  const currentObject = useCurrentObject();
  const currentGroupId = useCurrentGroupId();
  const getGroup = useGroup();
  const objectsGraphicObjectsMap = useObjectsGraphicObjectsMap();
  const simulationObjectGroup = useSimulationObjectGroup();
  const openTab = useSwitchToGroup();
  const streamPropertiesById = useMemo(() => {
    const propertiesById = new Map<number, SimulationObjectRetrieveRead>();
 
    currentGroupObjects.forEach((object) => {
      const streamData = flowsheetObjectIdMap.get(object.id);
      if (streamData) {
        propertiesById.set(object.id, streamData);
      }
    });
 
    return propertiesById;
  }, [currentGroupObjects, flowsheetObjectIdMap]);
 
  const getFlowsheetTabFromGroupId = useFlowsheetTabFromGroupId();
 
  const ports = useFlowsheetPorts();
  const { data: connectionGraphics } =
    useGraphicsgroupingsConnectionsRetrieveQuery(
      { group: currentGroupId },
      { skip: !currentGroupId || currentGroupId <= 0 },
    );
  const { data: recycleConnectionsData } = useCoreRecycledataListQuery(
    { group: currentGroupId },
    { skip: !currentGroupId || currentGroupId <= 0 },
  );
  const recycleConnections = useMemo(
    () => recycleConnectionsData ?? [],
    [recycleConnectionsData],
  );
  const mergeStreams = useMergeStreams();
  const addPortAndConnectStream = useAddPortAndConnectStream();
  const mergeDecisionNodes = useMergeDecisionNodes();
  const [updateGroupPosition] = useGraphicsgroupingsPartialUpdateMutation();
  const [updateGraphicObject] = useGraphicsObjectsPartialUpdateMutation();
  const [makeGroup] = useGraphicsgroupingsMakeGroupCreateMutation();
  const [ungroup] = useGraphicsgroupingsUngroupCreateMutation();
  const [deleteSelectionObjects] =
    useGraphicsgroupingsDeleteSelectedObjectsCreateMutation();
  const [trackStreamFlow] =
    useLazyUnitopsSimulationobjectsTrackedStreamFlowRetrieveQuery();
  const optimisticallyDeleteSelection = useOptimisticallyDeleteSelection();
  const [trackedStream, setTrackedStream] = useState<TrackedStreamState>();
  const trackedStreamIds = useMemo(
    () => new Set(trackedStream?.streamIds ?? []),
    [trackedStream],
  );
  const { renderNodes, renderEdges } = useRenderOperations({
    currentGroupObjects,
    graphicsObjects,
    connectionGraphics,
    recycleConnections,
    objectsGraphicObjectsMap,
    streamPropertiesById,
    trackedStreamIds,
  });
  const {
    getIntersectingNodes,
    getViewport,
    screenToFlowPosition,
    fitView,
    getNodesBounds,
  } = useReactFlow();
  const [duplicateObject] =
    useUnitopsSimulationobjectsDuplicateSimulationObjectCreateMutation();
  const copiedObjects = useSelector(
    (state: RootState) => state.copiedObject.ids,
  );
  const captureConnections = useCaptureDeletionConnections();
  const { addHistory, isReady } = useUndoRedoStore();
  const handleAutoSortCanvas = useAutoSortCanvas();
 
  // React Flow Hooks
  const initialUnitOps: Node[] = [];
  const initialConnections: Edge[] = [];
  const [unitOps, setUnitOps] = useNodesState(initialUnitOps);
  const [connections, setConnections] = useEdgesState(initialConnections);
  const [selectedNodes, setSelectedNodes] = useState<Node[]>([]);
  const [contextMenuEnabled, setContextMenuEnabled] = useState<boolean>(false);
  const [contextMenuPosition, setContextMenuPosition] = useState<Coordinates>({
    x: 0,
    y: 0,
  });
  const [dragStartPositions, setDragStartPositions] = useState<Coordinates[]>(
    [],
  );
  const handleSetPointer = (pointerMode: "select" | "move") => {
    dispatch(setPointerState(pointerMode));
  };
 
  const togglePointerState = () => {
    const nextState = pointerState.state === "select" ? "move" : "select";
    handleSetPointer(nextState);
  };
  const {
    hoveredObjectId,
    isHovered: hoverActive,
    showHover,
    clearHover,
  } = useHoveredObject();
  const [hoverPos, setHoverPos] = useState<{ x: number; y: number }>({
    x: 0,
    y: 0,
  });
  const hoveredSimulationObject =
    hoveredObjectId === undefined
      ? undefined
      : flowsheetObjectIdMap.get(hoveredObjectId);
  const [isDragging, setIsDragging] = useState<boolean>(false);
 
  /* Save Position */
  const savePosition = useCallback(
    (node: RFNode) => {
      Iif (!canMutate) return;
      const graphicObject: GraphicObjectRead = node.data.graphicObject;
      const simulationObject: SimulationObjectRetrieveRead =
        node.data.simulationObject;
 
      dispatch(
        api.util.updateQueryData(
          "graphicsObjectsList",
          { group: currentGroupId },
          (cachedGraphicObjects) => {
            const gObj = cachedGraphicObjects?.find(
              (graphicObject) =>
                graphicObject.simulationObject.id.toString() ===
                simulationObject.id.toString(),
            );
            if (gObj) {
              gObj.x = node.position.x;
              gObj.y = node.position.y;
            }
          },
        ),
      );
 
      updateGraphicObject({
        id: graphicObject.id,
        patchedGraphicObject: {
          x: node.position.x,
          y: node.position.y,
        },
      });
    },
    [canMutate, currentGroupId, dispatch, updateGraphicObject],
  );
 
  /* Merge Streams */
  const handleMerging = useCallback(
    (dragged: RFNode, target: RFNode) => {
      const activeObject: SimulationObjectRead = dragged.data.simulationObject;
      const overObject: SimulationObjectRead = target.data.simulationObject;
 
      if (isStream(activeObject)) {
        if (
          overObject &&
          (overObject.objectType === ObjectTypeEnum.Mixer ||
            overObject.objectType === ObjectTypeEnum.Splitter ||
            overObject.objectType === ObjectTypeEnum.DecisionNode)
        ) {
          addPortAndConnectStream(overObject, activeObject);
          return;
        }
 
        if (
          overObject &&
          isStream(overObject) &&
          overObject.id !== activeObject.id &&
          overObject.objectType === activeObject.objectType
        ) {
          mergeStreams(activeObject, overObject);
          return;
        }
      }
 
      if (
        activeObject.objectType === ObjectTypeEnum.DecisionNode &&
        overObject?.objectType === ObjectTypeEnum.DecisionNode &&
        overObject.id !== activeObject.id
      ) {
        mergeDecisionNodes(activeObject, overObject);
        return;
      }
 
      if (activeObject.objectType === ObjectTypeEnum.DecisionNode) {
        if (overObject && isStream(overObject)) {
          addPortAndConnectStream(activeObject, overObject);
        }
      }
 
      if (activeObject.objectType === ObjectTypeEnum.Group) {
        const group: GroupingRead = simulationObjectGroup(activeObject.id);
        updateGroupPosition({
          id: group.id,
          patchedGrouping: {
            x: dragged.position.x,
            y: dragged.position.y,
          },
        });
        return;
      }
 
      dispatch(
        api.util.updateQueryData(
          "graphicsObjectsList",
          { group: currentGroupId },
          (cachedGraphicObjects) => {
            const gObj = cachedGraphicObjects?.find(
              (graphicObject) =>
                graphicObject.simulationObject.id === activeObject.id,
            );
            if (gObj) {
              gObj.x = dragged.position.x;
              gObj.y = dragged.position.y;
            }
          },
        ),
      );
 
      updateGraphicObject({
        id: dragged.data.graphicObject.id,
        patchedGraphicObject: {
          x: dragged.position.x,
          y: dragged.position.y,
        },
      });
    },
    [
      addPortAndConnectStream,
      currentGroupId,
      dispatch,
      mergeDecisionNodes,
      mergeStreams,
      simulationObjectGroup,
      updateGraphicObject,
      updateGroupPosition,
    ],
  );
 
  /* Clear Object Selection */
  const clearObjectSelection = useCallback(() => {
    setParams((prev) => {
      const newSearchParams = new URLSearchParams(prev);
      newSearchParams.delete("object");
      return newSearchParams;
    });
  }, [setParams]);
 
  /* Delete Selected Nodes */
  const deleteSelectedNodes = useCallback(
    (containedObjects: number[]) => {
      Iif (!canMutate) return;
      // Get objects to be deleted
      const objectsToDelete = currentGroupObjects.filter((obj) =>
        containedObjects.includes(obj.id),
      );
 
      Iif (objectsToDelete.length === 0) return;
 
      // Capture connection data before deletion
      const connectionData = captureConnections(containedObjects);
      // Add to undo history before optimistic update
      const deleteCommand = createDeleteCommand({
        objects: objectsToDelete.map((obj) => ({
          id: obj.id,
          objectType: obj.objectType || "SimulationObject",
          fullObjectData: obj,
        })),
        connectionData,
      });
 
      if (isReady) {
        addHistory(deleteCommand);
      } else if (process.env.NODE_ENV === "development") {
        console.warn("[UndoRedo] Delete command skipped - context not ready");
      }
 
      optimisticallyDeleteSelection(containedObjects);
      // Delete the objects in the backend
      deleteSelectionObjects({
        deleteSelectedObjects: {
          containedObjects: containedObjects,
        },
      });
      clearObjectSelection();
    },
    [
      addHistory,
      captureConnections,
      clearObjectSelection,
      currentGroupObjects,
      deleteSelectionObjects,
      isReady,
      canMutate,
      optimisticallyDeleteSelection,
    ],
  );
 
  /* Left Sidebar Drag and Drop */
  const [{ isOver }, drop] = useDrop(
    () => ({
      accept: "unit_operation",
      drop: handleDrop,
      collect: (monitor) => ({
        isOver: !!monitor.isOver(),
      }),
    }),
    [rootGroup],
  );
 
  /**
   * Returns a unique array of nodes from either a single node or an array of nodes
   * @param inputs
   * @returns a unique array of nodes
   */
  function getNodeArray(inputs: Node | Node[]) {
    // MULTI-SELECT
    if (Array.isArray(inputs)) {
      const uniqueNodes: Node[] = inputs.filter(
        (value, index, array) =>
          index === array.findIndex((t) => t.id === value.id),
      );
      return uniqueNodes;
      // SINGLE SELECT
    } else {
      const uniqueNodes: Node[] = [inputs];
      return uniqueNodes;
    }
  }
 
  const getConnectedStreams = useCallback(
    (unitopId: number): number[] => {
      const streams: number[] = [];
      ports?.forEach((port) => {
        if (port.unitOp === unitopId && port.stream != null) {
          streams.push(port.stream);
        }
      });
      return streams;
    },
    [ports],
  );
 
  const getGroupViewport = useMemo(() => {
    const savedViewport = flowsheetSurface[currentGroupId];
    if (savedViewport) return savedViewport;
 
    const viewport = getViewport();
    return {
      x: viewport.x,
      y: viewport.y,
      zoom: viewport.zoom,
    };
  }, [currentGroupId, flowsheetSurface, getViewport]);
 
  useEffect(() => {
    setFlowsheetSurface((previousSurface) => {
      if (previousSurface[currentGroupId]) return previousSurface;
 
      const viewport = getViewport();
      return {
        ...previousSurface,
        [currentGroupId]: {
          x: viewport.x,
          y: viewport.y,
          zoom: viewport.zoom,
        },
      };
    });
  }, [currentGroupId, getViewport]);
 
  // React Flow Handlers
  const handleNodesChange = useCallback(
    (changes) => {
      setUnitOps((nodesSnapshot) => applyNodeChanges(changes, nodesSnapshot));
    },
    [setUnitOps],
  );
 
  const handleEdgesChange = useCallback(
    (changes) =>
      setConnections((edgesSnapshot) =>
        applyEdgeChanges(changes, edgesSnapshot),
      ),
    [setConnections],
  );
 
  const handleConnect = useCallback(
    (params) =>
      setConnections((edgesSnapshot) => addEdge(params, edgesSnapshot)),
    [setConnections],
  );
 
  const handleNodeClick = useCallback(
    (event, node) => {
      setParams((prev) => {
        const newParams = new URLSearchParams(prev);
        newParams.set("object", node.data.simulationObject.id.toString());
        newParams.set("content", ContentTypes.objectDetails);
        return newParams;
      });
    },
    [setParams],
  );
 
  const handlePositionUndoRedo = useCallback(
    (dragEndPositions) => {
      Iif (selectedNodes.length === 0) return;
      const activeSimulationObject = selectedNodes[0].data.simulationObject;
      const activeGraphicObject = selectedNodes[0].data.graphicObject;
      const oldPosition = dragStartPositions[0];
      const newPosition = dragEndPositions[0];
      let groupObjects = undefined;
 
      if (selectedNodes) {
        if (selectedNodes.length > 1) {
          groupObjects = selectedNodes.map((node) => {
            return {
              objectId: node.data.simulationObject.id,
              graphicObjectId: node.data.graphicObject.id,
              oldPosition: dragStartPositions[selectedNodes.indexOf(node)],
              newPosition: dragEndPositions[selectedNodes.indexOf(node)],
            };
          });
        }
      }
 
      const moveCommand = createMoveCommand({
        objectId: activeSimulationObject.id,
        graphicObjectId: activeGraphicObject.id,
        oldPosition: oldPosition,
        newPosition: newPosition,
        groupObjects: groupObjects,
      });
 
      if (isReady) {
        addHistory(moveCommand);
      } else if (process.env.NODE_ENV === "development") {
        console.warn("[UndoRedo] Move command skipped - context not ready");
      }
    },
    [dragStartPositions, selectedNodes, isReady, addHistory],
  );
 
  const handleNodeDragStart = useCallback((event, node) => {
    setDragStartPositions([{ x: node.position.x, y: node.position.y }]);
    setContextMenuEnabled(false);
    setIsDragging(true);
  }, []);
 
  const handleNodeDrag = useCallback(
    (event, node) => {
      const intersections: Node[] = getIntersectingNodes(node);
 
      if (intersections.length > 0) {
        const targetId = intersections[0].id;
        const prevId = hoverRef.current;
 
        // Still hovering over the same node, do nothing
        if (prevId === targetId) return;
 
        hoverRef.current = targetId;
        // Apply highlights to the hovered node
        setUnitOps((prevNodes) => {
          const nodes = prevNodes.slice();
          const targetIndex = nodes.findIndex((n) => n.id === targetId);
          if (targetIndex >= 0) {
            const targetNode = nodes[targetIndex];
            nodes[targetIndex] = {
              ...targetNode,
              data: { ...targetNode.data, hovered: true },
            };
          }
          return nodes;
        });
      } else {
        // No node intersections, remove highlights
        const prevId = hoverRef.current;
 
        if (!prevId) return;
 
        hoverRef.current = null;
        setUnitOps((prevNodes) => {
          const nodes = prevNodes.slice();
          const prevIdx = nodes.findIndex((n) => n.id === prevId);
          if (prevIdx >= 0) {
            const prevNode = nodes[prevIdx];
            nodes[prevIdx] = {
              ...prevNode,
              data: { ...prevNode.data, hovered: false },
            };
          }
          return nodes;
        });
      }
    },
    [getIntersectingNodes, setUnitOps],
  );
 
  const handleNodeDragStop = useCallback(
    (event, node) => {
      const endPositions = [{ x: node.position.x, y: node.position.y }];
      handlePositionUndoRedo(endPositions);
 
      // Handle Merging
      const intersections: Node[] = getIntersectingNodes(node);
 
      if (intersections.length > 0) {
        const draggedNode: Node = node;
        const targetNode: Node = intersections[0];
 
        handleMerging(draggedNode, targetNode);
        return;
      }
      // Handle Position Updates
      savePosition(node);
      setIsDragging(false);
    },
    [handlePositionUndoRedo, getIntersectingNodes, savePosition, handleMerging],
  );
 
  const handleSelectionChange = useCallback((selectedElements) => {
    setSelectedNodes(selectedElements.nodes);
  }, []); // Empty dependency needed. Causes bugs with the context menu otherwise.
 
  const handleSelectionDragStart = (event, inputs) => {
    // Save starting positions of each node dragged
    const startPositions: Coordinates[] = [];
    inputs.forEach((input) => {
      startPositions.push({ x: input.position.x, y: input.position.y });
    });
    setDragStartPositions(startPositions);
  };
 
  const handleSelectionDragStop = useCallback(
    (event, inputs) => {
      const nodes = getNodeArray(inputs);
      nodes.forEach((node) => {
        savePosition(node);
      });
    },
    [savePosition],
  );
 
  const handleKeyboardDelete = useCallback(
    (elementsToDelete?: { nodes?: Node[] }) => {
      Iif (!canMutate) return false;
      const nodesToDelete =
        elementsToDelete?.nodes && elementsToDelete.nodes.length > 0
          ? elementsToDelete.nodes
          : selectedNodes;
 
      if (!nodesToDelete || nodesToDelete.length === 0) return false;
      const containedObjects: number[] = nodesToDelete.map(
        (node) => node.data.simulationObject.id,
      );
      deleteSelectedNodes(containedObjects);
      return false; // Prevent reactflow's default delete behaviour
    },
    [canMutate, selectedNodes, deleteSelectedNodes],
  );
 
  const getContextMenuPosition = (event): Coordinates => {
    const pane = canvasDiv.current?.getBoundingClientRect();
    Iif (!pane) return;
 
    // Set position of the context menu based on the DOM element that wraps the react flow canvas
    const position = {
      x: event.clientX - pane.left,
      y: event.clientY - pane.top,
    };
    return position;
  };
 
  // Right click context menu
  const handleContextMenu = useCallback((event, inputs) => {
    event.preventDefault();
    // Check if inputs is type Node[] for onSelectionContextMenu
    if (Array.isArray(inputs)) {
      setSelectedNodes(inputs);
    } else {
      setSelectedNodes([{ ...inputs }]);
    }
 
    setContextMenuEnabled(true);
    setContextMenuPosition(getContextMenuPosition(event));
  }, []);
 
  const handlePaneContextMenu = useCallback((event) => {
    event.preventDefault();
    setContextMenuEnabled(true);
    setContextMenuPosition(getContextMenuPosition(event));
  }, []);
 
  const handleTrackStream = useCallback(
    async (node: Node) => {
      const simulationObject = node.data
        .simulationObject as SimulationObjectRetrieveRead;
      Iif (!isStream(simulationObject)) return;
 
      try {
        const trackedFlow = await trackStreamFlow({
          id: simulationObject.id,
        }).unwrap();
 
        setTrackedStream({
          sourceStreamId: trackedFlow.sourceStreamId,
          sourceName:
            simulationObject.componentName || `#${simulationObject.id}`,
          streamIds: trackedFlow.streamIds ?? [],
        });
      } catch (error) {
        console.error("[FlowsheetSurface] Failed to track stream flow:", error);
        toast.error("Failed to track stream flow.");
      }
    },
    [trackStreamFlow],
  );
 
  const clearTrackedStream = useCallback(() => {
    setTrackedStream(undefined);
  }, []);
 
  const handlePaneClick = useCallback(
    (event) => {
      setSelectedNodes([]);
      setContextMenuEnabled(false);
      clearObjectSelection();
    },
    [clearObjectSelection],
  );
 
  const handlePaneDoubleClick = useCallback(
    (event) => {
      // event.preventDefault();
 
      // Bring up the flowsheet details on the right side-bar
      const newSearchParams = new URLSearchParams(searchParams);
      const id = getGroup(currentGroupId).simulationObject;
      newSearchParams.set("object", id.toString());
      newSearchParams.set("content", ContentTypes.objectDetails);
      setParams(newSearchParams);
    },
    [currentGroupId, getGroup, searchParams, setParams],
  );
 
  const handleDeleteObject = useCallback(() => {
    Iif (!canMutate) return;
    Iif (!selectedNodes) return;
    const containedObjects: number[] = selectedNodes.map(
      (node) => node.data.simulationObject.id,
    );
    clearHover();
    deleteSelectedNodes(containedObjects);
  }, [canMutate, clearHover, deleteSelectedNodes, selectedNodes]);
 
  const handleCopyObject = useCallback(() => {
    Iif (!selectedNodes) return;
    const containedObjects: number[] = selectedNodes.map(
      (node) => node.data.simulationObject.id,
    );
    if (selectedNodes.length != 1) {
      dispatch(setCopiedObject(containedObjects));
    } else {
      // Get connected streams
      const connectedStreams = getConnectedStreams(+selectedNodes[0].id);
      // Include the unitop and its connected streams
      const objectsToCopy = [+selectedNodes[0].id, ...connectedStreams];
      dispatch(setCopiedObject(objectsToCopy));
    }
  }, [dispatch, getConnectedStreams, selectedNodes]);
 
  const handlePasteObject = useCallback(
    (position?: Coordinates) => {
      Iif (!canMutate) return;
      if (copiedObjects) {
        const bounds = canvasDiv.current?.getBoundingClientRect();
        const screenPoint = position
          ? { x: bounds.left + position.x, y: bounds.top + position.y }
          : {
              x: bounds.left + bounds.width / 2,
              y: bounds.top + bounds.height / 2,
            };
        const flowPosition = screenToFlowPosition(screenPoint);
        duplicateObject({
          duplicateSimulationObject: {
            objectIDs: copiedObjects,
            x: flowPosition.x,
            y: flowPosition.y,
          },
        }).unwrap();
      } else {
        toast.error("No object copied to paste.");
      }
    },
    [canMutate, copiedObjects, duplicateObject, screenToFlowPosition],
  );
 
  const onKeyDown = (e) => {
    if (e.key === "Backspace" || e.key === "Delete") {
      e.preventDefault();
      handleKeyboardDelete();
      return;
    }
 
    if (e.ctrlKey && e.key === "c") {
      e.preventDefault();
      handleCopyObject();
      return;
    }
 
    if (e.ctrlKey && e.key === "v") {
      e.preventDefault();
      handlePasteObject();
      return;
    }
  };
 
  const handleGroupObjects = useCallback(() => {
    Iif (!canMutate) return;
    Iif (!selectedNodes) return;
    makeGroup({
      makeGroup: {
        containedObjects:
          selectedNodes.length > 0
            ? selectedNodes.map((node) => node.data.simulationObject.id)
            : selectedNodes[0].id,
      },
    });
  }, [canMutate, makeGroup, selectedNodes]);
 
  const handleUngroupObject = useCallback(() => {
    Iif (!canMutate) return;
    Iif (!selectedNodes) return;
    const selectedNodeId = selectedNodes[0].data.simulationObject.id;
    const group = simulationObjectGroup(selectedNodeId);
 
    ungroup({
      ungroup: {
        parentGroup: group.id,
      },
    });
    optimisticallyDeleteSelection([selectedNodeId]);
  }, [
    canMutate,
    optimisticallyDeleteSelection,
    selectedNodes,
    simulationObjectGroup,
    ungroup,
  ]);
 
  const handleNodeDoubleClick = useCallback(
    (event, node) => {
      event.stopPropagation();
      Iif (!(node.data.simulationObject.objectType === "group")) return;
 
      const flowsheetTab = getFlowsheetTabFromGroupId(
        node.data.simulationObject.groupId,
      );
 
      Iif (!flowsheetTab) return;
      openTab(flowsheetTab);
    },
    [getFlowsheetTabFromGroupId, openTab],
  );
 
  const handleViewportChange = useCallback(
    (newViewport: Viewport) => {
      setFlowsheetSurface((previousSurface) => {
        const currentViewport = previousSurface[currentGroupId];
        if (
          currentViewport &&
          currentViewport.x === newViewport.x &&
          currentViewport.y === newViewport.y &&
          currentViewport.zoom === newViewport.zoom
        ) {
          return previousSurface;
        }
 
        return {
          ...previousSurface,
          [currentGroupId]: newViewport,
        };
      });
    },
    [currentGroupId],
  );
 
  const handleRotateOrFlipObject = useCallback(
    (direction: string) => {
      Iif (!canMutate) return;
      const bounds = getNodesBounds(selectedNodes);
      const selectionCentre: { x: number; y: number } = {
        x: bounds.x + bounds.width / 2,
        y: bounds.y + bounds.height / 2,
      };
      const singleSelect = selectedNodes.length == 1 ? true : false;
      selectedNodes.map((node) => {
        rotateFlipSelectedObject(
          node.data.graphicObject,
          direction,
          selectionCentre,
          singleSelect,
        );
      });
    },
    [canMutate, getNodesBounds, rotateFlipSelectedObject, selectedNodes],
  );
 
  // Build unitOp lookup map for monitoring tables
  const unitOpLookup = useMemo(() => {
    try {
      const entries = Array.from(flowsheetObjectIdMap.entries()).map(
        ([id, simObj]) => [id, simObj.componentName || `#${id}`],
      );
      return Object.fromEntries(entries as [number, string][]);
    } catch {
      return {};
    }
  }, [flowsheetObjectIdMap]);
 
  const handleInit = useCallback(() => {
    fitView({ duration: 600 });
  }, [fitView]);
 
  const handleNodeMouseEnter = useCallback(
    (event, node) => {
      Iif (contextMenuEnabled) return;
 
      setHoverPos({ x: event.clientX, y: event.clientY });
 
      showHover(node.data.simulationObject.id);
    },
    [contextMenuEnabled, showHover],
  );
 
  const handleNodeMouseMove = useCallback(
    (event, node) => {
      Iif (contextMenuEnabled) return;
 
      setHoverPos({ x: event.clientX, y: event.clientY });
      showHover(node.data.simulationObject.id);
    },
    [contextMenuEnabled, showHover],
  );
 
  const handleNodeMouseLeave = useCallback(
    (event, node) => {
      clearHover();
    },
    [clearHover],
  );
 
  // Prevents hover properties from displaying when deleting nodes
  useEffect(() => {
    if (hoveredObjectId === undefined) return;
 
    const stillExists = unitOps.some(
      (n) => n.data?.simulationObject?.id === hoveredObjectId,
    );
 
    if (!stillExists) {
      clearHover();
    }
  }, [clearHover, hoveredObjectId, unitOps]);
 
  /* Render Nodes and Edges using Cache */
  useEffect(() => {
    Iif (!currentGroupObjects) return;
    // Create nodes
    const nodes: Node[] = renderNodes();
 
    // Preserve selection state when updating nodes
    setUnitOps((prevNodes) => {
      // Create a set of currently selected node IDs
      const selectedNodeIds = new Set(
        prevNodes.filter((n) => n.selected).map((n) => n.id),
      );
 
      // Apply selection state to new nodes
      return nodes.map((node) => ({
        ...node,
        selected: selectedNodeIds.has(node.id),
      }));
    });
 
    // Create edges
    const edges: Edge[] = renderEdges();
    setConnections(edges);
  }, [graphicsObjects, connectionGraphics, trackedStreamIds]); // eslint suggestions cause unnecessary re-renders.
 
  return (
    <IndicatorVisibilityContext.Provider value={indicatorsVisible}>
      <UnitOpCommands canvasDiv={canvasDiv} />
      <SwitchGroupCommands
        setFlowsheetSurfaceState={setFlowsheetSurfaceState}
        zoomToFit={zoomToFit}
      />
      <FlowsheetCommands
        togglePointerState={togglePointerState}
        handleAutoSortCanvas={handleAutoSortCanvas}
      />
      <ExportMSSRResultsCommand />
      <ConnectToExcelCommand />
      <DownloadTagMappingsCommand />
      <DownloadFlowsheetTagMappingsCommand />
      <div className="grow relative" ref={canvasDiv}>
        <ReactFlow
          id="canvas"
          aria-label="flowsheet-canvas"
          nodes={unitOps}
          nodeTypes={nodeTypes}
          edges={connections}
          ref={drop}
          onNodesChange={handleNodesChange}
          onEdgesChange={handleEdgesChange}
          onConnect={handleConnect}
          onNodeClick={handleNodeClick}
          onNodeDoubleClick={handleNodeDoubleClick}
          onNodeDragStart={handleNodeDragStart}
          onNodeDrag={handleNodeDrag}
          onNodeDragStop={handleNodeDragStop}
          onNodeMouseEnter={handleNodeMouseEnter}
          onNodeMouseMove={handleNodeMouseMove}
          onNodeMouseLeave={handleNodeMouseLeave}
          onNodeContextMenu={handleContextMenu}
          onInit={handleInit}
          onSelectionChange={handleSelectionChange}
          onSelectionDragStart={handleSelectionDragStart}
          onSelectionDragStop={handleSelectionDragStop}
          onSelectionContextMenu={handleContextMenu}
          onPaneClick={handlePaneClick}
          onDoubleClick={handlePaneDoubleClick}
          onPaneContextMenu={handlePaneContextMenu}
          onBeforeDelete={handleKeyboardDelete}
          zoomOnDoubleClick={false}
          minZoom={0.25}
          maxZoom={1.5}
          deleteKeyCode={["Delete", "Backspace"]}
          nodesDraggable={canMutate}
          width={canvasWidth}
          style={{ backgroundColor: "#ffffff", color: "#000000" }}
          colorMode="light"
          panOnDrag={pointerState.state === "select" ? [1] : true}
          selectionOnDrag={pointerState.state === "select" ? true : false}
          selectionMode={SelectionMode.Partial}
          proOptions={{ hideAttribution: true }}
          viewport={getGroupViewport}
          onViewportChange={handleViewportChange}
          onKeyDown={onKeyDown}
          tabIndex={0} // To ensure the div is focusable to capture key events
        >
          <MiniMap zoomable pannable inversePan offsetScale={10} />
          <TemperatureScale />
 
          <Background gap={50} variant={BackgroundVariant.Lines} />
          <Controls showInteractive={false} />
 
          {contextMenuEnabled && (
            <ContextMenu
              nodes={selectedNodes}
              position={contextMenuPosition}
              onClick={handlePaneClick}
              handleAutoSortCanvas={handleAutoSortCanvas}
              canMutate={canMutate}
              handleCopyObject={handleCopyObject}
              handlePasteObject={handlePasteObject}
              handleDeleteObject={handleDeleteObject}
              handleGroupObjects={handleGroupObjects}
              handleUngroupObject={handleUngroupObject}
              handleRotateObjectLeft={handleRotateOrFlipObject}
              handleRotateObjectRight={handleRotateOrFlipObject}
              handleFlipObjectHorizontal={handleRotateOrFlipObject}
              handleFlipObjectVertical={handleRotateOrFlipObject}
              handleTrackStream={handleTrackStream}
            />
          )}
          {hoverActive &&
            hoveredSimulationObject &&
            !contextMenuEnabled &&
            !isDragging && (
              <div
                aria-label="property-hover"
                style={{
                  position: "fixed",
                  top: hoverPos.y,
                  left: hoverPos.x + 5,
                  zIndex: 100,
                  pointerEvents: "none",
                }}
              >
                <PropertyHover simulationObject={hoveredSimulationObject} />
              </div>
            )}
        </ReactFlow>
 
        {/* This div positions breadcrumbs at top-left - Don't modify positioning without testing
         * as it prevents dead space at the top of flowsheet */}
        <div className="top-2 absolute left-2 flex flex-row items-center">
          <BreadCrumbs />
        </div>
 
        {/* This div positions controls at top-right - Don't modify positioning without testing
         * as changes may create unused dead band between controls and breadcrumbs */}
        <div className="top-2 absolute right-2 flex flex-row items-center gap-2">
          <FlowsheetControls
            trackedStreamName={trackedStream?.sourceName}
            onClearTrackedStream={clearTrackedStream}
          />
          {/* Render all visible monitoring tables */}
          <MonitoringTablesContainer
            tables={props.monitoringTables ?? []}
            onHideTable={props.onHideTable ?? (() => {})}
            onRenameTable={props.onRenameTable ?? (() => {})}
            unitOpLookup={unitOpLookup}
          />
        </div>
      </div>
    </IndicatorVisibilityContext.Provider>
  );
};
 
export default memo(FlowsheetSurface);