All files / src/pages/flowsheet-page/flowsheet/PropertiesSidebar/components DataPanel.tsx

75% Statements 93/124
61.95% Branches 57/92
69.04% Functions 29/42
78.76% Lines 89/113

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                                                                                        89x       89x 40x     49x 485x                                                       89x 89x     89x     89x 89x   89x 89x 89x 89x                 89x   89x 89x       89x   89x 298x 298x   298x         72x     226x 226x 246x   226x       226x         226x     89x   89x       89x             89x         286x               89x 32x 32x 56x 56x 56x   32x   32x   4x 4x 4x           89x 32x 23x 23x 45x   27x 27x 27x   23x   9x       89x   89x     226x           89x 89x       89x 89x 88x   1x 1x     89x                                     89x       16x   16x 16x 23x       16x 16x 16x   16x                                                 16x           89x   89x       89x       127x                                       926x     16x                               89x   72x                                                                           72x                                 226x 226x   226x       7x                                                                                        
// Import necessary components and hooks
 
import type { ColumnDef } from "@tanstack/react-table";
import { HelpCircle, Search } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/ahuora-design-system/ui/accordion";
import { Button } from "@/ahuora-design-system/ui/button";
import { Checkbox } from "@/ahuora-design-system/ui/checkbox";
import { DataTable } from "@/ahuora-design-system/ui/data-table";
import { Input } from "@/ahuora-design-system/ui/input";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import { useGraphicsObjectsListQuery } from "@/api/apiStore.gen";
import {
  useFlowsheetGroups,
  useFlowsheetObjectsIdMap,
} from "@/hooks/flowsheetObjects";
import { useProjectId } from "@/hooks/project";
import { useSimulationObjectPropertySet } from "@/hooks/properties";
import { cn } from "@/lib/utils";
import { SelectedPropertyInfo } from "../ObjectDetailsPanel";
 
interface UnitOpDataType {
  id: number;
  name: string;
  selected: boolean;
}
 
interface PropertyDataType {
  id: number;
  key: string;
  displayName: string;
  value: string | number | string[] | null;
  unit?: string;
  type?: string;
}
 
function useUnitOpProperties(
  selectedUnitOpId: number | null,
): PropertyDataType[] {
  const propertySet = useSimulationObjectPropertySet(
    selectedUnitOpId ?? undefined,
  );
 
  if (!propertySet || !selectedUnitOpId) {
    return [];
  }
 
  return (
    propertySet.ContainedProperties?.map((prop) => ({
      ...prop,
      value:
        prop.values?.[0]?.value ??
        prop.values?.[0]?.displayValue ??
        prop.displayName ??
        null,
    })) ?? []
  );
}
 
interface DataPanelProps {
  setSelectedProperties: React.Dispatch<
    React.SetStateAction<SelectedPropertyInfo[]>
  >;
  selectedProperties: SelectedPropertyInfo[];
}
 
interface GroupUnitOpsDataType {
  groupId: number;
  groupName: string;
  unitOps: UnitOpDataType[];
}
 
export function DataPanel({
  setSelectedProperties,
  selectedProperties,
}: DataPanelProps) {
  const [selectedUnitOp, setSelectedUnitOp] = useState<number | null>(null);
  const [rowSelectionUnitOps, setRowSelectionUnitOps] = useState<{
    [key: string]: boolean;
  }>({});
  const [rowSelectionProperties, setRowSelectionProperties] = useState<{
    [key: string]: boolean;
  }>({});
  const [searchedObj, setSearch] = useState<string>("");
  const [openGroupIds, setOpenGroupIds] = useState<string[] | null>(null);
 
  const flowsheetId = useProjectId();
  const objectsIdMap = useFlowsheetObjectsIdMap();
  const groups = useFlowsheetGroups();
  const { data: allGraphicObjects } = useGraphicsObjectsListQuery(
    {
      flowsheet: flowsheetId,
    },
    {
      skip: !flowsheetId,
    },
  );
 
  const properties = useUnitOpProperties(selectedUnitOp);
 
  const groupedUnitOps: GroupUnitOpsDataType[] = useMemo(() => {
    Iif (!groups) {
      return [];
    }
 
    const unitOpsByGroup = new Map<number, UnitOpDataType[]>();
 
    allGraphicObjects?.forEach((graphicObject) => {
      const groupId = graphicObject.group;
      const simulationObject = graphicObject.simulationObject;
 
      if (
        !groupId ||
        !simulationObject ||
        simulationObject.objectType === "group"
      ) {
        return;
      }
 
      const existing = unitOpsByGroup.get(groupId) ?? [];
      const alreadyInGroup = existing.some(
        (obj) => obj.id === simulationObject.id,
      );
      Iif (alreadyInGroup) {
        return;
      }
 
      existing.push({
        id: simulationObject.id,
        name: simulationObject.componentName ?? `Object ${simulationObject.id}`,
        selected: rowSelectionUnitOps[simulationObject.id.toString()] || false,
      });
      unitOpsByGroup.set(groupId, existing);
    });
 
    return groups
      .flatMap((group) => {
        const groupSimulationObject = group.simulationObject
          ? objectsIdMap.get(group.simulationObject)
          : undefined;
 
        Iif (
          !groupSimulationObject ||
          groupSimulationObject.objectType !== "group"
        ) {
          return [];
        }
 
        return {
          groupId: group.id,
          groupName:
            groupSimulationObject.componentName ?? `Unnamed group ${group.id}`,
          unitOps: (unitOpsByGroup.get(group.id) ?? []).sort((a, b) =>
            a.name.localeCompare(b.name),
          ),
        };
      })
      .sort((a, b) => a.groupName.localeCompare(b.groupName));
  }, [allGraphicObjects, groups, objectsIdMap, rowSelectionUnitOps]);
 
  // Initialize unit ops selection
  useEffect(() => {
    const newRowSelectionUnitOps: { [key: string]: boolean } = {};
    selectedProperties.forEach((prop) => {
      const unitOpId = prop.unitOpId ?? prop.unitOp;
      Iif (unitOpId == null) return;
      newRowSelectionUnitOps[unitOpId.toString()] = true;
    });
    setRowSelectionUnitOps(newRowSelectionUnitOps);
 
    if (selectedProperties.length > 0 && !selectedUnitOp) {
      const firstUnitOpId =
        selectedProperties[0]?.unitOpId ?? selectedProperties[0]?.unitOp;
      if (firstUnitOpId != null) {
        setSelectedUnitOp(firstUnitOpId);
      }
    }
  }, [selectedProperties, selectedUnitOp]);
 
  // Initialize properties selection
  useEffect(() => {
    if (selectedUnitOp) {
      const newRowSelectionProperties: { [key: string]: boolean } = {};
      selectedProperties
        .filter((prop) => (prop.unitOpId ?? prop.unitOp) === selectedUnitOp)
        .forEach((prop) => {
          const propertyId = prop.propertyId ?? prop.property;
          Iif (propertyId == null) return;
          newRowSelectionProperties[propertyId.toString()] = true;
        });
      setRowSelectionProperties(newRowSelectionProperties);
    } else {
      setRowSelectionProperties({});
    }
  }, [selectedUnitOp, selectedProperties]);
 
  const filteredGroupedUnitOps = useMemo(
    () =>
      groupedUnitOps.map((group) => ({
        ...group,
        unitOps: group.unitOps.filter((unitOp) =>
          unitOp.name.toLowerCase().includes(searchedObj.toLowerCase()),
        ),
      })),
    [groupedUnitOps, searchedObj],
  );
 
  const allGroupIds = useMemo(
    () => groupedUnitOps.map((group) => group.groupId.toString()),
    [groupedUnitOps],
  );
 
  const accordionOpenValues = useMemo(() => {
    if (openGroupIds === null) {
      return allGroupIds;
    }
    const validGroupIdSet = new Set(allGroupIds);
    return openGroupIds.filter((groupId) => validGroupIdSet.has(groupId));
  }, [allGroupIds, openGroupIds]);
 
  const handleUnitOpSelect = (unitOpId: number, isSelected: boolean) => {
    setRowSelectionUnitOps((prev) => ({
      ...prev,
      [unitOpId.toString()]: isSelected,
    }));
 
    if (isSelected) {
      setSelectedUnitOp(unitOpId);
    } else {
      // Remove properties of deselected unit op
      setSelectedProperties((prev) =>
        prev.filter((p) => (p.unitOpId ?? p.unitOp) !== unitOpId),
      );
      Iif (selectedUnitOp === unitOpId) {
        setSelectedUnitOp(null);
      }
    }
  };
 
  const handlePropertySelect = (
    property: PropertyDataType,
    isSelected: boolean,
  ) => {
    Iif (!selectedUnitOp) return;
 
    setSelectedProperties((prev) => {
      const exists = prev.some(
        (p) =>
          (p.propertyId ?? p.property) === property.id &&
          (p.unitOpId ?? p.unitOp) === selectedUnitOp,
      );
      if (isSelected && !exists) {
        const unitOp = objectsIdMap.get(selectedUnitOp);
        Iif (!unitOp) return prev;
 
        return [
          ...prev,
          {
            unitOpId: selectedUnitOp,
            unitOpName: unitOp.componentName,
            propertyId: property.id,
            propertyName: property.displayName,
            propertyValue: Array.isArray(property.value)
              ? property.value[0]
              : property.value,
            propertyUnit: property.unit,
          },
        ];
      IE} else if (!isSelected) {
        return prev.filter(
          (p) =>
            !(
              (p.propertyId ?? p.property) === property.id &&
              (p.unitOpId ?? p.unitOp) === selectedUnitOp
            ),
        );
      }
      return prev;
    });
 
    setRowSelectionProperties((prev) => ({
      ...prev,
      [property.id]: isSelected,
    }));
  };
 
  const isAnyUnitOpSelected = Object.values(rowSelectionUnitOps).some(Boolean);
 
  const anyPropertiesSelected = Object.values(rowSelectionProperties).some(
    Boolean,
  );
  // Define columns for the Properties table
  const propertyColumns: ColumnDef<PropertyDataType>[] = [
    {
      id: "select",
      header: () => (
        <Checkbox
          checked={Object.values(rowSelectionProperties).every(Boolean)}
          onCheckedChange={(value) => {
            const isChecked = !!value;
            const newSelection: { [key: string]: boolean } = {};
            properties.forEach((property) => {
              newSelection[property.id.toString()] = isChecked;
              handlePropertySelect(property, isChecked);
            });
            setRowSelectionProperties(newSelection);
          }}
          aria-label="Select all properties"
          className={cn(
            anyPropertiesSelected
              ? "w-4 h-4 data-[state=checked]:bg-primary data-[state=checked]:text-foreground"
              : "  border-foreground data-[state=checked]:bg-background data-[state=checked]:text-background",
          )}
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={rowSelectionProperties[row.original.id.toString()] || false}
          onCheckedChange={(checked) => {
            handlePropertySelect(row.original, !!checked);
          }}
          aria-label="Select property"
          className="w-4 h-4 data-[state=checked]:bg-background data-[state=checked]:text-primary"
        />
      ),
      enableSorting: false,
      enableHiding: false,
      size: 0,
    },
    {
      accessorKey: "displayName",
      header: "Property",
    },
  ];
 
  if (!groups || allGraphicObjects == undefined) return "loading";
 
  return (
    <div className="grid grid-cols-2 gap-4 w-[50vw]">
      {/* Left section: Unit Operations */}
      <div className="h-[54vh] overflow-hidden">
        <div className="flex flex-col gap-2 h-[15%]">
          <div className="flex items-center gap-1">
            <h3 className="text-sm font-medium">Unit Operations</h3>
            <ToolTipCover
              asChild
              content="Browse all groups and select objects. If an object appears in multiple groups, it can be selected from any of them."
            >
              <Button
                variant="ghost"
                size="icon"
                className="h-5 w-5 text-card-foreground"
              >
                <HelpCircle className="h-4 w-4" />
              </Button>
            </ToolTipCover>
          </div>
 
          <Input
            type="text"
            className="w-full"
            startIcon={Search}
            value={searchedObj}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search unit operations"
          />
        </div>
        <div className="h-[46vh] overflow-y-auto border rounded-sm">
          <Accordion
            type="multiple"
            value={accordionOpenValues}
            onValueChange={setOpenGroupIds}
            className="w-full"
          >
            {filteredGroupedUnitOps.map((group) => (
              <AccordionItem
                key={group.groupId}
                value={group.groupId.toString()}
                className="border-b"
              >
                <AccordionTrigger variant="objectPanel" className="text-sm">
                  <span className="truncate">{group.groupName}</span>
                </AccordionTrigger>
                <AccordionContent className="px-0 pb-2 pt-0 ">
                  {group.unitOps.length === 0 ? (
                    <p className="text-xs text-muted-foreground px-4 py-2">
                      No matching objects in this group.
                    </p>
                  ) : (
                    <div className="flex flex-col gap-1 px-2">
                      {group.unitOps.map((unitOp) => {
                        const isSelected =
                          rowSelectionUnitOps[unitOp.id.toString()] || false;
                        const isActive = selectedUnitOp === unitOp.id;
 
                        return (
                          <button
                            key={`${group.groupId}-${unitOp.id}`}
                            type="button"
                            onClick={() => setSelectedUnitOp(unitOp.id)}
                            className={cn(
                              "w-full flex items-center gap-2 px-2 py-1.5 rounded-sm text-left text-sm hover:bg-accent",
                              isActive && "bg-accent",
                            )}
                          >
                            <Checkbox
                              checked={isSelected}
                              onCheckedChange={(checked) => {
                                handleUnitOpSelect(unitOp.id, !!checked);
                              }}
                              onClick={(event) => event.stopPropagation()}
                              className={cn(
                                isAnyUnitOpSelected
                                  ? "data-[state=checked]:bg-primary data-[state=checked]:text-foreground"
                                  : "border-foreground data-[state=checked]:bg-background data-[state=checked]:text-background",
                              )}
                              aria-label={`Select ${unitOp.name}`}
                            />
                            <span className="truncate">{unitOp.name}</span>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </AccordionContent>
              </AccordionItem>
            ))}
          </Accordion>
        </div>
      </div>
      <div className="h-[54vh]">
        <DataTable
          columns={propertyColumns}
          data={selectedUnitOp == null ? [] : properties}
          rowSelection={rowSelectionProperties}
          handleSelect={() => {}} // No need to handle selection here
          hideHeader={false}
          emptyInfo="Select a unit operation to view its properties in this box."
        />
      </div>
    </div>
  );
}