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 | 45x 45x 45x 5533x 5533x 10470x 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 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 10470x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 5533x 10470x 5533x 5533x 5533x 13x 13x 13x 13x 36x 13x 13x 13x 13x 5533x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5533x 32x 32x 32x 32x 5533x 4x 28x 4x 3x 3x 3x 3x 3x 3x 3x 3x 5533x 93x 5621x 2x 2x 12x 2x 1x 1x 12x 2x 1x 5533x 772x 772x 92x 92x 772x 5533x 593x 5533x 21x 21x 5533x 5533x 46x 46x 46x 46x 46x 5533x 10x 10x 10x 10x 10x 10x 10x 10x 2x 6x 10x 10x 10x 5533x 10x 10x 10x 5533x 85x 85x 14x 14x 14x 5x 5x 5x 18x 5x 5x 5x 5x 71x 71x 2x 2x 2x 5x 2x 2x 2x 2x 5533x 10x 10x 10x 10x 3x 3x 3x 3x 7x 7x 5533x 174x 5533x 2x 2x 6x 2x 5533x 2x 2x 6x 5533x 3x 3x 2x 3x 3x 5533x 17x 17x 17x 17x 5533x 16x 16x 8x 8x 16x 16x 5533x 1x 1x 1x 5533x 29x 29x 29x 29x 29x 29x 29x 29x 5533x 1x 1x 1x 1x 1x 5533x 2x 2x 6x 2x 1x 1x 1x 1x 5533x 2x 2x 2x 2x 2x 5533x 6x 6x 5533x 5x 5x 14x 5533x 5533x 3x 5533x 701x 701x 700x 5533x 7x 7x 7x 7x 23x 5533x 5533x 5533x 5533x 33519x 5533x 5533x 49x 5533x 100x 100x 100x 5533x 70x 70x 70x 5533x 96x 5533x 1430x 240x 240x 931x 240x 2x 5533x 581x 581x 581x 580x 2335x 2582x 581x 581x 5533x | import {
api,
GraphicObjectRead,
GroupingRead,
MonitoringTableRead,
ObjectTypeEnum,
SimulationObjectRead,
SimulationObjectRetrieveRead,
useGraphicsgroupingsConnectionsRetrieveQuery,
useGraphicsgroupingsDeleteSelectedObjectsCreateMutation,
useGraphicsgroupingsMakeGroupCreateMutation,
useGraphicsgroupingsPartialUpdateMutation,
useGraphicsgroupingsUngroupCreateMutation,
useGraphicsObjectsPartialUpdateMutation,
useUnitopsSimulationobjectsDuplicateSimulationObjectCreateMutation,
} from "@/api/apiStore.gen";
import { SwitchGroupCommands } from "@/commands/SwitchCurrentGroup";
import {
useAddPortAndConnectStream,
useMergeDecisionNodes,
useMergeStreams,
} from "@/hooks/connections";
import {
useCaptureDeletionConnections,
useOptimisticallyDeleteSelection,
} from "@/hooks/deleteObjects";
import {
useCurrentGroupId,
useCurrentGroupObjects,
useCurrentObject,
useFlowsheetObjectsIdMap,
useFlowsheetPorts,
useGraphicsObjects,
useGroup,
useObjectsGraphicObjectsMap,
useSimulationObjectGroup,
} from "@/hooks/flowsheetObjects";
import {
useFlowsheetTabFromGroupId,
useSwitchToGroup,
} from "@/hooks/projectTabs";
import { useRecycleData } from "@/hooks/recycleData";
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 {
addEdge,
applyEdgeChanges,
applyNodeChanges,
Background,
BackgroundVariant,
Controls,
Edge,
MiniMap,
Node,
Position,
ReactFlow,
Node as RFNode,
SelectionMode,
useEdgesState,
useNodesState,
useReactFlow,
Viewport,
} from "@xyflow/react";
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 { 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 { useRenderOperations } from "./RenderOperations";
import { SimulationObjectGraphic } from "./SimulationObjectGraphic";
import { setHoveredObject, clearHoveredObject } from "@/store/ObjectHoverSlice";
import PropertyHover from "./PropertyHover";
const nodeTypes = {
simulationObjectGraphic: SimulationObjectGraphic,
};
interface FlowsheetProps {
width: number;
monitoringTables?: MonitoringTableRead[];
onHideTable?: (tableId: number) => void;
onRenameTable?: (tableId: number, newName: string) => void;
}
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({});
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();
// Hooks
const dispatch = useAppDispatch();
const rootGroup = useCurrentGroupId();
const graphicsObjects = useGraphicsObjects();
const currentGroupObjects = useCurrentGroupObjects();
const currentObject = useCurrentObject();
const currentGroupId = useCurrentGroupId();
const getGroup = useGroup();
const objectsGraphicObjectsMap = useObjectsGraphicObjectsMap();
const simulationObjectGroup = useSimulationObjectGroup();
const recycleConnections = useRecycleData();
const openTab = useSwitchToGroup();
const getFlowsheetTabFromGroupId = useFlowsheetTabFromGroupId();
const ports = useFlowsheetPorts();
const { data: connectionGraphics } =
useGraphicsgroupingsConnectionsRetrieveQuery(
{ group: currentGroupId },
{ skip: !currentGroupId || currentGroupId <= 0 },
);
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 optimisticallyDeleteSelection = useOptimisticallyDeleteSelection();
const { renderNodes, renderEdges } = useRenderOperations({
currentGroupObjects,
graphicsObjects,
connectionGraphics,
recycleConnections,
objectsGraphicObjectsMap,
});
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();
// 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 hoverState = useSelector((state: RootState) => state.hover);
const [hoverPos, setHoverPos] = useState<{ x: number; y: number }>({
x: 0,
y: 0,
});
const [isDragging, setIsDragging] = useState<boolean>(false);
/* Save Position */
const savePosition = useCallback(
(node: RFNode) => {
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,
},
});
},
[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)) {
Iif (
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;
}
}
Iif (
activeObject.objectType === ObjectTypeEnum.DecisionNode &&
overObject?.objectType === ObjectTypeEnum.DecisionNode &&
overObject.id !== activeObject.id
) {
mergeDecisionNodes(activeObject, overObject);
return;
}
Iif (activeObject.objectType === ObjectTypeEnum.DecisionNode) {
Iif (overObject && isStream(overObject)) {
addPortAndConnectStream(activeObject, overObject);
}
}
Iif (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[]) => {
// Get objects to be deleted
const objectsToDelete = currentGroupObjects.filter((obj) =>
containedObjects.includes(obj.id),
);
if (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);
IE} 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,
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 E{
const uniqueNodes: Node[] = [inputs];
return uniqueNodes;
}
}
function getConnectedStreams(unitopId: number): number[] {
const streams: number[] = [];
ports?.forEach((port) => {
if (port.unitOp === unitopId && port.stream != null) {
streams.push(port.stream);
}
});
return streams;
}
const getGroupViewport = useMemo(() => {
const viewport = getViewport();
if (!flowsheetSurface[currentGroupId]) {
flowsheetSurface[currentGroupId] = {
x: viewport.x,
y: viewport.y,
zoom: viewport.zoom,
};
setFlowsheetSurface(flowsheetSurface);
}
return flowsheetSurface[currentGroupId];
}, [currentGroupId, flowsheetSurface, 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);
IE} 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(() => {
Iif (!selectedNodes) return false;
const containedObjects: number[] = selectedNodes.map(
(node) => node.data.simulationObject.id,
);
deleteSelectedNodes(containedObjects);
return false; // Prevent reactflow's default delete behaviour
}, [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));
},
[setContextMenuEnabled],
);
const handlePaneContextMenu = (event) => {
event.preventDefault();
setContextMenuEnabled(true);
setContextMenuPosition(getContextMenuPosition(event));
};
const handlePaneClick = useCallback(
(event) => {
setSelectedNodes([]);
setContextMenuEnabled(false);
// clear the object selection
clearObjectSelection();
// 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);
},
[clearObjectSelection, currentGroupId, getGroup, searchParams, setParams],
);
const handleDeleteObject = useCallback(() => {
Iif (!selectedNodes) return;
const containedObjects: number[] = selectedNodes.map(
(node) => node.data.simulationObject.id,
);
clearHoveredObject();
deleteSelectedNodes(containedObjects);
}, [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));
}
}, [currentObject, selectedNodes]);
const handlePasteObject = useCallback(
(position?: Coordinates) => {
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 E{
toast.error("No object copied to paste.");
}
},
[copiedObjects, duplicateObject, screenToFlowPosition],
);
const onKeyDown = (e) => {
Iif (e.ctrlKey && e.key === "c") {
e.preventDefault();
handleCopyObject();
return;
}
Iif (e.ctrlKey && e.key === "v") {
e.preventDefault();
handlePasteObject();
return;
}
};
const handleGroupObjects = useCallback(() => {
Iif (!selectedNodes) return;
makeGroup({
makeGroup: {
containedObjects:
selectedNodes.length > 0
? selectedNodes.map((node) => node.data.simulationObject.id)
: selectedNodes[0].id,
},
});
}, [makeGroup, selectedNodes]);
const handleUngroupObject = useCallback(() => {
Iif (!selectedNodes) return;
const selectedNodeId = selectedNodes[0].data.simulationObject.id;
const group = simulationObjectGroup(selectedNodeId);
ungroup({
ungroup: {
parentGroup: group.id,
},
});
optimisticallyDeleteSelection([selectedNodeId]);
}, [
optimisticallyDeleteSelection,
selectedNodes,
simulationObjectGroup,
ungroup,
]);
const handleNodeDoubleClick = useCallback(
(event, node) => {
if (!(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) => {
const currentViewport = flowsheetSurface[currentGroupId];
if (
currentViewport.x !== newViewport.x ||
currentViewport.y !== newViewport.y ||
currentViewport.zoom !== newViewport.zoom
) {
setFlowsheetSurface({
...flowsheetSurface,
[currentGroupId]: newViewport,
});
}
},
[currentGroupId, flowsheetSurface],
);
const handleRotateOrFlipObject = useCallback(
(direction: string) => {
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,
);
});
},
[rotateFlipSelectedObject, selectedNodes],
);
// Build unitOp lookup map for monitoring tables
const flowsheetObjectIdMap = useFlowsheetObjectsIdMap();
const unitOpLookup = React.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 });
dispatch(
setHoveredObject({
simulationObject: node.data.simulationObject,
}),
);
},
[dispatch, contextMenuEnabled],
);
const handleNodeMouseMove = useCallback(
(event, node) => {
Iif (contextMenuEnabled) return;
setHoverPos({ x: event.clientX, y: event.clientY });
dispatch(
setHoveredObject({
simulationObject: node.data.simulationObject,
}),
);
},
[contextMenuEnabled, dispatch],
);
const handleNodeMouseLeave = useCallback(
(event, node) => {
dispatch(clearHoveredObject());
},
[dispatch],
);
// Prevents hover properties from displaying when deleting nodes
useEffect(() => {
if (!hoverState?.simulationObject) return;
const hoveredId = hoverState.simulationObject.id;
const stillExists = unitOps.some(
(n) => n.data?.simulationObject?.id === hoveredId,
);
if (!stillExists) {
dispatch(clearHoveredObject());
}
}, [unitOps, hoverState?.simulationObject, dispatch]);
/* 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]); // eslint suggestions cause unnecessary re-renders.
return (
<IndicatorVisibilityContext.Provider value={indicatorsVisible}>
<UnitOpCommands canvasDiv={canvasDiv} />
<SwitchGroupCommands
setFlowsheetSurfaceState={setFlowsheetSurfaceState}
zoomToFit={zoomToFit}
/>
<FlowsheetCommands togglePointerState={togglePointerState} />
<ExportMSSRResultsCommand />
<DownloadTagMappingsCommand />
<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}
onPaneContextMenu={handlePaneContextMenu}
onBeforeDelete={handleKeyboardDelete}
zoomOnDoubleClick={false}
minZoom={0.25}
maxZoom={1.5}
deleteKeyCode={["Delete", "Backspace"]}
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 offSetScale={10} />
<Background gap={50} variant={BackgroundVariant.Lines} />
<Controls showInteractive={false} />
{contextMenuEnabled && (
<ContextMenu
nodes={selectedNodes}
position={contextMenuPosition}
onClick={handlePaneClick}
handleCopyObject={handleCopyObject}
handlePasteObject={handlePasteObject}
handleDeleteObject={handleDeleteObject}
handleGroupObjects={handleGroupObjects}
handleUngroupObject={handleUngroupObject}
handleRotateObjectLeft={handleRotateOrFlipObject}
handleRotateObjectRight={handleRotateOrFlipObject}
handleFlipObjectHorizontal={handleRotateOrFlipObject}
handleFlipObjectVertical={handleRotateOrFlipObject}
/>
)}
{hoverState.state && !contextMenuEnabled && !isDragging && (
<div
aria-label="property-hover"
style={{
position: "fixed",
top: hoverPos.y,
left: hoverPos.x + 5,
zIndex: 100,
pointerEvents: "none",
}}
>
<PropertyHover simulationObject={hoverState?.simulationObject} />
</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 />
{/* 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);
|