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

96.77% Statements 30/31
76.36% Branches 42/55
88.89% Functions 8/9
96.55% Lines 28/29

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              1x 1x 1x 1x               1x 1x 1x 1x 1x 1x     1x                                                         1x                           16x   15x 34x 136x 34x     15x 15x 15x                                           14x     14x   56x                                                 1x                           5x 5x 5x                                                             1x  
/*
 * Copyright 2022 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,
  FormInput,
  Button,
  getMultiTypeFromValue,
  MultiTypeInputType,
  MultiTextInputProps
} from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import { FieldArray, connect, FormikContext } from 'formik'
import { get } 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 './MultiTypeCustomMap.module.scss'
 
export type MapValue = { id: string; key: string; value: string }[]
export type MultiTypeMapValue = MapValue | string
type MultiTypeMapConfigureOptionsOmit = 'value' | 'type' | 'variableName' | 'onChange'
 
interface MultiTypeMapConfigureOptionsProps extends Omit<ConfigureOptionsProps, MultiTypeMapConfigureOptionsOmit> {
  variableName?: ConfigureOptionsProps['variableName']
}
 
interface MultiTypeMapKey {
  label: string
  value: string
}
export interface MultiTypeCustomMapProps {
  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
  appearance?: 'default' | 'minimal'
  restrictToSingleEntry?: boolean
  multiTypeMapKeys: MultiTypeMapKey[]
}
 
export const MultiTypeCustomMap = (props: MultiTypeCustomMapProps): React.ReactElement => {
  const {
    name,
    multiTypeFieldSelectorProps,
    valueMultiTextInputProps = {},
    enableConfigureOptions = true,
    configureOptionsProps,
    cardStyle,
    formik,
    disabled,
    appearance = 'default',
    restrictToSingleEntry,
    multiTypeMapKeys = [],
    ...restProps
  } = props
 
  const getDefaultResetValue = () => {
    const defaultKeys: { [key: string]: string }[] = [{ id: uuid('', nameSpace()) }]
    multiTypeMapKeys.forEach((key: MultiTypeMapKey) => (defaultKeys[0][key.value] = ''))
    return defaultKeys
  }
 
  const value = get(formik?.values, name, ...getDefaultResetValue()) as MultiTypeMapValue
  const { getString } = useStrings()
  return (
    <div className={cx(css.group, css.withoutSpacing, appearance === 'minimal' ? css.minimalCard : '')} {...restProps}>
      {typeof value === 'string' && getMultiTypeFromValue(value) === MultiTypeInputType.RUNTIME ? (
        <FormInput.MultiTextInput
          style={{ flexGrow: 1, marginBottom: 0 }}
          name={name}
          multiTextInputProps={{
            allowableTypes: [MultiTypeInputType.FIXED, MultiTypeInputType.RUNTIME]
          }}
          {...multiTypeFieldSelectorProps}
        />
      ) : (
        <MultiTypeFieldSelector
          name={name}
          defaultValueToReset={getDefaultResetValue()}
          style={{ flexGrow: 1, marginBottom: 0 }}
          {...multiTypeFieldSelectorProps}
          disableTypeSelection={multiTypeFieldSelectorProps.disableTypeSelection || disabled}
        >
          <FieldArray
            name={name}
            render={({ remove }) => (
              <>
                {Array.isArray(value) &&
                  value.map((row, index: number) => (
                    <div className={cx(css.group)} key={row.id}>
                      {multiTypeMapKeys.map(({ label: keyLabel, value: keyValue }, keyIndex) => {
                        return (
                          <div key={`${row.id + keyIndex}`}>
                            {index === 0 && (
                              <Text font={{ variation: FontVariation.FORM_LABEL }} margin={{ bottom: 'xsmall' }}>
                                {keyLabel ?? getString('keyLabel')}
                              </Text>
                            )}
                            <FormInput.MultiTextInput
                              label=""
                              name={`${name}[${index}][${keyValue}]`}
                              multiTextInputProps={{
                                allowableTypes: [MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION],
                                ...valueMultiTextInputProps
                              }}
                              disabled={disabled}
                            />
                          </div>
                        )
                      })}
                      <div className={cx(css.group, css.withoutAligning, css.withoutSpacing)}>
                        <Button
                          icon="main-trash"
                          iconProps={{ size: 20 }}
                          minimal
                          data-testid={`remove-${name}-[${index}]`}
                          onClick={() => remove(index)}
                          disabled={disabled}
                        />
                      </div>
                    </div>
                  ))}
 
                {restrictToSingleEntry && Array.isArray(value) && value?.length === 1 ? null : (
                  <Button
                    intent="primary"
                    minimal
                    text={getString('plusAdd')}
                    data-testid={`add-${name}`}
                    onClick={() => {
                      const currentValue = formik?.values?.[name] || []
                      const newVal = [...currentValue, ...getDefaultResetValue()]
                      formik?.setFieldValue(name, newVal)
                    }}
                    disabled={disabled}
                    style={{ padding: 0 }}
                  />
                )}
              </>
            )}
          />
        </MultiTypeFieldSelector>
      )}
      {enableConfigureOptions &&
        typeof value === 'string' &&
        getMultiTypeFromValue(value) === MultiTypeInputType.RUNTIME && (
          <ConfigureOptions
            style={{ marginTop: 11 }}
            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(MultiTypeCustomMap)