All files / src/components/script/fields useVariableFieldContext.ts

100% Statements 26/26
100% Branches 16/16
100% Functions 7/7
100% Lines 25/25

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 442x 2x 2x 2x       2x     2x 3x 3x 6x   3x 6x   3x 6x   3x 3x     3x   3x 28x 28x 28x 2x   26x 1x   25x         3x    
import { useContext, useMemo } from "react";
import { ScriptEditorContext } from "components/script/context/ScriptEditorContext";
import { namedVariablesByContext } from "renderer/lib/variables";
import {
  customEventSelectors,
  variableSelectors,
} from "store/features/entities/entitiesSelectors";
import { useAppSelector } from "store/hooks";
import type { VariableFieldCandidate } from "./fieldHelpers";
 
export const useVariableFieldContext = (entityId: string) => {
  const context = useContext(ScriptEditorContext);
  const variablesLookup = useAppSelector((state) =>
    variableSelectors.selectEntities(state),
  );
  const allVariables = useAppSelector((state) =>
    variableSelectors.selectAll(state),
  );
  const customEvent = useAppSelector((state) =>
    customEventSelectors.selectById(state, entityId),
  );
  const variables = useMemo(
    () => namedVariablesByContext(context, allVariables, customEvent),
    [allVariables, context, customEvent],
  );
  const candidates = useMemo<VariableFieldCandidate[]>(
    () =>
      variables.map(({ id }) => {
        const variable = variablesLookup[id];
        const customEventVariable = customEvent?.variables[id];
        if (variable?.type === "array") {
          return { id, type: variable.type, length: variable.length };
        }
        if (customEventVariable?.passByReference === "array") {
          return { id, type: "array", length: customEventVariable.length };
        }
        return { id, type: "number" };
      }),
    [customEvent, variables, variablesLookup],
  );
 
  return { candidates, customEvent, variables, variablesLookup };
};