All files / src/pages/flowsheet-page/flowsheet/LeftSideBar FlowsheetObjectsContent.tsx

63.71% Statements 144/226
68.49% Branches 100/146
20.37% Functions 11/54
64% Lines 112/175

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 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550                                                                                                103x                 927x         5039x 5039x   5039x                               13703x     3542x   3044x     3542x   3044x       9630x   4622x 9630x   9630x           56x   191x   1306x         5039x               5039x 5039x 5039x 5039x 5039x   5039x   5039x 197x 197x 197x 197x     197x           17079x   5039x                       40312x   5039x     5039x 5039x                                                                                                                                         65507x 15117x       7142x             1082x 1082x 31x   1007x   1000x   4x                                                                           3x     20x               20x   11x               20x           1006x               1x                   2x 30x   3x       1007x 5000x                 7093x     851x   851x 851x       851x 851x   851x 8x       2553x   851x                               2553x   851x       1702x   851x 2x       2553x   851x         2553x   248x     851x 248x 248x 248x   248x 248x 248x       9609x 2339x     243x   243x         851x         243x                   1945x     1337x       851x           242x                 851x     2553x 851x 851x   1702x     1702x       8510x         2x           2553x 851x                       3404x                             3404x           3404x 5957x     851x         851x     5106x 5106x 5106x      
import { useRunCommand } from "just-search-it";
import { ArrowRightToLine, Search, Tag, X } from "lucide-react";
import { useState } from "react";
import { useSearchParams } from "react-router-dom";
import { ModuleMark } from "@/ahuora-design-system/componentIcons/ModuleMark";
import SelectInput from "@/ahuora-design-system/inputs/SelectInput";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/ahuora-design-system/ui/accordion";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Button } from "@/ahuora-design-system/ui/button";
import { Input } from "@/ahuora-design-system/ui/input";
import { SelectableItem } from "@/ahuora-design-system/ui/selectable-item";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import { GraphicObjectRead, ObjectTypeEnum } from "@/api/apiStore.gen";
import {
  useCurrentGroupId,
  useGroupGraphicsObjects,
  useSimulationObjectGroup,
  useStreamType,
} from "@/hooks/flowsheetObjects";
import { useSearchParam } from "@/hooks/searchParams";
import usePersistentState from "@/hooks/usePersistentState";
import { setClick } from "@/store/ClickSlice";
import { useAppDispatch } from "@/store/hooks";
import { ScrollArea } from "../../../../ahuora-design-system/ui/scroll-area";
import {
  Tabs,
  TabsList,
  TabsTrigger,
} from "../../../../ahuora-design-system/ui/tabs";
import { SwitchGroup } from "../../../../commands/SwitchCurrentGroup";
import { useFlowsheetTabFromGroupId } from "../../../../hooks/projectTabs";
import { isStream } from "../../../../lib/isStream";
import { PropertiesStatus } from "../PropertiesSidebar/PropertyPanel/PropertiesStatus";
import {
  FilterConfig,
  SortOptions,
  StatusDisplay,
  StreamDisplay,
} from "./Filterconfig";
import { ContentTypes } from "./LeftSideBarTabDefinitions";
import { ObjectsFilter } from "./ObjectsFilter";
import { PANEL_DATA } from "./PanelItems";
 
const defaultConfig: FilterConfig = {
  tagged: [],
  sorting: SortOptions.latest,
  filterUnits: [],
  streamDisplay: StreamDisplay.all,
  statusDisplay: StatusDisplay.all,
  tagDisplay: false,
};
 
const unitOpsGroups = PANEL_DATA.map((element) => ({
  label: element.label,
  objects: element.objects,
}));
 
const EndBadge = ({ item, getIdString, filterConfig, setFilterConfig }) => {
  const isModule = item.simulationObject.objectType === "group";
 
  const handleFilterArrayChanges = (key, value) => {
    if (filterConfig[key].includes(value)) {
      const updatedFilters = filterConfig[key].filter(
        (existingFilter) => existingFilter !== value,
      );
      setFilterConfig({
        ...filterConfig,
        [key]: updatedFilters,
      });
    } else {
      const updatedFilters = [...filterConfig[key], value];
      setFilterConfig({
        ...filterConfig,
        [key]: updatedFilters,
      });
    }
  };
 
  if (isStream(item.simulationObject)) {
    const isTagged = filterConfig.tagged.includes(getIdString!);
    return (
      <div className="flex items-center justify-center w-4 h-4">
        <ToolTipCover
          asChild
          content={isTagged ? "Untag Stream" : "Tag Stream"}
        >
          <Button
            variant="ghost"
            size="icon"
            className="p-0"
            onClick={() => handleFilterArrayChanges("tagged", getIdString!)}
          >
            <Tag size={16} color={isTagged ? "hsl(var(--success))" : "gray"} />
          </Button>
        </ToolTipCover>
      </div>
    );
  }
 
  if (isModule) {
    return (
      <div className="flex items-center justify-center w-4 h-4 text-emerald-600">
        <ModuleMark />
      </div>
    );
  }
 
  return null;
};
 
const FlowsheetObjectItem = ({
  item,
  getIdString,
  filterConfig,
  setFilterConfig,
  type,
  searchedObj,
}) => {
  const dispatch = useAppDispatch();
  const [objectID, setObjectID] = useSearchParam("object");
  const [, setSearchParams] = useSearchParams();
  const switchGroup = useRunCommand(SwitchGroup);
  const getFlowsheetTabFromGroupId = useFlowsheetTabFromGroupId();
 
  const isSelected = getIdString == objectID;
 
  const handleShowProperties = () => {
    setSearchParams((prev) => {
      const newParams = new URLSearchParams(prev);
      newParams.set("object", getIdString);
      newParams.set("content", ContentTypes.objectDetails);
      return newParams;
    });
    dispatch(
      setClick({
        type: item.simulationObject.objectType!,
        id: parseInt(getIdString, 10),
      }),
    );
  };
 
  const handleGoToObject = () => {
    setObjectID(getIdString);
    const flowsheetTab = getFlowsheetTabFromGroupId(item.group!);
    if (flowsheetTab) {
      switchGroup(flowsheetTab.id);
    }
    dispatch(
      setClick({
        type: item.simulationObject.objectType!,
        id: +getIdString,
      }),
    );
  };
 
  const simulationObject = item.simulationObject;
 
  return (
    <div key={`${getIdString}-${simulationObject.componentName}`}>
      {simulationObject.objectType == ObjectTypeEnum.Group ? (
        <Accordion type="single" collapsible className="w-full">
          <AccordionItem value={getIdString}>
            <AccordionTrigger variant="objectPanel">
              <div
                className="flex items-center justify-between w-full"
                onDoubleClick={handleGoToObject}
                aria-label={`flowsheetObject-${simulationObject.componentName}`}
              >
                <div className="flex items-center gap-2">
                  <PropertiesStatus
                    propertySet={simulationObject.unspecifiedProperties}
                  />
                  <p>{simulationObject.componentName}</p>
                </div>
                <EndBadge
                  item={item}
                  getIdString={getIdString}
                  filterConfig={filterConfig}
                  setFilterConfig={setFilterConfig}
                />
              </div>
            </AccordionTrigger>
            <AccordionContent className="p-0 relative border-l border-border ml-3">
              <SelectableItem
                isSelected={false}
                startIcon={<ArrowRightToLine className="mx-2" />}
                name={"Go to " + simulationObject.componentName}
                onClick={handleGoToObject}
              />
              <SelectableItem
                isSelected={false}
                startIcon={<ArrowRightToLine className="mx-2" />}
                name={"Show " + simulationObject.componentName + " Details"}
                onClick={handleShowProperties}
              />
              <GroupItem
                groupId={item.simulationObject.groupId}
                filterConfig={filterConfig}
                setFilterConfig={setFilterConfig}
                type={type}
                searchedObj={searchedObj}
              />
            </AccordionContent>
          </AccordionItem>
        </Accordion>
      ) : (
        <SelectableItem
          name={simulationObject?.componentName}
          onClick={handleShowProperties}
          onDoubleClick={handleGoToObject}
          isSelected={isSelected}
          startIcon={
            <div className="flex items-center mr-2">
              <PropertiesStatus
                propertySet={simulationObject.unspecifiedProperties}
              />
            </div>
          }
          endIcon={
            <EndBadge
              item={item}
              getIdString={getIdString}
              filterConfig={filterConfig}
              setFilterConfig={setFilterConfig}
            />
          }
          aria-label={`flowsheetObject-${simulationObject.componentName}`}
        />
      )}
    </div>
  );
};
 
const GroupItem = ({
  groupId,
  filterConfig,
  setFilterConfig,
  type,
  searchedObj,
}) => {
  const streamType = useStreamType();
  const objects = useGroupGraphicsObjects(groupId);
  Iif (objects == undefined) return null;
 
  let filteredObjs = objects;
  if (type === "all") {
    filteredObjs = objects;
  } else if (type === "Unit Operations") {
    filteredObjs = objects.filter((obj) => !isStream(obj.simulationObject));
    if (filterConfig.filterUnits.length > 0) {
      if (filterConfig.filterUnits.includes("Groups")) {
        const groupObjects = objects.filter(
          (obj) => obj.simulationObject.objectType === "group",
        );
        const otherFilteredObjects = filterConfig.filterUnits
          .filter((filter) => filter !== "Groups")
          .map((element) => {
            const group = unitOpsGroups.find(
              (group) => group.label === element,
            );
            if (group) {
              return objects.filter((unitOp) =>
                group.objects.includes(unitOp.simulationObject.objectType),
              );
            }
            return [];
          })
          .flat();
        filteredObjs = [...groupObjects, ...otherFilteredObjects];
      } else {
        filteredObjs = filterConfig.filterUnits
          .map((element) => {
            const group = unitOpsGroups.find(
              (group) => group.label === element,
            );
            if (group) {
              return objects.filter((unitOp) =>
                group.objects.includes(unitOp.simulationObject.objectType),
              );
            }
            return [];
          })
          .flat();
      }
    }
  } else if (type === "streams") {
    filteredObjs = objects
      .filter((obj) => isStream(obj.simulationObject))
      .filter((stream) => {
        const isStreamTagged = filterConfig.tagged.includes(
          stream.simulationObject.id?.toString(),
        );
        Iif (filterConfig.tagDisplay && !isStreamTagged) return false;
        if (filterConfig.streamDisplay === StreamDisplay.feeds) {
          return streamType(stream.simulationObject.id) === "feed";
        } else if (filterConfig.streamDisplay === StreamDisplay.products) {
          return streamType(stream.simulationObject.id) === "product";
        }
        return true;
      });
  }
 
  if (filterConfig.statusDisplay === StatusDisplay.defined) {
    filteredObjs = filteredObjs.filter((item) => {
      return item.simulationObject.unspecifiedProperties.length === 0;
    });
  } else if (filterConfig.statusDisplay === StatusDisplay.underdefined) {
    filteredObjs = filteredObjs.filter((item) => {
      return item.simulationObject.unspecifiedProperties.length > 0;
    });
  }
 
  if (filterConfig.sorting === SortOptions.latest) {
    filteredObjs = filteredObjs
      .slice()
      .sort((a, b) =>
        a.simulationObject.id && b.simulationObject.id
          ? b.simulationObject.id - a.simulationObject.id
          : b.simulationObject.id - a.simulationObject.id,
      );
  } else {
    filteredObjs = filteredObjs
      .slice()
      .sort((a, b) =>
        a.simulationObject.componentName!.localeCompare(
          b.simulationObject.componentName!,
        ),
      );
  }
 
  if (searchedObj.length > 0) {
    filteredObjs = filteredObjs.filter((item) =>
      item.simulationObject
        .componentName!.toLowerCase()
        .includes(searchedObj.toLowerCase()),
    );
  }
 
  return filteredObjs?.map((obj) => (
    <FlowsheetObjectItem
      key={obj.simulationObject.id}
      item={obj}
      getIdString={obj.simulationObject.id?.toString()}
      filterConfig={filterConfig}
      setFilterConfig={setFilterConfig}
      type={type}
      searchedObj={searchedObj}
    />
  ));
};
 
export default function FlowsheetObjectsContent() {
  const editable = true;
  const [currTab, setCurrTab] = useState("all");
  const [filterConfig, setFilterConfig] = usePersistentState(
    "config",
    defaultConfig,
  );
  const [searchedObj, setSearchedObj] = useState("");
  const groupId = useCurrentGroupId();
 
  const toggleDisplay = (value, type) => {
    setFilterConfig({
      ...filterConfig,
      [type]: value,
    });
  };
 
  const handleFilterArrayChanges = (key, value) => {
    if (filterConfig[key].includes(value)) {
      const updatedFilters = filterConfig[key].filter(
        (existingFilter) => existingFilter !== value,
      );
      setFilterConfig({
        ...filterConfig,
        [key]: updatedFilters,
      });
    } else {
      const updatedFilters = [...filterConfig[key], value];
      setFilterConfig({
        ...filterConfig,
        [key]: updatedFilters,
      });
    }
  };
 
  const handleSelectedUnits = (value) => {
    value.forEach((element) => {
      handleFilterArrayChanges("filterUnits", element);
    });
  };
 
  const setSortDisplay = (selected) => {
    setFilterConfig({
      ...filterConfig,
      sorting: selected,
    });
  };
 
  const handleTagDisplay = () => {
    setFilterConfig({
      ...filterConfig,
      tagDisplay: !filterConfig.tagDisplay,
    });
  };
 
  const objectTabs = ["all", "Unit Operations", "streams"];
 
  return (
    <Tabs
      className="flex flex-col h-full w-full"
      value={currTab}
      onValueChange={setCurrTab}
    >
      <div className="flex flex-col h-full w-full pt-2">
        <TabsList type="hShort" bg="default" rounded="yes" className="mx-2">
          {objectTabs.map((tab) => (
            <TabsTrigger value={tab} key={tab}>
              {tab.charAt(0).toUpperCase() + tab.slice(1)}
            </TabsTrigger>
          ))}
        </TabsList>
 
        {/* Header with search and filters */}
        <div className="px-4 items-center flex flex-wrap justify-between gap-4 mt-4">
          <div className="relative flex-1">
            <Input
              name="search"
              placeholder="Search flowsheet objects"
              type="text"
              startIcon={Search}
              onChange={(e) => setSearchedObj(e.target.value)}
              value={searchedObj}
              className="w-full pr-10"
              aria-label="search-flowsheetObjectsContent"
            />
            {searchedObj && (
              <Button
                variant="ghost"
                size="icon"
                className="absolute right-1 top-1/2 transform -translate-y-1/2 hover:bg-transparent hover:text-neutral-500"
                onClick={() => setSearchedObj("")}
                aria-label="Clear search"
              >
                <X size={16} />
              </Button>
            )}
          </div>
          {/* You can put quick filter controls here if you want side-by-side layout */}
        </div>
 
        {/* Filters badges and controls */}
        <div className="flex flex-wrap w-full mx-4 gap-2 items-center">
          <div className="lg:w-44 md:w-40 sm:w-full  items-center gap-2">
            <SelectInput
              ariaLabel="flowsheetObjectsContent-sort-by"
              handleChange={setSortDisplay}
              disabled={!editable}
              title={"Sort by"}
              data={[
                {
                  label: SortOptions.latest,
                  value: SortOptions.latest,
                },
                {
                  label: SortOptions.alphabetical,
                  value: SortOptions.alphabetical,
                },
              ]}
              value={filterConfig.sorting}
            />
          </div>
          <ObjectsFilter
            activeTab={currTab as "streams" | "Unit Operations" | "all"}
            selectedStat={filterConfig.statusDisplay}
            setSelectedStat={(value) => toggleDisplay(value, "statusDisplay")}
            unitsFiltered={filterConfig.filterUnits}
            setUnitsFiltered={handleSelectedUnits}
            setStreamFilter={(value) => toggleDisplay(value, "streamDisplay")}
            streamFilter={filterConfig.streamDisplay}
            setIsTagged={handleTagDisplay}
            isTagged={filterConfig.tagDisplay}
          />
          {filterConfig.statusDisplay !== "All" && (
            <Badge
              variant="secondary"
              size="sm"
              onClick={() => toggleDisplay(StatusDisplay.all, "statusDisplay")}
              aria-label={`filter-object-close-${filterConfig.statusDisplay}`}
            >
              {filterConfig.statusDisplay}
              <X className="ml-1 w-4 h-4" />
            </Badge>
          )}
          {filterConfig.filterUnits.length > 0 &&
            currTab === "Unit Operations" &&
            filterConfig.filterUnits.map((unit) => (
              <Badge
                key={unit}
                variant="secondary"
                size="sm"
                onClick={() => handleFilterArrayChanges("filterUnits", unit)}
              >
                <span className="text-balance">{unit}</span>
                <X className="w-4 h-4" />
              </Badge>
            ))}
          {filterConfig.streamDisplay !== StreamDisplay.all &&
            currTab === "streams" && (
              <Badge
                variant="secondary"
                size="sm"
                onClick={() =>
                  toggleDisplay(StreamDisplay.all, "streamDisplay")
                }
              >
                <span className="text-balance">
                  {filterConfig.streamDisplay}
                </span>
                <X className="w-4 h-4" />
              </Badge>
            )}
          {filterConfig.tagDisplay && currTab === "streams" && (
            <Badge variant="secondary" size="sm" onClick={handleTagDisplay}>
              <span className="text-balance">Tagged</span>
              <X className="w-4 h-4" />
            </Badge>
          )}
        </div>
 
        {/* Scrollable content area */}
        <ScrollArea className="flex-1">
          <GroupItem
            groupId={groupId}
            filterConfig={filterConfig}
            setFilterConfig={setFilterConfig}
            type={currTab as "all" | "Unit Operations" | "streams"}
            searchedObj={searchedObj}
          />
        </ScrollArea>
      </div>
    </Tabs>
  );
}