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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 | 152x 70x 82x 82x 45x 45x 11006x 7x 7x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 1x 1x 1x 11006x 3889x 3889x 3889x 3889x 45054x 3889x 6173x 6173x 3889x 3889x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 11006x 2199x 1535x 664x 664x 56x 664x 664x 664x 11006x 11x 11006x 195x 11006x 11006x 1x 11006x 3x 3x 3x 3x 3x 1x 11006x 1x 11006x 11006x 11006x 11006x 11006x 1x 1x 1x | import DebouncedInput from "@/ahuora-design-system/ui/debounced-input";
import {
PropertyInfoRead,
PropertyValueRead,
useCoreControlvaluesCreateMutation,
useCoreControlvaluesPartialUpdateMutation,
useCorePropertyvalueAutoReplaceCreateMutation,
useCorePropertyvaluePartialUpdateMutation,
useCoreRecyclepropertyPartialUpdateMutation,
} from "@/api/apiStore.gen";
import { round_to_sf_dp } from "@/functions/roundNumber";
import { useCurrentObject, useSimulationObjectGroup, useStreamType } from "@/hooks/flowsheetObjects";
import { getPropertyData, useSimulationObjectPropertySet } from "@/hooks/properties";
import { Repeat2, Replace, X } from "lucide-react";
import { useMemo, useState } from "react";
import { Button } from "../../../../../../ahuora-design-system/ui/button";
import { ToolTipCover } from "../../../../../../ahuora-design-system/ui/tooltip";
import { cn } from "../../../../../../lib/utils";
import { FormulaInputField } from "../../../LeftSideBar/Formulas/FormulaInputField";
import { useRatingMode } from "../../../LeftSideBar/Scenarios/useCurrentScenario";
import { CalculateFromTarget, ControlTarget, isFreeVariable, isStateVariable } from "../ControlTarget";
import { PropertySelector } from "../PropertySelector";
import PropertyOptions from "./PropertyOptions";
import { UnitsDropdown } from "./UnitsDropdown";
import { ReplaceInfo } from "./VariableWithUnit/ReplaceInfo";
import type { RuleFinding, RuleSeverity } from "../../../Diagnostics/useRuleValidation";
function _hasStateVariable(valueDict) {
if (valueDict.id !== undefined) {
return isStateVariable(valueDict);
} else {
return Object.values(valueDict).some(_hasStateVariable);
}
}
function hasStateVariable(property: PropertyInfoRead) {
return property.type === "numeric" && _hasStateVariable(property.values);
}
export interface VariableWithUnitProps {
property: PropertyInfoRead;
displayName?: string;
objectId?: number;
onUpdateValue: (value: string) => void;
onUpdateUnit: (unit: string) => void;
withMSSConnection?: boolean; // should be applied if multi steady state applies
deletePropertyFunction?: () => void; // should only be for compounds
value: PropertyValueRead;
ruleFindings?: RuleFinding[];
}
const severityRank: Record<RuleSeverity, number> = {
error: 4,
warning: 3,
info: 2,
suggestion: 1,
};
const pickTopFinding = (findings: RuleFinding[]) =>
findings.reduce<RuleFinding | null>((current, finding) => {
if (!current) {
return finding;
}
return severityRank[finding.severity] > severityRank[current.severity]
? finding
: current;
}, null);
export function VariableWithUnit(props: VariableWithUnitProps) {
// Track only user intent to add a formula (not synced with props)
const [isAddingFormula, setIsAddingFormula] = useState(false);
const deletePropertyFunction = props.deletePropertyFunction;
const [updateRecycleProperty] = useCoreRecyclepropertyPartialUpdateMutation();
const [updateValue] = useCorePropertyvaluePartialUpdateMutation();
const [replaceDof] = useCorePropertyvalueAutoReplaceCreateMutation();
const ratingMode = useRatingMode();
const object = useCurrentObject();
const properties = useSimulationObjectPropertySet(object?.id);
const getStreamType = useStreamType();
const streamType = getStreamType(object?.id);
const [showChangeDof, setShowChangeDof] = useState(false);
const [createControlValue] = useCoreControlvaluesCreateMutation();
const [patchControlValue] = useCoreControlvaluesPartialUpdateMutation();
// Placeholder function for onSelect prop
const onSelectControl = async (manipulatedProperty: PropertyValueRead) => {
if (props.value.controlSetPoint) {
await patchControlValue({
id: props.value.controlSetPoint,
patchedControlValue: {
manipulated: manipulatedProperty.id,
setPoint: props.value.id,
},
});
return;
}
await createControlValue({
controlValue: {
flowsheet: props.property.flowsheet,
manipulated: manipulatedProperty.id,
setPoint: props.value.id,
},
});
};
const dofs = useMemo(() => {
const unspecifiedProperties = properties?.unspecifiedProperties;
const containedProperties = properties?.ContainedProperties;
// get property keys from unspecifiedProperties for fast lookup
const unspecifiedKeys = new Set<string>(unspecifiedProperties);
// filter ContainedProperties by matching property key of unspecified properties (enabled)
const filteredContained = (containedProperties ?? []).filter(cp =>
unspecifiedKeys.has(cp.key)
);
// count how many have values[0] not null or undefined
const filledCount = filteredContained.reduce((count, item) => {
const value = item.values?.[0]?.controlManipulatedId;
return value !== null ? count + 1 : count;
}, 0);
// compare counts
const allFilled =
filledCount === unspecifiedProperties?.length || 0; // -1 for now, to exclude compounds. But this may change in future.
return {
filledCount,
totalUnspecified: unspecifiedProperties?.length || 0,
allFilled,
};
}, [properties]);
const recycleFixed = props.property.recycleConnection?.fixed ?? false;
// Derive whether formula exists directly from props
const hasFormula = Boolean(props.value.formula);
const fixed = ![undefined, null, ""].includes(props.value.value);
const { isControlManipulated, isControlSetPoint, displayName, isRecycle } =
getPropertyData(props.property, props.value, props.displayName);
const disabled = !props.value.enabled && !isControlSetPoint;
const isEditable = Boolean(!disabled || isControlSetPoint || isControlManipulated)
const isGuess = Boolean(
(isEditable && isControlManipulated) || (isRecycle && !isControlSetPoint && !recycleFixed))
// Show formula input if formula exists OR user is adding one
const showFormula = (hasFormula || isAddingFormula) && isEditable && !isGuess;
const roundedValue = useMemo(() => {
if (!fixed) {
return "";
}
let value = props.value.value;
if (props.property.displayName === "Compounds" && isEditable) {
value = props.value.displayValue;
}
const propertyValue = value;
const parsedValue = parseFloat(propertyValue);
return round_to_sf_dp(parsedValue);
}, [fixed, isEditable, props.property.displayName, props.value.displayValue, props.value.value]);
const handleUnitChange = (unit: string) => {
props.onUpdateUnit(unit);
};
const handleUpdate = (update: string | number) => {
props.onUpdateValue(update as string);
};
const handleShowFormula = () => {
if (hasFormula || isAddingFormula) {
// Remove the formula and close
updateValue({
id: props.value.id,
patchedPropertyValue: {
formula: "",
},
});
setIsAddingFormula(false);
} else {
// Open to add a formula
setIsAddingFormula(true);
}
};
const handleChangeRecycleFixed = () => {
updateRecycleProperty({
id: props.property.recycleConnection!.id,
patchedRecycleProperty: {
fixed: !recycleFixed,
},
});
};
const handleAutoReplace = () => {
// Try server auto-replace. if backend doesn't create a setPoint, fall back to manual selection
(async () => {
try {
const resp = await replaceDof({ id: props.value.id });
// rtk query might return {data: ...} or the unwrapped payload depending on usage
const payload = resp && (resp as any).data ? (resp as any).data : resp;
if (!payload || !payload.controlSetPoint) {
// No set point returned, show manual selection
setShowChangeDof(true);
}
} catch (e) {
setShowChangeDof(true);
}
})();
}
const handleDofChange = () => {
setShowChangeDof(true);
}
// Rule findings come back from the backend when we update a value.
// For now we pass them down from the Properties panel so the input can show
// an inline border/tooltip without any global state.
const findings = props.ruleFindings ?? [];
const topFinding = pickTopFinding(findings);
// I surface the highest-severity finding on the input border so users get
// immediate feedback while editing.
const validationState = topFinding?.severity;
Iif (props.property.type === "numeric_arg") {
return (
<div className="w-full p-2 border rounded-lg my-1 bg-muted">
<div className="flex flex-row justify-between items-center">
<div className="flex items-center gap-1">
<p>{displayName}</p>
</div>
</div>
<div className="flex flex-col ap-2">
<div className="flex flex-row gap-2 h-full items-end">
<div className="flex flex-col w-full">
<DebouncedInput
onUpdate={(val) => props.onUpdateValue(val as string)}
value={roundedValue}
type="number"
style={{ width: "100%" }}
isFixed={fixed}
placeholder={"Enter a value..."}
aria-label={`inputField-${displayName}`}
className="bg-transparent"
validationState={validationState}
/>
</div>
{props.property.displayName !== "Compounds" && (
<UnitsDropdown
property={props.property}
onUpdate={props.onUpdateUnit}
/>
)}
</div>
</div>
</div>
);
}
return (
<div
className={cn(
"w-full p-2",
(isEditable || isRecycle) && "border rounded-lg my-1",
(isEditable || isRecycle) && (!isGuess || recycleFixed)
? "bg-muted"
: ""
)}
>
<div className="flex flex-row justify-between items-center">
<div
className="flex items-center gap-1"
color={disabled ? "disabled" : "default"}
>
<p>{displayName}</p>
{isRecycle && !isControlManipulated && !isControlSetPoint && (
<ToolTipCover
content={
recycleFixed
? "This property is fixed."
: "This guess is adjusted by the recycle. Click to fix this property."
}
>
<Repeat2
size={14}
className={recycleFixed ? "text-gray-500" : "text-normal"}
aria-label={`recycle-fix-${displayName}`}
onClick={handleChangeRecycleFixed}
/>
</ToolTipCover>
)}
{isRecycle &&
recycleFixed &&
!isControlManipulated &&
!isControlSetPoint &&
!ratingMode && (
<ToolTipCover content="Replace DoF">
<CalculateFromTarget value={props.value} property={props.property} />
</ToolTipCover>
)}
{isRecycle &&
!isControlSetPoint &&
!isControlManipulated &&
!recycleFixed && (
<ToolTipCover content="Replace an existing parameter">
<ControlTarget
disabled={disabled}
property={props.property}
value={props.value}
>
<Replace
size={14}
color="hsl(var(--muted-foreground))"
aria-label={`recycle-control-${displayName}`}
/>
</ControlTarget>
</ToolTipCover>
)}
</div>
<div className="flex flex-row gap-2">
<PropertyOptions
value={props.value}
property={props.property}
isEditable={isEditable}
isControlSetPoint={isControlSetPoint}
isControlManipulated={isControlManipulated}
onToggleFormula={handleShowFormula}
ratingMode={ratingMode}
recycleFixed={recycleFixed}
isGuess={isGuess}
showFormula={showFormula}
/>
{deletePropertyFunction && (
<X
className="cursor-pointer hover:opacity-70"
aria-label={`deleteProperty-${displayName}`}
onClick={deletePropertyFunction}
/>
)}
</div>
</div>
<div className="flex flex-col ap-2">
<div className="flex flex-row gap-2 h-full items-end">
<div className="flex flex-col w-full">
{(isEditable || isRecycle) && (
<DebouncedInput
onUpdate={handleUpdate}
value={roundedValue}
type="number"
style={{ width: "100%" }}
isFixed={fixed}
placeholder={
isGuess && !recycleFixed
? "Enter a guess..."
: "Enter a value..."
}
aria-label={`inputField-${displayName}`}
className="bg-transparent"
validationState={validationState}
/>
)}
{!isRecycle && !isEditable &&
(
streamType === "feed" && !dofs.allFilled ? (
<Button
className=""
variant="outline"
size="sm"
aria-label={`auto-replace-${displayName}`}
onClick={handleAutoReplace}
>
Not calculated
</Button>
) : (
<ControlTarget
disabled={disabled}
value={props.value}
property={props.property}
>
<div>
<ToolTipCover
asChild
content="This is not a parameter, but you can choose one to replace."
>
<Button
aria-label={`Choose a parameter for ${props.property.displayName} to replace`}
variant="outline"
size="sm"
className="w-full font-normal mt-2"
>
{![undefined, null, ""].includes(roundedValue)
? roundedValue
: "Not calculated"}
</Button>
</ToolTipCover>
</div>
</ControlTarget>
)
)}
</div>
{props.property.displayName !== "Compounds" && (
<UnitsDropdown
property={props.property}
onUpdate={handleUnitChange}
/>
)}
</div>
{!!topFinding?.description && (
<p
className={cn(
"text-xs mt-1",
topFinding.severity === "error" && "text-rose-600",
topFinding.severity === "warning" && "text-amber-600",
topFinding.severity === "info" && "text-blue-600",
topFinding.severity === "suggestion" && "text-emerald-600",
)}
>
{topFinding.description}
</p>
)}
{!ratingMode && (
<ReplaceInfo value={props.value} displayName={displayName} onChangeDof={handleDofChange} />
)}
{showChangeDof && (
<PropertySelector
onSelect={(selected) => {
onSelectControl(selected); // handle selection
setShowChangeDof(false); // close after select
}}
title={`Choose a parameter for ${props.property.displayName} to replace`}
variant="secondary" // buttons Shaded as these are variables that are currently set
// Filter to only properties that are state variables and not controlled in any way.
filter={hasStateVariable}
filterValue={isStateVariable}
header=""
description=""
open={showChangeDof} // open programmatically
onOpenChange={(open) => setShowChangeDof(open)} // closes when clicked outside
>
{/* dropdown anchors beside the Replace/Change UI */}
<div className="w-40 h-0" />
</PropertySelector>
)}
{showFormula && (
<div className="flex flex-row items-baseline gap-2">
<FormulaInputField
property={props.property}
propertyValue={props.value}
/>
<ToolTipCover content="Remove constraint">
<X
color="hsl(var(--muted-foreground))"
onClick={handleShowFormula}
aria-label={`remove-constraint-${displayName}`}
/>
</ToolTipCover>
</div>
)}
</div>
</div>
);
}
|