All files / src/hooks flowsheetObjects.ts

68.82% Statements 234/340
65.54% Branches 78/119
65.57% Functions 40/61
79.47% Lines 182/229

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                                                71965x 71965x 71965x 14776x 71965x 86741x 78947x   6312x   65653x           41982x         22453x 2690x 19763x 19732x       160506x     160506x 160506x 9599x   170105x 170105x 160506x       128667x 128667x 128667x 5090x   133757x 133757x 128667x             9x 9x 9x   4x 7x   7x   17x     61184x     61184x 1611x   62795x 62774x 61184x         58398x       34626x 34626x 34626x   1760x   1829x 2631x               36524x     118836x 118836x 118836x   124561x               26x 26x 58x             34809x       34809x 7997x 70951x             8015x 8015x 566x 566x 2487x 8581x               99693x 99693x 99693x 15620x   15620x 116242x   15620x 85358x   71371x   130933x                 46844x 46844x   21429x 266x   2398x   14165x 4600x       55004x     44962x 44962x 44962x 386x   45348x 45348x 44962x               44959x 44959x 44959x   1733x     43226x               46199x       462914x 462914x 409812x                                                 7930x 7930x 161x 8519x 10222x   8091x     18408x 18408x 20130x                   17095x 17095x 334x 334x 243x 17429x 334x   17429x     66841x 66841x 3302x 3302x 3323x 70143x 3302x 2899x 70143x     56452x 56452x 56452x 62800x     2374x     2374x 2374x 2374x 2374x 10139x   2374x     2332x                     7960x   7960x     7960x 149x   8109x 8107x   7279x         7930x               7930x     7930x   72x 60x 12x 4x 8x   8011x   7930x         64x     64x 64x 64x 64x 8011x     72x   8x 8x           64x 64x           39650x             8015x   8015x 8015x 8015x     8015x   81x       8x 8x           8x     8x 8x 8x 8x   9377x       8282x    
import { useEffect, useRef } from "react";
import {
  GraphicObjectRead,
  Grouping,
  GroupingRead,
  ObjectTypeEnum,
  PortRead,
  SimulationObjectRead,
  SimulationObjectRetrieveRead,
  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 { 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();
  Iif (!objectId) return undefined;
  const simulationObject = simulationObjectIdMap.get(objectId);
  Iif (!simulationObject) return undefined;
  return objects[simulationObject.objectType!];
}
 
export function useFlowsheetUnitOps():
  | SimulationObjectRetrieveRead[]
  | 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: SimulationObjectRetrieveRead | 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();
 
  Iif (!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;
}
 
/**
 * @param simulationObjectId The ID of the simulation object that is currently being hovered
 * @returns string representing the port's (inlet/outlet) display name
 */
export function usePortName(simulationObjectId: number): string {
  const ports = useFlowsheetPorts();
  const port = ports?.find((port) => port.stream === simulationObjectId);
  return port?.displayName;
}
 
/**
 * @returns A map of object IDs to the simulation object
 */
export function useFlowsheetObjectsIdMap(): Map<
  number,
  SimulationObjectRetrieveRead
> {
  const objects = useFlowsheetUnitOps();
  const objectIdMap = new Map<number, SimulationObjectRetrieveRead>();
  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);
    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) => {
    if (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();
  Iif (!currentGroupId) return project?.rootGrouping;
  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) || [];
  };
}
 
/**
 * 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 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;
  }
}
 
/**
 * 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 },
    );
  Iif (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);
    Iif (!coordinates || !projectId || !groupId) return false;
    const parsedCoordinates = JSON.parse(coordinates);
    Iif (!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)
    Iif (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,
  ]);
}