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

88% Statements 44/50
86.95% Branches 40/46
90% Functions 9/10
95.45% Lines 42/44

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                                477x 78x 78x 78x 78x 78x 78x 78x 78x                 197x   197x     197x           104x                   93x 207x         93x                                   223x 102x           121x 477x 477x         477x     477x 399x         477x           477x                                                 69x                                           168x       168x   168x 70x     70x     70x 1x 1x           69x 69x 69x 69x 69x 654x             168x                                  
import { Card, CardContent, CardHeader } from "@/ahuora-design-system/ui/card";
import { Separator } from "@/ahuora-design-system/ui/separator";
import {
  ObjectTypeEnum,
  PropertyInfoRead,
  PropertySetRead,
  SimulationObjectRead,
  useUnitopsSimulationobjectsRetrieveQuery,
} from "@/api/apiStore.gen";
import { memo, useMemo, useState } from "react";
import { useLocalStorage } from "usehooks-ts";
import objects from "@/data/objects.json";
import { GetQuickUnits } from "@/data/UnitsLibrary";
import { usePortName } from "@/hooks/flowsheetObjects";
 
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: SimulationObjectRead;
}) {
  const { data: simulationObjectData } =
    useUnitopsSimulationobjectsRetrieveQuery({ id: simulationObject.id });
 
  const properties = simulationObjectData?.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 listOfProperties = properties?.ContainedProperties?.filter((p) =>
    (objects as any)[simulationObject.objectType]?.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) ---------- **/
 
type MolarMassKeys = { molar?: string[]; mass?: string[] };
 
function isMolarMassKeys(x: unknown): x is MolarMassKeys {
  return (
    !!x &&
    typeof x === "object" &&
    ("molar" in (x as any) || "mass" in (x as any))
  );
}
 
/**
 * Handles:
 * - Material stream: keyProperties is { molar: string[]; mass: string[] } and respects localStorage "molarOrMass"
 * - Energy stream:   keyProperties is string[]
 */
function RenderStreamHoverGeneric({
  properties,
  streamName,
  simulationObject,
}: {
  simulationObject: SimulationObjectRead;
  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 = useMemo(() => {
    const keyProps = (objects as any)[simulationObject.objectType]
      ?.keyProperties as string[] | MolarMassKeys | undefined;
 
    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 [];
  }, [properties, simulationObject.objectType, molarOrMass]);
 
  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 memo(PropertyHover);