All files / src/pages/flowsheet-page/flowsheet/LeftSideBar/Formulas FormulaInputField.tsx

84.48% Statements 49/58
74.13% Branches 43/58
77.77% Functions 14/18
88.46% Lines 46/52

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                                                                                                                                                    53x                           53x     53x 53x 53x     53x 53x 53x 53x     53x           6x 6x       2x 2x         2x 3x     2x                   2x           2x       53x 53x   24x               53x               181x 181x         181x     196x                           53x     2x     151x       28x         28x   168x               28x                           53x           53x       36x               7x 7x   7x 7x         53x             12x                                                                                                                                                             200x                 3x               1x                
import type { FocusEvent, ReactElement } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Mention, MentionsInput } from "react-mentions";
import {
  api,
  PropertyInfoRead,
  PropertyValueRead,
  SimulationObjectRetrieveRead,
  useCorePropertyvaluePartialUpdateMutation,
} from "@/api/apiStore.gen";
import {
  useCurrentObject,
  useFlowsheetUnitOps,
} from "@/hooks/flowsheetObjects";
import { useSimulationObjectPropertySet } from "@/hooks/properties";
import { useAppDispatch } from "@/store/hooks";
import {
  AGGREGATE_FUNCTION_TRIGGER,
  AGGREGATE_KEY_TRIGGER,
  AGGREGATE_SUGGESTION_MARKUP,
  type AggregateSuggestion,
} from "./aggregateFormula";
import { useAggregateFormulaSuggestions } from "./useAggregateFormulaSuggestions";
import { useFormulaEditorState } from "./useFormulaEditorState";
 
const formulaSuggestionsScrollbarStyle = `
  .formula-mentions-list > ul {
    max-height: 200px !important;
  }
 
  .formula-mentions-list > ul::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
 
  .formula-mentions-list > ul::-webkit-scrollbar-thumb {
    background-color: hsl(var(--border));
    border-radius: 5px;
    border: 1px solid hsl(var(--background));
  }
 
  .formula-mentions-list > ul::-webkit-scrollbar-track {
    border-radius: 5px;
  }
 
  .formula-mentions-list > ul::-webkit-scrollbar-button {
    display: none;
  }
`;
 
export type FormulaMentionGroup = {
  id: string;
  objectId: number;
  display: string;
  includeProperty: (propertyInfo: PropertyInfoRead) => boolean;
  displayPrefix?: string;
  hideFromDefaultSuggestions?: boolean;
};
 
export function FormulaInputField({
  property,
  propertyValue,
  simulationObjectId,
  onSave,
  disabled = false,
  formulaMentionGroups = [],
}: {
  property: PropertyInfoRead;
  propertyValue: PropertyValueRead;
  simulationObjectId?: number;
  onSave?: () => void;
  disabled?: boolean;
  formulaMentionGroups?: FormulaMentionGroup[];
}): ReactElement {
  const initialFormula = propertyValue?.formula || "";
  const {
    inputRef,
    mentionRef,
    formula,
    plainFormula,
    prevSectionIsUnit,
    selectedUnitId,
    selectedUnitDisplayText,
    cursorPosition,
    isAggregateKeyContext,
    isAggregateFunctionContext,
    changeValue,
    changeSelection,
  } = useFormulaEditorState({ initialFormula, disabled });
 
  // data options: list of objects
  const flowsheetUnitOps = useFlowsheetUnitOps();
  const currentObject = useCurrentObject();
  const dispatch = useAppDispatch();
 
  // Determine which object ID to use for cache updates
  const effectiveObjectId = simulationObjectId ?? currentObject?.id;
  const properties = useSimulationObjectPropertySet(selectedUnitId);
  const [updateValue] = useCorePropertyvaluePartialUpdateMutation();
  const [dropdownPosition, setDropdownPosition] = useState<"bottom" | "top">(
    "bottom",
  );
  const mentionMarkup = "@[__display__](__id__)";
 
  const handleBackendUpdate = (
    _e: FocusEvent<HTMLInputElement | HTMLTextAreaElement>,
    clickedSuggestion?: boolean,
  ): void => {
    Iif (disabled) return;
    if (clickedSuggestion) return; // don't update backend if a suggestion was clicked
 
    // Update the cache optimistically so both table and sidebar stay in sync
    if (effectiveObjectId && Number.isFinite(effectiveObjectId)) {
      try {
        dispatch(
          api.util.updateQueryData(
            "unitopsSimulationobjectsRetrieve",
            { id: effectiveObjectId },
            (draft: SimulationObjectRetrieveRead | undefined) => {
              const targetProp = draft?.properties?.ContainedProperties?.find(
                (prop: PropertyInfoRead) => prop.id === property.id,
              );
              if (targetProp?.values?.length) {
                targetProp.values[0].formula = formula;
              }
            },
          ),
        );
      } catch {
        // A missing optimistic cache entry should not block the server update.
      }
    }
 
    updateValue({
      id: propertyValue.id,
      patchedPropertyValue: {
        formula: formula,
      },
    }).then(() => {
      onSave?.();
    });
  };
 
  const trigger: string = prevSectionIsUnit ? "" : "@";
  const selectedMentionGroup = useMemo(
    () =>
      formulaMentionGroups.find(
        (group) =>
          group.objectId === selectedUnitId &&
          group.display === selectedUnitDisplayText,
      ),
    [formulaMentionGroups, selectedUnitDisplayText, selectedUnitId],
  );
 
  const displayOptions = useCallback(
    (propertyInfo: PropertyInfoRead): AggregateSuggestion[] => {
      if (
        selectedMentionGroup &&
        !selectedMentionGroup.includeProperty(propertyInfo)
      ) {
        return [];
      }
      const sourceObjectId = selectedUnitId ?? currentObject?.id;
      const displayGroup = formulaMentionGroups.find(
        (group) =>
          group.objectId === sourceObjectId &&
          group.includeProperty(propertyInfo),
      );
      const prefix = selectedMentionGroup
        ? ""
        : (displayGroup?.displayPrefix ?? "");
      return propertyInfo.values.map((value) => ({
        id: "prop" + value.id,
        display:
          prefix + propertyInfo.displayName + value.indexedSetNames.join(" "),
      }));
    },
    [
      currentObject?.id,
      formulaMentionGroups,
      selectedMentionGroup,
      selectedUnitId,
    ],
  );
 
  const dataOptions = useMemo(() => {
    if (prevSectionIsUnit) {
      // display the properties of the unit
      return properties?.ContainedProperties?.flatMap(displayOptions);
    }
    const unitOptions =
      flowsheetUnitOps?.map((obj) => ({
        id: "unit" + obj.id,
        display: obj.componentName + ": ",
      })) ?? [];
    const groupedObjectOptions = formulaMentionGroups.map((group) => ({
      id: "unit" + group.objectId,
      display: group.display,
    }));
    const currentObjectProperties =
      currentObject?.properties?.ContainedProperties?.filter(
        (propertyInfo) =>
          !formulaMentionGroups.some(
            (group) =>
              group.hideFromDefaultSuggestions &&
              currentObject.id === group.objectId &&
              group.includeProperty(propertyInfo),
          ),
      ).flatMap(displayOptions) || [];
 
    return groupedObjectOptions
      .concat(unitOptions)
      .concat(currentObjectProperties);
  }, [
    prevSectionIsUnit,
    properties,
    flowsheetUnitOps,
    formulaMentionGroups,
    displayOptions,
    currentObject?.properties?.ContainedProperties,
    currentObject?.id,
  ]);
 
  const { aggregateFunctionSuggestions, aggregateKeySuggestions } =
    useAggregateFormulaSuggestions({
      flowsheetUnitOps,
      plainFormula,
      cursorPosition,
    });
 
  useEffect(() => {
    // React-mentions query positions are plain-text coordinates, so this must
    // pass plainFormula rather than the persisted markup formula.
    if (mentionRef.current && dataOptions) {
      mentionRef.current.updateMentionsQueries(
        plainFormula,
        inputRef.current?.selectionStart ?? 0,
      );
    }
  }, [dataOptions, inputRef, mentionRef, plainFormula]);
 
  const calculateDropdownPosition = (): void => {
    const inputRect = inputRef.current?.getBoundingClientRect();
    Iif (!inputRect) return;
 
    const dropdownHeight = 200;
    setDropdownPosition(
      window.innerHeight - inputRect.bottom < dropdownHeight ? "top" : "bottom",
    );
  };
 
  return (
    <div className="flex flex-col gap-3 w-full mb-2">
      <MentionsInput
        ref={mentionRef}
        aria-label={"mentions-input-" + property.displayName}
        value={formula}
        onChange={changeValue}
        onSelect={(event) => changeSelection(event.currentTarget)}
        onBlur={handleBackendUpdate}
        inputRef={inputRef}
        readOnly={disabled}
        disabled={disabled}
        onFocus={calculateDropdownPosition}
        allowSpaceInQuery={true}
        allowSuggestionsAboveCursor={true}
        style={{
          control: {
            fontSize: "14px",
            padding: "5px",
            border: "1px solid hsl(var(--input))",
            borderRadius: "0.375rem",
          },
          input: {
            padding: "7px",
          },
          suggestions: {
            left: 0,
            width: "100%",
            backgroundColor: "transparent",
            marginTop: dropdownPosition === "bottom" ? "5px" : "auto",
            marginBottom: dropdownPosition === "top" ? "5px" : "auto",
            top: dropdownPosition === "top" ? "auto" : "100%",
            bottom: dropdownPosition === "top" ? "100%" : "auto",
            zIndex: 9999,
            list: {
              backgroundColor: "hsl(var(--background))",
              fontSize: "14px",
              overflowY: "auto",
              maxHeight: "100px",
            },
            item: {
              width: "100%",
              padding: "6px",
              borderBottom: "1px solid rgba(0,0,0,0.15)",
              "&focused": {
                backgroundColor: "hsl(var(--accent))",
              },
            },
          },
        }}
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            // prevent new line (and blur input)
            // TODO: probably a better way to handle this
            inputRef.current?.blur();
            e.preventDefault();
          }
        }}
        placeholder="Use @ to mention variables"
        customSuggestionsContainer={(children) => (
          <div
            id="mentions-container"
            aria-label="Formula suggestions"
            className="bg-background border-border border rounded-md"
            role="region"
          >
            <div className="p-2">
              <strong className="text-sm">
                {isAggregateKeyContext
                  ? "Property Keys"
                  : isAggregateFunctionContext
                    ? "Aggregate Functions"
                    : prevSectionIsUnit
                      ? "Properties"
                      : "Unit Operations"}
              </strong>
            </div>
            <div className="justify-self-center w-11/12 border-b m-1"></div>
            <div className="formula-mentions-list">{children}</div>
            <style>{formulaSuggestionsScrollbarStyle}</style>
          </div>
        )}
      >
        <Mention
          trigger={trigger}
          markup={mentionMarkup}
          displayTransform={(_id, display) => display ?? ""}
          data={dataOptions ?? []}
          appendSpaceOnAdd={prevSectionIsUnit ? true : false}
          className="bg-secondary rounded-md text-sm items-center"
        />
        <Mention
          trigger={AGGREGATE_FUNCTION_TRIGGER}
          data={aggregateFunctionSuggestions}
          markup={AGGREGATE_SUGGESTION_MARKUP}
          displayTransform={(id) => id}
          appendSpaceOnAdd={false}
          className="bg-secondary rounded-md text-sm items-center"
        />
        <Mention
          trigger={AGGREGATE_KEY_TRIGGER}
          data={aggregateKeySuggestions}
          markup={AGGREGATE_SUGGESTION_MARKUP}
          displayTransform={(id) => id}
          appendSpaceOnAdd={false}
          className="bg-secondary rounded-md text-sm items-center"
        />
      </MentionsInput>
    </div>
  );
}