All files / modules/10-common/components/MultiTypeMapInputSet MultiTypeMapInputSet.tsx

78.38% Statements 58/74
59.68% Branches 74/124
65% Functions 13/20
79.71% Lines 55/69

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              118x 118x 118x 118x                   118x 118x 118x 118x 118x 118x     118x                                                           31x     118x                         81x   74x 26x 26x     26x             26x 26x     26x     74x   74x 74x 74x   74x 2x     74x 2x 2x 2x 2x       74x                 74x 29x 29x     29x   29x 3x             3x 3x     3x       74x 33x 33x 33x 34x           33x 33x 33x                 74x                     76x     76x                                                                                     2x                                                                                 118x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React from 'react'
import { v4 as nameSpace, v5 as uuid } from 'uuid'
import cx from 'classnames'
import {
  Text,
  TextInput,
  MultiTextInput,
  Button,
  getMultiTypeFromValue,
  MultiTypeInputType,
  MultiTextInputProps,
  RUNTIME_INPUT_VALUE
} from '@wings-software/uicore'
import { Intent, FontVariation } from '@harness/design-system'
import { connect, FormikContext } from 'formik'
import { get, isEmpty } from 'lodash-es'
import { ConfigureOptions, ConfigureOptionsProps } from '@common/components/ConfigureOptions/ConfigureOptions'
import { useStrings } from 'framework/strings'
import MultiTypeFieldSelector, {
  MultiTypeFieldSelectorProps
} from '@common/components/MultiTypeFieldSelector/MultiTypeFieldSelector'
import css from './MultiTypeMapInputSet.module.scss'
 
export type MapType = { [key: string]: string }
export type MultiTypeMapType = MapType | string
 
export type MapUIType = { id: string; key: string; value: string }[]
export type MultiTypeUIMapType = MapUIType | string
 
interface MultiTypeMapConfigureOptionsProps
  extends Omit<ConfigureOptionsProps, 'value' | 'type' | 'variableName' | 'onChange'> {
  variableName?: ConfigureOptionsProps['variableName']
}
 
export interface MultiTypeMapProps {
  name: string
  multiTypeFieldSelectorProps: Omit<MultiTypeFieldSelectorProps, 'name' | 'defaultValueToReset' | 'children'>
  valueMultiTextInputProps?: Omit<MultiTextInputProps, 'name'>
  enableConfigureOptions?: boolean
  configureOptionsProps?: MultiTypeMapConfigureOptionsProps
  formik?: FormikContext<any>
  style?: React.CSSProperties
  cardStyle?: React.CSSProperties
  disabled?: boolean
  keyLabel?: string
  valueLabel?: string
  appearance?: 'default' | 'minimal'
  restrictToSingleEntry?: boolean
}
 
function generateNewValue(): { id: string; key: string; value: string } {
  return { id: uuid('', nameSpace()), key: '', value: '' }
}
 
export const MultiTypeMapInputSet = (props: MultiTypeMapProps): React.ReactElement => {
  const {
    name,
    multiTypeFieldSelectorProps,
    valueMultiTextInputProps = {},
    enableConfigureOptions = true,
    configureOptionsProps,
    cardStyle,
    formik,
    disabled,
    appearance = 'default',
    restrictToSingleEntry,
    ...restProps
  } = props
 
  const [value, setValue] = React.useState<MapUIType>(() => {
    let initialValue = get(formik?.values, name, '')
    Iif (initialValue === RUNTIME_INPUT_VALUE) {
      initialValue = []
    }
    const initialValueInCorrectFormat = Object.keys(initialValue || {}).map(key => ({
      id: uuid('', nameSpace()),
      key: key,
      value: initialValue[key]
    }))
 
    // Adding a default value
    Eif (Array.isArray(initialValueInCorrectFormat) && initialValueInCorrectFormat.length === 0) {
      initialValueInCorrectFormat.push(generateNewValue())
    }
 
    return initialValueInCorrectFormat as MapUIType
  })
 
  const { getString } = useStrings()
 
  const error = get(formik?.errors, name, '')
  const touched = get(formik?.touched, name)
  const hasSubmitted = get(formik, 'submitCount', 0) > 0
 
  const addValue = (): void => {
    setValue(currentValue => [...currentValue, generateNewValue()])
  }
 
  const removeValue = (index: number): void => {
    setValue(currentValue => {
      const newCurrentValue = [...currentValue]
      newCurrentValue.splice(index, 1)
      return newCurrentValue
    })
  }
 
  const changeValue = (index: number, key: 'key' | 'value', newValue: string): void => {
    formik?.setFieldTouched(name, true)
    setValue(currentValue => {
      const newCurrentValue = [...currentValue]
      newCurrentValue[index][key] = newValue
      return newCurrentValue
    })
  }
 
  React.useEffect(() => {
    let initialValue = get(formik?.values, name, '')
    Iif (initialValue === RUNTIME_INPUT_VALUE) {
      initialValue = []
    }
    const valueWithoutEmptyItems = value.filter(item => !!item.value)
 
    if (isEmpty(valueWithoutEmptyItems) && initialValue) {
      const initialValueInCorrectFormat = Object.keys(initialValue || {}).map(key => ({
        id: uuid('', nameSpace()),
        key: key,
        value: initialValue[key]
      }))
 
      // Adding a default value
      Eif (Array.isArray(initialValueInCorrectFormat) && initialValueInCorrectFormat.length === 0) {
        initialValueInCorrectFormat.push(generateNewValue())
      }
 
      setValue(initialValueInCorrectFormat)
    }
  }, [formik?.values, name])
 
  React.useEffect(() => {
    const valueInCorrectFormat: MapType = {}
    Eif (Array.isArray(value)) {
      value.forEach(mapValue => {
        Iif (mapValue.key) {
          valueInCorrectFormat[mapValue.key] = mapValue.value
        }
      })
    }
 
    Eif (get(formik?.values, name, '') !== RUNTIME_INPUT_VALUE) {
      Eif (isEmpty(valueInCorrectFormat)) {
        formik?.setFieldValue(name, undefined)
      } else {
        formik?.setFieldValue(name, valueInCorrectFormat)
      }
    } else if (!isEmpty(valueInCorrectFormat)) {
      formik?.setFieldValue(name, valueInCorrectFormat)
    }
  }, [name, value, formik?.setFieldValue])
 
  return (
    <div className={cx(css.group, css.withoutSpacing, appearance === 'minimal' ? css.minimalCard : '')} {...restProps}>
      <MultiTypeFieldSelector
        name={name}
        defaultValueToReset={[{ id: uuid('', nameSpace()), key: '', value: '' }]}
        style={{ flexGrow: 1, marginBottom: 0 }}
        {...multiTypeFieldSelectorProps}
        disableTypeSelection={multiTypeFieldSelectorProps.disableTypeSelection || disabled}
      >
        <>
          {value.map(({ id, key, value: valueValue }, index: number) => {
            const keyError = get(error, `[${index}].key`)
            // const valueError = get(error, `[${index}].value`)
 
            return (
              <div className={cx(css.group, css.withoutAligning)} key={id}>
                <div>
                  {index === 0 && (
                    <Text margin={{ bottom: 'xsmall' }} font={{ variation: FontVariation.FORM_LABEL }}>
                      {props.keyLabel || getString('keyLabel')}
                    </Text>
                  )}
                  <TextInput
                    name={`${name}[${index}].key`}
                    value={key}
                    intent={(touched || hasSubmitted) && error ? Intent.DANGER : Intent.NONE}
                    errorText={(touched || hasSubmitted) && keyError ? keyError : undefined}
                    disabled={disabled}
                    onChange={e => changeValue(index, 'key', (e.currentTarget as HTMLInputElement).value)}
                    data-testid={`key-${name}-[${index}]`}
                  />
                </div>
                <div>
                  {index === 0 && (
                    <Text margin={{ bottom: 'xsmall' }} font={{ variation: FontVariation.FORM_LABEL }}>
                      {props.valueLabel || getString('valueLabel')}
                    </Text>
                  )}
                  <div className={cx(css.group, css.withoutAligning, css.withoutSpacing)}>
                    <MultiTextInput
                      name=""
                      textProps={{ name: `${name}[${index}].value` }}
                      value={valueValue}
                      intent={(touched || hasSubmitted) && error ? Intent.DANGER : Intent.NONE}
                      disabled={disabled}
                      onChange={v => changeValue(index, 'value', v as any)}
                      data-testid={`value-${name}-[${index}]`}
                      allowableTypes={[MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION]}
                      {...valueMultiTextInputProps}
                      style={{ flexShrink: 1 }}
                    />
                    {!disabled && (
                      <Button
                        icon="main-trash"
                        iconProps={{ size: 20 }}
                        minimal
                        data-testid={`remove-${name}-[${index}]`}
                        onClick={() => removeValue(index)}
                      />
                    )}
                  </div>
                </div>
              </div>
            )
          })}
 
          {(restrictToSingleEntry && Array.isArray(value) && value?.length === 1) || disabled ? null : (
            <Button
              intent="primary"
              minimal
              text={getString('plusAdd')}
              data-testid={`add-${name}`}
              onClick={addValue}
              style={{ padding: 0 }}
            />
          )}
        </>
      </MultiTypeFieldSelector>
      {enableConfigureOptions &&
        typeof value === 'string' &&
        getMultiTypeFromValue(value) === MultiTypeInputType.RUNTIME && (
          <ConfigureOptions
            style={{ marginTop: 2 }}
            value={value}
            type={getString('map')}
            variableName={name}
            showRequiredField={false}
            showDefaultField={false}
            showAdvanced={true}
            onChange={val => formik?.setFieldValue(name, val)}
            {...configureOptionsProps}
            isReadonly={props.disabled}
          />
        )}
    </div>
  )
}
 
export default connect(MultiTypeMapInputSet)