All files / src/components/forms VariableSelect.tsx

97.87% Statements 92/94
83.72% Branches 72/86
100% Functions 25/25
97.82% Lines 90/92

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 3538x 8x             8x 8x       8x       8x 8x 8x 8x 8x 8x 8x   8x     8x                                     8x           8x             8x             8x             10x                   10x 10x                                             8x             7x                                               8x                     28x 28x 28x 28x 28x 46x   28x 46x   28x 46x   28x   28x 28x   28x   28x   18x   186x 136x   50x           18x     32x       32x           28x 18x 18x 159x         39x             28x 134x       28x 18x     28x   28x 4x 4x 4x 4x       28x 4x     28x 3x     28x 2x 1x 1x 1x       28x 2x 2x               2x                 2x     28x     7x 1x       28x 1x 1x         1x     1x 1x 1x     28x                                 1x 1x         87x                                                                     8x      
import React, { memo, useContext, useMemo, useState } from "react";
import {
  CreatableSelect,
  Option,
  OptGroup,
  SelectCommonProps,
  findSelectOption,
} from "ui/form/Select";
import styled from "styled-components";
import {
  customEventSelectors,
  variableSelectors,
} from "store/features/entities/entitiesSelectors";
import {
  groupVariables,
  namedVariablesByContext,
} from "renderer/lib/variables";
import { CheckIcon, PencilIcon } from "ui/icons/Icons";
import { IMEInput } from "ui/form/IMEInput";
import entitiesActions from "store/features/entities/entitiesActions";
import l10n from "shared/lib/lang/l10n";
import editorActions from "store/features/editor/editorActions";
import { ScriptEditorContext } from "components/script/context/ScriptEditorContext";
import { UnitsSelectButtonInputOverlay } from "./UnitsSelectButtonInputOverlay";
import { UnitType } from "shared/lib/entities/entitiesTypes";
import { useAppDispatch, useAppSelector } from "store/hooks";
import { SingleValue } from "react-select";
import type { VariableType } from "shared/lib/resources/types";
import { isVariableCustomEvent } from "shared/lib/entities/entitiesHelpers";
 
type VariableOption = Option & {
  variableName: string;
};
 
interface VariableSelectProps extends SelectCommonProps {
  id?: string;
  name: string;
  value?: string;
  entityId: string;
  allowRename?: boolean;
  onChange: (newValue: string) => void;
  units?: UnitType;
  unitsAllowed?: UnitType[];
  onChangeUnits?: (newUnits: UnitType) => void;
  allowedVariableTypes?: VariableType[];
}
 
export const VariableSelectWrapper = styled.div`
  position: relative;
  width: 100%;
  min-width: 78px;
`;
 
export const VariableCreatableSelect: typeof CreatableSelect = styled(
  CreatableSelect,
)`
  .CustomSelect__control {
  }
`;
 
export const VariableRenameInput = styled(IMEInput)`
  &&&& {
    padding-right: 32px;
    height: 28px;
  }
`;
 
export const VariableRenameButton = styled.button`
  position: absolute;
  top: 3px;
  right: 20px;
  width: 22px;
  height: 22px;
  border: 0;
  border-radius: ${(props) => Math.max(0, props.theme.borderRadius - 1)}px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  line-height: 10px;
  font-size: 12px;
  font-weight: bold;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  background: ${(props) => props.theme.colors.input.background};
  border-color: ${(props) => props.theme.colors.input.background};
 
  ${VariableSelectWrapper}:hover & {
    opacity: 1;
  }
 
  &:focus {
    opacity: 1;
  }
  &:hover {
    background: rgba(128, 128, 128, 0.3);
  }
  &:active {
    background: rgba(128, 128, 128, 0.4);
  }
 
  svg {
    width: 12px;
    height: 12px;
    fill: #666;
  }
`;
 
export const VariableRenameCompleteButton = styled.button`
  position: absolute;
  top: 3px;
  right: 3px;
  width: 22px;
  height: 22px;
  border: 0;
  border-radius: ${(props) => Math.max(0, props.theme.borderRadius - 1)}px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  line-height: 10px;
  font-size: 12px;
  font-weight: bold;
  background: transparent;
  border-color: transparent;
 
  &:hover {
    background: rgba(128, 128, 128, 0.3);
  }
  &:active {
    background: rgba(128, 128, 128, 0.4);
  }
  svg {
    width: 12px;
    height: 12px;
    fill: #333;
  }
`;
 
const VariableSelectComponent = ({
  value,
  onChange,
  entityId,
  allowRename,
  units,
  unitsAllowed,
  onChangeUnits,
  allowedVariableTypes,
  ...selectProps
}: VariableSelectProps) => {
  const context = useContext(ScriptEditorContext);
  const [renameVisible, setRenameVisible] = useState(false);
  const [editValue, setEditValue] = useState("");
  const [renameId, setRenameId] = useState("");
  const variablesLookup = useAppSelector((state) =>
    variableSelectors.selectEntities(state),
  );
  const allVariables = useAppSelector((state) =>
    variableSelectors.selectAll(state),
  );
  const customEvent = useAppSelector((state) =>
    customEventSelectors.selectById(state, entityId),
  );
  const dispatch = useAppDispatch();
 
  const valueIsLocal = value && value.startsWith("L");
  const valueIsTemp = value && value.startsWith("T");
  const canRename =
    allowRename && !valueIsTemp && context.entityType !== "customEvent";
 
  const variables = useMemo(
    () =>
      namedVariablesByContext(context, allVariables, customEvent).filter(
        (variable) => {
          if (!allowedVariableTypes) {
            return true;
          }
          if (
            allowedVariableTypes.includes("array") &&
            customEvent &&
            isVariableCustomEvent(variable.id) &&
            !customEvent.variables[variable.id]
          ) {
            return true;
          }
          const variableType =
            variablesLookup[variable.id]?.type ??
            (customEvent?.variables[variable.id]?.passByReference === "array"
              ? "array"
              : "number");
          return allowedVariableTypes.includes(variableType);
        },
      ),
    [allVariables, variablesLookup, context, customEvent, allowedVariableTypes],
  );
 
  const options = useMemo<OptGroup[]>(() => {
    const groupedVariables = groupVariables(variables);
    return groupedVariables.map((g) => {
      const options = g.variables.map((v) => ({
        value: v.id,
        label: v.displayName,
        variableName: v.name,
      }));
      return {
        label: g.name,
        options,
      };
    });
  }, [variables]);
 
  const currentVariable = useMemo(
    () => variables.find((variable) => variable.id === value),
    [value, variables],
  );
 
  const currentValue = useMemo(() => {
    return findSelectOption(options, value);
  }, [options, value]);
 
  const currentLabel = currentVariable ? `$${currentVariable.name}` : "";
 
  const onRenameStart = () => {
    Eif (currentValue) {
      setEditValue(currentVariable?.name ?? currentValue.label);
      setRenameId(currentValue.value);
      setRenameVisible(true);
    }
  };
 
  const onRenameFocus = (e: React.FocusEvent<HTMLInputElement>) => {
    e.currentTarget.select();
  };
 
  const onRename = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditValue(e.currentTarget.value);
  };
 
  const onRenameKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      onRenameFinish();
    } else Eif (e.key === "Escape") {
      setRenameVisible(false);
    }
  };
 
  const onRenameFinish = () => {
    Eif (renameId) {
      Iif (valueIsLocal) {
        dispatch(
          entitiesActions.renameVariable({
            variableId: `${entityId}__${renameId}`,
            name: editValue,
          }),
        );
      } else {
        dispatch(
          entitiesActions.renameVariable({
            variableId: renameId || "0",
            name: editValue,
          }),
        );
      }
    }
 
    setRenameVisible(false);
  };
 
  const onJumpToVariable = (
    e: React.MouseEvent<HTMLDivElement, MouseEvent>,
  ) => {
    if (e.altKey && value && variablesLookup[value]) {
      dispatch(editorActions.selectVariable({ variableId: value }));
    }
  };
 
  const onCreateVariable = (inputValue: string) => {
    const name = inputValue.trim();
    Iif (!name) {
      return;
    }
 
    const type =
      allowedVariableTypes?.length === 1 && allowedVariableTypes[0] === "array"
        ? "array"
        : "number";
    const action = entitiesActions.addVariable({ name, type });
    dispatch(action);
    onChange(action.payload.variableId);
  };
 
  return (
    <VariableSelectWrapper onClick={onJumpToVariable}>
      {renameVisible ? (
        <VariableRenameInput
          key={renameId}
          value={editValue}
          onChange={onRename}
          onKeyDown={onRenameKeyDown}
          onFocus={onRenameFocus}
          onBlur={onRenameFinish}
          autoFocus
        />
      ) : (
        <VariableCreatableSelect
          value={currentValue}
          options={options}
          onChange={(newValue: SingleValue<Option>) => {
            Eif (newValue) {
              onChange(newValue.value);
            }
          }}
          onCreateOption={onCreateVariable}
          formatOptionLabel={(option, { context }) =>
            context === "value"
              ? `$${(option as VariableOption).variableName ?? option.label}`
              : option.label
          }
          {...selectProps}
        />
      )}
      {canRename &&
        (renameVisible ? (
          <VariableRenameCompleteButton
            onClick={onRenameFinish}
            title={l10n("FIELD_RENAME")}
          >
            <CheckIcon />
          </VariableRenameCompleteButton>
        ) : (
          <VariableRenameButton
            onClick={onRenameStart}
            title={l10n("FIELD_RENAME")}
          >
            <PencilIcon />
          </VariableRenameButton>
        ))}
      {units && (
        <UnitsSelectButtonInputOverlay
          parentValue={currentLabel}
          value={units}
          allowedValues={unitsAllowed}
          onChange={onChangeUnits}
        />
      )}
    </VariableSelectWrapper>
  );
};
 
export const VariableSelect = memo<VariableSelectProps>(
  VariableSelectComponent,
);