All files / modules/70-pipeline/components/PipelineSteps/AdvancedSteps/FailureStrategyPanel FailureTypeMultiSelect.tsx

98.08% Statements 51/52
85.71% Branches 18/21
100% Functions 15/15
97.92% Lines 47/48

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              37x 37x 37x 37x 37x   37x 37x   37x     37x 37x             37x                       37x   37x 1199x     37x                                   37x 91x 91x   91x 91x 91x 91x     91x 91x 91x   91x 91x 91x     91x 801x 673x       1x 1x         93x 689x       689x 8x     681x         91x             2x 1x 1x         1x   1x 1x     91x                                                                     37x  
/*
 * 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 { FormGroup, Menu, Intent, Checkbox } from '@blueprintjs/core'
import { MultiSelect as BPMultiSelect, ItemRenderer } from '@blueprintjs/select'
import { connect, FormikContext } from 'formik'
import { get } from 'lodash-es'
 
import { errorCheck } from '@common/utils/formikHelpers'
import { useStrings } from 'framework/strings'
import type { StringKeys } from 'framework/strings'
import { FailureErrorType, ErrorType } from '@pipeline/utils/FailureStrategyUtils'
import type { StageType } from '@pipeline/utils/stageHelpers'
 
import { errorTypesForStages } from './StrategySelection/StrategyConfig'
import css from './FailureStrategyPanel.module.scss'
 
interface Option {
  label: string
  value: FailureErrorType
}
 
const stringsMap: Record<FailureErrorType, StringKeys> = {
  AllErrors: 'common.allErrors',
  Unknown: 'pipeline.failureStrategies.errorTypeLabels.Unknown',
  Authentication: 'pipeline.failureStrategies.errorTypeLabels.Authentication',
  Authorization: 'pipeline.failureStrategies.errorTypeLabels.Authorization',
  Connectivity: 'common.connectivityErrors',
  DelegateProvisioning: 'pipeline.failureStrategies.errorTypeLabels.DelegateProvisioning',
  Timeout: 'pipeline.failureStrategies.errorTypeLabels.Timeout',
  Verification: 'pipeline.failureStrategies.errorTypeLabels.Verification',
  PolicyEvaluationFailure: 'pipeline.failureStrategies.errorTypeLabels.PolicyEvaluationFailure'
}
 
const MultiSelect = BPMultiSelect.ofType<Option>()
 
const itemRenderer: ItemRenderer<Option> = (item, itemProps) => {
  return <Menu.Item key={item.value} onClick={itemProps.handleClick} text={item.label} />
}
 
const tagRenderer = (item: Option): string => {
  /* istanbul ignore next */
  return item?.label
}
 
export interface FailureTypeMultiSelectProps {
  label: string
  name: string
  filterTypes?: FailureErrorType[]
  stageType: StageType
  disabled?: boolean
}
 
export interface ConnectedFailureTypeMultiSelectProps extends FailureTypeMultiSelectProps {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  formik: FormikContext<any>
}
 
export function FailureTypeMultiSelect(props: ConnectedFailureTypeMultiSelectProps): React.ReactElement {
  const { name, label, formik, stageType, filterTypes, disabled } = props
  const { getString } = useStrings()
 
  const hasError = errorCheck(name, formik)
  const intent = hasError ? Intent.DANGER : Intent.NONE
  const helperText = hasError ? get(formik?.errors, name) : null
  const selectedValues: FailureErrorType[] = get(formik.values, name) || []
 
  // remove 'AllErrors' from selected values as we don't want to show it inside the multislect component
  const filteredValues = selectedValues.filter(val => val !== ErrorType.AllErrors)
  const selectedValuesSet = new Set<FailureErrorType>(filteredValues)
  const hasAllErrors = selectedValues.includes(ErrorType.AllErrors)
 
  const options: Option[] = (() => {
    const filterTypesSet = new Set(filterTypes || /* istanbul ignore next */ [])
    const errorTypes = errorTypesForStages[stageType]
 
    // remove already selected values and "AllErrors" from options
    return errorTypes
      .filter(e => !filterTypesSet.has(e) && e !== ErrorType.AllErrors)
      .map(e => ({ value: e, label: getString(stringsMap[e]) }))
  })()
 
  function handleItemSelect(item: Option): void {
    formik.setFieldValue(name, [...selectedValues, item.value])
    formik.setFieldTouched(name, true)
  }
 
  // list of options to show
  function itemListPredicate(query: string, listItems: Option[]): Option[] {
    return listItems.filter(item => {
      Iif (selectedValuesSet.has(item.value)) {
        return false
      }
 
      if (query) {
        return item.value.trim().toLowerCase().startsWith(query.trim().toLowerCase())
      }
 
      return true
    })
  }
 
  // selected options to show
  const selectedOptions: Option[] = filteredValues.map((key: FailureErrorType) => ({
    value: key,
    label: getString(stringsMap[key])
  }))
 
  // when x is clicked on an option
  function onRemove(value: string): void {
    const newItems = selectedOptions.filter(item => item.label !== value).map(item => item.value)
    formik.setFieldValue(name, newItems)
    formik.setFieldTouched(name, true)
  }
 
  // handler for AllErrors checkbox
  function handleAllErrorsChanges(e: React.ChangeEvent<HTMLInputElement>): void {
    const { checked } = e.target
 
    formik.setFieldValue(name, checked ? [ErrorType.AllErrors] : [])
    formik.setFieldTouched(name, true)
  }
 
  return (
    <FormGroup label={label} labelFor={name} helperText={helperText} intent={intent} className={css.failureSelect}>
      <div className={css.selectWrapper}>
        <MultiSelect
          className={css.errorSelect}
          selectedItems={selectedOptions}
          itemListPredicate={itemListPredicate}
          onItemSelect={handleItemSelect}
          items={options}
          fill
          popoverProps={{ minimal: true }}
          itemRenderer={itemRenderer}
          tagRenderer={tagRenderer}
          tagInputProps={{
            onRemove,
            tagProps: { className: css.tag },
            inputProps: { name },
            disabled: disabled || hasAllErrors
          }}
          itemsEqual="value"
          resetOnSelect
        />
        <Checkbox
          name={name}
          disabled={disabled}
          value={ErrorType.AllErrors}
          checked={hasAllErrors}
          label={getString(stringsMap.AllErrors)}
          onChange={handleAllErrorsChanges}
        />
      </div>
    </FormGroup>
  )
}
 
export default connect<FailureTypeMultiSelectProps>(FailureTypeMultiSelect)