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

92.5% Statements 74/80
86.95% Branches 40/46
94.11% Functions 16/17
93.15% Lines 68/73

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                                            41x 41x               41x     41x 41x   41x 41x         41x 41x 41x   41x 4x 4x   4x               4x 10x 4x 6x       3x 3x     3x 3x 3x 3x   3x       4x       1x       7x   4x 4x     41x 7x 6x 6x 6x 6x 7x 7x         6x   7x 7x 7x           7x 7x 7x               41x 4x 2x               41x   41x   41x   13x   17x         72x       18x           41x     13x 12x             41x 4x 4x 4x 4x   4x 1x   3x         41x                                                                                                             10x                                                                                                    
import {
    PropertyInfoRead,
    PropertyValue,
    useCorePropertyvaluePartialUpdateMutation
} from "@/api/apiStore.gen";
import {
  useCurrentObject,
    useFlowsheetUnitOps
} from "@/hooks/flowsheetObjects";
import { useSimulationObjectPropertySet } from "@/hooks/properties";
import { useEffect, useMemo, useRef, useState } from "react";
import { Mention, MentionsInput } from "react-mentions";
import { getValuesList } from "./getValuesList";
 
 
export function FormulaInputField({
  property,
  propertyValue,
}: {
  property: PropertyInfoRead;
  propertyValue: PropertyValue;
}) {
  const [formula, setFormula] = useState(propertyValue?.formula || "");
  const sectionsRef = useRef<
    {
      id: number;
      type: "text" | "unit" | "prop";
      displayText: string;
      value: string;
    }[]
  >([]);
  const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
 
  // data options: list of objects
  const flowsheetUnitOps = useFlowsheetUnitOps();
  const currentObject = useCurrentObject();
  const prevSectionIsUnit =
    sectionsRef.current[currentSectionIndex - 1]?.type === "unit";
  const properties = useSimulationObjectPropertySet(
    prevSectionIsUnit
      ? +sectionsRef.current[currentSectionIndex - 1]?.id
      : undefined,
  );
  const [updateValue] = useCorePropertyvaluePartialUpdateMutation();
  const [dropdownPosition, setDropdownPosition] = useState("bottom");
  const inputRef = useRef<HTMLInputElement>(null);
 
  const changeValue = (e) => {
    const inputElement = inputRef.current;
    Iif (!inputElement) return;
    // const newValue = inputElement.value;
    let newValue = e.target.value;
    // split into sections
 
    // a tag is like @[First Last](unit1) or @[First Last](prop1)
    // a section is a tag or a string of text
    // store sections as {type: "text"|"unit"|"prop", displayText: string, value: string}
 
    // split by tag
    let newSections = newValue.split(/(@\[[^\]]+\]\([^)]+\))/g);
    newSections = newSections.filter((section) => section !== "");
    newSections = newSections.map((section) => {
      if (section.startsWith("@[")) {
        // value: "@[First Last](1)"
        // displayText: "First Last"
        // use regex to extract the display text
        const match = section.match(/@\[([^\]]+)\]\([^)]+\)/);
        const displayText = match ? match[1] : section;
        // type: "unit" if id = "unit[id]" or "prop" if id = "prop[id]"
        // id: "unit123"
        const idType = section.match(/\(([^)]+)\)/)?.[1];
        const type = idType?.startsWith("unit") ? "unit" : "prop";
        const id = idType.replace(type, "");
        return { id: id, type: type, value: section, displayText: displayText };
      } else {
        return { id: -1, type: "text", value: section, displayText: section };
      }
    });
    // if final section is "unit" or "prop", add an empty text section
    if (
      newSections.length > 0 &&
      newSections[newSections.length - 1].type !== "text"
    ) {
      newSections.push({ id: -1, type: "text", value: "", displayText: "" });
    }
 
    // join sections back together
    newValue = newSections.map((section) => section.value).join("");
 
    setFormula(newValue);
    sectionsRef.current = newSections;
  };
 
  useEffect(() => {
    const handleSelectionChange = () => {
      const cursorPosition = inputRef.current?.selectionStart ?? 0;
      let newSectionIndex = sectionsRef.current.length - 1; // initialize to last section (to handle cursor at end of input)
      let totalSectionLengths = 0;
      for (let i = 0; i < sectionsRef.current.length; i++) {
        totalSectionLengths += sectionsRef.current[i].displayText.length;
        Iif (cursorPosition < totalSectionLengths) {
          newSectionIndex = i;
          break;
        }
      }
      setCurrentSectionIndex(newSectionIndex);
    };
    const inputElement = inputRef.current;
    if (inputElement) {
      inputRef.current.addEventListener(
        "selectionchange",
        handleSelectionChange,
      );
    }
 
    return () => {
      if (inputElement) {
        inputElement.removeEventListener(
          "selectionchange",
          handleSelectionChange,
        );
      }
    };
  }, []);
 
  const handleBackendUpdate = (e, clickedSuggestion) => {
    if (clickedSuggestion) return; // don't update backend if a suggestion was clicked
    updateValue({
      id: propertyValue.id,
      patchedPropertyValue: {
        formula: formula,
      },
    });
  };
 
  const trigger = prevSectionIsUnit ? "" : "@";
 
  const mentionRef = useRef(null);
 
  const dataOptions = useMemo(() => {
    // HERE
    if (prevSectionIsUnit) {
      // display the properties of the unit
      return properties?.ContainedProperties?.flatMap(getValuesList).map(value=>({
        id: "prop" + value.propertyValue.id,
        display: value.displayPath
      }));
    }
    return flowsheetUnitOps?.map((obj) => ({
      id: "unit" + obj.id,
      display: obj.componentName + ": ",
    })).concat(
      (currentObject?.properties?.ContainedProperties?.flatMap(getValuesList) || []).map(value=>({
        id: "prop" + value.propertyValue.id,
        display: value.displayPath
      })))
  }, [prevSectionIsUnit, properties, flowsheetUnitOps, currentObject?.properties?.ContainedProperties]);
 
  useEffect(() => {
    // manually trigger updateMentionsQueries to update the suggestions
    // we need to run this when dataOptions changes (ie. when the backend gives us new data)
    if (mentionRef.current && dataOptions) {
      mentionRef.current.updateMentionsQueries(
        formula,
        inputRef.current?.selectionStart ?? 0,
      );
    }
  }, [dataOptions]);
 
  const calculateDropdownPosition = () => {
    if (inputRef.current) {
      const inputRect = inputRef.current.getBoundingClientRect();
      const spaceBelow = window.innerHeight - inputRect.bottom;
      const dropdownHeight = 200; // Approximate height of the dropdown
 
      if (spaceBelow < dropdownHeight) {
        setDropdownPosition("top");
      } else {
        setDropdownPosition("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}
        onBlur={handleBackendUpdate}
        inputRef={inputRef}
        onFocus={calculateDropdownPosition}
        allowSpaceInQuery={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",
            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) => {
          Iif (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"
            className="bg-background border-border border rounded-md"
          >
            <div className="p-2">
              <strong className="text-sm">
                {prevSectionIsUnit ? "Properties" : "Unit Operations"}
              </strong>
            </div>
            <div className="justify-self-center w-11/12 border-b m-1"></div>
            <div id="mentions-list">{children}</div>
            <style>
              {`
                            /* webKit scrollbar styling */
                            ::-webkit-scrollbar {
                                width: 8px;
                                height: 8px;
                            }
 
                            ::-webkit-scrollbar-thumb {
                                background-color: hsl(var(--border));
                                border-radius: 5px;
                                border: 1px solid hsl(var(--background));
                            }
 
                            ::-webkit-scrollbar-track {
                                border-radius: 5px;
                            }
 
                            ::-webkit-scrollbar-button {
                                display: none;
                            }
                           
                            #mentions-list > ul {
                                max-height: 200px !important;
                            }
                            `}
            </style>
          </div>
        )}
      >
        <Mention
          trigger={trigger} // the dataOptions for prop mentions will not properly style unless you change the trigger to something other than "". e.g. ":" shows expected styling.
          data={dataOptions}
          appendSpaceOnAdd={prevSectionIsUnit ? true : false}
          className="bg-secondary rounded-md text-sm items-center"
        />
      </MentionsInput>
    </div>
  );
}