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

64.73% Statements 112/173
50% Branches 24/48
65.62% Functions 21/32
67.27% Lines 111/165

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                                                                                          33x         102x           33x     3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x 3763x                             3763x 16x 16x 16x 16x 16x         16x                     3763x   69x 69x 69x 69x 69x         69x 69x   69x                 3763x             131x 131x 131x   131x                 131x     3763x           16x   16x       16x       16x             99x             99x               16x 99x 459x   99x     99x             26x     16x     3763x 16x 16x 16x 16x 16x         16x 16x 16x           16x 16x 16x 16x 16x 16x         16x 6x   26x 150x     26x   6x     6x 6x 6x 6x 6x 26x     26x 26x 26x 26x   6x   16x               26x       3763x   5x             3763x 5x               5x     3763x                                                                         3763x                                   33x         4582x   4582x 4582x 4582x 4582x     4582x 1x 1x 1x         1x 1x 1x 6x 21x   6x       1x                     4582x                                                                                     4582x                                                                                                                         4582x 152x                                
import { useState } from "react";
import { KonvaEventObject } from "konva/lib/Node";
import {
  api,
  GraphicObjectRead,
  SimulationObjectRead,
  useGraphicsgroupingsDeleteSelectedObjectsCreateMutation,
  useGraphicsgroupingsMakeGroupCreateMutation,
  useGraphicsgroupingsMoveSelectionCreateMutation,
} from "@/api/apiStore.gen.ts";
import { useAppDispatch } from "@/store/hooks";
import { Rect } from "react-konva";
import { useSearchParam } from "@/hooks/searchParams";
import {
  useOptimisticallyDeleteSelection,
  useCaptureDeletionConnections,
} from "@/hooks/deleteObjects";
import {
  useCurrentGroupObjects,
  useCurrentObject,
  useCurrentGroupId,
  useGraphicsObjects,
} from "@/hooks/flowsheetObjects";
import { useUndoRedoStore } from "@/hooks/useUndoRedoStore";
import {
  createMoveCommand,
  createDeleteCommand,
} from "@/utils/commandCreators";
import { FlowsheetSurfaceStateDef } from "./FlowsheetFunctions";
 
export type selectionRectType = {
  x: number;
  y: number;
  width: number;
  height: number;
  xInitial: number;
  yInitial: number;
  offsetX: number;
  offsetY: number;
  selectVisible?: boolean;
  selectEnabled?: boolean;
  containedObjects: number[];
  objCoordMap: Map<number, { x: number; y: number }>;
};
 
const getRelativePosition = (
  FlowsheetSurfaceState: FlowsheetSurfaceStateDef,
  x: number,
  y: number,
) => {
  return {
    x: (x - FlowsheetSurfaceState.stageX) / FlowsheetSurfaceState.scale,
    y: (y - FlowsheetSurfaceState.stageY) / FlowsheetSurfaceState.scale,
  };
};
 
export const useSelectionRect = (
  FlowsheetSurfaceState: FlowsheetSurfaceStateDef,
) => {
  const graphicsObjects = useGraphicsObjects();
  const { addHistory, isReady } = useUndoRedoStore();
  const [, setObjectId] = useSearchParam("object");
  const [makeGrouping] = useGraphicsgroupingsMakeGroupCreateMutation();
  const [deleteSelectionObjects] = useGraphicsgroupingsDeleteSelectedObjectsCreateMutation();
  const optimisticallyDeleteSelection = useOptimisticallyDeleteSelection();
  const captureConnections = useCaptureDeletionConnections();
  const containedObjects = useCurrentGroupObjects();
  const currentObject = useCurrentObject();
  const [selectionRect, setSelectionRect] = useState({
    x: 0,
    y: 0,
    width: 0,
    height: 0,
    xInitial: 0,
    yInitial: 0,
    offsetX: 0,
    offsetY: 0,
    selectVisible: false,
    selectEnabled: false,
    containedObjects: [],
    objCoordMap: new Map<number, { x: number; y: number }>(),
  } as selectionRectType);
 
  const onSelectionStart = (e: KonvaEventObject<MouseEvent>) => {
    const stage = e.target.getStage();
    Iif (!stage) return;
    const pos = stage.getPointerPosition();
    Iif (!pos) return;
    const relativePos = getRelativePosition(
      FlowsheetSurfaceState,
      pos.x,
      pos.y,
    );
    setSelectionRect({
      ...selectionRect,
      x: Math.floor(relativePos.x),
      y: Math.floor(relativePos.y),
      width: 0,
      height: 0,
      selectVisible: true,
      selectEnabled: true,
    });
  };
 
  const onResizeSelectionRect = (e: KonvaEventObject<MouseEvent>) => {
    // update selection rectangle
    const stage = e.target.getStage();
    Iif (!stage) return;
    const pos = stage.getPointerPosition();
    Iif (!pos) return;
    const relativePos = getRelativePosition(
      FlowsheetSurfaceState,
      pos.x,
      pos.y,
    );
    const width = Math.ceil(relativePos.x - selectionRect.x);
    const height = Math.ceil(relativePos.y - selectionRect.y);
    // find selected items
    setSelectionRect({
      ...selectionRect,
      width: width,
      height: height,
    });
  };
 
  // compute axis-aligned bounding box from raw params,
  // accounting for 90° / 270° rotations (width/height swap around center)
  const computeAABBFromParams = (
    x: number,
    y: number,
    w: number,
    h: number,
    rotationIn: number = 0,
  ) => {
    const rotation = (rotationIn || 0) % 360;
    const centerX = x + w / 2;
    const centerY = y + h / 2;
 
    Iif (rotation === 90 || rotation === 270) {
      const effW = h;
      const effH = w;
      const minX = centerX - effW / 2;
      const minY = centerY - effH / 2;
      return { minX, minY, maxX: minX + effW, maxY: minY + effH };
    }
 
    // 0° and 180° rotate about center but keep same AABB for axis-aligned rectangles
    return { minX: x, minY: y, maxX: x + w, maxY: y + h };
  };
 
  const getSelectedObjects = (
    rectX: number,
    rectY: number,
    rectWidth: number,
    rectHeight: number,
  ) => {
    const selectedSimulationObjects: SimulationObjectRead[] = [];
    // make sure rectWidth and rectHeight are positive
    Iif (rectX > rectX + rectWidth) {
      rectX = rectX + rectWidth;
      rectWidth = -rectWidth;
    }
    Iif (rectY > rectY + rectHeight) {
      rectY = rectY + rectHeight;
      rectHeight = -rectHeight;
    }
    const withinBounds = (
      objX: number,
      objY: number,
      objWidth: number,
      objHeight: number,
      rotation: number = 0
    ) => {
      const aabb = computeAABBFromParams(
        objX,
        objY,
        objWidth,
        objHeight,
        rotation,
      );
      return (
        aabb.minX < rectX + rectWidth &&
        aabb.maxX > rectX &&
        aabb.minY < rectY + rectHeight &&
        aabb.maxY > rectY
      );
    };
 
    containedObjects!.forEach((simObj) => {
      const gObj = graphicsObjects?.find(
        (graphicObj) => graphicObj.simulationObject.id === simObj.id,
      );
      Iif (!gObj || !gObj.visible) return;
      
      // Check if they intersect, accounting for rotation
      if (withinBounds(
        +gObj.x!, 
        +gObj.y!, 
        +gObj.width!, 
        +gObj.height!,
        +gObj.rotation! || 0
      )) {
        selectedSimulationObjects.push(simObj);
      }
    });
    return selectedSimulationObjects;
  };
 
  const onSelectionRectResizeEnd = (e: KonvaEventObject<MouseEvent>) => {
    const stage = e.target.getStage();
    Iif (!stage) return;
    const pos = stage.getPointerPosition();
    Iif (!pos) return;
    const relativePos = getRelativePosition(
      FlowsheetSurfaceState,
      pos.x,
      pos.y,
    );
    const width = Math.ceil(relativePos.x - selectionRect.x);
    const height = Math.ceil(relativePos.y - selectionRect.y);
    let selectedSimulationObjects = getSelectedObjects(
      selectionRect.x,
      selectionRect.y,
      width,
      height,
    );
    let minX = 0;
    let minY = 0;
    let maxX = 0;
    let maxY = 0;
    let visible = false;
    Iif (selectedSimulationObjects.length === 1) {
      // only one object selected, so act as if it was clicked
      const selectedObject = selectedSimulationObjects[0];
      selectedSimulationObjects = [];
      setObjectId(selectedObject.id);
    } else if (selectedSimulationObjects.length > 0) {
      const gObjs = selectedSimulationObjects
        .map((simObj) =>
          graphicsObjects?.find(
            (graphicObj) => graphicObj.simulationObject.id === simObj.id,
          ),
        )
        .filter((obj): obj is GraphicObjectRead => obj !== undefined);
 
      const firstAABB = computeAABBFromParams(
        +gObjs[0].x!, +gObjs[0].y!, +gObjs[0].width!, +gObjs[0].height!, +gObjs[0].rotation! || 0
      );
      minX = firstAABB.minX;
      minY = firstAABB.minY;
      maxX = firstAABB.maxX;
      maxY = firstAABB.maxY;
      gObjs.forEach((gObj) => {
        const aabb = computeAABBFromParams(
          +gObj.x!, +gObj.y!, +gObj.width!, +gObj.height!, +gObj.rotation! || 0
        );
        minX = Math.min(minX, aabb.minX);
        minY = Math.min(minY, aabb.minY);
        maxX = Math.max(maxX, aabb.maxX);
        maxY = Math.max(maxY, aabb.maxY);
      });
      visible = true;
    }
    setSelectionRect({
      ...selectionRect,
      x: Math.floor(minX),
      y: Math.floor(minY),
      selectEnabled: false,
      selectVisible: visible,
      width: Math.ceil(maxX - minX),
      height: Math.ceil(maxY - minY),
      containedObjects: selectedSimulationObjects.map((simObj) => simObj.id),
    });
  };
 
  const onSelectionRemoved = () => {
    // Reset selection rect
    setSelectionRect({
      ...selectionRect,
      selectVisible: false,
      selectEnabled: false,
    });
  };
 
  const makeGroup = () => {
    makeGrouping({
      makeGroup: {
        containedObjects:
          selectionRect.containedObjects?.length > 0
            ? selectionRect.containedObjects
            : [currentObject!.id],
      },
    });
    onSelectionRemoved();
  };
 
  const deleteSelectedObjects = () => {
    // Get the objects that will be deleted
    const objects = containedObjects!.filter((obj) =>
      selectionRect.containedObjects.includes(obj.id),
    );
 
    Iif (objects.length > 0) {
      // Capture connection data before deletion
      const connectionData = captureConnections(selectionRect.containedObjects);
 
      // Add to undo history before deleting with connection data
      const deleteCommand = createDeleteCommand({
        objects: objects.map((obj) => ({
          id: obj.id,
          objectType: obj.objectType || "SimulationObject",
          fullObjectData: obj,
        })),
        connectionData, // Include captured connection data for bulk deletion
      });
      // 🎯 ALTERNATIVE 3: Check Ready State Before Adding Commands
      if (isReady) {
        addHistory(deleteCommand);
      I} else if (process.env.NODE_ENV === "development") {
        console.warn("[UndoRedo] Delete command skipped - context not ready");
      }
    }
 
    // Delete the objects in the backend
    deleteSelectionObjects({
      deleteSelectedObjects: {
        containedObjects: selectionRect.containedObjects,
      },
    });
    onSelectionRemoved();
    optimisticallyDeleteSelection(selectionRect.containedObjects);
  };
 
  return {
    selectionRect: selectionRect,
    setSelectionRect: setSelectionRect,
    onSelectionRemoved,
    onSelectionStart,
    onResizeSelectionRect,
    onSelectionRectResizeEnd,
    makeGroup,
    deleteSelectedObjects,
    getRelativePosition,
  };
};
 
interface DrawSelectionRectProps {
  selectionRect: selectionRectType;
  FlowsheetSurfaceState: FlowsheetSurfaceStateDef;
  setSelectionRect: (selectionRectType) => void;
}
export const SelectionRect = ({
  selectionRect,
  FlowsheetSurfaceState,
  setSelectionRect,
}: DrawSelectionRectProps) => {
  const graphicsObjects = useGraphicsObjects();
  const [updateSelectionRect] =
    useGraphicsgroupingsMoveSelectionCreateMutation();
  const groupId = useCurrentGroupId();
  const dispatch = useAppDispatch();
  const { addHistory, isReady } = useUndoRedoStore();
 
  // Dragging start function for multiselect
  const onDragSelectionStart = (e) => {
    const stage = e.target.getStage();
    const pos = stage.getPointerPosition();
    const relativePos = getRelativePosition(
      FlowsheetSurfaceState,
      pos.x,
      pos.y,
    );
    const objCoordMap = new Map<number, { x: number; y: number }>();
    const containedObjects = selectionRect.containedObjects;
    containedObjects.forEach((objId) => {
      const gObj = graphicsObjects!.find(
        (graphicObj) => graphicObj.simulationObject.id === objId,
      )!;
      objCoordMap.set(objId, { x: +(gObj.x ?? 0), y: +(gObj.y ?? 0) });
    });
 
    // set the offset between the selection rectangle and the position of the mouse
    setSelectionRect({
      ...selectionRect,
      offsetX: relativePos.x - selectionRect.x,
      offsetY: relativePos.y - selectionRect.y,
      xInitial: relativePos.x,
      yInitial: relativePos.y,
      objCoordMap: objCoordMap,
    });
  };
 
  //optimistically update the position of all selected objects in the selection rectangle
  const onDragSelectionMove = (e) => {
    const stage = e.target.getStage();
    const pos = stage.getPointerPosition();
    const relativePos = getRelativePosition(
      FlowsheetSurfaceState,
      pos.x,
      pos.y,
    );
    //update the offset for each object in the selection rectangle to be moved
    const newOffX = relativePos.x - selectionRect.x;
    const newOffY = relativePos.y - selectionRect.y;
    //optimistic update for all selected simulation objects
    dispatch(
      api.util.updateQueryData(
        "graphicsObjectsList",
        { group: groupId },
        (graphicObjects: GraphicObjectRead[]) => {
          // update the position of all selected objects in the selection
          const containedObjects = selectionRect.containedObjects;
          containedObjects.forEach((objId) => {
            const gObj = graphicObjects.find(
              (graphicObj) => graphicObj.simulationObject.id === objId,
            )!;
            gObj.x =
              selectionRect.objCoordMap.get(objId)!.x +
              relativePos.x -
              selectionRect.xInitial;
            gObj.y =
              selectionRect.objCoordMap.get(objId)!.y +
              relativePos.y -
              selectionRect.yInitial;
          });
        },
      ),
    );
    setSelectionRect({
      ...selectionRect,
      offsetX: newOffX,
      offsetY: newOffY,
    });
  };
 
  //update the position of all selected objects in the selection
  const onDragSelectionEnd = (e) => {
    const stage = e.target.getStage();
    const pos = stage.getPointerPosition();
    const relativePos = getRelativePosition(
      FlowsheetSurfaceState,
      pos.x,
      pos.y,
    );
 
    // Get the first object as the main object
    const mainObjectId = selectionRect.containedObjects[0];
    const mainGraphicObj = graphicsObjects!.find(
      (graphicObj) => graphicObj.simulationObject.id === mainObjectId,
    );
 
    const offset = {
      x: relativePos.x - selectionRect.xInitial,
      y: relativePos.y - selectionRect.yInitial,
    };
 
    const moveCommand = createMoveCommand({
      objectId: mainObjectId,
      graphicObjectId: mainGraphicObj!.id,
      oldPosition: selectionRect.objCoordMap.get(mainObjectId)!,
      newPosition: {
        x: selectionRect.objCoordMap.get(mainObjectId)!.x + offset.x,
        y: selectionRect.objCoordMap.get(mainObjectId)!.y + offset.y,
      },
      groupObjects: selectionRect.containedObjects.slice(1).map((objId) => {
        const gObj = graphicsObjects!.find(
          (graphicObj) => graphicObj.simulationObject.id === objId,
        );
        return {
          objectId: objId,
          graphicObjectId: gObj!.id,
          oldPosition: selectionRect.objCoordMap.get(objId)!,
          newPosition: {
            x: selectionRect.objCoordMap.get(objId)!.x + offset.x,
            y: selectionRect.objCoordMap.get(objId)!.y + offset.y,
          },
        };
      }),
    });
 
    // 🎯 ALTERNATIVE 3: Check Ready State Before Adding Commands
    if (isReady) {
      addHistory(moveCommand);
    I} else if (process.env.NODE_ENV === "development") {
      console.warn("[UndoRedo] Move command skipped - context not ready");
    }
 
    // Update backend about the move
    updateSelectionRect({
      selectionRectangle: {
        containedObjects: selectionRect.containedObjects,
        deltaX: offset.x,
        deltaY: offset.y,
      },
    });
  };
 
  if (!selectionRect.selectVisible) return;
  return (
    <Rect
      draggable={true}
      onPointerDown={onDragSelectionStart}
      ondragmove={onDragSelectionMove}
      onDragEnd={onDragSelectionEnd}
      x={selectionRect.x}
      y={selectionRect.y}
      width={selectionRect.width}
      height={selectionRect.height}
      stroke="#0088FF"
      strokeWidth={1}
      fill="#0088FF50"
    />
  );
};