All files / src/components/forms VariableElementSelect.tsx

77.5% Statements 62/80
56.79% Branches 46/81
75% Functions 18/24
76.92% Lines 60/78

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 2391x   1x 1x             1x       1x 1x       1x 1x 1x   1x 1x 1x                                                 1x 10x       1x               3x 3x 3x 3x 3x 3x 6x   3x 6x   3x 6x   3x   3x   31x       3x   5x     21x 21x   21x         21x 3x 8x         8x               18x                       3x 3x 1x   2x       2x 1x   1x 3x 9x   11x 3x 3x   3x         3x                       3x                   3x     2x                                                 2x 2x         55x                                                           1x      
import React, { memo, useContext, useMemo, useState } from "react";
import { SingleValue } from "react-select";
import { ScriptEditorContext } from "components/script/context/ScriptEditorContext";
import {
  VariableCreatableSelect,
  VariableRenameButton,
  VariableRenameCompleteButton,
  VariableRenameInput,
  VariableSelectWrapper,
} from "components/forms/VariableSelect";
import {
  customEventSelectors,
  variableSelectors,
} from "store/features/entities/entitiesSelectors";
import { useAppDispatch, useAppSelector } from "store/hooks";
import {
  groupVariables,
  namedVariablesByContext,
} from "renderer/lib/variables";
import entitiesActions from "store/features/entities/entitiesActions";
import editorActions from "store/features/editor/editorActions";
import l10n from "shared/lib/lang/l10n";
import type { ScriptVariableElement } from "shared/lib/scriptValue/types";
import { isVariableCustomEvent } from "shared/lib/entities/entitiesHelpers";
import { CheckIcon, PencilIcon } from "ui/icons/Icons";
import {
  findSelectOption,
  Option,
  OptGroup,
  SelectCommonProps,
} from "ui/form/Select";
 
type VariableElementOption = Option & {
  variable: ScriptVariableElement;
  variableName: string;
};
 
interface VariableElementOptionGroup extends OptGroup {
  options: VariableElementOption[];
}
 
interface VariableElementSelectProps extends SelectCommonProps {
  name: string;
  value: ScriptVariableElement | undefined;
  entityId: string;
  allowRename?: boolean;
  allowCustomEventParameters?: boolean;
  onChange: (newValue: ScriptVariableElement) => void;
}
 
const optionValue = (variable: ScriptVariableElement): string =>
  variable.index
    ? JSON.stringify([variable.value, variable.index.value])
    : variable.value;
 
const VariableElementSelectComponent = ({
  value,
  onChange,
  entityId,
  allowRename,
  allowCustomEventParameters = true,
  ...selectProps
}: VariableElementSelectProps) => {
  const context = useContext(ScriptEditorContext);
  const dispatch = useAppDispatch();
  const [renameVisible, setRenameVisible] = useState(false);
  const [editValue, setEditValue] = useState("");
  const variableId = value?.value ?? "";
  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).filter(
        (variable) =>
          allowCustomEventParameters || !isVariableCustomEvent(variable.id),
      ),
    [allowCustomEventParameters, allVariables, context, customEvent],
  );
  const options = useMemo<VariableElementOptionGroup[]>(
    () =>
      groupVariables(variables).map((group) => ({
        label: group.name,
        options: group.variables.flatMap<VariableElementOption>((variable) => {
          const definition = variablesLookup[variable.id];
          const customEventVariable = customEvent?.variables[variable.id];
          const arrayLength =
            definition?.type === "array"
              ? definition.length
              : customEventVariable?.passByReference === "array"
                ? customEventVariable.length
                : undefined;
          if (arrayLength !== undefined) {
            return Array.from({ length: arrayLength }, (_, index) => {
              const indexedVariable: ScriptVariableElement = {
                type: "variable",
                value: variable.id,
                index: { type: "number", value: index },
              };
              return {
                value: optionValue(indexedVariable),
                label: `${variable.name}[${index}]`,
                variable: indexedVariable,
                variableName: `${variable.name}[${index}]`,
              };
            });
          }
          return [
            {
              value: variable.id,
              label: variable.displayName,
              variable: { type: "variable", value: variable.id },
              variableName: variable.name,
            },
          ];
        }),
      })),
    [customEvent, variables, variablesLookup],
  );
  const currentValue = useMemo(() => {
    if (!value) {
      return undefined;
    }
    const selectedOption = findSelectOption<VariableElementOption>(
      options,
      optionValue(value),
    );
    if (selectedOption || value.index !== undefined) {
      return selectedOption;
    }
    return options
      .flatMap((group) => group.options)
      .find((option) => option.variable.value === value.value);
  }, [options, value]);
  const currentVariable = variables.find(({ id }) => id === variableId);
  const valueIsLocal = variableId.startsWith("L");
  const valueIsTemp = variableId.startsWith("T");
  const canRename =
    !!variableId &&
    allowRename &&
    !valueIsTemp &&
    context.entityType !== "customEvent";
 
  const onRenameFinish = () => {
    if (variableId) {
      dispatch(
        entitiesActions.renameVariable({
          variableId: valueIsLocal ? `${entityId}__${variableId}` : variableId,
          name: editValue,
        }),
      );
    }
    setRenameVisible(false);
  };
 
  const onCreateVariable = (inputValue: string) => {
    const name = inputValue.trim();
    if (!name) {
      return;
    }
    const action = entitiesActions.addVariable({ name });
    dispatch(action);
    onChange({ type: "variable", value: action.payload.variableId });
  };
 
  return (
    <VariableSelectWrapper
      onClick={(event) => {
        Iif (event.altKey && variablesLookup[variableId]) {
          dispatch(editorActions.selectVariable({ variableId }));
        }
      }}
    >
      {renameVisible ? (
        <VariableRenameInput
          value={editValue}
          onChange={(event) => setEditValue(event.currentTarget.value)}
          onKeyDown={(event) => {
            if (event.key === "Enter") {
              onRenameFinish();
            } else if (event.key === "Escape") {
              setRenameVisible(false);
            }
          }}
          onFocus={(event) => event.currentTarget.select()}
          onBlur={onRenameFinish}
          autoFocus
        />
      ) : (
        <VariableCreatableSelect
          value={currentValue}
          options={options}
          onChange={(newValue: SingleValue<Option>) => {
            Eif (newValue) {
              onChange((newValue as VariableElementOption).variable);
            }
          }}
          onCreateOption={onCreateVariable}
          formatOptionLabel={(option, { context: labelContext }) =>
            labelContext === "value"
              ? `$${(option as VariableElementOption).variableName}`
              : option.label
          }
          {...selectProps}
        />
      )}
      {canRename &&
        (renameVisible ? (
          <VariableRenameCompleteButton
            onClick={onRenameFinish}
            title={l10n("FIELD_RENAME")}
          >
            <CheckIcon />
          </VariableRenameCompleteButton>
        ) : (
          <VariableRenameButton
            onClick={() => {
              setEditValue(currentVariable?.name ?? currentValue?.label ?? "");
              setRenameVisible(true);
            }}
            title={l10n("FIELD_RENAME")}
          >
            <PencilIcon />
          </VariableRenameButton>
        ))}
    </VariableSelectWrapper>
  );
};
 
export const VariableElementSelect = memo<VariableElementSelectProps>(
  VariableElementSelectComponent,
);