All files / src/pages/flowsheet-page/flowsheet/PropertiesSidebar/PropertyPanel CompoundList.tsx

56.16% Statements 82/146
55.71% Branches 78/140
25% Functions 4/16
78.4% Lines 69/88

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                                                        2826x 2088x 2088x 2088x 2088x 2088x 2088x 2088x     2088x       945x       1143x 11x     88x             1044x 22x 1022x         1929x 1257x 1257x 1257x 1257x 1257x 1257x 1257x     425x         7x           825x   825x 2x 812x         831x             831x 831x 831x   831x   831x   831x   831x   831x 831x     286x     286x     286x           286x         286x     286x       286x 286x 286x 831x 286x         8051x 831x   1689x   831x                 1069x   831x   1188x   831x 5x 2x             1749x   831x                     1069x     468x                                                                                                                       4835x   683x                   6295x 2235x      
// CompoundListSection.tsx
 
import * as React from "react";
import { toast } from "sonner";
import { AccordionContent } from "@/ahuora-design-system/ui/accordion";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Button } from "@/ahuora-design-system/ui/button";
import { ToolTipCover } from "@/ahuora-design-system/ui/tooltip";
import {
  MonitoringTableRead,
  ObjectTypeEnum as ObjEnum,
  PropertyInfoRead,
  PropertySetRead,
  useCoreSchemapropertysetNormalizeCompoundValuesCreateMutation,
  useCoreSchemapropertysetUpdateCompoundModeUpdateMutation,
  useUnitopsSimulationobjectsUpdateCompoundsCreateMutation,
} from "@/api/apiStore.gen";
import { useFlowsheetAccess } from "@/hooks/flowsheetAccess";
import {
  useCurrentObjectId,
  useFlowsheetObjectsIdMap,
  useObjectsPortsMap,
} from "@/hooks/flowsheetObjects";
import { useObjectConnectedToRecycle } from "@/hooks/recycleData";
import type { RuleFinding } from "../Diagnostics/useRuleValidation";
import { OrderedPropertyList } from "./Properties";
import { QuickAddCompoundsModal } from "./QuickAddCompoundsModal";
 
export const useIsStreamSpecification = () => {
  const id = useCurrentObjectId();
  const simulationObjectPortMap = useObjectsPortsMap();
  const ports = simulationObjectPortMap.get(+id!);
  const objectIdMap = useFlowsheetObjectsIdMap();
  const objectConnectedToRecycle = useObjectConnectedToRecycle();
  const outletPort = ports?.find((port) => port.direction === "outlet");
  const inletPort = ports?.find((port) => port.direction === "inlet");
 
  // decision node
  const unitopd = objectIdMap.get(+id!);
  Iif (unitopd?.objectType === "decisionNode") return true;
 
  // inlet stream (no outlet)
  Iif (!outletPort) return true;
 
  // Don't show stream specifications if connected to a translator block downstream
  const downstreamUnitOp =
    inletPort?.unitOp != null ? objectIdMap.get(inletPort.unitOp) : undefined;
  Iif (downstreamUnitOp?.objectType === ObjEnum.Translator) return false;
 
  // intermediate stream (has both inlet and outlet)
  Iif (inletPort && outletPort && unitopd?.objectType === "stream") return true;
 
  // connected to recycle
  Iif (objectConnectedToRecycle(+id!)) return true;
 
  // connected to translator block
  if (outletPort?.unitOp) {
    const upstreamOp = objectIdMap.get(outletPort.unitOp);
    Iif (upstreamOp?.objectType === ObjEnum.Translator) return true;
  }
 
  return false;
};
 
export const useDisplayInsertTranslatorButton = () => {
  const id = useCurrentObjectId();
  const simulationObjectPortMap = useObjectsPortsMap();
  const ports = simulationObjectPortMap.get(+id!);
  const objectIdMap = useFlowsheetObjectsIdMap();
  const unitopd = objectIdMap.get(+id!);
  const inletPort = ports?.find((port) => port.direction === "inlet");
  const outletPort = ports?.find((port) => port.direction === "outlet");
 
  // An inlet stream
  Iif (!outletPort) return false;
 
  // Decision node or Translator block
  Iif (
    unitopd?.objectType === "decisionNode" ||
    unitopd?.objectType === "translator"
  )
    return false;
 
  // If connected to translator block, consider it as a regular stream
  const downstreamUnitOp =
    inletPort?.unitOp != null ? objectIdMap.get(inletPort.unitOp) : undefined;
  const upstreamUnitOp =
    outletPort?.unitOp != null ? objectIdMap.get(outletPort.unitOp) : undefined;
  Iif (downstreamUnitOp?.objectType === ObjEnum.Translator) return false;
  Iif (upstreamUnitOp?.objectType === ObjEnum.Translator) return false;
 
  return true;
};
 
export function CompoundListSection(props: {
  schema: object;
  properties: PropertyInfoRead[];
  propertySet: PropertySetRead;
  ruleFindingsByPropertyKey?: Record<string, RuleFinding[]>;
  monitoringTables?: MonitoringTableRead[];
}) {
  const id = useCurrentObjectId();
  const access = useFlowsheetAccess();
  const canMutate = access?.can_edit ?? true;
 
  const showAddCompoundButton = useIsStreamSpecification();
  const [updateMode] =
    useCoreSchemapropertysetUpdateCompoundModeUpdateMutation();
  const [updateCompounds] =
    useUnitopsSimulationobjectsUpdateCompoundsCreateMutation();
  const [normaliseCompounds] =
    useCoreSchemapropertysetNormalizeCompoundValuesCreateMutation();
 
  const { propertySet } = props;
  const moleFracComp = props.properties.find(
    (prop) => prop.key === "mole_frac_comp",
  );
  Iif (!moleFracComp) return null;
 
  // Derive the current selection straight from props/server (single source of truth)
  const selectedCompounds =
    moleFracComp.values.map((value) => value.indexedSets[0]) ?? {};
 
  const { basis, flowType } = (() => {
    switch (propertySet.compoundMode) {
      case "MolarFraction":
        return { basis: "Molar", flowType: "Fraction" as const };
      case "MassFraction":
      default:
        return { basis: "Mass", flowType: "Fraction" as const };
    }
  })();
 
  const calculateCompoundTotal = () => {
    const compoundTotal = moleFracComp.values.reduce(
      (total, value) => total + Number(value.value ?? 0),
      0,
    );
    return parseFloat(compoundTotal.toFixed(3));
  };
 
  const compoundTotal = calculateCompoundTotal();
  const compoundTotalError = compoundTotal !== 1;
  const noCompounds = selectedCompounds.length === 0;
  const quickAddMoleFracComp = {
    values: Object.fromEntries(
      moleFracComp.values.map((value) => [
        value.indexedSets[0],
        Number(value.value ?? 0),
      ]),
    ),
    type: moleFracComp.type ?? "",
    unit: moleFracComp.unit,
  };
 
  const switchCompoundMode = (
    newBasis: "Molar" | "Mass",
    fType: "Fraction" | "Flow",
  ) => {
    const newMode = newBasis + fType;
    updateMode({
      id: propertySet.id,
      updateCompoundMode: { compoundMode: newMode },
    });
  };
 
  const onClickBasis = () => {
    switchCompoundMode(basis === "Molar" ? "Mass" : "Molar", flowType);
  };
 
  const deleteCompound = (propertyValueKey: string) => {
    const updated = selectedCompounds.filter((c) => c !== propertyValueKey);
    updateCompounds({
      updateCompound: {
        simulationObject: +id!,
        compounds: updated,
      },
    });
    // no local state needed; UI will reflect server once mutation settles
  };
 
  const normaliseCompoundValues = () => {
    normaliseCompounds({ id: propertySet.id })
      .unwrap()
      .then(() => {
        toast.success("Compound values normalised successfully!");
      })
      .catch((error) => {
        toast.error("Failed to normalise compound values:", {
          description: error?.data?.message,
        });
      });
  };
 
  return (
    <AccordionContent key={id} className="px-0 mt-0 flex flex-col">
      {showAddCompoundButton && (
        <div className="flex flex-row-reverse gap-2 items-center mx-4">
          <QuickAddCompoundsModal
            key={`modal-${id}`} // ✅ don't re-mount on server value changes
            schema={props.schema}
            moleFracComp={quickAddMoleFracComp}
            // pass current server truth (the modal may keep a temp local copy while open)
            selectedCompounds={selectedCompounds}
            disabled={!canMutate}
          />
 
          {noCompounds ? (
            <p className="w-full">Add a compound to get started.</p>
          ) : (
            <div className="flex w-full gap-1 justify-between">
              <ToolTipCover
                content="Click to toggle between mass and molar basis."
                delay={0}
                asChild
              >
                <Button
                  aria-label="Compound Basis"
                  variant="secondary"
                  onClick={onClickBasis}
                  disabled={!canMutate}
                >
                  {basis} {flowType}
                </Button>
              </ToolTipCover>
 
              <ToolTipCover
                content={
                  compoundTotalError
                    ? "Total compound fractions must equal to 1!"
                    : `Total compound ${
                        flowType === "Flow" ? "flow" : "fraction"
                      }.\nClick to normalise values`
                }
                variant={compoundTotalError ? "error" : "default"}
                delay={0}
                asChild
              >
                <Badge
                  className={
                    canMutate
                      ? "pointer-events-auto cursor-pointer"
                      : "pointer-events-none"
                  }
                  variant={compoundTotalError ? "destructive" : "secondary"}
                  size="xs"
                  tabIndex={0}
                  onClick={canMutate ? normaliseCompoundValues : undefined}
                >
                  Total: {compoundTotal}{" "}
                </Badge>
              </ToolTipCover>
            </div>
          )}
        </div>
      )}
 
      {!noCompounds && (
        <OrderedPropertyList
          schema={props.schema}
          properties={props.properties}
          ruleFindingsByPropertyKey={props.ruleFindingsByPropertyKey}
          monitoringTables={props.monitoringTables}
          deletePropertyFunction={
            showAddCompoundButton && canMutate ? deleteCompound : undefined
          }
        />
      )}
    </AccordionContent>
  );
}