All files / modules/75-cf/components/CreateFlagWizard FlagElemMultivariate.tsx

98.11% Statements 52/53
80.36% Branches 45/56
100% Functions 18/18
98.08% Lines 51/52

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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315              6x 6x 6x 6x 6x                           6x 6x 6x   6x 6x     6x                                 6x                   108x 107x 107x 107x         107x         107x   107x 1x                   107x 2x 2x         2x     107x 1x     107x 226x   2x       224x       107x 216x   216x 95x     192x   63x   95x     107x                     107x                               267x         1x       226x                             1x                           1x                   226x   458x                                                                     1x 1x                           2x 2x                                                                                                                       6x  
/*
 * 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, { useState, Dispatch, SetStateAction, useCallback } from 'react'
import * as yup from 'yup'
import { isEqual } from 'lodash-es'
import { Classes } from '@blueprintjs/core'
import {
  Formik,
  FormikForm as Form,
  FormInput,
  StepProps,
  Text,
  Layout,
  Select,
  SelectOption,
  Button,
  Container,
  ModalErrorHandler,
  FlexExpander
} from '@wings-software/uicore'
import { FieldArray } from 'formik'
import { Color } from '@harness/design-system'
import { FormikEffect, FormikEffectProps } from '@common/components/FormikEffect/FormikEffect'
import type { Variation } from 'services/cf'
import { useStrings } from 'framework/strings'
import { FeatureFlagMutivariateKind, useValidateVariationValues } from '@cf/utils/CFUtils'
 
import type { FlagWizardFormValues } from './FlagWizard'
import css from './FlagElemVariations.module.scss'
 
export interface FlagElemMultivariateProps extends StepProps<Partial<FlagWizardFormValues>> {
  toggleFlagType: (newFlag: string) => void
  flagTypeOptions: SelectOption[]
  projectIdentifier?: string | number | null | undefined
  // FIXME: Check for the right type
  setModalErrorHandler: Dispatch<SetStateAction<any>>
  isLoadingCreateFeatureFlag: boolean
}
 
interface FlagMultivariateSelectOptions {
  id: string
  label: string
  value: string
}
 
const FlagElemMultivariate: React.FC<FlagElemMultivariateProps> = props => {
  const {
    toggleFlagType,
    flagTypeOptions,
    prevStepData,
    currentStep,
    totalSteps,
    previousStep,
    setModalErrorHandler,
    isLoadingCreateFeatureFlag
  } = props
  const { getString } = useStrings()
  const validateVariationValues = useValidateVariationValues()
  const flagVariationOptions = [
    { label: getString('string'), value: FeatureFlagMutivariateKind.string },
    { label: getString('cf.creationModal.jsonType'), value: FeatureFlagMutivariateKind.json },
    { label: getString('number'), value: FeatureFlagMutivariateKind.number }
  ]
  const [flagMultiRules, setFlagMultiRules] = useState<FlagMultivariateSelectOptions[]>([
    { id: 'variation1', label: 'Variation 1', value: 'variation1' },
    { id: 'variation2', label: 'Variation 2', value: 'variation2' }
  ])
 
  const isLastStep = currentStep?.() === totalSteps?.()
 
  const handleNewFlagType = (newFlagTypeVal: string): void => {
    toggleFlagType(newFlagTypeVal)
  }
 
  /**
   * Since we are dynamically creating new fields, on top of the two that already exists
   * i.e. see 'flagMultiRules' length,
   * we are tracking each individual field with Formik name 'variations.<number>.identifier'
   * and it's label it based on the length of an array from 'flagMultiRules',
   * we are putting dummy values because of weird key render bug
   */
  const addNewFlagMultiRules = (): void => {
    const len = flagMultiRules.length + 1
    const newFlagMultivariateOption = {
      id: `variation${len}`,
      label: `Variation ${len}`,
      value: `variation${len}`
    }
    setFlagMultiRules(prevState => [...prevState, newFlagMultivariateOption])
  }
 
  const onClickBack = (): void => {
    previousStep?.({ ...prevStepData })
  }
 
  const kindToSelectValue = useCallback(kind => {
    switch (kind) {
      case FeatureFlagMutivariateKind.number:
        return flagVariationOptions[2]
      case FeatureFlagMutivariateKind.json:
        return flagVariationOptions[1]
      default:
        return flagVariationOptions[0]
    }
  }, [])
 
  const onFormikEffect: FormikEffectProps['onChange'] = ({ prevValues, nextValues }) => {
    const { variations } = nextValues
 
    if (!isEqual(variations, prevValues.variations)) {
      const selectItems = variations
        .filter(
          ({ identifier, name, value }: Variation) =>
            !!(identifier || '').trim() && !!(name || '').trim() && !!(value || '').trim()
        )
        .map(({ identifier, name }: Variation) => ({ id: identifier, label: name, value: identifier }))
 
      setFlagMultiRules(selectItems)
    }
  }
  const initialValues = {
    kind: FeatureFlagMutivariateKind.string,
    variations: [
      { identifier: '', name: '', value: '' },
      { identifier: '', name: '', value: '' }
    ],
    defaultOnVariation: '',
    defaultOffVariation: '',
    ...prevStepData
  }
 
  return (
    <Formik
      initialValues={initialValues}
      validationSchema={yup.object().shape({
        variations: yup.array().of(
          yup.object().shape({
            name: yup.string().trim().required(getString('cf.creationModal.nameIsRequired')),
            value: yup.string().trim().required(getString('cf.creationModal.valueIsRequired')),
            identifier: yup.string().trim().required(getString('cf.creationModal.idIsRequired'))
          })
        ),
        defaultOnVariation: yup.string().trim().required(getString('cf.creationModal.defaultVariationIsRequired')),
        defaultOffVariation: yup.string().trim().required(getString('cf.creationModal.defaultVariationIsRequired'))
      })}
      formName="flagElemMulti"
      validate={(values: typeof initialValues) => {
        return validateVariationValues(values.variations, values.kind)
      }}
      onSubmit={vals => {
        // TODO: Convert values in data.variations to proper type when backend supports it
        // Right now everything is string
        props.nextStep?.({ ...vals, ...prevStepData })
      }}
    >
      {formikProps => (
        <Form data-testid="create-multivariate-flag-form">
          <FormikEffect onChange={onFormikEffect} formik={formikProps} />
          <Container flex height="100%" style={{ flexDirection: 'column', alignItems: 'baseline' }}>
            <Container style={{ flexGrow: 1, overflow: 'auto' }} width="100%" padding={{ left: 'xsmall' }}>
              <ModalErrorHandler bind={setModalErrorHandler} />
              <Text style={{ fontSize: '18px', color: Color.GREY_700 }} margin={{ bottom: 'xlarge' }}>
                {getString('cf.creationModal.variationSettingsHeading')}
              </Text>
              <Layout.Vertical>
                <Layout.Horizontal>
                  <Container className={Classes.FORM_GROUP} width={180}>
                    <FormInput.Select
                      name="kind"
                      label={getString('cf.creationModal.flagType')}
                      items={flagTypeOptions}
                      onChange={newFlagType => handleNewFlagType(newFlagType.value as string)}
                      style={{ width: '188px' }}
                    />
                  </Container>
                  <Container width={20} />
                  <Container className={Classes.FORM_GROUP} width={180}>
                    <label className={Classes.LABEL}>{getString('cf.creationModal.dataType')}</label>
                    <Container className={Classes.FORM_CONTENT}>
                      <Select
                        name="dataTypes"
                        value={kindToSelectValue(formikProps.values.kind)}
                        items={flagVariationOptions}
                        className={css.spacingSelectVariation}
                        onChange={kindVariation => {
                          formikProps.setFieldValue('kind', kindVariation.value)
                        }}
                      />
                    </Container>
                  </Container>
                </Layout.Horizontal>
 
                <Container>
                  <FieldArray name="variations">
                    {arrayProps => {
                      return (
                        <>
                          {formikProps.values?.variations?.map((_: Variation, index: number) => (
                            <Layout.Horizontal
                              key={`flagElem-${index}`}
                              style={{
                                background: '#FAFBFC',
                                boxShadow: '0px 0px 1px rgba(40, 41, 61, 0.04), 0px 2px 4px rgba(96, 97, 112, 0.16)',
                                borderRadius: '4px',
                                width: '570px',
                                marginBottom: 'var(--spacing-small)',
                                padding: 'var(--spacing-small) var(--spacing-small) 0 var(--spacing-medium)'
                              }}
                            >
                              <Container width={255}>
                                <FormInput.InputWithIdentifier
                                  inputName={`variations.${index}.name`}
                                  idName={`variations.${index}.identifier`}
                                  inputLabel={getString('name')}
                                  isIdentifierEditable={true}
                                  inputGroupProps={{ inputGroup: { autoFocus: index === 0 } }}
                                />
                              </Container>
                              <Container width={20} />
                              <Container width={255}>
                                <FormInput.Text name={`variations.${index}.value`} label={getString('valueLabel')} />
                              </Container>
                              <Container width={5} />
                              <Container flex={{ align: 'center-center' }} height={70}>
                                <Button
                                  data-testid={`delete_icon_${index}`}
                                  minimal
                                  icon="trash"
                                  style={{
                                    visibility: formikProps.values?.variations.length === 2 ? 'hidden' : 'visible'
                                  }}
                                  onClick={() => {
                                    formikProps.values?.variations.splice(index, 1)
                                    formikProps.setFieldValue('variations', formikProps.values?.variations)
                                  }}
                                />
                              </Container>
                            </Layout.Horizontal>
                          ))}
                          <Button
                            minimal
                            intent="primary"
                            icon="small-plus"
                            text={getString('cf.shared.variation')}
                            margin={{ bottom: 'large' }}
                            style={{ paddingLeft: 0 }}
                            onClick={() => {
                              arrayProps.push({ identifier: '', name: '', value: '' })
                              addNewFlagMultiRules()
                            }}
                          />
                        </>
                      )
                    }}
                  </FieldArray>
                </Container>
 
                <Container margin={{ bottom: 'large' }}>
                  <Text
                    color={Color.BLACK}
                    inline
                    tooltip={getString('cf.creationModal.defaultRulesTooltip')}
                    rightIconProps={{ size: 10, color: Color.BLUE_500 }}
                    rightIcon="info-sign"
                  >
                    {getString('cf.creationModal.defaultRules')}
                  </Text>
                  <Layout.Vertical margin={{ top: 'medium' }}>
                    <Container>
                      <Layout.Horizontal>
                        <Text width="150px" className={css.serveTextAlign}>
                          {getString('cf.creationModal.flagOn')}
                        </Text>
                        <FormInput.Select name="defaultOnVariation" items={flagMultiRules} />
                      </Layout.Horizontal>
                    </Container>
                    <Container>
                      <Layout.Horizontal>
                        <Text width="150px" className={css.serveTextAlign}>
                          {getString('cf.creationModal.flagOff')}
                        </Text>
                        <FormInput.Select name="defaultOffVariation" items={flagMultiRules} />
                      </Layout.Horizontal>
                    </Container>
                  </Layout.Vertical>
                </Container>
              </Layout.Vertical>
            </Container>
 
            <Layout.Horizontal spacing="small" margin={{ top: 'large' }} width="100%">
              <Button text={getString('back')} onClick={onClickBack} />
              <Button
                type="submit"
                intent="primary"
                rightIcon={isLastStep ? undefined : 'chevron-right'}
                text={isLastStep ? getString('cf.creationModal.saveAndClose') : getString('next')}
                disabled={isLoadingCreateFeatureFlag}
                loading={isLoadingCreateFeatureFlag}
              />
              <FlexExpander />
            </Layout.Horizontal>
          </Container>
        </Form>
      )}
    </Formik>
  )
}
 
export default FlagElemMultivariate