All files / src/hooks flowsheetObjects.ts

76.08% Statements 175/230
64.47% Branches 49/76
82.81% Functions 53/64
75.9% Lines 167/220

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                                                37612x 37612x           37612x 2267x   35345x         51574x 51574x       41245x 41245x 39195x 39195x 39135x       265361x 265361x           265361x       90014x 90014x           90014x             28x 28x   28x 52x 52x             169614x           169614x       163311x 163311x       10857x 10857x   10857x   10489x 14974x   14974x                   164314x 164314x     164314x             82139x 82139x 867987x 82139x             45925x 45925x 45925x 389089x   45925x               153412x 153412x 153412x   153412x 1588430x   153412x 1135483x 1135483x 977017x     153412x                 75332x 75332x 2x 2x   2x   2x 1x   1x                                                               41401x 41401x           41401x               41400x 41400x 41400x 60890x     60890x   60890x                   553645x 553645x 553645x 537281x 3144x 3144x           553645x         39254x   39254x 39254x 349591x 349591x 38717x   349591x   39254x 1x           39254x 39254x 39254x 1x 1x 1x           1x                 4292x 4292x 5211x 7043x                                                                   49707x 409596x                     40529x 40529x 40529x 62249x   40529x 1x         34308x 34308x 34308x 40977x   34308x 29924x         29820x 29820x 29820x           191x 191x 191x 191x 1307x   191x 191x   99x     92x                                                         4308x     4308x           4308x   4062x                     4292x 4292x   4292x   18x 18x 6x 6x 3x 3x     4292x       15x 15x     15x 15x 15x 15x     4292x 18x 18x 3x 3x           15x 15x                             4297x 4297x 4297x 4297x   4297x   114x 66x 24x   66x 52x           52x     52x 52x 52x 52x                
import {
  GraphicObjectRead,
  Grouping,
  GroupingRead,
  ObjectTypeEnum,
  PortRead,
  SimulationObjectRead,
  useCoreProcesspathListQuery,
  useGraphicsgroupingsBreadcrumbsRetrieveQuery,
  useGraphicsgroupingsListQuery,
  useGraphicsObjectsListQuery,
  useUnitopsPortsListQuery,
  useUnitopsSimulationobjectsListQuery,
  useUnitopsSimulationobjectsRetrieveQuery,
} from "@/api/apiStore.gen";
import objects from "@/data/objects.json";
import { useProject, useProjectId } from "@/hooks/project";
import { useSearchParam } from "@/hooks/searchParams";
import { useEffect, useRef } from "react";
import { ContentTypes } from "../pages/flowsheet-page/flowsheet/LeftSideBar/LeftSideBarTabDefinitions";
import { LocalTab } from "./localTabModels";
import { useObjectConnectedToRecycle } from "./recycleData";
 
export function useCurrentObject() {
  const [currentObjectId] = useSearchParam("object");
  const { data: object } = useUnitopsSimulationobjectsRetrieveQuery(
    {
      id: +currentObjectId!,
    },
    { skip: !currentObjectId },
  );
  if (!currentObjectId) {
    return undefined;
  }
  return object;
}
 
export function useCurrentObjectId() {
  // assumes that object id is not undefined
  const [currentObjectId] = useSearchParam("object");
  return +currentObjectId!;
}
 
export function useObjectSchema(objectId?: number) {
  const simulationObjectIdMap = useFlowsheetObjectsIdMap();
  if (!objectId) return undefined;
  const simulationObject = simulationObjectIdMap.get(objectId);
  if (!simulationObject) return undefined;
  return objects[simulationObject.objectType!];
}
 
export function useFlowsheetUnitOps(): SimulationObjectRead[] | undefined {
  const flowsheetId = useProjectId();
  const { data: simulationObjects } = useUnitopsSimulationobjectsListQuery(
    {
      flowsheet: flowsheetId,
    },
    { skip: !flowsheetId },
  );
  return simulationObjects;
}
 
export function useFlowsheetGroups(): GroupingRead[] | undefined {
  const flowsheetId = useProjectId();
  const { data: Groups } = useGraphicsgroupingsListQuery(
    {
      flowsheet: flowsheetId,
    },
    { skip: !flowsheetId },
  );
  return Groups;
}
 
export interface GroupWithObject extends GroupingRead {
  simulationObjectRead: SimulationObjectRead | undefined;
}
export function useFlowsheetGroupsWithSimulationObjects(){
  const groups = useFlowsheetGroups();
  const flowsheetObjectIdMap = useFlowsheetObjectsIdMap();
 
  return groups?.map((group) => {
    const simulationObjectRead = flowsheetObjectIdMap.get(group.simulationObject);
    return { ...group, simulationObjectRead };
  });
}
 
export function useGroupGraphicsObjects(
  groupId,
): GraphicObjectRead[] | undefined {
  const { data: graphicObjects } = useGraphicsObjectsListQuery(
    {
      group: groupId,
    },
    { skip: !groupId },
  );
  return graphicObjects;
}
 
export function useGraphicsObjects(): GraphicObjectRead[] | undefined {
  const currentGroup = useCurrentGroupId();
  return useGroupGraphicsObjects(currentGroup);
}
 
export function useFlowsheetTabs(): LocalTab[] {
  const flowsheetId = useProjectId();
  const groups = useFlowsheetGroups();
 
  if (!groups) return [];
 
  return groups.map((group) => {
    const groupId = group.id;
 
    return {
      id: groupId,
      type: ContentTypes.flowsheet,
      tabOwner: groupId,
      flowsheet: flowsheetId,
    };
  });
}
 
export function useFlowsheetPorts() {
  const flowsheetId = useProjectId();
  const { data: ports } = useUnitopsPortsListQuery({
    flowsheet: flowsheetId,
  });
  return ports;
}
 
/**
 * @returns A map of object IDs to the simulation object
 */
export function useFlowsheetObjectsIdMap(): Map<number, SimulationObjectRead> {
  const objects = useFlowsheetUnitOps();
  const objectIdMap = new Map<number, SimulationObjectRead>();
  objects?.forEach((obj) => objectIdMap.set(obj.id, obj));
  return objectIdMap;
}
 
/**
 * @returns A map of simulation object IDs to their graphic object
 */
export function useObjectsGraphicObjectsMap(): Map<number, GraphicObjectRead> {
  const graphicObjects = useGraphicsObjects();
  const simObjGraphicObjMap = new Map<number, GraphicObjectRead>(); // Map of simulation object ID to graphic object
  graphicObjects?.forEach((obj) =>
    simObjGraphicObjMap.set(obj.simulationObject.id, obj),
  );
  return simObjGraphicObjMap;
}
 
/**
 * @returns A map of unit operation IDs to an array of ports
 *   in the format of { unitOpId: [port1, port2, ...] }
 */
export function useObjectsPortsMap(): Map<number, PortRead[]> {
  const ports = useFlowsheetPorts();
  const objects = useFlowsheetUnitOps();
  const objectsPortsMap = new Map<number, PortRead[]>();
 
  objects?.forEach((obj) => {
    objectsPortsMap.set(obj.id, []);
  });
  ports?.forEach((port) => {
    objectsPortsMap.get(port.unitOp)?.push(port);
    if (port.stream) {
      objectsPortsMap.get(port.stream)?.push(port);
    }
  });
  return objectsPortsMap;
}
 
type StreamType = "floating" | "intermediate" | "product" | "feed";
/**
 * Get the type of a stream (feed, product, intermediate)
 * @returns string representing the stream type
 */
export function useStreamType(): (stream_id: number) => StreamType {
  const objectsPortsMap = useObjectsPortsMap();
  return (stream: number) => {
    const objPorts = objectsPortsMap.get(stream);
    Iif (!objPorts || objPorts.length === 0) {
      return "floating";
    I} else if (objPorts.length === 2) {
      return "intermediate";
    } else if (objPorts[0].direction === "inlet") {
      return "feed";
    } else {
      return "product";
    }
  };
}
 
/**
 * Get the type of a stream (feed, product, intermediate)
 * but takes into account recycles: streams connected to recycles
 * are classed as feed streams (ie. for the purposes of control blocks)
 * @returns string representing the stream type
 */
export function useStreamTypeWithRecycles(): (stream_id: number) => StreamType {
  const objectsPortsMap = useObjectsPortsMap();
  const objectConnectedToRecycle = useObjectConnectedToRecycle();
  return (stream: number) => {
    Iif (objectConnectedToRecycle(stream)) {
      return "feed";
    }
    const objPorts = objectsPortsMap.get(stream);
    if (!objPorts || objPorts.length === 0) {
      return "floating";
    } else if (objPorts.length === 2) {
      return "intermediate";
    } else if (objPorts[0].direction === "inlet") {
      return "feed";
    } else {
      return "product";
    }
  };
}
 
export function useFlowsheetProcessPaths() {
  const flowsheetId = useProjectId();
  const { data: processPaths } = useCoreProcesspathListQuery(
    {
      flowsheet: flowsheetId,
    },
    { skip: !flowsheetId },
  );
  return processPaths;
}
 
/**
 * Quickly lookup if a simulation object is part of a process path
 * @returns a function that takes a solution number and simulation object ID
 */
export function useProcessPathHasObject() {
  const [solutionId] = useSearchParam("solution", "-1");
  const processPaths = useFlowsheetProcessPaths();
  return (simulationObjectId: number) => {
    Iif (processPaths === undefined) {
      return false;
    }
    if (+solutionId! == -1) {
      // no process paths, assume everything is part of the solution
      return true;
    }
    const objectSet = new Set<number>();
    const solution = processPaths[+solutionId!];
    solution?.pathwayObjects.forEach((obj) => objectSet.add(obj));
    return objectSet.has(simulationObjectId);
  };
}
 
export function useCurrentGroupId() {
  const [currentGroupId, setCurrentGroupId] = useSearchParam("parentGroup");
  const project = useProject();
  useEffect(() => {
    if (project && !currentGroupId) {
      try {
        setCurrentGroupId(project.rootGrouping);
      } catch (error) {
        console.warn("Failed to update URL parameter:", error);
      }
    }
  }, [project, currentGroupId, setCurrentGroupId]);
  return currentGroupId ? +currentGroupId : -1;
}
 
export function useSimulationObjectGroupMap(): (groupId: number) => number[] {
  //map group id to simualtion object IDs
  const simulationObjectGroupMap = new Map<number, number[]>();
 
  const graphicObjects = useGraphicsObjects();
  graphicObjects?.forEach((obj) => {
    const group = obj.group!;
    if (!simulationObjectGroupMap.has(group)) {
      simulationObjectGroupMap.set(group, []);
    }
    simulationObjectGroupMap.get(group)!.push(obj.id);
  });
  return (groupId: number) => {
    return simulationObjectGroupMap.get(groupId) || [];
  };
}
 
export function useGroupObjects(): (groupId: number) => SimulationObjectRead[] {
  // TODO: Remove all instances of this method, pretty sure it's broken. replaced wtih new group stuff.
  const simulationObjectIdMap = useFlowsheetObjectsIdMap();
  const simulationObjectGroupMap = useSimulationObjectGroupMap();
  return (groupId: number) => {
    const simulationObjectIds = simulationObjectGroupMap(groupId);
    const objects: SimulationObjectRead[] = [];
    simulationObjectIds.forEach((id) => {
      const obj = simulationObjectIdMap.get(id);
      Iif (obj) {
        objects.push(obj);
      }
    });
    return objects;
  };
}
 
/**
 * Returns the group object for a group simulation object
 * @returns Group object related to simulation object
 */
export function useGetGroupFromSimobject() {
  const groups: GroupingRead[] | undefined = useFlowsheetGroups();
  return (simulationObjectID) => {
    return groups?.find(
      (group) => group.simulationObject === simulationObjectID,
    );
  };
}
 
export function useFindDirectChildOfCurrentGroup() {
  const getHigherLevelParent = useGetHigherLevelParent();
  const getSimGroup = useSimulationObjectGroup();
  const currGroup = useCurrentGroupId();
  const currGroups = useCurrentGroupObjects()
    .filter(
      (obj) =>
        obj.objectType == ObjectTypeEnum.Group ||
        obj.objectType == ObjectTypeEnum.Grouping,
    )
    .map((obj) => getSimGroup(obj.id)?.id);
 
  return (groupID: number): number | null => {
    Iif (!getHigherLevelParent || !currGroups || currGroup === undefined)
      return null;
 
    let currentGroup: number | null = groupID;
 
    while (currentGroup && currentGroup !== currGroup) {
      Iif (currGroups.includes(currentGroup)) {
        return currentGroup;
      }
      currentGroup = getHigherLevelParent(currentGroup) ?? null;
    }
    return null;
  };
}
 
export function useCurrentGroupObjects(): SimulationObjectRead[] {
  const graphicObjects = useGraphicsObjects();
  return graphicObjects?.map((obj) => obj.simulationObject) || [];
}
 
export function useSelectedObjectGroup() {
  const selectedObjectId = useCurrentObjectId();
  const simulationObjectGroup = useSimulationObjectGroup();
  const group = simulationObjectGroup(selectedObjectId);
  return group;
}
 
export function useSimulationObjectGroup() {
  const groups = useFlowsheetGroups();
  const groupMap = new Map<number, GroupingRead>();
  groups?.forEach((group) => {
    groupMap.set(group.simulationObject, group);
  });
  return (simulationObjectId: number) => {
    return groupMap.get(simulationObjectId);
  };
}
 
export function useGroup() {
  const groups = useFlowsheetGroups();
  const groupMap = new Map<number, GroupingRead>();
  groups?.forEach((group) => {
    groupMap.set(group.id, group);
  });
  return (groupId: number) => {
    return groupMap.get(groupId);
  };
}
 
export function useCurrentGroup() {
  const currentGroupId = useCurrentGroupId();
  const getGroup = useGroup();
  return currentGroupId ? getGroup(+currentGroupId) : undefined;
}
 
export function useSelectedGroup(): GroupingRead | undefined {
  // If a flowsheet, module, or group simulationobject is selected, this returns the group for that module.
  // otherwise, it returns the current group.
  const currentGroup = useCurrentGroup()
  const getGroup = useGroup();
  const currentObjectId = useCurrentObjectId();
  const groupingSimulationObject = useCurrentGroupObjects()?.filter(
    (obj) => obj.id == currentObjectId,
  )[0]; 
  const groupId = groupingSimulationObject?.groupId;
  if (groupId) {
    // there is a currently selected group, return that one
    return getGroup(+groupId);
  }else {
    // return the current group we are in.
    return currentGroup;
  }
 
 
}
 
export function useGetHigherLevelParent() {
  const getGroup = useGroup();
  const simulationObjectIdMap = useFlowsheetObjectsIdMap();
 
  return (groupID: number) => {
    const group = getGroup(groupID);
    Iif (!group) {
      return groupID;
    }
    const simulationObjectId = group.simulationObject;
    const obj = simulationObjectIdMap.get(simulationObjectId!);
    const nextGroupId = obj?.graphicObject.group;
 
    return nextGroupId;
  };
}
 
/**
 * Get the breadcrumbs for the current group
 * @returns list of group ids representing the path to the current group
 */
export function useBreadcrumbs() {
  // get the list of breadcrukmbs from the backend end point
  const groupId = useCurrentGroupId();
  // map the breadcrumb list to just return the list of ids
  const { data: breadcrumbsList } =
    useGraphicsgroupingsBreadcrumbsRetrieveQuery(
      {
        group: groupId,
      },
      { skip: !groupId },
    );
  if (breadcrumbsList === undefined) return [];
  // return the gorup ids
  return breadcrumbsList;
}
 
export function useUpdateCoordinatesOnSwitchGroup(
  setFlowsheetSurfaceState,
  zoomToFit: (groupId: number) => {
    newScale: number;
    newStageX: number;
    newStageY: number;
  },
) {
  const projectId = useProjectId();
  const storageKey = "flowsheetCoordinates";
 
  const getFromLocalStorage = (groupId: string) => {
    // use the session storage to set the initial coordinates, or return false to zoom to fit
    const coordinates = sessionStorage.getItem(storageKey);
    if (!coordinates || !projectId || !groupId) return false;
    const parsedCoordinates = JSON.parse(coordinates);
    if (!parsedCoordinates[projectId] || !parsedCoordinates[projectId][groupId])
      return false;
    return parsedCoordinates[projectId][groupId];
  };
 
  const saveToLocalStorage = (
    groupId: string,
    coordinates: { x: string; y: string; scale: string },
  ) => {
    Iif (!projectId || !groupId) return;
    const storedCoordinates = JSON.parse(
      sessionStorage.getItem(storageKey) || "{}",
    );
    const projectCoordinates = storedCoordinates[projectId] || {};
    projectCoordinates[groupId] = coordinates;
    storedCoordinates[projectId] = projectCoordinates;
    sessionStorage.setItem(storageKey, JSON.stringify(storedCoordinates));
  };
 
  return (groupId: string) => {
    const storedCoordinates = getFromLocalStorage(groupId);
    if (storedCoordinates) {
      const { x, y, scale } = storedCoordinates;
      setFlowsheetSurfaceState({
        scale: parseFloat(scale) / 100,
        stageX: parseFloat(x),
        stageY: parseFloat(y),
      });
    } else {
      const { newScale, newStageX, newStageY } = zoomToFit(+groupId);
      saveToLocalStorage(groupId, {
        x: newStageX.toFixed(0),
        y: newStageY.toFixed(0),
        scale: (newScale * 100).toFixed(0),
      });
    }
  };
}
 
/**
 * This hook manages the coordinates and scale of the flowsheet and stores
 * them in session storage.
 */
export function useTrackCoordinates(FlowsheetSurfaceState, loading) {
  const updateCoordinatesTimeout: React.MutableRefObject<NodeJS.Timeout | null> =
    useRef(null);
  const projectId = useProjectId();
  const currentGroupId = useCurrentGroupId();
  const storageKey = "flowsheetCoordinates";
 
  useEffect(() => {
    // update the coordinates whenever the flowsheet surface state (x, y, scale) changes (after a debounce)
    if (loading || !currentGroupId) return;
    if (updateCoordinatesTimeout.current) {
      clearTimeout(updateCoordinatesTimeout.current);
    }
    updateCoordinatesTimeout.current = setTimeout(() => {
      const coordinates = {
        x: FlowsheetSurfaceState.stageX.toFixed(0),
        y: FlowsheetSurfaceState.stageY.toFixed(0),
        scale: (FlowsheetSurfaceState.scale * 100).toFixed(0),
      };
      // store the coordinates for the current project and group
      const storedCoordinates = JSON.parse(
        sessionStorage.getItem(storageKey) || "{}",
      );
      const projectCoordinates = storedCoordinates[projectId] || {};
      projectCoordinates[currentGroupId] = coordinates;
      storedCoordinates[projectId] = projectCoordinates;
      sessionStorage.setItem(storageKey, JSON.stringify(storedCoordinates));
    }, 300);
  }, [
    FlowsheetSurfaceState.stageX,
    FlowsheetSurfaceState.stageY,
    FlowsheetSurfaceState.scale,
  ]);
}