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

93.54% Statements 58/62
84.21% Branches 16/19
81.25% Functions 13/16
93.1% Lines 54/58

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                                                                  33x   33x 3763x 7430x 7430x 3763x   3763x 3763x 3763x   3763x           7430x 7430x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x   3763x       3763x 3763x         3763x                                                     3763x                   3763x 35x 35x     3763x 27x 27x     3763x 123x     3960x                       3763x 3763x   3763x 589x           40x 40x         40x       3763x 291x 291x 291x         3763x 8x 8x 8x 8x 8x 8x     3763x                                                                                                                                                                                                           1x                                                        
import {
  ContextMenu,
  ContextMenuTrigger,
} from "@/ahuora-design-system/ui/context-menu";
import { SwitchGroupCommands } from "@/commands/SwitchCurrentGroup";
import { useCurrentGroupId, useCurrentObject, useGraphicsObjects, useFlowsheetUnitOps } from "@/hooks/flowsheetObjects";
import { useSearchParam } from "@/hooks/searchParams";
import { resetClick } from "@/store/ClickSlice";
import { useAppDispatch } from "@/store/hooks";
import { setPointerState } from "@/store/PointerSlice";
import { RootState } from "@/store/store";
import React, { createContext, memo, useEffect, useRef, useState } from "react";
import { useDrop } from "react-dnd";
import { Layer, Stage } from "react-konva";
import { useSelector } from "react-redux";
import { useMousePosition } from "react-use-mouse-position";
import { useResizeObserver } from "usehooks-ts";
import { UnitOpCommands } from "../../../../commands/AddUnitOp";
import SolveButton from "../SolveButton";
import AllElements from "./AllElements";
import BreadCrumbs from "./BreadCrumbs";
import { CanvasContextMenu } from "./CanvasContextMenu";
import { FlowsheetCommands } from "./FlowsheetCommands";
import { useFlowsheetCanvasFunctions } from "./FlowsheetFunctions";
import { Gridlines } from "./Gridlines";
import PropertyHover from "./PropertyHover";
import CanvasControls from "./ZoomControls";
import { ExportMSSRResultsCommand } from "../../multi-steady-state/ExportMSSResultsCommand";
 
interface FlowsheetProps {
  width: number;
}
 
export const IndicatorVisibilityContext = createContext<boolean>(true);
 
const FlowsheetSurface: React.FC<FlowsheetProps> = (props) => {
  const canvasDiv = useRef<HTMLDivElement>(null);
  const pointerState = useSelector((state: RootState) => state.pointer);
  const objectHoverState = useSelector((state: RootState) => state.hover);
  const { mouseX, mouseY } = useMousePosition();
 
  const { height = 480 } = useResizeObserver({ ref: canvasDiv });
  const canvasWidth = Math.floor(props.width);
  const canvasHeight = Math.floor(height);
 
  const [FlowsheetSurfaceState, setFlowsheetSurfaceState] = useState({
    scale: 1,
    stageX: canvasWidth,
    stageY: canvasHeight,
  });
  
  const clicked = useSelector((state: RootState) => state.click.clicked);
  const clickedId = useSelector((state: RootState) => state.click.id);
  const dispatch = useAppDispatch();
  const [objectId] = useSearchParam("object");
  const objectID = parseInt(objectId || "0");
  const currentObject = useCurrentObject();
  const rootGroup = useCurrentGroupId();
  const graphicsObjects = useGraphicsObjects();
  const flowsheetObjects = useFlowsheetUnitOps();
  const currentGroupId = useCurrentGroupId();
  // Inside the FlowsheetSurface component
  const [contextMenuPosition, setContextMenuPosition] = useState({
    x: 0,
    y: 0,
  });
  const [isMouseDown, setIsMouseDown] = useState(false);
  const handleSetPointer = (pointerMode: "select" | "move") => {
    // arc will be added in the future
    dispatch(setPointerState(pointerMode));
  };
 
  const togglePointerState = () => {
    const nextState = pointerState.state === "select" ? "move" : "select";
    handleSetPointer(nextState);
  };
 
  const {
    changeZoom,
    handleDrop,
    onKeyDown,
    zoomToFit,
    resetZoom,
    onMouseDown,
    onMouseUp,
    onMouseMove,
    onDoubleClick,
    onScroll,
    onStageDrag,
    deleteSelectedObject,
    rotateFlipSelectedObject,
    onObjectSelect,
    convertStreamToDecisionNode,
    groupSelectedObjects,
    unGroupCurrentObject,
    handleObjectCopy,
    handleObjectPaste,
    selectionRect,
    setSelectionRect,
  } = useFlowsheetCanvasFunctions({
    canvasDiv,
    pointerState,
    FlowsheetSurfaceState,
    setFlowsheetSurfaceState,
    canvasWidth,
    canvasHeight,
  });
 
  // necessary for the property hover to be disabled on drag
  const handleMouseDown = (e) => {
    setIsMouseDown(true);
    onMouseDown(e);
  };
 
  const handleMouseUp = (e) => {
    setIsMouseDown(false);
    onMouseUp(e);
  };
 
  const [{ isOver }, drop] = useDrop(
    () => ({
      accept: "unit_operation",
      drop: handleDrop,
      collect: (monitor) => ({
        isOver: !!monitor.isOver(),
      }),
    }),
    [
      FlowsheetSurfaceState.stageX,
      FlowsheetSurfaceState.stageY,
      FlowsheetSurfaceState.scale,
      rootGroup,
    ],
  );
 
  const [indicatorsVisible, setIndicatorsVisible] = useState(true);
  const [hasZoomedToFit, setHasZoomedToFit] = useState(false);
 
  useEffect(() => {
    if (
      !hasZoomedToFit &&
      graphicsObjects !== undefined &&
      flowsheetObjects !== undefined &&
      currentGroupId !== undefined
    ) {
      const { newScale, newStageX, newStageY } = zoomToFit();
      setFlowsheetSurfaceState({
        scale: newScale,
        stageX: newStageX,
        stageY: newStageY,
      });
      setHasZoomedToFit(true);
    }
  }, [graphicsObjects, flowsheetObjects, currentGroupId, hasZoomedToFit]);
 
  if (clicked && clickedId) {
    onObjectSelect(clickedId);
    setTimeout(() => {
      dispatch(resetClick());
    }, 1);
  }
 
 
  const handleContextMenu = (event: React.MouseEvent<HTMLDivElement>) => {
    event.preventDefault();
    if (canvasDiv.current) {
      const rect = canvasDiv.current.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      setContextMenuPosition({ x, y });
    }
  };
  return (
    <IndicatorVisibilityContext.Provider value={indicatorsVisible}>
      <UnitOpCommands
        state={FlowsheetSurfaceState}
        width={canvasWidth}
        height={canvasHeight}
      />
      <SwitchGroupCommands
        setFlowsheetSurfaceState={setFlowsheetSurfaceState}
        zoomToFit={zoomToFit}
      />
      <FlowsheetCommands
        zoomToFit={zoomToFit}
        resetZoom={resetZoom}
        togglePointerState={togglePointerState}
      />
      <ExportMSSRResultsCommand />
      <ContextMenu>
        <div className="grow relative" ref={canvasDiv}>
          <div
            className="skia-canvas overflow-hidden bg-white"
            ref={drop}
            data-testid={10}
            role="Space"
            aria-label="Flowsheet Canvas"
            tabIndex={0}
            onKeyDown={onKeyDown}
            onContextMenu={handleContextMenu}
          >
            <ContextMenuTrigger>
              <Stage
                id="canvas"
                width={canvasWidth}
                height={canvasHeight}
                onMouseDown={handleMouseDown}
                onMouseUp={handleMouseUp}
                onMouseMove={onMouseMove}
                onDblClick={onDoubleClick}
                onWheel={onScroll}
                onDragMove={onStageDrag}
                scaleX={FlowsheetSurfaceState.scale}
                scaleY={FlowsheetSurfaceState.scale}
                x={FlowsheetSurfaceState.stageX}
                y={FlowsheetSurfaceState.stageY}
                className={
                  pointerState.state === "move"
                    ? "cursor-grab"
                    : "cursor-default"
                }
              >
                {
                  <>
                    <Gridlines
                      x={FlowsheetSurfaceState.stageX}
                      y={FlowsheetSurfaceState.stageY}
                      w={canvasWidth}
                      h={canvasHeight}
                      spacing={50}
                      zoom={FlowsheetSurfaceState.scale}
                      color="#BBBBBB"
                    />
                    <Layer>
                      <AllElements
                        selectionRect={selectionRect}
                        setSelectionRect={setSelectionRect}
                        FlowsheetSurfaceState={FlowsheetSurfaceState}
                      />
                    </Layer>
                  </>
                }
              </Stage>
            </ContextMenuTrigger>
          </div>
          {/* 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">
            <CanvasControls
              solveButton={<SolveButton className="h-full" />}         
              canvasWidth={canvasWidth}
              canvasHeight={canvasHeight}
              canvasScale={FlowsheetSurfaceState.scale}
              canvasChangeZoom={changeZoom}
              viewStatusData={{
                visibilitySetter: (indicatorsVisible: boolean) =>
                  setIndicatorsVisible(indicatorsVisible),
                visibility: indicatorsVisible,
              }}
            />
          </div>
        </div>
        <CanvasContextMenu
          deleteSelectedObject={deleteSelectedObject}
          rotateFlipSelectedObject={rotateFlipSelectedObject}
          unGroupCurrentObject={unGroupCurrentObject}
          groupSelectedObjects={groupSelectedObjects}
          convertStreamToDecisionNode={convertStreamToDecisionNode}
          copyObject={handleObjectCopy}
          pasteObject={() => handleObjectPaste(contextMenuPosition)}
          objectType={currentObject?.objectType}
          isSelectionVisible={selectionRect.selectVisible}
          objectId={objectID}
        />
        {
          // !isMouseDown so that the property hover is disabled on drag
          objectHoverState.state && !isMouseDown && (
            <div
              style={{
                position: "fixed",
                top: mouseY,
                left: mouseX + 5,
                zIndex: 100,
              }}
            >
              <PropertyHover
                simulationObject={objectHoverState?.simulationObject}
              />
            </div>
          )
        }
      </ContextMenu>
    </IndicatorVisibilityContext.Provider>
  );
};
 
export default memo(FlowsheetSurface);