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

94.64% Statements 106/112
80.95% Branches 51/63
94.59% Functions 35/37
95.41% Lines 104/109

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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418                                                                  45x                       45x 193x 2x                 45x 193x             9289x 9289x 9289x 9289x 9289x             9289x   9289x 9289x 9289x     9289x 200x         200x 200x             193x 193x 171x 171x 169x   2x   171x         9289x   11x           11x 31x   11x 11x         11x 11x                 9289x           211x     204x 204x 204x       204x       3x     3x     9289x     8775x                         495x                               19x                                           1422x 1422x   1422x 8862x                   1422x 17724x             1422x 8862x   1422x 8862x     1422x       331x             8531x                                               1010x 1010x 1010x   1010x 1627x               1627x 1627x 1107x     520x 520x 318x 318x 296x     520x       1627x 1627x 1627x 1627x 1627x 1627x 687x 682x   7444x             5x     9293x       1627x 321x     156x   156x   101x     101x 101x       156x       1627x 1627x   9293x     1627x 520x   1627x               1627x 8862x     1627x 1627x 9293x     1627x                                                                                
import {
  api,
  PropertyInfoRead,
  useCorePropertyinfoPartialUpdateMutation,
  PropertySetRead,
  useCorePropertyvaluePartialUpdateMutation,
  PropertyValueRead,
} from "@/api/apiStore.gen";
import { useAppDispatch } from "@/store/hooks";
import { toast } from "sonner";
import { useCurrentObject } from "@/hooks/flowsheetObjects";
import {
  PropertyTextField
} from "./InputFields/PropertyTextField";
import {
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/ahuora-design-system/ui/accordion";
import { PropertiesStatus } from "./PropertiesStatus";
import { ObjectType, PropertySetType } from "@/data/ObjectTypes.gen";
import objs from "@/data/objects.json";
import { CompoundListSection } from "./CompoundList";
import React, { useMemo } from "react";
import { infoMessages } from "../../InfoData";
import { isStream } from "@/lib/isStream";
import { IndexedVariableWithUnit } from "./InputFields/IndexedVariableWithUnit";
import { PropertyCheckbox } from "./InputFields/PropertyCheckbox";
import { PropertyDropdown } from "./InputFields/PropertyDropdown";
import { buildRuleValidationKey } from "../../Diagnostics/ruleValidationKey";
import type { RuleFinding, RuleSeverity } from "../../Diagnostics/useRuleValidation";
import type { Finding, PatchedPropertyValueRead } from "@/api/apiStore.gen";
 
const objects = objs as Record<string, ObjectType>;
interface PropertyProps {
  property: PropertyInfoRead;
  isOperatingVariable?: boolean;
  withMSSConnection?: boolean;
  deletePropertyFunction?: (property_val_key: string) => void;
}
 
type MutationResult = ReturnType<
  typeof useCorePropertyinfoPartialUpdateMutation
>[0];
 
const toRuleFindings = (findings: Finding[]): RuleFinding[] =>
  findings
    .map((f) => ({
      id: f.id ?? "",
      severity: f.severity as RuleSeverity,
      title: f.title,
      description: f.description,
      ruleReference: f.ruleReference,
      propertyKey: f.propertyKey ?? undefined,
    }));
 
const getDiagnosticFindings = (data: PatchedPropertyValueRead): Finding[] =>
  data.diagnosticFindings ?? [];
 
export function Property({
  property,
  withMSSConnection,
  deletePropertyFunction,
}: PropertyProps) {
  const [updateValue] = useCorePropertyvaluePartialUpdateMutation();
  const [updateProperty] = useCorePropertyinfoPartialUpdateMutation();
  const currentObject = useCurrentObject();
  const printToast = true; // TODO: Make this a prop
  const dispatch = useAppDispatch();
 
  // Local, per-panel cache of the latest backend rule findings for each input.
  // This is only used to show inline borders/tooltips on inputs.
  //
  // The full Diagnostics panel work (global cache, persistence, etc.) will land
  // in a follow-up PR.
  const [ruleFindingsByKey, setRuleFindingsByKey] = React.useState<Record<string, RuleFinding[]>>({});
 
  const currentObjectType = currentObject?.objectType;
  const objectSchema = currentObjectType ? objects[currentObjectType] : undefined;
  const propertySchema = objectSchema?.properties[property.key];
  
 
  const onUpdateIndexedValue = (value: string, id: number) => {
    const validationKey = buildRuleValidationKey({
      objectId: currentObject?.id,
      propertyKey: property.key,
      propertyValueId: id,
    });
    updateBackendWithToast(() => {
      return updateValue({
        id: id,
        patchedPropertyValue: {
          value: value,
        },
      });
    }, value, (data) => {
      const findings = toRuleFindings(getDiagnosticFindings(data));
      setRuleFindingsByKey((prev) => {
        const next = { ...prev };
        if (findings.length === 0) {
          delete next[validationKey];
        } else {
          next[validationKey] = findings;
        }
        return next;
      });
    });
  };
 
  const onUpdateUnit = (unit: string) => {
    // Optimistically update the property
    dispatch(
      api.util.updateQueryData(
        "unitopsSimulationobjectsRetrieve",
        { id: currentObject!.id },
        (cachedSimulationObject) => {
          const cachedProperty =
            cachedSimulationObject.properties.ContainedProperties.find(
              (prop) => prop.id === property.id,
            );
          if (cachedProperty) {
            cachedProperty.unit = unit;
          }
        },
      ),
    );
    updateBackendWithToast(() => {
      return updateProperty({
        id: property.id,
        patchedPropertyInfo: {
          unit: unit,
        },
      });
    }, unit);
  };
 
  const updateBackendWithToast = (
    fn: () => ReturnType<MutationResult>,
    updatedValue: string | number | boolean,
    onSuccess?: (data: unknown) => void,
  ) => {
    // Update the backend
    fn()
      .unwrap()
      .then((data) => {
        onSuccess?.(data);
        if (printToast) {
          toast.success(
            `Successfully updated ${property.displayName} to ${updatedValue}`,
          );
        }
        return;
      })
      .catch((error) => {
        // TODO: Add error handling in future to correctly display this error
        console.error(
          `Failed to update ${property.displayName} to ${updatedValue}: ${error.data.error}`,
        );
        return;
      });
  };
  switch (property.type) {
    case "numeric_arg":
    case "numeric": {
      return (
        <IndexedVariableWithUnit
          property={property}
          objectId={currentObject?.id}
          onUpdateValue={onUpdateIndexedValue}
          onUpdateUnit={onUpdateUnit}
          withMSSConnection={withMSSConnection}
          deletePropertyFunction={deletePropertyFunction}
          ruleFindingsByKey={ruleFindingsByKey}
        />
      );
    }
    case "checkbox": {
      return (
        <PropertyCheckbox
          property={property}
          onUpdateValue={onUpdateIndexedValue}
        />
      );
    }
    case "text": {
      return (
        <PropertyTextField
          property={property}
          onUpdateValue={onUpdateIndexedValue}
        />
      );
    }
    case "dropdown": {
      return (
        <PropertyDropdown
          property={property}
          onUpdateValue={onUpdateIndexedValue}
          schema={propertySchema}
        ></PropertyDropdown>
      )
    }
    default: {
      return <>Default Type</>;
    }
  }
}
 
export interface OrderedPropertyListProps {
  properties: PropertyInfoRead[];
  schema: PropertySetType;
  deletePropertyFunction?: (property_val_key: string) => void;
}
 
export function OrderedPropertyList(props: OrderedPropertyListProps) {
  // With no calculation modes, we don't really want to order the property list, other than splitting out operating variables and reactive properties.
  const isComposition = props.schema.type === "composition" ? true : false;
  const withMSSConnection = props.schema.type === "composition" ? false : true;
 
  const mapFn = (property, index) => {
    return (
      <Property
        key={index}
        property={property}
        withMSSConnection={withMSSConnection}
        deletePropertyFunction={props.deletePropertyFunction}
      />
    );
  };
 
  const isOperatingVariable = (prop: PropertyValueRead) => {
    return (
      prop.controlManipulated !== null ||
      props.schema.stateVars?.includes(prop.key)
      // && prop.controlSetPoint === null
    );
  };
 
  const operatingVariables = props.properties.filter((prop) =>
    isOperatingVariable(prop),
  );
  const reactiveProperties = props.properties.filter(
    (prop) => !isOperatingVariable(prop),
  );
 
  return (
    <div className=" mx-4">
      {isComposition ? (
        <div className="mt-2">
          {operatingVariables.map((property, index) => mapFn(property, index))}
        </div>
      ) : (
        <div className="flex flex-col gap-4">
          <div className="flex flex-col gap-2">
            <div className="gap-2">
              {operatingVariables.map((property, index) =>
                mapFn(property, index),
              )}
            </div>
          </div>
          <div className="flex flex-col gap-1">
            <div>
              {reactiveProperties.map((property, index) =>
                mapFn(property, index),
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
 
export type PropertySetComponentProps = {
  schema: PropertySetType;
  properties: PropertyInfoRead[];
  propertySet: PropertySetRead;
};
 
export function Properties() {
  const currentObj = useCurrentObject();
  const objectSchema = objects[currentObj!.objectType!];
  const propertySetGroups = objectSchema.propertySetGroups!;
 
  return Object.keys(propertySetGroups).map((groupKey) => (
    <PropertySetGroup key={groupKey} groupKey={groupKey} />
  ));
}
 
function manageCompoundDisplay(
  isStreamObj: boolean,
  compositionData: PropertyInfoRead | undefined,
) {
  const compounds: PropertyValueRead | undefined = compositionData?.values;
  if (!compounds || !isStreamObj) {
    return infoMessages.error;
  }
 
  let total: number = 0;
  Object?.keys(compounds).forEach((key) => {
    const compValue = compounds[key]?.value;
    if (compValue || compValue != undefined) {
      total += +compValue;
    }
  });
  return total === 1 ? infoMessages.success : infoMessages.error;
}
 
function PropertySetGroup({ groupKey }) {
  const currentObj = useCurrentObject();
  const propertySet = currentObj!.properties;
  const objectSchema = objects[currentObj!.objectType!];
  const propertySetGroups = objectSchema.propertySetGroups!;
  const schema = propertySetGroups[groupKey];
  const propertyInfos = useMemo(() => {
    if (Object.keys(objectSchema?.properties).length !== 0) {
      return propertySet.ContainedProperties.filter(
        (prop) =>{
          return objectSchema?.properties[prop.key]?.propertySetGroup == groupKey
        },
      );
    }
    // If there are no properties defined in the group schema, it must be something
    // like machineLearning block where there are custom properties
    // TODO: Improve how machineLearningBlock is handled (so that we can still have custom properties as well as the ML properties)
    return propertySet.ContainedProperties;
  }, [groupKey, objectSchema?.properties, propertySet.ContainedProperties]);
 
  const moleFracComp = propertyInfos.find((p) => p.key === "mole_frac_comp");
  // Convert compound values to a simpler format for validation
  //uses useMemo to avoid recalculating when inputs haven't changed
  // only processes data when viewing composition tab
  const compoundValues = useMemo(() => {
    if (groupKey !== "composition" || !moleFracComp?.values) return undefined;
 
    // convert to the format expected by PropertiesStatus
    const result: { [key: string]: { value: string | number } } = {};
 
    Object.entries(moleFracComp.values).forEach(([key, valueObj]) => {
      // skip the id property and any non-object values
      Iif (key === "id" || !valueObj || typeof valueObj !== "object") return;
 
      // only include if it has a value property
      if ("value" in valueObj) {
        result[key] = { value: valueObj.value };
      }
    });
 
    return result;
  }, [moleFracComp?.values, groupKey]);
 
  // Showing property set status
  let statusInfo = propertySet.unspecifiedProperties;
  const compInfo = manageCompoundDisplay(
    isStream(currentObj),
    propertyInfos.find((property) => property.key === "mole_frac_comp"),
  );
 
  if (groupKey === "composition" && isStream(currentObj)) {
    statusInfo = compInfo === infoMessages.success ? [] : ["mole_frac_comp"];
  }
  Iif (compInfo === infoMessages.success && groupKey !== "composition") {
    // Remove "Compounds" if compInfo is success
    statusInfo = propertySet.unspecifiedProperties?.filter(
      (prop) => prop !== "Compounds" && prop !== "mole_frac_comp",
    );
  }
 
  // Enable/Disable additional properties
  const toggleProperty = propertyInfos.find(
    (prop) => prop.key === schema.toggle,
  );
  const toggleEnabled =
    !toggleProperty || toggleProperty?.values[0].value == true; // there is only one propertyValue for a toggle property
  const otherProperties = propertyInfos.filter(
    (prop) => prop.key !== schema.toggle,
  );
 
  return (
    <AccordionItem value={groupKey}>
      <AccordionTrigger
        variant="default"
        statusIcon={
          <PropertiesStatus
            propertySet={statusInfo}
            propertySetGroup={groupKey}
            compoundValues={compoundValues}
          />
        }
      >
        {schema.displayName}
      </AccordionTrigger>
      <AccordionContent className="p-0">
        {toggleProperty && (
          <div className="p-2">
            <Property property={toggleProperty} />
          </div>
        )}
        {toggleEnabled &&
          (schema.type === "composition" ? (
            <CompoundListSection
              schema={schema}
              properties={otherProperties}
              propertySet={propertySet}
            />
          ) : currentObj!.objectType! === "specificationBlock" ? (
            <SpecificationBlockProperties
              schema={schema}
              properties={otherProperties}
              propertySet={propertySet}
            />
          ) : (
            <OrderedPropertyList properties={otherProperties} schema={schema} />
          ))}
      </AccordionContent>
    </AccordionItem>
  );
}