All files / modules/70-pipeline/components/PipelineSteps/Steps/CustomVariables CustomVariablesEditableStage.tsx

82.76% Statements 48/58
71.74% Branches 33/46
56.25% Functions 9/16
82.76% Lines 48/58

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              113x 113x 113x 113x 113x                 113x 113x 113x   113x   113x 113x 113x 113x     113x   113x   113x 113x 113x   113x 33x       113x                       33x 33x 33x 33x   33x   33x                       33x   33x   33x 11x 11x 10x 10x         33x               37x 37x 37x 37x                           1x 1x     37x                                     14x 6x   14x 14x   14x                                                                                                                             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 { debounce } from 'lodash-es'
import { Formik, FieldArray, FormikProps } from 'formik'
import { v4 as uuid } from 'uuid'
import {
  Button,
  FormInput,
  MultiTypeInputType,
  getMultiTypeFromValue,
  ButtonSize,
  ButtonVariation,
  Text
} from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import cx from 'classnames'
import * as Yup from 'yup'
 
import { String, useStrings } from 'framework/strings'
import type { UseStringsReturn } from 'framework/strings'
import { TextInputWithCopyBtn } from '@common/components/TextInputWithCopyBtn/TextInputWithCopyBtn'
import { useVariablesExpression } from '@pipeline/components/PipelineStudio/PiplineHooks/useVariablesExpression'
import MultiTypeSecretInput from '@secrets/components/MutiTypeSecretInput/MultiTypeSecretInput'
import { ConfigureOptions } from '@common/components/ConfigureOptions/ConfigureOptions'
import type { NGVariable } from 'services/cd-ng'
 
import { StageErrorContext } from '@pipeline/context/StageErrorContext'
import type { AllNGVariables } from '@pipeline/utils/types'
import { getVariablesValidationField } from '@pipeline/components/PipelineSteps/AdvancedSteps/FailureStrategyPanel/validation'
import type { CustomVariableEditableProps, CustomVariablesData } from './CustomVariableEditable'
import { VariableType, labelStringMap } from './CustomVariableUtils'
import AddEditCustomVariable, { VariableState } from './AddEditCustomVariable'
import css from './CustomVariables.module.scss'
 
const getValidationSchema = (getString: UseStringsReturn['getString']): Yup.Schema<unknown> =>
  Yup.object().shape({
    ...getVariablesValidationField(getString)
  })
 
export function CustomVariablesEditableStage(props: CustomVariableEditableProps): React.ReactElement {
  const {
    initialValues,
    onUpdate,
    domId,
    className,
    yamlProperties,
    enableValidation,
    readonly,
    formName,
    tabName = 'OVERVIEW',
    allowableTypes
  } = props
  const uids = React.useRef<string[]>([])
  const { expressions } = useVariablesExpression()
  const { getString } = useStrings()
 
  const [selectedVariable, setSelectedVariable] = React.useState<VariableState | null>(null)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const debouncedUpdate = React.useCallback(
    debounce((data: CustomVariablesData) => onUpdate?.(data), 500),
    [onUpdate]
  )
 
  function addNew(): void {
    setSelectedVariable({
      variable: { name: '', type: 'String', value: '' },
      index: -1
    })
  }
 
  const { subscribeForm, unSubscribeForm } = React.useContext(StageErrorContext)
 
  const formikRef = React.useRef<FormikProps<unknown> | null>(null)
 
  React.useEffect(() => {
    enableValidation && subscribeForm({ tab: tabName, form: formikRef })
    return () => {
      Eif (enableValidation) {
        unSubscribeForm({ tab: tabName, form: formikRef })
      }
    }
  }, [enableValidation, subscribeForm, unSubscribeForm, tabName])
 
  return (
    <Formik
      initialValues={initialValues}
      onSubmit={data => onUpdate?.(data)}
      validate={debouncedUpdate}
      validationSchema={enableValidation ? getValidationSchema(getString) : undefined}
    >
      {formik => {
        const { values, setFieldValue } = formik
        window.dispatchEvent(new CustomEvent('UPDATE_ERRORS_STRIP', { detail: tabName }))
        formikRef.current = formik
        return (
          <FieldArray name="variables">
            {({ remove, push, replace }) => {
              function handleAdd(variable: NGVariable): void {
                uids.current.push(uuid())
                push(variable)
              }
 
              function handleUpdate(index: number, variable: AllNGVariables): void {
                variable.value = ''
                replace(index, variable)
              }
 
              function handleRemove(index: number): void {
                uids.current.splice(index, 1)
                remove(index)
              }
 
              return (
                <div className={cx(css.customVariablesStage, className)} id={domId}>
                  <AddEditCustomVariable
                    selectedVariable={selectedVariable}
                    setSelectedVariable={setSelectedVariable}
                    addNewVariable={handleAdd}
                    updateVariable={handleUpdate}
                    existingVariables={values.variables}
                    formName={formName}
                  />
                  {values.variables?.length > 0 ? (
                    <div className={cx(css.tableRow, css.headerRow)}>
                      <Text font={{ variation: FontVariation.TABLE_HEADERS }}>{getString('name')}</Text>
                      <Text font={{ variation: FontVariation.TABLE_HEADERS }}>{getString('typeLabel')}</Text>
                      <Text font={{ variation: FontVariation.TABLE_HEADERS }}>{getString('valueLabel')}</Text>
                    </div>
                  ) : null}
                  {values.variables.map?.((variable, index) => {
                    // generated uuid if they are not present
                    if (!uids.current[index]) {
                      uids.current[index] = uuid()
                    }
                    const key = uids.current[index]
                    const yamlData = yamlProperties?.[index] || {}
 
                    return (
                      <div key={key} className={css.tableRow}>
                        <TextInputWithCopyBtn
                          name={`variables[${index}].name`}
                          label=""
                          disabled={true}
                          localName={yamlData.localName}
                          fullName={yamlData.fqn}
                        />
                        <String
                          className={css.valueString}
                          stringID={labelStringMap[variable.type as VariableType]}
                          data-testid={`variables[${index}].type`}
                        />
                        <div className={css.valueColumn} data-type={getMultiTypeFromValue(variable.value as string)}>
                          {variable.type === VariableType.Secret ? (
                            <MultiTypeSecretInput name={`variables[${index}].value`} label="" disabled={readonly} />
                          ) : (
                            <FormInput.MultiTextInput
                              className="variableInput"
                              name={`variables[${index}].value`}
                              label=""
                              disabled={readonly}
                              multiTextInputProps={{
                                defaultValueToReset: '',
                                expressions,
                                textProps: {
                                  disabled: !initialValues.canAddVariable || readonly,
                                  type: variable.type === VariableType.Number ? 'number' : 'text'
                                },
                                allowableTypes
                              }}
                            />
                          )}
                          {getMultiTypeFromValue(variable.value as string) === MultiTypeInputType.RUNTIME ? (
                            <ConfigureOptions
                              value={variable.value as string}
                              defaultValue={variable.default}
                              type={variable.type || /* istanbul ignore next */ 'String'}
                              variableName={variable.name || /* istanbul ignore next */ ''}
                              onChange={(value, defaultValue) => {
                                setFieldValue(`variables[${index}].value`, value)
                                setFieldValue(`variables[${index}].default`, defaultValue)
                              }}
                              isReadonly={readonly}
                            />
                          ) : null}
                          <div className={css.actionButtons}>
                            {initialValues.canAddVariable ? (
                              <React.Fragment>
                                <Button
                                  icon="Edit"
                                  disabled={readonly}
                                  tooltip={<String className={css.tooltip} stringID="common.editVariableType" />}
                                  data-testid={`edit-variable-${index}`}
                                  onClick={() => setSelectedVariable({ variable, index })}
                                  minimal
                                />
                                <Button
                                  icon="main-trash"
                                  disabled={readonly}
                                  data-testid={`delete-variable-${index}`}
                                  tooltip={<String className={css.tooltip} stringID="common.removeThisVariable" />}
                                  onClick={() => handleRemove(index)}
                                  minimal
                                />
                              </React.Fragment>
                            ) : /* istanbul ignore next */ null}
                          </div>
                        </div>
                      </div>
                    )
                  })}
                  {values.canAddVariable && (
                    <Button
                      className={css.addVariable}
                      size={ButtonSize.SMALL}
                      variation={ButtonVariation.LINK}
                      onClick={addNew}
                      text={'+ ' + getString('common.addVariable')}
                    />
                  )}
                </div>
              )
            }}
          </FieldArray>
        )
      }}
    </Formik>
  )
}