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

69.01% Statements 49/71
51.02% Branches 75/147
55.56% Functions 5/9
68.57% Lines 48/70

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              498x 498x               498x                     498x 498x 498x 498x 498x     498x   498x 498x 498x                                 498x       23x   23x     23x     15x 15x 15x 3x   3x       15x 8x 8x     8x       8x       8x         7x 4x 4x       4x       4x           15x                                 498x                       55x 55x 55x             55x     55x                                                                                                                                         498x 54x 54x           54x   54x   54x 54x   54x                                   498x  
/*
 * 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 {
  Button,
  FormikTooltipContext,
  getMultiTypeFromValue,
  HarnessDocTooltip,
  MultiTextInput,
  MultiTypeInputType
} from '@wings-software/uicore'
import {
  FormGroup,
  HTMLInputProps,
  IFormGroupProps,
  IInputGroupProps,
  Intent,
  Menu,
  MenuItem,
  Popover,
  Position
} from '@blueprintjs/core'
import { connect } from 'formik'
import { get, isNil } from 'lodash-es'
import * as Yup from 'yup'
import { useStrings, UseStringsReturn } from 'framework/strings'
import { errorCheck } from '@common/utils/formikHelpers'
// import { ConfigureOptions } from '@common/components/ConfigureOptions/ConfigureOptions'
 
import css from './InstanceDropdownField.module.scss'
 
export enum InstanceTypes {
  Percentage = 'Percentage',
  Instances = 'Count'
}
export interface InstanceFieldValue {
  type: InstanceTypes
  spec: {
    percentage?: number | string
    count?: number | string
  }
}
export interface GetDurationValidationSchemaProps {
  maximum?: number
  required?: boolean
  requiredErrorMessage?: string
  minimumErrorMessage?: string
  maximumErrorMessage?: string
}
 
export function getInstanceDropdownSchema(
  props: GetDurationValidationSchemaProps = {},
  getString: UseStringsReturn['getString']
): Yup.ObjectSchema {
  const { maximum } = props
 
  Iif (maximum && typeof maximum !== 'number') {
    throw new Error(`Invalid format "${maximum}" provided for maximum value`)
  }
  return Yup.object({
    type: Yup.string().test({
      test(val: InstanceTypes): boolean | Yup.ValidationError {
        const { maximumErrorMessage, minimumErrorMessage, required = false, requiredErrorMessage } = props
        let type: InstanceTypes | undefined = val
        if (isNil(val)) {
          Iif (!isNil(this.parent?.spec?.count)) {
            type = InstanceTypes.Instances
          } else Iif (!isNil(this.parent?.spec?.percentage)) {
            type = InstanceTypes.Percentage
          }
        }
        if (type === InstanceTypes.Instances) {
          const value = this.parent?.spec?.count
          Iif (getMultiTypeFromValue(value as unknown as string) !== MultiTypeInputType.FIXED) {
            return true
          }
          Iif (required && isNil(value)) {
            return this.createError({
              message: requiredErrorMessage || getString('common.instanceValidation.required')
            })
          } else Iif (value < 0) {
            return this.createError({
              message: minimumErrorMessage || getString('common.instanceValidation.minimumCountInstance')
            })
          } else Iif (maximum && value > maximum) {
            return this.createError({
              message: maximumErrorMessage || getString('common.instanceValidation.maximumCountInstance', { maximum })
            })
          }
        } else if (type === InstanceTypes.Percentage) {
          const value = this.parent?.spec?.percentage
          Iif (required && isNil(value)) {
            return this.createError({
              message: requiredErrorMessage || getString('common.instanceValidation.required')
            })
          } else Iif (value < 1) {
            return this.createError({
              message: minimumErrorMessage || getString('common.instanceValidation.minimumCountPercentage')
            })
          } else Iif (value > 100) {
            return this.createError({
              message: maximumErrorMessage || getString('common.instanceValidation.maximumCountPercentage')
            })
          }
        }
        return true
      }
    })
  })
}
interface InstanceDropdownFieldProps extends Omit<IFormGroupProps, 'label' | 'placeholder'> {
  onChange?: (value: InstanceFieldValue) => void
  value: InstanceFieldValue
  label: string | JSX.Element
  expressions: string[]
  allowableTypes?: MultiTypeInputType[]
  disabledType?: boolean
  readonly?: boolean
  name: string
  textProps?: Omit<IInputGroupProps & HTMLInputProps, 'onChange' | 'value' | 'type' | 'placeholder'>
}
 
export const InstanceDropdownField: React.FC<InstanceDropdownFieldProps> = ({
  value,
  label,
  name,
  onChange,
  allowableTypes,
  expressions,
  disabledType = false,
  textProps,
  readonly,
  ...restProps
}): JSX.Element => {
  const { getString } = useStrings()
  let isPercentageType = value.type === InstanceTypes.Percentage
  Iif (isNil(value.type)) {
    if (!isNil(value.spec.percentage)) {
      isPercentageType = true
    } else {
      isPercentageType = false
    }
  }
  const selectedText = isPercentageType
    ? getString('instanceFieldOptions.percentageText')
    : getString('instanceFieldOptions.instanceText')
  return (
    <FormGroup labelFor={name} label={label} className={css.formGroup} {...restProps}>
      <MultiTextInput
        name={`${name}.spec.${isPercentageType ? 'percentage' : 'count'}`}
        textProps={{
          type: 'number',
          placeholder: isPercentageType
            ? getString('instanceFieldOptions.percentagePlaceHolder')
            : getString('instanceFieldOptions.instanceHolder'),
          ...textProps,
          min: 1
        }}
        onChange={(val, _valType, typeInput) => {
          let finalValue: string | number | undefined
          if (typeInput === MultiTypeInputType.FIXED) {
            finalValue = val && typeof val === 'string' ? parseFloat(val) : undefined
          } else if (val) {
            finalValue = val as string
          }
          if (isPercentageType) {
            onChange?.({ ...value, spec: { percentage: finalValue } })
          } else {
            onChange?.({ ...value, spec: { count: finalValue } })
          }
        }}
        expressions={expressions}
        allowableTypes={allowableTypes}
        disabled={readonly}
        key={isPercentageType ? 'percent' : 'count'}
        value={(isPercentageType ? value.spec.percentage : value.spec.count) as unknown as string}
      />
 
      <Popover
        disabled={disabledType}
        content={
          <Menu className={css.popMenu}>
            <MenuItem
              text={getString('instanceFieldOptions.percentageText')}
              onClick={() => {
                onChange?.({ spec: { percentage: 100 }, type: InstanceTypes.Percentage })
              }}
              data-name="percentage"
              disabled={readonly}
            />
            <MenuItem
              text={getString('instanceFieldOptions.instanceText')}
              onClick={() => {
                onChange?.({ spec: { count: 1 }, type: InstanceTypes.Instances })
              }}
              data-name="instances"
              disabled={readonly}
            />
          </Menu>
        }
        position={Position.BOTTOM}
        className={css.instancePopover}
      >
        <Button rightIcon="caret-down" disabled={disabledType} text={selectedText} minimal />
      </Popover>
    </FormGroup>
  )
}
 
export interface FormInstanceDropdownFieldProps extends Omit<InstanceDropdownFieldProps, 'value' | 'disabled'> {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  formik?: any
  readonly?: boolean
}
 
const FormInstanceDropdownField: React.FC<FormInstanceDropdownFieldProps> = (props): JSX.Element => {
  const { label, textProps, formik, name, onChange, readonly, ...restProps } = props
  const hasError = errorCheck(`${name}.type`, formik)
 
  const {
    intent = hasError ? Intent.DANGER : Intent.NONE,
    helperText = hasError ? get(formik?.errors, `${name}.type`) : null,
    ...rest
  } = restProps
 
  const value: InstanceFieldValue = get(formik?.values, name, { type: InstanceTypes.Instances, spec: { count: 0 } })
 
  const tooltipContext = React.useContext(FormikTooltipContext)
  const dataTooltipId = tooltipContext?.formName ? `${tooltipContext?.formName}_${name}` : ''
 
  return (
    <InstanceDropdownField
      label={<HarnessDocTooltip tooltipId={dataTooltipId} labelText={label} />}
      name={name}
      textProps={{ ...textProps }}
      value={value}
      intent={intent}
      helperText={helperText}
      readonly={readonly}
      onChange={valueObj => {
        /* istanbul ignore next */
        formik.setFieldValue(name, { ...valueObj })
      }}
      {...rest}
    />
  )
}
 
export const FormInstanceDropdown = connect(FormInstanceDropdownField)