All files / src/pages/flowsheet-page/flowsheet/LeftSideBar/Formulas useFormulaEditorState.ts

59.64% Statements 34/57
61.01% Branches 36/59
66.66% Functions 2/3
86.11% Lines 31/36

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                                                                                                                                                                              29x 29x                                                 53x       53x 8x     61x   29x             111x 53x 53x   53x 53x 53x   86x   119x 53x       53x           9x   9x         9x 9x         9x               104x   53x       12x 12x   12x 12x               125x   18x                         233x    
import type { RefObject } from "react";
import { useRef, useState } from "react";
import {
  isCursorInAggregateFunctionContext,
  isCursorInAggregateKeyContext,
  unwrapAggregateSuggestionMarkup,
} from "./aggregateFormula";
import { isFormulaWithinMaxLength } from "./formulaLimits";
import {
  type FormulaSection,
  getFormulaSectionIndex,
  inferPlainTextChangeCursorPosition,
  markupToPlainText,
  parseFormulaSections,
} from "./formulaSections";
 
export type FormulaMentionRef = {
  /** Clear react-mentions' internal suggestion menu. */
  clearSuggestions: () => void;
  /** Re-run react-mentions query parsing with plain-text coordinates. */
  updateMentionsQueries: (value: string, caretPosition: number) => void;
};
 
type FormulaEditorState = {
  /** Ref for the real input rendered by react-mentions. */
  inputRef: RefObject<HTMLInputElement>;
  /** Ref for the react-mentions component imperative API. */
  mentionRef: RefObject<FormulaMentionRef | null>;
  /** Persisted formula markup, including react-mentions tokens. */
  formula: string;
  /** User-visible formula text with mention markup converted to display text. */
  plainFormula: string;
  /** Whether the caret is immediately after a selected unit mention. */
  prevSectionIsUnit: boolean;
  /** Unit ID used to request property suggestions after a unit mention. */
  selectedUnitId: number | undefined;
  /** Unit mention display text immediately before the caret. */
  selectedUnitDisplayText: string;
  /** Caret position in plain-text coordinates. */
  cursorPosition: number;
  /** Whether the caret is completing `@property_key` inside an aggregate call. */
  isAggregateKeyContext: boolean;
  /** Whether the caret is completing an aggregate function name. */
  isAggregateFunctionContext: boolean;
  /** Sync a react-mentions change event into markup and plain-text state. */
  changeValue: (
    e: { target: { value: string } },
    newValue?: string,
    newPlainTextValue?: string,
  ) => void;
  /** Sync caret-derived suggestion context after the user moves the selection. */
  changeSelection: (target?: {
    value: string;
    selectionStart: number | null;
  }) => void;
};
 
type FormulaEditorStateParams = {
  /** Formula markup loaded from the property value record. */
  initialFormula: string;
  /** Prevents local edits when the parent field is read-only. */
  disabled: boolean;
};
 
type FormulaEditorSnapshot = {
  /** Prop value this local editor state was initialized from. */
  sourceFormula: string;
  formula: string;
  plainFormula: string;
  sections: FormulaSection[];
  currentSectionIndex: number;
  cursorPosition: number;
  isAggregateKeyContext: boolean;
  isAggregateFunctionContext: boolean;
};
 
function formulaEditorSnapshot({
  sourceFormula,
  formula,
  plainFormula = markupToPlainText(formula),
  cursorPosition = plainFormula.length,
}: {
  sourceFormula: string;
  formula: string;
  plainFormula?: string;
  cursorPosition?: number;
}): FormulaEditorSnapshot {
  const sections = parseFormulaSections(formula);
  return {
    sourceFormula,
    formula,
    plainFormula,
    sections,
    currentSectionIndex: getFormulaSectionIndex(sections, cursorPosition),
    cursorPosition,
    isAggregateKeyContext: isCursorInAggregateKeyContext(
      plainFormula,
      cursorPosition,
    ),
    isAggregateFunctionContext: isCursorInAggregateFunctionContext(
      plainFormula,
      cursorPosition,
    ),
  };
}
 
/**
 * Keep persisted react-mentions markup separate from plain-text editing state.
 *
 * ``formula`` is the markup value saved to the backend. ``plainFormula`` and
 * ``cursorPosition`` use the textarea's plain-text coordinates so
 * react-mentions queries can be refreshed after async property data arrives.
 */
export function useFormulaEditorState({
  initialFormula,
  disabled,
}: FormulaEditorStateParams): FormulaEditorState {
  const [editor, setEditor] = useState(() =>
    formulaEditorSnapshot({
      sourceFormula: initialFormula,
      formula: initialFormula,
    }),
  );
  let currentEditor = editor;
  if (currentEditor.sourceFormula !== initialFormula) {
    currentEditor = formulaEditorSnapshot({
      sourceFormula: initialFormula,
      formula: initialFormula,
    });
    setEditor(currentEditor);
  }
  const inputRef = useRef<HTMLInputElement>(null);
  const mentionRef = useRef<FormulaMentionRef | null>(null);
  const previousSection =
    currentEditor.sections[currentEditor.currentSectionIndex - 1];
  const prevSectionIsUnit = previousSection?.type === "unit";
  const selectedUnitNumericId = Number(previousSection?.id);
  const selectedUnitId =
    prevSectionIsUnit && Number.isFinite(selectedUnitNumericId)
      ? selectedUnitNumericId
      : undefined;
  const selectedUnitDisplayText = prevSectionIsUnit
    ? previousSection.displayText
    : "";
 
  const changeValue = (
    e: { target: { value: string } },
    newValue?: string,
    newPlainTextValue?: string,
  ): void => {
    Iif (disabled) return;
    const inputElement = inputRef.current;
    Iif (!inputElement) return;
    const updatedValue = unwrapAggregateSuggestionMarkup(
      newValue ?? e.target.value,
    );
    Iif (!isFormulaWithinMaxLength(updatedValue)) return;
    const updatedPlainValue =
      newPlainTextValue ?? markupToPlainText(updatedValue);
    const nextCursorPosition = inferPlainTextChangeCursorPosition(
      currentEditor.plainFormula,
      updatedPlainValue,
      inputElement.selectionStart ?? updatedPlainValue.length,
    );
    setEditor(
      formulaEditorSnapshot({
        sourceFormula: currentEditor.sourceFormula,
        formula: updatedValue,
        plainFormula: updatedPlainValue,
        cursorPosition: nextCursorPosition,
      }),
    );
  };
 
  const changeSelection = (target?: {
    value: string;
    selectionStart: number | null;
  }): void => {
    const inputElement = target ?? inputRef.current;
    const nextPlainFormula = inputElement?.value ?? currentEditor.plainFormula;
    const nextCursorPosition =
      inputElement?.selectionStart ?? currentEditor.cursorPosition;
    setEditor(
      formulaEditorSnapshot({
        sourceFormula: currentEditor.sourceFormula,
        formula: currentEditor.formula,
        plainFormula: nextPlainFormula,
        cursorPosition: nextCursorPosition,
      }),
    );
  };
 
  return {
    inputRef,
    mentionRef,
    formula: currentEditor.formula,
    plainFormula: currentEditor.plainFormula,
    prevSectionIsUnit,
    selectedUnitId,
    selectedUnitDisplayText,
    cursorPosition: currentEditor.cursorPosition,
    isAggregateKeyContext: currentEditor.isAggregateKeyContext,
    isAggregateFunctionContext: currentEditor.isAggregateFunctionContext,
    changeValue,
    changeSelection,
  };
}