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

94.44% Statements 51/54
71.74% Branches 99/138
88.89% Functions 8/9
96.08% Lines 49/51

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              113x 113x 113x 113x 113x 113x 113x 113x   113x 113x   113x 113x 113x 113x           113x                                                       153x 153x 153x 153x 153x 153x   153x 67x       67x   67x 73x 82x     73x 73x 60x     73x             67x 23x         153x   153x                     159x 159x 159x     159x 159x 159x 3x 3x 3x   3x 6x       159x                                                                                                     113x 113x  
/*
 * 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 { useParams } from 'react-router-dom'
import { Text, FormInput, MultiTypeInputType, getMultiTypeFromValue, SelectOption } from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import cx from 'classnames'
import { defaultTo, get, isEqual, isUndefined } from 'lodash-es'
import { connect } from 'formik'
import { useStrings } from 'framework/strings'
import type { AllNGVariables } from '@pipeline/utils/types'
import { StepViewType } from '@pipeline/components/AbstractSteps/Step'
import MultiTypeSecretInput from '@secrets/components/MutiTypeSecretInput/MultiTypeSecretInput'
import type { InputSetData } from '@pipeline/components/AbstractSteps/Step'
import { useVariablesExpression } from '@pipeline/components/PipelineStudio/PiplineHooks/useVariablesExpression'
import { useQueryParams } from '@common/hooks'
import { VariableType } from './CustomVariableUtils'
import css from './CustomVariables.module.scss'
export interface CustomVariablesData {
  variables: AllNGVariables[]
  isPropagating?: boolean
  canAddVariable?: boolean
}
export const RegExAllowedInputExpression = /^<\+input>\.(?:allowedValues\((.*?)\))?$/
export interface CustomVariableInputSetExtraProps {
  variableNamePrefix?: string
  domId?: string
  template?: CustomVariablesData
  path?: string
  allValues?: CustomVariablesData
}
export interface CustomVariableInputSetProps extends CustomVariableInputSetExtraProps {
  initialValues: CustomVariablesData
  onUpdate?: (data: CustomVariablesData) => void
  stepViewType?: StepViewType
  inputSetData?: InputSetData<CustomVariablesData>
  formik?: any
  allowableTypes: MultiTypeInputType[]
}
function CustomVariableInputSetBasic(props: CustomVariableInputSetProps): React.ReactElement {
  const {
    initialValues,
    template,
    stepViewType = StepViewType.Edit,
    path,
    variableNamePrefix = '',
    domId,
    inputSetData,
    formik,
    allValues,
    allowableTypes
  } = props
  const basePath = path?.length ? `${path}.` : ''
  const { expressions } = useVariablesExpression()
  const { getString } = useStrings()
  const { executionId } = useQueryParams<Record<string, string>>()
  const { executionIdentifier, triggerIdentifier } = useParams<Record<string, string>>()
 
  React.useEffect(() => {
    Eif (
      (isUndefined(executionIdentifier) && isUndefined(executionId) && isUndefined(triggerIdentifier)) ||
      triggerIdentifier === 'new'
    ) {
      const VariablesFromFormik = get(formik?.values, `${basePath}variables`, [])
      const updatedVariables =
        template?.variables?.map((templateVariable: AllNGVariables) => {
          const index = defaultTo(
            allValues?.variables?.findIndex((variable: AllNGVariables) => variable.name === templateVariable.name),
            -1
          )
          const pipelineVariable = allValues?.variables?.[index]
          const formikValue = VariablesFromFormik.find(
            (variable: AllNGVariables) => variable.name === templateVariable.name
          )
 
          return {
            name: pipelineVariable?.name,
            type: pipelineVariable?.type,
            value: formikValue?.value || pipelineVariable?.default || ''
          }
        }) || []
 
      if (!isEqual(get(formik?.values, `${basePath}variables`, []), updatedVariables)) {
        formik.setFieldValue(`${basePath}variables`, updatedVariables)
      }
    }
  }, [formik?.values, template?.variables, allValues?.variables])
 
  const formikVariables = get(formik?.values, `${basePath}variables`, [])
 
  return (
    <div className={cx(css.customVariablesInputSets, 'customVariables')} id={domId}>
      {stepViewType === StepViewType.StageVariable && initialValues.variables.length > 0 && (
        <section className={css.subHeader}>
          <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>
        </section>
      )}
      {template?.variables?.map?.(variable => {
        // find Index from values, not from template variables
        const index = formikVariables.findIndex((fVar: AllNGVariables) => variable.name === fVar.name)
        const value = defaultTo(variable.value, '')
        Iif (getMultiTypeFromValue(value as string) !== MultiTypeInputType.RUNTIME) {
          return
        }
        const isAllowedValues = RegExAllowedInputExpression.test(value as string)
        const items: SelectOption[] = []
        if (isAllowedValues) {
          const match = (value as string).match(RegExAllowedInputExpression)
          Eif (match && match?.length > 1) {
            Iif (variable.type === 'Number') {
              items.push(...match[1].split(',').map(item => ({ label: item, value: parseFloat(item) })))
            } else Eif (variable.type === 'String') {
              items.push(...match[1].split(',').map(item => ({ label: item, value: item })))
            }
          }
        }
        return (
          <div key={`${variable.name}${index}`} className={css.variableListTable}>
            <Text>{`${variableNamePrefix}${variable.name}`}</Text>
            <Text>{variable.type}</Text>
            <div className={css.valueRow}>
              {variable.type === VariableType.Secret ? (
                <MultiTypeSecretInput
                  expressions={expressions}
                  allowableTypes={allowableTypes}
                  name={`${basePath}variables[${index}].value`}
                  disabled={inputSetData?.readonly}
                  label=""
                />
              ) : (
                <>
                  {isAllowedValues ? (
                    <FormInput.MultiTypeInput
                      className="variableInput"
                      name={`${basePath}variables[${index}].value`}
                      label=""
                      useValue
                      selectItems={items}
                      multiTypeInputProps={{
                        allowableTypes,
                        expressions,
                        selectProps: { disabled: inputSetData?.readonly, items: items }
                      }}
                      disabled={inputSetData?.readonly}
                    />
                  ) : (
                    <FormInput.MultiTextInput
                      className="variableInput"
                      name={`${basePath}variables[${index}].value`}
                      multiTextInputProps={{
                        textProps: { type: variable.type === 'Number' ? 'number' : 'text' },
                        allowableTypes,
                        expressions
                      }}
                      label=""
                      disabled={inputSetData?.readonly}
                    />
                  )}
                </>
              )}
            </div>
          </div>
        )
      })}
    </div>
  )
}
const CustomVariableInputSet = connect(CustomVariableInputSetBasic)
export { CustomVariableInputSet }