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

63.88% Statements 69/108
61.17% Branches 52/85
45.45% Functions 5/11
86.44% Lines 51/59

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                                  103x         74x       219x 29x 29x 29x 29x 29x 29x 29x 29x     84x         84x                   20x       63x         54x 61x   184x   169x       53x         114x 115x 169x       74x             15x   15x     59x 219x 219x         219x       190x         219x       219x                                     118x           20x                         39x                   39x       39x   39x 20x                           20x   20x 20x 300x       99x           58x 19x         58x 77x 59x 79x          
import { useLocalStorage } from "usehooks-ts";
import { Card, CardContent, CardHeader } from "@/ahuora-design-system/ui/card";
import { Separator } from "@/ahuora-design-system/ui/separator";
import {
  ObjectTypeEnum,
  PropertyInfoRead,
  PropertySetRead,
  SimulationObjectRetrieveRead,
} from "@/api/apiStore.gen";
import { GetQuickUnits } from "@/data/UnitsLibrary";
import objects from "@/data/unitOpConfigs";
import { usePortName } from "@/hooks/flowsheetObjects";
 
type MolarMassKeys = { molar?: string[]; mass?: string[] };
type KeyProperties = string[] | MolarMassKeys | null;
 
type ObjectDefinitions = typeof objects;
const objectDefinitions = objects as ObjectDefinitions;
 
function getKeyProperties(
  objectType: ObjectTypeEnum,
): KeyProperties | undefined {
  return objectDefinitions[objectType]?.keyProperties;
}
 
function valueFormatter(raw: number | string | null | undefined) {
  if (raw === null || raw === undefined) return "";
  const num = typeof raw === "number" ? raw : Number(raw);
  Iif (Number.isNaN(num)) return "";
  let out: number | string = num;
  const [intPart, decRaw] = num.toString().split(".");
  const dec = decRaw ? decRaw.padEnd(4, "0") : "";
  if (dec !== "" && dec.length > 4) out = +num.toFixed(4);
  Iif (intPart && intPart.length > 6) out = num.toExponential(4);
  return out;
}
 
function PropertyHover({
  simulationObject,
}: {
  simulationObject: SimulationObjectRetrieveRead;
}) {
  const properties = simulationObject.properties;
 
  // Streams (Material or Energy) -> use generic hover
  if (
    simulationObject.objectType === ObjectTypeEnum.EnergyStream ||
    simulationObject.objectType === ObjectTypeEnum.Stream ||
    simulationObject.objectType === ObjectTypeEnum.AcStream ||
    simulationObject.objectType === ObjectTypeEnum.HumidAirStream
  ) {
    return (
      <RenderStreamHoverGeneric
        simulationObject={simulationObject}
        properties={properties}
        streamName={simulationObject.componentName}
      />
    );
  }
 
  // Generic objects: flat key list from backend unit op configs.
  const keyProperties = getKeyProperties(simulationObject.objectType);
  const listOfProperties = Array.isArray(keyProperties)
    ? properties?.ContainedProperties?.filter((p) =>
        keyProperties.includes(p.key),
      )
    : [];
 
  return (
    <Card className="w-80">
      <CardHeader
        className="flex flex-row justify-between p-0 items-center"
        aria-label={`property-hover-card-header`}
      >
        <span>{simulationObject.componentName}</span>
      </CardHeader>
      <RenderHover properties={listOfProperties} />
    </Card>
  );
}
 
function RenderHover({
  properties,
}: {
  properties: PropertyInfoRead[] | undefined;
}) {
  if (!properties?.length) {
    return (
      <CardContent>
        <small>No properties to display</small>
      </CardContent>
    );
  }
  return properties.map((property, index) => {
    const unit = GetQuickUnits(property.unitType, property.unit);
    const rawValue = property.values[0]?.value as
      | number
      | string
      | null
      | undefined;
    let value = valueFormatter(rawValue);
 
    // Show "unspecified" if the value is missing/empty
    if (value === "") {
      value = "unspecified";
    }
 
    // Decide if the unit should be shown
    const showUnit =
      value !== "unspecified" &&
      unit &&
      unit !== "-" &&
      unit !== "dimensionless" &&
      unit !== "—"; // exclude em dash too
 
    return (
      <CardContent key={property.id}>
        <div className="flex justify-between">
          <small className="w-max">{property.displayName}</small>
          <small
            className={
              value === "unspecified" ? "italic text-muted-foreground" : ""
            }
            aria-label={`property-hover-value-${property.displayName}`}
          >
            {value}
            {showUnit ? ` ${unit}` : ""}
          </small>
        </div>
        {index !== properties.length - 1 && <Separator className="mt-3" />}
      </CardContent>
    );
  });
}
 
/** ---------- Generic Stream Hover (Material + Energy) ---------- **/
 
function isMolarMassKeys(x: unknown): x is MolarMassKeys {
  return (
    !!x &&
    typeof x === "object" &&
    !Array.isArray(x) &&
    ("molar" in x || "mass" in x)
  );
}
 
/**
 * Handles:
 * - Material stream: keyProperties is { molar: string[]; mass: string[] } and respects localStorage "molarOrMass"
 * - Energy stream:   keyProperties is string[]
 */
function RenderStreamHoverGeneric({
  properties,
  streamName,
  simulationObject,
}: {
  simulationObject: SimulationObjectRetrieveRead;
  properties: PropertySetRead | undefined;
  streamName: string | undefined;
}) {
  // Only used for material streams; harmless for energy streams
  const [molarOrMass] = useLocalStorage<"molar" | "mass">(
    "molarOrMass",
    "molar",
  );
  const portName = usePortName(simulationObject.id);
 
  const listOfProperties = (() => {
    const keyProps = getKeyProperties(simulationObject.objectType);
 
    Iif (!keyProps) return [];
 
    // Energy Stream -> flat list of keys (string[])
    if (Array.isArray(keyProps)) {
      const set = new Set(keyProps);
      return (
        properties?.ContainedProperties?.filter((p) => set.has(p.key)) ?? []
      );
    }
 
    // Material Stream -> pick molar or mass keys
    if (isMolarMassKeys(keyProps)) {
      const keys = keyProps[molarOrMass] ?? [];
      Iif (!keys.length) return [];
      const set = new Set(keys);
      return (
        properties?.ContainedProperties?.filter((p) => set.has(p.key)) ?? []
      );
    }
 
    return [];
  })();
 
  return (
    <Card className="w-80">
      <CardHeader className="flex flex-row justify-between items-center p-0 mb-2">
        <span aria-label={`property-hover-card-header`}>{streamName}</span>
        <div
          className="px-5 py-1 bg-muted rounded-xl border text-xs "
          aria-label={`property-hover-portType`}
        >
          {portName}
        </div>
      </CardHeader>
      <RenderHover properties={listOfProperties} />
    </Card>
  );
}
 
export default PropertyHover;