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

67.65% Statements 46/68
51.72% Branches 45/87
61.9% Functions 13/21
66.1% Lines 39/59

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              119x 119x 119x 119x 119x 119x 119x 119x 119x                                   119x         119x                     19x 19x 19x 12x               12x       12x     19x 19x 19x   19x 2x 2x                     2x       21x 2x     19x                                                       19x   19x 12x 12x 3x           3x 2x     3x       19x         22x 22x                                                                                                             119x  
/*
 * 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 cx from 'classnames'
import { v4 as nameSpace, v5 as uuid } from 'uuid'
import { Text, TextInput, Card, Button, MultiTypeInputType, MultiTextInput } from '@wings-software/uicore'
import { Intent } from '@harness/design-system'
import { get, isEmpty } from 'lodash-es'
import { connect, FormikContext } from 'formik'
import { useStrings } from 'framework/strings'
import css from './List.module.scss'
 
export type ListType = string[]
export type ListUIType = { id: string; value: string }[]
 
export interface ListProps {
  name: string
  label?: string | React.ReactElement
  placeholder?: string
  disabled?: boolean
  style?: React.CSSProperties
  formik?: FormikContext<any>
  expressions?: string[]
  enableExpressions?: boolean
  isNameOfArrayType?: boolean
  labelClassName?: string
}
 
const generateNewValue: () => { id: string; value: string } = () => ({
  id: uuid('', nameSpace()),
  value: ''
})
 
export const List = (props: ListProps): React.ReactElement => {
  const {
    name,
    label,
    placeholder,
    disabled,
    style,
    formik,
    expressions,
    isNameOfArrayType,
    labelClassName = ''
  } = props
  const { getString } = useStrings()
  const [value, setValue] = React.useState<ListUIType>(() => {
    const initialValueInCorrectFormat = [
      {
        id: uuid('', nameSpace()),
        value: ''
      }
    ]
 
    // Adding a default value
    Iif (Array.isArray(initialValueInCorrectFormat) && !initialValueInCorrectFormat.length) {
      initialValueInCorrectFormat.push(generateNewValue())
    }
 
    return initialValueInCorrectFormat
  })
 
  const error = get(formik?.errors, name, '')
  const touched = get(formik?.touched, name)
  const hasSubmitted = get(formik, 'submitCount', 0) > 0
 
  const addValue: () => void = () => {
    setValue(currentValue => {
      Iif (expressions?.length) {
        const updatedValue = currentValue.map((listItem: { id: string; value: string }, listItemIndex: number) => {
          const currentItemFormikValue = get(formik?.values, `${name}[${listItemIndex}]`, '')
          return {
            ...listItem,
            value: currentItemFormikValue
          }
        })
 
        return [...updatedValue, generateNewValue()]
      }
      return currentValue.concat(generateNewValue())
    })
  }
 
  const removeValue: (id: string) => () => void = id => () => {
    setValue(currentValue => currentValue.filter(item => item.id !== id))
  }
 
  const changeValue: (id: string, newValue: string) => void = React.useCallback(
    (id, newValue) => {
      formik?.setFieldTouched(name, true)
      setValue(currentValue => {
        const updatedValue = currentValue.map(item => {
          if (item.id === id) {
            return {
              id,
              value: newValue
            }
          }
          return item
        })
        let valueInCorrectFormat: ListType = []
        if (Array.isArray(updatedValue)) {
          valueInCorrectFormat = updatedValue.filter(item => !!item.value).map(item => item.value)
        }
 
        if (isEmpty(valueInCorrectFormat)) {
          formik?.setFieldValue(name, undefined)
        } else {
          formik?.setFieldValue(name, valueInCorrectFormat)
        }
        return updatedValue
      })
    },
    [formik, name]
  )
  const initialValue = get(formik?.values, name, '') as ListType
 
  React.useEffect(() => {
    const valueWithoutEmptyItems = value.filter(item => !!item.value)
    if (isEmpty(valueWithoutEmptyItems) && initialValue) {
      const initialValueInCorrectFormat = (Array.isArray(initialValue) ? initialValue : []).map(item => ({
        id: uuid('', nameSpace()),
        value: item
      }))
 
      // Adding a default value
      if (Array.isArray(initialValueInCorrectFormat) && !initialValueInCorrectFormat.length) {
        initialValueInCorrectFormat.push(generateNewValue())
      }
 
      setValue(initialValueInCorrectFormat)
    }
  }, [initialValue, name])
 
  return (
    <div style={style}>
      <div className={cx(css.label, labelClassName)}>{label}</div>
      <Card style={{ width: '100%' }}>
        {value.map(({ id, value: valueValue }, index: number) => {
          const valueError = get(error, `[${index}].value`)
          return (
            <div className={css.group} key={id}>
              <div style={{ flexGrow: 1 }}>
                {!expressions && (
                  <TextInput
                    value={valueValue}
                    placeholder={placeholder}
                    onChange={e => changeValue(id, (e.currentTarget as HTMLInputElement).value.trim())}
                    data-testid={`value-${name}-[${index}]`}
                    intent={(touched || hasSubmitted) && error ? Intent.DANGER : Intent.NONE}
                    disabled={disabled}
                    errorText={(touched || hasSubmitted) && valueError ? valueError : undefined}
                  />
                )}
                {expressions && (
                  <MultiTextInput
                    textProps={{ name: isNameOfArrayType ? `${name}[${index}]` : `${name}-${index}` }}
                    placeholder={placeholder}
                    name={isNameOfArrayType ? `${name}[${index}]` : `${name}-${index}`}
                    expressions={expressions}
                    allowableTypes={[MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION]}
                    value={valueValue}
                    onChange={val => {
                      changeValue(id, (val as string)?.trim())
                    }}
                  />
                )}
              </div>
              {!disabled && (
                <Button
                  icon="main-trash"
                  iconProps={{ size: 20 }}
                  minimal
                  onClick={removeValue(id)}
                  data-testid={`remove-${name}-[${index}]`}
                />
              )}
            </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>
      ) : null}
    </div>
  )
}
 
export default connect(List)