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                                  76x         62x       208x 37x 37x 37x 37x 37x 37x 37x 37x     250x         250x                   18x       90x         44x 196x   213x   284x       41x         237x 240x 284x       62x             5x   5x     57x 208x 208x         208x       171x         208x       208x                                     114x           18x                         26x                   26x       26x   26x 18x                           18x   18x 18x 234x       80x           42x 16x         42x 58x 44x 62x          
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 objects from "@/data/objects.json";
import { GetQuickUnits } from "@/data/UnitsLibrary";
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 objects.json
  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;