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

71.62% Statements 212/296
57.63% Branches 117/203
78.37% Functions 29/37
71.82% Lines 209/291

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                                                                                                                                                    33x     33x 26431x 26431x 26431x 26431x 26431x     26431x     26431x                                                                                                                                                         33x         27215x 27215x 27215x 27215x 27215x 27215x                                                                 27215x     33x 6473x 6473x 6473x 6473x     6473x 231x   6473x 6473x 6473x 6473x 6473x   6473x 6473x   6473x 6473x 6473x 6473x           6473x 25892x   6473x 6473x   6473x           6473x   6473x   6473x 6473x                                                                                                                                                                                                               33x 20742x 20742x 20742x 20742x 20742x 20742x 20742x   20742x 20742x   20742x 20742x 20742x 20742x 20742x   20742x 20742x 20742x   20742x 2636x 18106x 1692x 16414x 8007x   8407x         20742x   20742x 10643x                                                                   20742x 8407x                                                                                                                                                             20742x 1692x                                                                                         20742x                                                           20742x     33x   1175x 1175x 1175x 1175x 1175x 1175x 1175x 1175x 1175x 1175x     1175x 41x     1175x     1175x             1175x                                                                                                                                                         33x 224x 224x   224x                     224x             224x               224x 224x   224x             224x                                                                               33x     28557x   28557x 28557x 28557x 28557x 28557x   28557x 28557x 28557x 28557x 28557x 46105x 28557x 28557x 28557x 28557x 28557x 28557x 28557x 28557x 28557x 28557x 13505x     28557x       28557x         28557x                                                                 28557x 11x 11x 11x 11x 11x 11x 11x   11x               57114x 24x       28557x 1x                         28557x 2x 2x 2x 2x 2x 2x 6x 4x                       4x 4x 4x 4x 4x 4x 4x             2x       28557x 1x 1x     1x   1x       1x       1x         1x   1x   1x 1x                               1x 1x               28557x 1x 1x 1x 1x 1x     1x 1x   1x                                             1x                 1x 1x           1x   1x                                         1x               1x         1x                           1x         1x   1x   1x 1x 1x           1x               1x 1x     28557x 28557x                       28557x 20318x   8239x       1180x   252x   6807x       28557x                                  
import { ModuleMark } from "@/ahuora-design-system/componentIcons/ModuleMark";
import {
  GraphicObjectRead,
  ObjectTypeEnum,
  SimulationObjectRead,
  api,
  useGraphicsObjectsPartialUpdateMutation,
  useGraphicsgroupingsPartialUpdateMutation,
  useUnitopsSimulationobjectsPartialUpdateMutation,
} from "@/api/apiStore.gen";
import {
  useAddPortAndConnectStream,
  useMergeDecisionNodes,
  useMergeStreams,
} from "@/hooks/connections";
import {
  useCurrentGroupId,
  useCurrentGroupObjects,
  useGroupObjects,
  useObjectsGraphicObjectsMap,
  useObjectsPortsMap,
  useProcessPathHasObject,
  useSimulationObjectGroup,
} from "@/hooks/flowsheetObjects";
import {
  TabStateEnum,
  useChangeTabState,
  useFlowsheetTabFromGroupId,
} from "@/hooks/projectTabs";
import { useSearchParam } from "@/hooks/searchParams";
import { useAppDispatch } from "@/store/hooks";
import { RootState } from "@/store/store";
import { useRunCommand } from "just-search-it";
import React, { useState } from "react";
import {
  Circle,
  Group,
  Image,
  KonvaNodeEvents,
  Line,
  Rect,
  Text,
} from "react-konva";
import  Zap from "@/ahuora-design-system/ui/zap";
import { Html } from "react-konva-utils";
import { useSelector } from "react-redux";
import useImage from "use-image";
import { SwitchGroup } from "../../../../commands/SwitchCurrentGroup";
import { isStream } from "../../../../lib/isStream";
import { PropertiesStatus } from "../PropertiesSidebar/PropertyPanel/PropertiesStatus";
import useHoverDebounce from "./DebounceHoverObject";
import { snap } from "./FlowsheetFunctions";
import { useUndoRedoStore } from "@/hooks/useUndoRedoStore";
import { createMoveCommand } from "@/utils/commandCreators";
 
import { ContentTypes } from "../LeftSideBar/LeftSideBarTabDefinitions";
import { useSearchParams } from "react-router-dom";
 
 
type BlockGraphicProps = {
  children: React.ReactNode;
  componentName: string;
  graphicObject: GraphicObjectRead;
  draggable: boolean;
  onMouseEnter?: KonvaNodeEvents["onMouseEnter"];
  onMouseLeave?: KonvaNodeEvents["onMouseLeave"];
  onDragStart?: KonvaNodeEvents["onDragStart"];
  onDragMove?: KonvaNodeEvents["onDragMove"];
  onDragEnd?: KonvaNodeEvents["onDragEnd"];
  onClick: KonvaNodeEvents["onClick"];
  simulationObject: SimulationObjectRead;
  isSpecified: boolean;
};
 
const textPadding = 8;
 
 
export const BlockGraphic = (props: BlockGraphicProps) => {
  const maxTextWidth = 150;
  const x = props.graphicObject.x || 0;
  const y = props.graphicObject.y || 0;
  const width = props.graphicObject.width || 100;
  const height = props.graphicObject.height || 100;
 
  const showStatusDot =
    isStream(props.simulationObject) ||
    props.simulationObject?.objectType === "decisionNode";
 
  return (
    <>
      <Group
        key={props.componentName + "group"}
        x={x}
        y={y}
        draggable={props.draggable}
        onMouseEnter={props.onMouseEnter}
        onMouseLeave={props.onMouseLeave}
        onDragStart={props.onDragStart}
        onDragMove={props.onDragMove}
        onDragEnd={props.onDragEnd}
        onClick={props.onClick}
        onContextMenu={props.onClick}
      >
        {props.children}
      </Group>
 
      {/* Text rendering moved outside main group */}
      {showStatusDot ? (
        <Group x={x} y={y + height + textPadding}>
          <Group x={width / 2 - (props.componentName.length * 3.5 + 15)}>
            <Group x={-5} y={-5}>
              <Html
                divProps={{
                  style: {
                    zIndex: 1,
                    position: "absolute",
                  },
                }}
              >
                <div
                  style={{ transform: "scale(0.6)" }}
                  className="select-none"
                >
                  <PropertiesStatus
                    hideSuccess={true}
                    propertySet={props.simulationObject.unspecifiedProperties}
                    
                  />
                </div>
              </Html>
            </Group>
                 {/* Stream Labels */}
            <Text
              listening={false}
              align="left"
              x={14}
              y={0}
              text={props.componentName}
              width={maxTextWidth - 26}
              fontSize={16}
              fontFamily="Inter"
              wrap="none"
              ellipsis={true}
              fill="#404040"
              letterSpacing={-0.2}
            />
          </Group>
        </Group>
      ) : (
        null
      )}
    </>
  );
};
 
type GenericObjectGraphicProps = {
  simulationObject: SimulationObjectRead;
  graphicObject: GraphicObjectRead;
  isSelected?: boolean;
  isHovered?: boolean;
  disabled?: boolean;
  highlight?: boolean;
  isSpecified?: boolean;
};
 
const getOffsetsAndScale = (
  gObj: GraphicObjectRead,
  width: number,
  height: number,
) => {
  let sX = 1;
  let sY = 1;
  let xOff = 0;
  let yOff = 0;
  if (gObj.rotation! == 0) {
    Iif (gObj.flipped!) {
      sX *= -1;
      sY *= -1;
      xOff = width;
      yOff = height;
    }
  E} else if (gObj.rotation! == 90) {
    yOff = height;
    Iif (gObj.flipped!) {
      sX *= -1;
      sY *= -1;
      xOff = width;
      yOff = 0;
    }
  } else if (gObj.rotation! == 180) {
    xOff = width;
    yOff = height;
    Iif (gObj.flipped!) {
      sX *= -1;
      sY *= -1;
      xOff = 0;
      yOff = 0;
    }
  I} else if (gObj.rotation! == 270) {
    xOff = width;
    Iif (gObj.flipped!) {
      sX *= -1;
      sY *= -1;
      xOff = 0;
      yOff = height;
    }
  }
 
  return { sX, sY, xOff, yOff };
};
 
const UnitOpGraphic = (props: GenericObjectGraphicProps) => {
  const imageName = props.simulationObject?.objectType;
  const [defaultImage] = useImage(`../../assets/UpdatedIcons/uo_default.svg`);
  const headerfallimage= useImage(`../../assets/UpdatedIcons/header-old.svg`);
  let [image] = useImage(`../../assets/UpdatedIcons/${imageName}.svg`) || [
    defaultImage,
  ];
  if (!image) {
    image = defaultImage;
  }
  const gObj = props.graphicObject;
  const width = gObj.width!;
  const height = gObj.height!;
  const rotation = gObj.rotation || 0;
  const offsetsAndScale = getOffsetsAndScale(gObj, width / 2, height / 2);
 
  const imageScaleX = Math.abs(offsetsAndScale.sX);
  const imageScaleY = Math.abs(offsetsAndScale.sY);
 
  const rad = (rotation * Math.PI) / 180;
  const halfW = width / 2;
  const halfH = height / 2;
  const corners = [
    { x: -halfW, y: -halfH },
    { x: halfW, y: -halfH },
    { x: halfW, y: halfH },
    { x: -halfW, y: halfH },
  ];
  const rotatedYs = corners.map(
    (c) => halfH + (c.x * Math.sin(rad) + c.y * Math.cos(rad))
  );
  const rectBottomY = Math.max(...rotatedYs);
  const labelY = rectBottomY + textPadding;
 
  const canConnect = [
    ObjectTypeEnum.DecisionNode,
    ObjectTypeEnum.Splitter,
    ObjectTypeEnum.Mixer,
  ];
  const setHighlight =
    canConnect.includes(props.simulationObject.objectType) && props.highlight;
 
  const isModule = props.simulationObject.objectType === "group";
 
  useHoverDebounce(props.isHovered, props.simulationObject);
  return (
    <>
      {/**background**/}
      <Group
        x={width / 2}
        y={height / 2}
        rotation={rotation}
        offsetX={0}
        offsetY={0}
      >
        {/* background */}
        <Rect
          width={width}
          height={height}
          x={-width / 2}
          y={-height / 2}
          fill={
            props.isSelected ? "#E9EDF0" : props.isHovered ? "#f2f3f5" : "#FFFFFF"
          }
          stroke={
            props.disabled
              ? "#aaaaaa"
              : setHighlight
                ? "#26967f"
                : props.isSelected
                  ? "#1077c4"
                  : "#404040"
          }
          strokeWidth={2}
          cornerRadius={4}
        />
        <Group
          // flip around center by applying negative scale on the inner group
          scaleX={gObj.flipped ? -1 : 1}
          x={0}
          y={0}
        >
          {/* Unit Operation Image */}
            {imageName === ObjectTypeEnum.Header ? null : (
        <Image
          image={image}
          scaleX={imageScaleX}
          scaleY={imageScaleY}
          width={width / 2}
          height={height / 2}
          x={-width / 4}
          y={-height / 4}
        />
            )}
        </Group>
 
        {isModule && (
          <Group x={-width / 2 + 10} y={-height / 2 + 10}>
            <Html>
              <div className="text-emerald-600 select-none">
                <ModuleMark />
              </div>
            </Html>
          </Group>
          
        )
        
        
        
        
        }
 
        {/* Status Indicator */}
        <Group x={width / 2 - 26} y={height / 2 - 26}>
          <Html>
            <div style={{ transform: "scale(0.9)" }} className="select-none">
              <PropertiesStatus
                hideSuccess={true}
                propertySet={props.simulationObject.unspecifiedProperties}
             
              />
            </div>
          </Html>
        </Group>
 
 
 
      </Group>
 
{/* Label for Unit Ops */}
<Text
        listening={false}
        align="center"
        x={0}
        y={labelY}
        text={props.simulationObject.componentName}
        width={width}
        fontSize={16}
        fontFamily="Inter"
        wrap="none"
        ellipsis={true}
        fill="#404040"
        letterSpacing={-0.2}
      />
      
    </>
  );
};
 
const MaterialStreamGraphic = (props: GenericObjectGraphicProps) => {
  const gObj = props.graphicObject;
  const width = gObj.width!;
  const height = gObj.height!;
  const objPortsMap = useObjectsPortsMap();
  const offsetsAndScale = getOffsetsAndScale(gObj, width / 1.5, height / 1.5);
  const [intermediateImage] = useImage(`../../assets/UpdatedIcons/feed.svg`)
  const [intermediateImageFlipped] = useImage(`../../assets/UpdatedIcons/feedleft.svg`)
 
  const [intermediatePowerImageFlipped] = useImage(`../../assets/UpdatedIcons/feedleftpowerl.svg`)
  const [intermediatePowerImage] = useImage(`../../assets/UpdatedIcons/feedpowerl.svg`)
  
  const [feedImage] = useImage(`../../assets/UpdatedIcons/connected.svg`)
  const [powerfeedImage] = useImage(`../../assets/UpdatedIcons/powerconnected.svg`)
   const isEnergy = props.simulationObject.objectType === ObjectTypeEnum.EnergyStream
  const [decisionImage] = useImage(`../../assets/UpdatedIcons/halfDecisionNode.svg`)
  useHoverDebounce(props.isHovered, props.simulationObject);
 
  const renderElement = () => {
    const objPorts = objPortsMap.get(props.simulationObject.id);
    Iif (props.simulationObject.objectType === "decisionNode") {
      return decisionNode();
    } else if (!objPorts || objPorts.length === 0) {
      return feed();
    } else if (objPorts.length === 2) {
      return intermediate();
    } else if (objPorts[0].direction === "inlet") {
      return feed("inlet");
    } else {
      return product(objPorts[0].key);
    }
  };
  // console.log(props.simulationObject.objectType === ObjectTypeEnum.EnergyStream)
 
  const flipped = props.graphicObject.is_flipped;
 
  const feed = (variant?: "coldInlet" | "hotInlet" | "inlet") => {
    return (
      <>
        <Circle
          x={width / 2}
          y={height / 2}
          radius={width / 2}
          fill={props.isSelected || props.isHovered ? "#E9EDF0" : "#FFFFFF"}
          stroke={
            props.disabled
              ? "#aaaaaa"
              : props.highlight
                ? "#26967f"
                : props.isSelected
                  ? "#1077c4"
                  : "#404040"
          }
          strokeWidth={2}
        />
        <Image
          image={isEnergy ? powerfeedImage : feedImage}
          width={width / 1.5}
          height={height / 1.5}
          scaleX={offsetsAndScale.sX}
          scaleY={offsetsAndScale.sY}
          offsetX={offsetsAndScale.xOff}
          offsetY={offsetsAndScale.yOff}
          rotation={gObj.rotation}
          x={width / 6}
          y={height / 6}
        />
      </>
    );
  };
 
  const product = (variant?: "coldOutlet" | "hotOutlet" | "inlet") => {
    return (
      <>
        {/* === Stream === */}
        {isStream(props.simulationObject) && props.simulationObject.objectType !== ObjectTypeEnum.EnergyStream && (
          <>
            {/* Outer Circle */}
            <Circle
              x={width / 2}
              y={height / 2}
              radius={width / 2}
              fill={props.isSelected || props.isHovered ? "#E9EDF0" : "#FFFFFF"}
              stroke={
                props.disabled
                  ? "#aaaaaa"
                  : props.highlight
                    ? "#26967f"
                    : props.isSelected
                      ? "#1077c4"
                      : "#404040"
              }
              strokeWidth={2}
            />
            {/* Inner black circle */}
            <Circle
              width={width - 10}
              height={height - 10}
              x={width / 2}
              y={height / 2}
              radius={(width - 10) / 2}
              fill="#000000"
            />
          </>
        )}
 
        {/* === EnergyStream === */}
        {props.simulationObject.objectType === ObjectTypeEnum.EnergyStream && (
          <>
            <Circle
              x={width / 2}
              y={height / 2}
              radius={width / 2}
              fill={props.isSelected || props.isHovered ? "#E9EDF0" : "#FFFFFF"}
              stroke={
                props.disabled
                  ? "#aaaaaa"
                  : props.highlight
                    ? "#26967f"
                    : props.isSelected
                      ? "#1077c4"
                      : "#404040"
              }
              strokeWidth={2}
            />
            {/* Inner yellow circle */}
    <Zap
  x={width / 2}
  y={height / 2}
  width={width - 10}
  height={height - 10}
  fill="#FFB300"
/>
            {/* <Circle
              width={width - 10}
              height={height - 10}
              x={width / 2}
              y={height / 2}
              radius={(width - 10) / 2}
              fill="#eab308"
            />  */}
          </>
        )}
      </>
    );
 
 
 
  }
  
 
  const intermediate = () => {
    return (
      <>
        <Circle
          x={width / 2}
          y={height / 2}
          radius={width / 2}
          fill={
            props.isSelected
              ? "#E9EDF0"
              : props.isHovered
                ? "#E9EDF0"
                : "#FFFFFF"
          }
          stroke={
            props.disabled
              ? "#aaaaaa"
              : props.highlight
                ? "#26967f"
                : props.isSelected
                  ? "#1077c4"
                  : "#404040"
          }
          strokeWidth={2}
        />
        <Image
        image={isEnergy
  ? (flipped ? intermediatePowerImageFlipped : intermediatePowerImage)
  : intermediateImage}
         // image={flipped ? intermediateImageFlipped : intermediateImage}
          width={width / 1.5}
          height={height / 1.5}
          scaleX={offsetsAndScale.sX}
          scaleY={offsetsAndScale.sY}
          offsetX={offsetsAndScale.xOff}
          offsetY={offsetsAndScale.yOff}
          rotation={gObj.rotation}
       
          x={(width) / 6}
          y={height / 6}
 
        />
      </>
    );
  };
 
  const decisionNode = () => {
    return (
      <>
        {/* Main circle */}
        <Circle
          x={width / 2}
          y={height / 2}
          radius={width / 2}
          fill={props.isSelected || props.isHovered ? "#E9EDF0" : "#FFFFFF"}
          stroke={
            props.disabled
              ? "#aaaaaa"
              : props.highlight
                ? "#26967f"
                : props.isSelected
                  ? "#1077c4"
                  : "#404040"
          }
          strokeWidth={2}
        />
        <Image
          image={decisionImage}
          width={width}
          height={height}
          x={width / 2 - width / 2}
          y={height / 2 - (height - 11) / 2}
        />
      </>
    );
  };
  return <>{renderElement()}</>;
};
 
const GroupGraphic = (props: GenericObjectGraphicProps) => {
  // draw a blue transparent rectangle around the group objects
  const gObj = props.graphicObject;
  const width = gObj.width!;
  const height = gObj.height!;
  const simulationObjectGroup = useSimulationObjectGroup();
  const imageName = props.simulationObject?.objectType;
  const [defaultImage] = useImage(`../../assets/UpdatedIcons/uo_default.svg`);
  const changeTabState = useChangeTabState();
  const switchGroup = useRunCommand(SwitchGroup);
  const getFlowsheetTabFromGroupId = useFlowsheetTabFromGroupId();
  let [image] = useImage(`../../assets/UpdatedIcons/${imageName}.svg`) || [
    defaultImage,
  ];
  if (!image) {
    image = defaultImage;
  }
 
  const isModule = props.simulationObject.objectType === "group";
 
  // double click on moudle to open the group
  const openGroup = () => {
    const group = simulationObjectGroup(props.simulationObject.id);
    Iif (!group) return;
    // Directly switch to the group
    switchGroup(group.id);
  };
 
  return (
    <>
      {/**background**/}
      <Rect
        width={width}
        height={height}
        fill={
          props.isSelected ? "#E9EDF0" : props.isHovered ? "#f2f3f5" : "#FFFFFF"
        }
        stroke={
          props.disabled ? "#aaaaaa" : props.isSelected ? "#1077c4" : "#404040"
        }
        strokeWidth={2}
        cornerRadius={2}
        onDblClick={openGroup}
      />
      {/**Unit Operation Image */}
      <Image
        image={image}
        width={width / 2}
        height={height / 2}
        x={width / 4}
        y={height / 4}
        onDblClick={openGroup}
      />
 
      {/* Module Mark in top left corner */}
      {isModule && (
        <Group x={10} y={10}>
          <Html>
            <div
              style={{
                transform: "scale(0.9)",
                position: "absolute",
                zIndex: 1,
                translate: "-5px -4px",
              }}
              className="select-none"
            >
              <div className="text-emerald-600">
                <ModuleMark />
              </div>
            </div>
          </Html>
        </Group>
      )}
 
      {/* Status Indicator */}
      <Group x={width - 26} y={height - 26}>
        <Html>
          <div style={{ transform: "scale(0.9)" }} className="select-none">
            <PropertiesStatus
              propertySet={props.simulationObject.unspecifiedProperties}
              hideSuccess={true}
            />
          </div>
        </Html>
      </Group>
      <Text
        listening={false}
        align="center"
        x={0}
        y={height + textPadding}
        text={props.simulationObject.componentName}
        width={width}
        fontSize={16}
        fontFamily="Inter"
        wrap="none"
        ellipsis={true}
        fill="#404040"
        letterSpacing={-0.2}
      />
    </>
    
  );
};
 
const LogicBlockGraphic = (props: GenericObjectGraphicProps) => {
  const gObj = props.graphicObject;
  const width = gObj.width!;
 
  const points = [
    0,
    width / 2,
    width / 2,
    0,
    width,
    width / 2,
    width / 2,
    width,
  ];
 
  const fill = props.disabled
    ? "#aaaaaa"
    : props.isSelected
      ? "#3a4869"
      : props.isHovered
        ? "#505050"
        : "#404040";
  const stroke = props.disabled
    ? "#aaaaaa"
    : props.highlight
      ? "#26967f"
      : props.isSelected
        ? "#1077c4"
        : "#404040";
 
  const character = (() => {
    switch (props.simulationObject.objectType) {
      case "recycle":
        return "R";
      default:
        return "";
    }
  })();
 
  // Create the diamond shape using Konva.Line
  return (
    <>
      <Line
        points={points}
        fill={fill}
        stroke={stroke}
        strokeWidth={2}
        closed={true}
        lineJoin="round"
      />
      <Text
        listening={false}
        align="center"
        verticalAlign="middle"
        width={width}
        height={width}
        text={character}
        fontSize={14}
        fontFamily="Inter"
        fill="#fff"
        fontStyle="bold"
      />
    </>
  );
};
 
type SimulationObjectGraphicProps = {
  simulationObject: SimulationObjectRead;
  graphicObject: GraphicObjectRead;
  hovered?: boolean;
  getOverStreamOrUnitOp: (
    x: number,
    y: number,
    activeObject: SimulationObjectRead,
  ) => SimulationObjectRead | undefined;
  addHoveredObject: (id: number) => void;
  removeAllHoveredObjects: () => void;
  hoveredObjects: number[];
};
 
export const SimulationObjectGraphic = (
  props: SimulationObjectGraphicProps,
) => {
  const currentGroupObjects = useCurrentGroupObjects();
 
  const dispatch = useAppDispatch();
  const { addHistory, isReady } = useUndoRedoStore();
  const objectsGraphicObjectsMap = useObjectsGraphicObjectsMap();
  const groupId = useCurrentGroupId();
  const [updateGraphicObject] = useGraphicsObjectsPartialUpdateMutation();
  const [updateSimulationObject] =
    useUnitopsSimulationobjectsPartialUpdateMutation();
  const gObj = props.graphicObject;
  const blockWidth = gObj.width!;
  const blockHeight = gObj.height!;
  const [objectId, setObjectId] = useSearchParam("object");
  const pointerState = useSelector((state: RootState) => state.pointer);
  const [mouseOver, setMouseOver] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const mergeStreams = useMergeStreams();
  const addPortAndConnectStream = useAddPortAndConnectStream();
  const mergeDecisionNodes = useMergeDecisionNodes();
  const getGroupObject = useGroupObjects();
  const [updateGroupPosition] = useGraphicsgroupingsPartialUpdateMutation();
  const simulationObjectGroup = useSimulationObjectGroup();
  const [params, setParams] = useSearchParams();
  const isSpecified = props.simulationObject?.unspecifiedProperties.every(
    (set) => set.length === 0,
  );
 
  const processPathHasObject = useProcessPathHasObject()(
    props.simulationObject.id,
  );
 
  const [dragStartPosition, setDragStartPosition] = useState<{
    x: number;
    y: number;
  } | null>(null);
 
  const handleNameChange = async (newName: string) => {
    Iif (!newName.trim()) {
      toast.error("Name cannot be empty");
      return;
    }
 
    try {
      // Optimistic update
      dispatch(
        api.util.updateQueryData(
          "unitopsSimulationobjectsRetrieve",
          { id: props.simulationObject.id },
          (draft) => {
            draft.componentName = newName;
          },
        ),
      );
 
      // Backend update
      await updateSimulationObject({
        id: props.simulationObject.id,
        patchedSimulationObject: {
          componentName: newName,
        },
      }).unwrap();
 
      toast.success(`Updated name to ${newName}`);
    } catch (error) {
      console.error("Failed to update name:", error);
      toast.error("Failed to update name");
    }
  };
 
  const onClick = (e) => {
    const shiftKey = e.evt.shiftKey;
    if (!objectId || !shiftKey) {
      setParams((prev) => {
        const newParams = new URLSearchParams(prev);
        newParams.set("object", props.simulationObject.id);
        newParams.set("content", ContentTypes.objectDetails);
        return newParams;
      });
      return;
    }
 
    Iif (shiftKey) {
      //Extend with adding to selection rectangle
    }
  };
 
  const isMouseOver = (value: boolean) => (e) => {
    setMouseOver(value);
  };
 
  // Add onDragStart handler
  const onDragStart = (e: KonvaNodeEvents["onDragStart"]) => {
    setDragStartPosition({
      x: e.target.x(),
      y: e.target.y(),
    });
  };
 
  /**
   * Get the stream or unit operation that is over the given x and y coordinates
   * @param x x coordinate
   * @param y y coordinate
   * @param activeObject the object that is being dragged
   * @returns SimulationObjectRead of the object that is over the given coordinates, or undefined if none
   */
  const getOverStreamOrUnitOp = (x, y, activeObject) => {
    const activeObjectGraphic = objectsGraphicObjectsMap.get(activeObject.id)!;
    const paddingX = activeObjectGraphic.width! / 2;
    const paddingY = activeObjectGraphic.height! / 2;
    const adjustedX = x + paddingX;
    const adjustedY = y + paddingY;
    const overObject = currentGroupObjects?.find((obj) => {
      if (obj.id === activeObject.id) return false;
      Iif (
        ![
          "energy_stream",
          "ac_stream",
          "stream",
          "mixer",
          "splitter",
          "decisionNode",
          "humid_air_stream",
        ].includes(obj.objectType)
      )
        return false;
      const gObj = objectsGraphicObjectsMap.get(obj.id);
      Iif (!gObj) return false;
      const minX = gObj.x!;
      const minY = gObj.y!;
      const maxX = minX + gObj.width!;
      const maxY = minY + gObj.height!;
      return (
        adjustedX >= minX - paddingX &&
        adjustedX <= maxX + paddingX &&
        adjustedY >= minY - paddingY &&
        adjustedY <= maxY + paddingY
      );
    });
    return overObject;
  };
 
  //Optimistically updates position in cache while dragging
  const onDragUnitOp = (e) => {
    const x = e.target.x();
    const y = e.target.y();
 
    // Continuously check if dragged object is hovering over another object
    const overObject = getOverStreamOrUnitOp(x, y, props.simulationObject);
    // Make sure the object is not hovering over itself
    Iif (overObject) {
      Iif (!props.hoveredObjects.includes(overObject.id)) {
        props.addHoveredObject(overObject.id);
      }
    I} else if (props.hoveredObjects.length > 0) {
      props.removeAllHoveredObjects();
    }
 
    dispatch(
      api.util.updateQueryData(
        "graphicsObjectsList",
        { group: groupId },
        (cachedGraphicObjects) => {
          const gObj = cachedGraphicObjects?.find(
            (graphicObject) =>
              graphicObject.simulationObject.id === props.simulationObject.id,
          );
          if (gObj) {
            Iif (props.simulationObject.objectType === "group") {
              const containedObjects = getGroupObject(props.simulationObject.id);
              Iif (containedObjects) {
                const deltaX = x - gObj.x!;
                const deltaY = y - gObj.y!;
                containedObjects.forEach((obj) => {
                  const objG = cachedGraphicObjects.find(
                    (g) => g.simulationObject.id === obj.id,
                  );
                  Iif (objG) {
                    objG.x += deltaX;
                    objG.y += deltaY;
                  }
                });
              }
            }
            gObj.x = x;
            gObj.y = y;
          }
        },
      ),
    );
  };
 
  // Updates Unit Operation x and y coordinates when a unitop is released on the surface
  const onDragEndUnitop = (e: KonvaNodeEvents["onDragEnd"]) => {
    const x = e.target.x();
    const y = e.target.y();
    const { snapX, snapY } = snap(x, y, blockWidth, blockHeight);
    const activeObject = props.simulationObject;
    const overObject = getOverStreamOrUnitOp(x, y, activeObject);
 
    // Add this block for undo/redo
    if (dragStartPosition) {
      let groupObjects = undefined;
 
      Iif (activeObject.objectType === ObjectTypeEnum.Group) {
        const containedObjects = getGroupObject(props.simulationObject.id);
        Iif (containedObjects) {
          const deltaX = snapX - dragStartPosition.x;
          const deltaY = snapY - dragStartPosition.y;
          groupObjects = containedObjects.map((obj) => {
            const objGraphic = objectsGraphicObjectsMap.get(obj.id);
            return {
              objectId: obj.id,
              graphicObjectId: objGraphic!.id,
              oldPosition: {
                x: objGraphic!.x! - deltaX,
                y: objGraphic!.y! - deltaY,
              },
              newPosition: {
                x: objGraphic!.x!,
                y: objGraphic!.y!,
              },
            };
          });
        }
      }
 
      const moveCommand = createMoveCommand({
        objectId: props.simulationObject.id,
        graphicObjectId: props.graphicObject.id,
        oldPosition: dragStartPosition,
        newPosition: { x: snapX, y: snapY },
        groupObjects: groupObjects,
      });
 
      // 🎯 ALTERNATIVE 3: Check Ready State Before Adding Commands
      if (isReady) {
        addHistory(moveCommand);
      IE} else if (process.env.NODE_ENV === "development") {
        console.warn("[UndoRedo] Move command skipped - context not ready");
      }
    }
 
    setDragStartPosition(null);
 
    Iif (isStream(activeObject)) {
      Iif (
        overObject &&
        (overObject.objectType === ObjectTypeEnum.Mixer ||
          overObject.objectType === ObjectTypeEnum.Splitter ||
          overObject.objectType === ObjectTypeEnum.DecisionNode)
      ) {
        addPortAndConnectStream(overObject, activeObject);
        return;
      }
 
      // Then check for stream merging
      Iif (
        overObject &&
        isStream(overObject) &&
        overObject.id !== activeObject.id &&
        overObject.objectType === activeObject.objectType // same type of stream (can't merge energy and material streams)
      ) {
        mergeStreams(activeObject, overObject);
        return;
      }
    I} else if (
      activeObject.objectType === ObjectTypeEnum.DecisionNode &&
      overObject &&
      overObject.objectType === ObjectTypeEnum.DecisionNode &&
      overObject.id !== activeObject.id
    ) {
      mergeDecisionNodes(activeObject, overObject);
      return;
    I} else if (activeObject.objectType === ObjectTypeEnum.DecisionNode) {
      Iif (overObject && isStream(overObject)) {
        addPortAndConnectStream(activeObject, overObject);
        return;
      }
    I} else if (activeObject.objectType === ObjectTypeEnum.Group) {
      const group = simulationObjectGroup(activeObject.id);
      // backend update
      updateGroupPosition({
        id: group.id,
        patchedGrouping: {
          x: snapX,
          y: snapY,
        },
      });
      return;
    }
 
    // optimistically update the position in the cache
    dispatch(
      api.util.updateQueryData(
        "graphicsObjectsList",
        { group: groupId },
        (cachedGraphicObjects) => {
          const gObj = cachedGraphicObjects?.find(
            (graphicObject) =>
              graphicObject.simulationObject.id === props.simulationObject.id,
          );
          if (gObj) {
            gObj.x = snapX;
            gObj.y = snapY;
          }
        },
      ),
    );
 
    updateGraphicObject({
      id: props.graphicObject.id,
      patchedGraphicObject: {
        x: snapX,
        y: snapY,
      },
    });
 
    setMouseOver(false);
    props.removeAllHoveredObjects();
  };
 
  const renderElement = () => {
    const objProps: GenericObjectGraphicProps = {
      simulationObject: props.simulationObject,
      graphicObject: props.graphicObject,
      isSelected: objectId == props.simulationObject.id + "",
      isHovered: pointerState.state !== "move" && mouseOver,
      disabled: !processPathHasObject,
      highlight: props.hovered,
      isSpecified: isSpecified,
      isEditing: isEditing,
      onToggleEdit: () => setIsEditing(!isEditing),
      onNameChange: handleNameChange,
    };
    if (isStream(props.simulationObject)) {
      return <MaterialStreamGraphic {...objProps} />;
    }
    switch (props.simulationObject.objectType) {
      case "decisionNode":
        return <MaterialStreamGraphic {...objProps} />;
      case "group":
        return <GroupGraphic {...objProps} />;
      case "recycle":
        return <LogicBlockGraphic {...objProps} />;
      default:
        return <UnitOpGraphic {...objProps} />;
    }
  };
 
  return (
    <BlockGraphic
      graphicObject={props.graphicObject}
      componentName={props.simulationObject.componentName!}
      draggable={pointerState.state !== "move"}
      onMouseEnter={isMouseOver(true)}
      onMouseLeave={isMouseOver(false)}
      onDragStart={onDragStart}
      onDragMove={onDragUnitOp}
      onDragEnd={onDragEndUnitop}
      onClick={onClick}
      simulationObject={props.simulationObject}
      isSpecified={isSpecified}
    >
      {renderElement()}
    </BlockGraphic>
  );
};