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

66.66% Statements 62/93
74% Branches 37/50
61.53% Functions 24/39
68.96% Lines 60/87

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                                                                      74x   74x 21x     53x 618x                                     74x 74x     74x     74x   74x 74x 74x 74x 213x     74x     74x 20x 20x 65x   20x   20x 2x         74x 27x 22x 22x 73x   25x   22x   5x       74x 213x 213x           74x 213x     74x                                     74x 15x   15x 15x 42x   15x 15x 15x   15x                                           15x           74x   74x       124x                                       372x               316x       316x                           74x       74x       124x                                       1140x     15x                               74x   71x                                                                       7x                                          
// Import necessary components and hooks
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 {
    useFlowsheetObjectsIdMap,
    useGroupGraphicsObjects,
    useSelectedGroup
} from "@/hooks/flowsheetObjects";
import { useSimulationObjectPropertySet } from "@/hooks/properties";
import { cn } from "@/lib/utils";
import type { ColumnDef } from "@tanstack/react-table";
import { HelpCircle, Search } from "lucide-react";
import { useEffect, useState } from "react";
import { SelectedPropertyInfo } from "../ObjectDetailsPanel";
interface UnitOpDataType {
  id: number;
  name: string;
  selected: boolean;
}
 
interface PropertyDataType {
  id: number;
  key: string;
  displayName: string;
  value: string | string[];
  unit?: string;
  type?: string;
}
 
function useUnitOpProperties(
  selectedUnitOpId: number | null,
): PropertyDataType[] {
  const propertySet = useSimulationObjectPropertySet(selectedUnitOpId);
 
  if (!propertySet || !selectedUnitOpId) {
    return [];
  }
 
  return (
    propertySet.ContainedProperties?.map((prop) => ({
      ...prop,
      // Use value as the source for dropdown options if it is an array
      value: Array.isArray(prop.value) ? prop.value : prop.value || null,
    })) ?? []
  );
}
 
interface DataPanelProps {
  setSelectedProperties: React.Dispatch<
    React.SetStateAction<SelectedPropertyInfo[]>
  >;
  selectedProperties: SelectedPropertyInfo[];
}
 
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 objectsIdMap = useFlowsheetObjectsIdMap();
  const selectedGroup = useSelectedGroup();
  const groupId = selectedGroup?.id
  const groupObjects = useGroupGraphicsObjects(groupId)?.map(
    (obj) => obj.simulationObject,
  );
 
  const properties = useUnitOpProperties(selectedUnitOp);
 
  // Initialize unit ops selection
  useEffect(() => {
    const newRowSelectionUnitOps: { [key: string]: boolean } = {};
    selectedProperties.forEach((prop) => {
      newRowSelectionUnitOps[prop.unitOpId.toString()] = true;
    });
    setRowSelectionUnitOps(newRowSelectionUnitOps);
 
    if (selectedProperties.length > 0 && !selectedUnitOp) {
      setSelectedUnitOp(selectedProperties[0].unitOpId);
    }
  }, [selectedProperties]);
 
  // Initialize properties selection
  useEffect(() => {
    if (selectedUnitOp) {
      const newRowSelectionProperties: { [key: string]: boolean } = {};
      selectedProperties
        .filter((prop) => prop.unitOpId === selectedUnitOp)
        .forEach((prop) => {
          newRowSelectionProperties[prop.propertyId.toString()] = true;
        });
      setRowSelectionProperties(newRowSelectionProperties);
    } else {
      setRowSelectionProperties({});
    }
  }, [selectedUnitOp, selectedProperties]);
 
  const data: UnitOpDataType[] = groupObjects
    ?.filter((obj) => obj.objectType !== "group")
    .map((obj) => ({
      id: obj.id!,
      name: obj.componentName!,
      selected: rowSelectionUnitOps[obj.id!.toString()] || false,
    }));
 
  const filteredData = data?.filter((unitOp) =>
    unitOp.name.toLowerCase().includes(searchedObj.toLowerCase()),
  );
 
  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 !== unitOpId),
      );
      Iif (selectedUnitOp === unitOpId) {
        setSelectedUnitOp(null);
      }
    }
  };
 
  const handlePropertySelect = (property, isSelected) => {
    Iif (!selectedUnitOp) return;
 
    setSelectedProperties((prev) => {
      const exists = prev.some(
        (p) => p.propertyId === property.id && p.unitOpId === 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 === property.id && p.unitOpId === selectedUnitOp),
        );
      }
      return prev;
    });
 
    setRowSelectionProperties((prev) => ({
      ...prev,
      [property.id]: isSelected,
    }));
  };
 
  const isAnyUnitOpSelected = Object.values(rowSelectionUnitOps).some(Boolean);
  // Define columns for the Unit Operations table
  const unitOpColumns: ColumnDef<UnitOpDataType>[] = [
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={Object.values(rowSelectionUnitOps).every(Boolean)}
          onCheckedChange={(value) => {
            const isChecked = !!value;
            const newSelection: { [key: string]: boolean } = {};
            data.forEach((unitOp) => {
              newSelection[unitOp.id.toString()] = isChecked;
              handleUnitOpSelect(unitOp.id, isChecked);
            });
            setRowSelectionUnitOps(newSelection);
          }}
          className={cn(
            isAnyUnitOpSelected
              ? "data-[state=checked]:bg-primary data-[state=checked]:text-white"
              : "border-foreground data-[state=checked]:bg-background data-[state=checked]:text-background",
          )}
          aria-label="Select all"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={rowSelectionUnitOps[row.original.id.toString()] || false}
          onCheckedChange={(checked) => {
            handleUnitOpSelect(row.original.id, !!checked);
          }}
          aria-label="Select row"
          className={cn(
            selectedUnitOp === row.original.id &&
              !selectedProperties.find((p) => p.unitOpId === selectedUnitOp)
              ? "bg-amber-700 border-amber-700 pointer-events-none"
              : "pointer-events-none  border-primary data-[state=checked]:bg-background data-[state=checked]:text-primary",
            selectedUnitOp === row.original.id &&
              selectedProperties.find((p) => p.unitOpId === selectedUnitOp) &&
              " border-primary data-[state=checked]:bg-primary data-[state=checked]:text-foreground pointer-events-none",
          )}
        />
      ),
      enableSorting: false,
      enableHiding: false,
      size: 0,
    },
    {
      accessorKey: "name",
      header: "Name",
    },
  ];
  const anyPropertiesSelected = Object.values(rowSelectionProperties).some(
    Boolean,
  );
  // Define columns for the Properties table
  const propertyColumns: ColumnDef<PropertyDataType>[] = [
    {
      id: "select",
      header: ({ table }) => (
        <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 (groupObjects == undefined) return "loading";
 
  return (
    <div className="grid grid-cols-2 gap-4 w-[50vw]">
      {/* Left section: Unit Operations */}
      <div className="">
        <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="View Unit objects by clicking them on the table. Orange indicates the selected unit has no selected properties."
            >
              <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]">
          <DataTable
            columns={unitOpColumns}
            data={filteredData}
            handleSelect={() => {}} // No need to handle selection here
            handleRowClick={(unitOp) => {
              setSelectedUnitOp(unitOp.id);
            }}
            rowSelection={rowSelectionUnitOps}
            getRowId={(row) => row.id.toString()}
          />
        </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."
          getRowId={(row) => row.id.toString()}
        />
      </div>
    </div>
  );
}