All files / src/hooks flowsheetObjects.ts

68.71% Statements 235/342
65.07% Branches 82/126
64.51% Functions 40/62
78.63% Lines 184/234

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                                            94009x 94009x 94009x 16499x 94009x 110508x 101972x   7186x   86823x           52131x         25159x 3258x 21901x 21818x       157733x     157733x 157733x 10847x   168580x 168515x 157733x       167713x 167713x 167713x 6352x   174065x 173950x 167713x             17x 17x 17x   8x 11x   11x   33x     73711x     73711x 2364x   76075x 76020x 73711x         69965x       47447x 47447x 47447x   2754x   2194x 2948x               49081x     104948x 104948x 104948x   111254x               39x 39x 77x             42239x       42239x   8159x 70565x               10681x 10681x 714x 714x 3030x 11395x               80929x 80929x 80929x 14602x   14602x 109121x   14602x 80023x   67208x   110133x                 52001x 52001x   28632x 349x   3301x   18663x 6319x       59864x     67506x 67506x 67506x 67506x 572x   68078x 68066x 67506x               67503x 67503x 67503x   860x                     69223x       430523x 430523x 430523x 59552x   370971x                                                 10523x 10523x 255x 11192x 13309x   10778x     24713x 24713x 26891x                   21675x 21675x 527x 527x 403x 22202x 527x   22202x     85439x 85439x 4177x 4177x 4048x 89616x 4177x 3335x 89616x     71410x 71410x 71410x 79366x     3348x     3348x 3348x 3348x 3348x 14170x   3348x     3269x                     2348x   2348x     2348x 233x   2581x 2576x   1915x         10523x               10523x     10523x   90x 73x 17x 9x 8x   10668x   10523x         82x     82x 82x 82x 82x 10668x     90x   8x 8x           82x 82x           52615x             10681x   10681x 10681x 10681x     10681x   136x       8x 7x           7x     7x 7x 7x 7x   12829x       11113x    
import { useEffect, useMemo, useRef } from "react";
import {
  GraphicObjectRead,
  GroupingRead,
  PortRead,
  SimulationObjectRead,
  SimulationObjectRetrieveRead,
  useCoreProcesspathListQuery,
  useGraphicsgroupingsBreadcrumbsRetrieveQuery,
  useGraphicsgroupingsListQuery,
  useGraphicsObjectsListQuery,
  useUnitopsPortsListQuery,
  useUnitopsSimulationobjectsListQuery,
  useUnitopsSimulationobjectsRetrieveQuery,
} from "@/api/apiStore.gen";
import objects from "@/data/unitOpConfigs";
import { useFlowsheetRevisionPreview } from "@/hooks/flowsheetRevisionPreview";
import { useFlowsheet, useFlowsheetId } from "@/hooks/project";
import { useSearchParam } from "@/hooks/searchParams";
import { ContentTypes } from "../pages/flowsheet-page/flowsheet/LeftSideBar/LeftSideBarTabDefinitions";
import { LocalTab } from "./localTabModels";
 
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 = useFlowsheetId();
  const { data: simulationObjects } = useUnitopsSimulationobjectsListQuery(
    {
      flowsheet: flowsheetId,
    },
    { skip: !flowsheetId },
  );
  return simulationObjects;
}
 
export function useFlowsheetGroups(): GroupingRead[] | undefined {
  const flowsheetId = useFlowsheetId();
  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 = useFlowsheetId();
  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 = useFlowsheetId();
  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();
  return useMemo(() => {
    const objectIdMap = new Map<number, SimulationObjectRetrieveRead>();
    objects?.forEach((obj) => objectIdMap.set(obj.id, obj));
    return objectIdMap;
  }, [objects]);
}
 
/**
 * @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 = useFlowsheetId();
  const { isPreview } = useFlowsheetRevisionPreview();
  const { data: processPaths } = useCoreProcesspathListQuery(
    {
      flowsheet: flowsheetId,
    },
    { skip: isPreview || !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 (+solutionId! == -1) {
      // no process paths, assume everything is part of the solution
      return true;
    }
    if (processPaths === undefined) {
      return false;
    }
    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] = useSearchParam("parentGroup");
  const project = useFlowsheet();
  const { isPreview, revision } = useFlowsheetRevisionPreview();
  if (!currentGroupId) {
    return isPreview ? revision?.root_grouping_id : 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 = useFlowsheetId();
  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 = useFlowsheetId();
  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,
  ]);
}