All files / modules/75-cd/components/OverrideSetsInputSelector OverrideSetsInputSelector.tsx

72.03% Statements 85/118
78.08% Branches 171/219
72.97% Functions 27/37
71.93% Lines 82/114

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 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395              101x 101x                       101x 101x 101x 101x 101x 101x   101x                     101x             7x 5x     10x             2x             1x 1x                 101x           17x 17x 17x 17x 17x 17x           17x   17x   17x 8x 8x     17x   17x 8x 8x 3x 3x 1x 1x           3x 1x 1x           3x 1x 1x           3x       17x 8x 5x 5x 3x 2x       17x   1x         17x         17x       17x       17x               17x                                                   17x   3x 6x 3x 3x       3x           17x   5x   4x     1x                 17x 18x                                                                         17x     5x 5x 12x 2x     5x   3x   3x       2x                       1x             17x               1x                                               1x               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 {
  Button,
  Checkbox,
  Icon,
  Layout,
  Popover,
  SelectOption,
  Tag,
  Text,
  TextInput,
  PageSpinner
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { isArray, clone } from 'lodash-es'
import cx from 'classnames'
import { Classes, Position } from '@blueprintjs/core'
import { usePipelineContext } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import { useStrings } from 'framework/strings'
import type { DeploymentStageElementConfig } from '@pipeline/utils/pipelineTypes'
import css from './OverrideSetsInputSelector.module.scss'
 
type InputSetValue = SelectOption | SelectOption[]
 
export interface InputSetSelectorProps {
  value?: InputSetValue
  onChange?: (value?: InputSetValue) => void
  width?: number
  context?: string
}
 
const RenderValue = React.memo(function RenderValue({
  value,
  onChange
}: {
  value: InputSetValue
  onChange?: (value?: InputSetValue) => void
}): JSX.Element {
  if (isArray(value)) {
    return (
      <>
        {value.map((item, index) => (
          <Tag minimal className={css.tag} key={index}>
            {item.label}
          </Tag>
        ))}
      </>
    )
  }
  return (
    <Layout.Horizontal flex={{ distribution: 'space-between' }}>
      <span>{value.label}</span>
      <Button
        noStyling
        className={css.clearButton}
        onClick={event => {
          event.stopPropagation()
          onChange?.()
        }}
      >
        <Icon name="cross" />
      </Button>
    </Layout.Horizontal>
  )
})
 
export const OverrideSetsInputSelector: React.FC<InputSetSelectorProps> = ({
  width = 350,
  value,
  onChange,
  context
}): JSX.Element => {
  const { getString } = useStrings()
  const [searchParam, setSearchParam] = React.useState('')
  const [multiple, setMultiple] = React.useState(false)
  const [selectedInputSets, setSelectedInputSets] = React.useState<SelectOption[]>([])
  const [useFromStageId, setUseFromStage] = React.useState('')
  const [inputSets, setInputSets] = React.useState<{ identifier: string; name: string }[]>([])
  const {
    state: {
      selectionState: { selectedStageId }
    },
    getStageFromPipeline
  } = usePipelineContext()
 
  const { stage: currentStage } = getStageFromPipeline<DeploymentStageElementConfig>(selectedStageId || '')
 
  React.useEffect(() => {
    const useFromStage = currentStage?.stage?.spec?.serviceConfig?.useFromStage?.stage
    if (useFromStage) setUseFromStage(useFromStage)
  }, [(currentStage?.stage?.spec?.serviceConfig?.stageOverrides as any)?.useFromStage])
 
  const { stage: useFromStageObj } = getStageFromPipeline<DeploymentStageElementConfig>(useFromStageId || '')
 
  React.useEffect(() => {
    const spec = useFromStageObj?.stage?.spec?.serviceConfig?.serviceDefinition?.spec
    if (spec) {
      const _overrideSets: { name: string; identifier: string }[] = []
      if (context === 'ARTIFACT') {
        spec.artifactOverrideSets?.map(overrideSets => {
          _overrideSets.push({
            name: overrideSets.overrideSet?.identifier || '',
            identifier: overrideSets.overrideSet?.identifier || ''
          })
        })
      }
      if (context === 'MANIFEST') {
        spec.manifestOverrideSets?.map(overrideSets => {
          _overrideSets.push({
            name: overrideSets.overrideSet?.identifier || '',
            identifier: overrideSets.overrideSet?.identifier || ''
          })
        })
      }
      if (context === 'VARIABLES') {
        spec.variableOverrideSets?.map(overrideSets => {
          _overrideSets.push({
            name: overrideSets.overrideSet?.identifier || '',
            identifier: overrideSets.overrideSet?.identifier || ''
          })
        })
      }
      setInputSets(_overrideSets)
    }
  }, [useFromStageObj?.stage?.spec?.serviceConfig?.serviceDefinition?.spec, context])
 
  React.useEffect(() => {
    if (isArray(value)) {
      setMultiple(true)
      setSelectedInputSets(value)
    } else if (value) {
      setSelectedInputSets([value as SelectOption])
    }
  }, [value])
 
  const onSelectHandler = React.useCallback(
    (inputSet: { name: string; identifier: string }) => {
      onChange?.({ label: inputSet.name || '', value: inputSet.identifier || '' })
    },
    [onChange]
  )
 
  const onDragStart = React.useCallback((event: React.DragEvent<HTMLLIElement>, row: SelectOption) => {
    event.dataTransfer.setData('data', JSON.stringify(row))
    event.currentTarget.classList.add(css.dragging)
  }, [])
 
  const onDragEnd = React.useCallback((event: React.DragEvent<HTMLLIElement>) => {
    event.currentTarget.classList.remove(css.dragging)
  }, [])
 
  const onDragLeave = React.useCallback((event: React.DragEvent<HTMLLIElement>) => {
    event.currentTarget.classList.remove(css.dragOver)
  }, [])
 
  const onDragOver = React.useCallback((event: React.DragEvent<HTMLLIElement>) => {
    if (event.preventDefault) {
      event.preventDefault()
    }
    event.currentTarget.classList.add(css.dragOver)
    event.dataTransfer.dropEffect = 'move'
  }, [])
 
  const onDrop = React.useCallback(
    (event: React.DragEvent<HTMLLIElement>, droppedLocation: SelectOption) => {
      if (event.preventDefault) {
        event.preventDefault()
      }
      const data = event.dataTransfer.getData('data')
      if (data) {
        try {
          const dropInputSet: SelectOption = JSON.parse(data)
          const selected = clone(selectedInputSets)
          const droppedItem = selected.filter(item => item.value === dropInputSet.value)[0]
          if (droppedItem) {
            const droppedItemIndex = selected.indexOf(droppedItem)
            selected.splice(droppedItemIndex, 1)
            const droppedLocationIndex = selected.indexOf(droppedLocation)
            selected.splice(droppedLocationIndex, 0, droppedItem)
            setSelectedInputSets(selected)
          }
          // eslint-disable-next-line no-empty
        } catch {}
      }
      event.currentTarget.classList.remove(css.dragOver)
    },
    [selectedInputSets]
  )
 
  const onCheckBoxHandler = React.useCallback(
    (checked: boolean, label: string, val: string) => {
      const selected = clone(selectedInputSets)
      const removedItem = selected.filter(set => set.value === val)[0]
      Eif (checked && !removedItem) {
        selected.push({ label, value: val })
      } else if (removedItem) {
        selected.splice(selected.indexOf(removedItem), 1)
      }
      setSelectedInputSets(selected)
    },
    [selectedInputSets]
  )
 
  const singleSelectList =
    inputSets &&
    inputSets
      .filter(set => (set.identifier || '').toLowerCase().indexOf(searchParam.toLowerCase()) > -1)
      .map(inputSet => (
        <li
          className={cx(Classes.POPOVER_DISMISS, css.item)}
          onClick={() => {
            onSelectHandler(inputSet)
          }}
          key={inputSet.identifier}
        >
          <Icon name="yaml-builder-input-sets" />
          &nbsp;&nbsp;{inputSet.name}
        </li>
      ))
 
  const selectedMultipleList = selectedInputSets.map((selected, index) => (
    <li
      className={cx(css.item)}
      draggable={true}
      onDragStart={event => {
        onDragStart(event, selected)
      }}
      onDragEnd={onDragEnd}
      onDragOver={onDragOver}
      onDragLeave={onDragLeave}
      onDrop={event => onDrop(event, selected)}
      onClick={() => {
        onCheckBoxHandler(false, selected.label, selected.value as string)
      }}
      key={`${index}-${selected.value as string}`}
    >
      <Layout.Horizontal flex={{ distribution: 'space-between' }}>
        <Checkbox
          className={css.checkbox}
          labelElement={
            <Text font={{ size: 'small' }} icon="yaml-builder-input-sets">
              {selected.label}
            </Text>
          }
          checked={true}
          onChange={event => {
            onCheckBoxHandler(event.currentTarget.checked, selected.label, selected.value as string)
          }}
        />
        <span className={css.order}>
          <Text className={css.orderText}>{index + 1}</Text>
          <Icon name="main-reorder" size={12} />
        </span>
      </Layout.Horizontal>
    </li>
  ))
 
  const multipleInputSetList =
    inputSets &&
    inputSets
      .filter(set => {
        let filter = true
        selectedInputSets.forEach(selectedSet => {
          if (selectedSet.value === set.identifier) {
            filter = false
          }
        })
        return filter
      })
      .filter(set => (set.identifier || '').toLowerCase().indexOf(searchParam.toLowerCase()) > -1)
      .map(inputSet => (
        <li
          className={cx(css.item)}
          key={inputSet.identifier}
          onClick={() => {
            onCheckBoxHandler(true, inputSet.name || '', inputSet.identifier || '')
          }}
        >
          <Layout.Horizontal flex={{ distribution: 'space-between' }}>
            <Checkbox
              className={css.checkbox}
              labelElement={
                <Text font={{ size: 'small' }} icon="yaml-builder-input-sets">
                  {inputSet.name}
                </Text>
              }
              onChange={event => {
                onCheckBoxHandler(event.currentTarget.checked, inputSet.name || '', inputSet.identifier || '')
              }}
            />
          </Layout.Horizontal>
        </li>
      ))
 
  return (
    <Popover
      position={Position.BOTTOM}
      minimal={true}
      onOpening={() => {
        // refetch()
      }}
      onClosing={() => {
        Iif (multiple) {
          if (selectedInputSets.length > 0) {
            onChange?.(selectedInputSets)
          } else {
            onChange?.()
          }
        }
      }}
    >
      <Button minimal className={css.container} style={{ width }} rightIcon="caret-down">
        {value ? (
          <RenderValue value={value} onChange={onChange} />
        ) : (
          <span className={css.placeholder}>{getString('overrideSet.placeholder')}</span>
        )}
      </Button>
      <Layout.Vertical spacing="small" padding="medium" className={css.popoverContainer}>
        <Layout.Horizontal spacing="medium">
          <TextInput
            leftIcon="search"
            placeholder={getString('overrideSet.searchInputSet')}
            className={css.search}
            value={searchParam}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              setSearchParam(e.target.value.trim())
            }}
          />
          <Checkbox
            label={getString('overrideSet.selectMultipleInputSets')}
            checked={multiple}
            className={css.checkbox}
            onChange={checkbox => {
              setMultiple(checkbox.currentTarget.checked)
            }}
          />
        </Layout.Horizontal>
        {multiple && (
          <Layout.Horizontal
            spacing="small"
            background={Color.GREY_200}
            flex={{ align: 'center-center' }}
            padding="small"
          >
            <Icon name="info-sign" color={Color.PRIMARY_4}></Icon>
            <Text font={{ size: 'small' }}>{getString('overrideSet.helpTextForMultiSelect')}</Text>
          </Layout.Horizontal>
        )}
        {!inputSets ? (
          <PageSpinner />
        ) : (
          <Layout.Vertical>
            {multiple && (
              <Layout.Horizontal padding="small" flex={{ distribution: 'space-between' }}>
                <Text color={Color.BLACK}>{getString('overrideSet.inputSet')}</Text>
                <Text color={Color.BLACK}>{getString('overrideSet.order')}</Text>
              </Layout.Horizontal>
            )}
            {inputSets && inputSets.length > 0 ? (
              <ul className={cx(Classes.MENU, css.list, { [css.multiple]: multiple })}>
                {!multiple ? (
                  singleSelectList
                ) : (
                  <>
                    {selectedMultipleList}
                    {multipleInputSetList}
                  </>
                )}
              </ul>
            ) : (
              <Layout.Horizontal
                spacing="small"
                background={Color.GREY_200}
                flex={{ align: 'center-center' }}
                padding="small"
                margin="small"
              >
                <Text>{getString('overrideSet.noRecord')}</Text>
              </Layout.Horizontal>
            )}
          </Layout.Vertical>
        )}
      </Layout.Vertical>
    </Popover>
  )
}