All files / src/pages/flowsheet-page/flowsheet/Canvas MonitoringTablesContainer.tsx

94.33% Statements 50/53
62.5% Branches 20/32
95.65% Functions 22/23
94.11% Lines 48/51

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                                                          5402x 5402x 5402x       5402x         5402x 577x       5402x           3x 3x 3x 3x         5402x           5402x 3x   3x   3x 3x 3x     5402x     120x     2x 1x                                                                                 141x 141x     141x 11x 16x               141x 141x 591x   141x 220x 220x         141x             8x     8x   16x       16x         8x               141x   3x               141x   3x               141x   3x               141x 3x                       141x                                            
import { useCallback, useMemo, useState } from "react";
import FloatingPropertyTable from "./FloatingPropertyTable";
import SelectPropertiesDialog from "../PropertiesSidebar/SelectPropertiesDialog";
import { SelectedPropertyInfo } from "../PropertiesSidebar/ObjectDetailsPanel";
import { useFlowsheetObjectsIdMap } from "@/hooks/flowsheetObjects";
import {
  MonitoringTableProperty,
  MonitoringTableRead,
  useCoreMonitoringTablesPartialUpdateMutation,
} from "@/api/apiStore.gen";
 
interface MonitoringTablesContainerProps {
  tables: MonitoringTableRead[];
  onHideTable: (tableId: number) => void;
  onRenameTable: (tableId: number, newName: string) => void;
  unitOpLookup: Record<number | string, string>;
}
 
/**
 * Container component that renders multiple FloatingPropertyTable instances
 * and manages the property selection dialog for each.
 */
export function MonitoringTablesContainer({
  tables,
  onHideTable,
  onRenameTable,
  unitOpLookup,
}: MonitoringTablesContainerProps) {
  // Track which table is currently being edited
  const [editingTableId, setEditingTableId] = useState<number | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [tempSelectedProperties, setTempSelectedProperties] = useState<
    SelectedPropertyInfo[]
  >([]);
  // Store the setter from the table instance so we can call it directly on save
  const [activeTableSetter, setActiveTableSetter] = useState<
    React.Dispatch<React.SetStateAction<SelectedPropertyInfo[]>> | null
  >(null);
 
  // Get the visible tables only
  const visibleTables = useMemo(
    () => tables.filter((t) => t.visible),
    [tables]
  );
 
  const handleOpenDialog = useCallback(
    (
      tableId: number,
      currentProperties: SelectedPropertyInfo[],
      setter: React.Dispatch<React.SetStateAction<SelectedPropertyInfo[]>>
    ) => {
      setEditingTableId(tableId);
      setTempSelectedProperties(currentProperties);
      setActiveTableSetter(() => setter);
      setIsDialogOpen(true);
    },
    []
  );
 
  const handleCancel = useCallback(() => {
    setIsDialogOpen(false);
    setEditingTableId(null);
    setActiveTableSetter(null);
  }, []);
 
  const handleSave = useCallback(() => {
    if (editingTableId != null && activeTableSetter) {
      // Call the setter directly to update state (and sync to backend)
      activeTableSetter(tempSelectedProperties);
    }
    setIsDialogOpen(false);
    setEditingTableId(null);
    setActiveTableSetter(null);
  }, [editingTableId, activeTableSetter, tempSelectedProperties]);
 
  return (
    <>
      {visibleTables.map((table) => (
        <MonitoringTableInstance
          key={table.id}
          table={table}
          onHide={() => onHideTable(table.id)}
          onRename={(newName: string) => onRenameTable(table.id, newName)}
          onOpenDialog={handleOpenDialog}
          unitOpLookup={unitOpLookup}
        />
      ))}
      {/* Single shared dialog for editing any table */}
      <SelectPropertiesDialog
        isDialogOpen={isDialogOpen}
        setIsDialogOpen={setIsDialogOpen}
        tempSelectedProperties={tempSelectedProperties}
        setTempSelectedProperties={setTempSelectedProperties}
        handleSave={handleSave}
        handleCancel={handleCancel}
      />
    </>
  );
}
 
interface MonitoringTableInstanceProps {
  table: MonitoringTableRead;
  onHide: () => void;
  onRename: (newName: string) => void;
  onOpenDialog: (
    tableId: number,
    currentProperties: SelectedPropertyInfo[],
    setter: React.Dispatch<React.SetStateAction<SelectedPropertyInfo[]>>
  ) => void;
  unitOpLookup: Record<number | string, string>;
}
 
/**
 * Individual monitoring table instance backed by the API.
 * Maps backend data to FloatingPropertyTable props and handles mutations.
 */
function MonitoringTableInstance({
  table,
  onHide,
  onRename,
  onOpenDialog,
  unitOpLookup,
}: MonitoringTableInstanceProps) {
  const [updateTable] = useCoreMonitoringTablesPartialUpdateMutation();
  const flowsheetObjectIdMap = useFlowsheetObjectsIdMap();
 
  // Map backend selectedProperties to SelectedPropertyInfo for the table component
  const selectedProperties = useMemo(
    () =>
      (table.selectedProperties ?? []).map((p) => ({
        unitOpId: p.simulationObject,
        propertyId: p.propertyInfo,
      })),
    [table.selectedProperties]
  );
 
  // Filter out properties for deleted unitOps at render time
  const validSelectedProperties = useMemo(() => {
    const existingIds = new Set<number>(
      Array.from(flowsheetObjectIdMap.keys()).map((id) => Number(id))
    );
    return selectedProperties.filter((p: SelectedPropertyInfo) => {
      const uId = Number(p.unitOpId ?? p.unitOp ?? NaN);
      return Number.isNaN(uId) || existingIds.has(uId);
    });
  }, [selectedProperties, flowsheetObjectIdMap]);
 
  // Convert SelectedPropertyInfo[] back to backend format and save via PATCH
  const handleSetSelectedProperties = useCallback(
    (
      newProps:
        | SelectedPropertyInfo[]
        | ((prev: SelectedPropertyInfo[]) => SelectedPropertyInfo[])
    ) => {
      const resolved =
        typeof newProps === "function"
          ? newProps(validSelectedProperties)
          : newProps;
      const backendProps: MonitoringTableProperty[] = resolved
        .filter(
          (p) =>
            (p.unitOpId ?? p.unitOp) != null &&
            (p.propertyId ?? p.property) != null
        )
        .map((p, i) => ({
          simulationObject: (p.unitOpId ?? p.unitOp)!,
          propertyInfo: (p.propertyId ?? p.property)!,
          sortIndex: i,
        }));
      updateTable({
        id: table.id,
        patchedMonitoringTable: { selectedProperties: backendProps },
      });
    },
    [updateTable, table.id, validSelectedProperties]
  );
 
  const handlePositionChange = useCallback(
    (pos: { x: number; y: number }) => {
      updateTable({
        id: table.id,
        patchedMonitoringTable: { x: pos.x, y: pos.y },
      });
    },
    [updateTable, table.id]
  );
 
  const handleSizeChange = useCallback(
    (sz: { width: number; height: number }) => {
      updateTable({
        id: table.id,
        patchedMonitoringTable: { width: sz.width, height: sz.height },
      });
    },
    [updateTable, table.id]
  );
 
  const handleMinimizedChange = useCallback(
    (minimised: boolean) => {
      updateTable({
        id: table.id,
        patchedMonitoringTable: { minimised },
      });
    },
    [updateTable, table.id]
  );
 
  const handleOpenDialogCallback = useCallback(() => {
    onOpenDialog(
      table.id,
      validSelectedProperties,
      handleSetSelectedProperties
    );
  }, [
    onOpenDialog,
    table.id,
    validSelectedProperties,
    handleSetSelectedProperties,
  ]);
 
  return (
    <FloatingPropertyTable
      tableId={table.id}
      handleOpenDialog={handleOpenDialogCallback}
      title={table.title}
      selectedProperties={validSelectedProperties}
      setSelectedProperties={handleSetSelectedProperties}
      unitOpLookup={unitOpLookup}
      isVisible={true} // Visibility is controlled by parent filtering
      position={{ x: table.x ?? 440, y: table.y ?? 110 }}
      size={{ width: table.width ?? 380, height: table.height ?? 100 }}
      isMinimized={table.minimised ?? true}
      onPositionChange={handlePositionChange}
      onSizeChange={handleSizeChange}
      onMinimizedChange={handleMinimizedChange}
      onHide={onHide}
      onRename={onRename}
    />
  );
}
 
export default MonitoringTablesContainer;