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

83.08% Statements 54/65
65.98% Branches 64/97
68.42% Functions 13/19
85% Lines 51/60

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              1x 1x 1x 1x 1x 1x 1x 1x 1x                               8x     1x 16x   16x   16x 4x   4x             4x 4x     4x     16x 16x 16x   16x 2x     16x 1x 1x 1x 1x       16x                 16x 9x 11x   9x 2x             2x 2x     2x       16x 9x 9x 9x 11x           9x 9x           16x         20x 20x   20x                                                                   1x                                             1x  
/*
 * 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, Card, Button, TextInput } from '@wings-software/uicore'
import { Intent } from '@harness/design-system'
import { connect, FormikContext } from 'formik'
import { get, isEmpty } from 'lodash-es'
import { useStrings } from 'framework/strings'
import css from './Map.module.scss'
 
export type MapType = { [key: string]: string }
export type MapUIType = { id: string; key: string; value: string }[]
 
export interface MapProps {
  name: string
  label?: string | React.ReactElement
  formik?: FormikContext<any>
  disabled?: boolean
  style?: React.CSSProperties
  keyLabel?: string
  valueLabel?: string
}
 
function generateNewValue(): { id: string; key: string; value: string } {
  return { id: uuid('', nameSpace()), key: '', value: '' }
}
 
export const Map = (props: MapProps): React.ReactElement => {
  const { name, label, formik, disabled, style } = props
 
  const { getString } = useStrings()
 
  const [value, setValue] = React.useState<MapUIType>(() => {
    const initialValue = get(formik?.values, name, '') as MapType
 
    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 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(() => {
    const initialValue = get(formik?.values, name, '') as MapType
    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, value])
 
  React.useEffect(() => {
    const valueInCorrectFormat: MapType = {}
    Eif (Array.isArray(value)) {
      value.forEach(mapValue => {
        Iif (mapValue.key && mapValue.value) {
          valueInCorrectFormat[mapValue.key] = mapValue.value
        }
      })
    }
 
    Eif (isEmpty(valueInCorrectFormat)) {
      formik?.setFieldValue(name, undefined)
    } else {
      formik?.setFieldValue(name, valueInCorrectFormat)
    }
  }, [name, value, formik?.setFieldValue])
 
  return (
    <div style={style}>
      {label}
      <Card style={{ width: '100%' }}>
        {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 style={{ flexGrow: 1 }}>
                {index === 0 && <Text margin={{ bottom: 'xsmall' }}>{props.keyLabel || getString('keyLabel')}</Text>}
                <TextInput
                  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 style={{ flexGrow: 1 }}>
                {index === 0 && (
                  <Text margin={{ bottom: 'xsmall' }}>{props.valueLabel || getString('valueLabel')}</Text>
                )}
                <div className={cx(css.group, css.withoutAligning, css.withoutSpacing)}>
                  <TextInput
                    value={valueValue}
                    intent={(touched || hasSubmitted) && error ? Intent.DANGER : Intent.NONE}
                    errorText={(touched || hasSubmitted) && valueError ? valueError : undefined}
                    disabled={disabled}
                    onChange={e => changeValue(index, 'value', (e.currentTarget as HTMLInputElement).value)}
                    data-testid={`value-${name}-[${index}]`}
                  />
                  {!disabled && (
                    <Button
                      icon="main-trash"
                      iconProps={{ size: 20 }}
                      minimal
                      data-testid={`remove-${name}-[${index}]`}
                      style={{ marginTop: 4 }}
                      onClick={() => removeValue(index)}
                    />
                  )}
                </div>
              </div>
            </div>
          )
        })}
 
        {!disabled && (
          <Button intent="primary" minimal text={getString('plusAdd')} data-testid={`add-${name}`} onClick={addValue} />
        )}
      </Card>
 
      {(touched || hasSubmitted) && error && typeof error === 'string' && (
        <Text intent={Intent.DANGER} margin={{ top: 'xsmall' }}>
          {error}
        </Text>
      )}
    </div>
  )
}
 
export default connect(Map)