All files / modules/70-pipeline/components/PipelineStudio/StepPalette StepPalette.tsx

88.89% Statements 104/117
73.5% Branches 172/234
88.89% Functions 24/27
88.79% Lines 103/116

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              25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x   25x     25x 25x   25x 22x 22x 19x 19x       11x         8x 8x       22x     25x         25x 25x 25x                   25x 22x 22x 22x 22x   22x 22x     22x           22x         22x             22x 22x 9x 9x 9x 7x 7x     9x 9x 9x       22x 3x 3x 3x 3x 3x 6x 1x 5x 3x 3x 3x 1x     3x 1x   1x   2x   2x 2x 4x         2x               6x 2x 2x 2x       2x           3x 3x 3x             22x                                 1x             13x 13x 13x 16x         4x 4x         4x                     13x 5x 5x 10x                                             13x                                                                         19x 19x 11x               1x 1x                         19x 8x 8x                                           8x 8x                   1x 1x                 19x                  
/*
 * 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, useEffect } from 'react'
import { ExpandingSearchInput, Text, Icon, Layout, Container, Heading } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { cloneDeep, uniqBy, isEmpty } from 'lodash-es'
import cx from 'classnames'
import { useParams } from 'react-router-dom'
import { StepCategory, StepData, StepPalleteModuleInfo, useGetStepsV2 } from 'services/pipeline-ng'
import { useMutateAsGet } from '@common/hooks'
import { useStrings } from 'framework/strings'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { StepActions } from '@common/constants/TrackingConstants'
import type { StageType } from '@pipeline/utils/stageHelpers'
import { StepPopover } from '@pipeline/components/PipelineStudio/StepPalette/StepPopover/StepPopover'
import type { AbstractStepFactory, StepData as FactoryStepData } from '../../AbstractSteps/AbstractStepFactory'
 
import { iconMapByName } from './iconMap'
import css from './StepPalette.module.scss'
 
export const getAllStepsCountForPalette = (originalData: StepCategory[]): number => {
  let count = 0
  originalData.forEach((data: StepCategory) => {
    const { stepCategories, stepsData } = data
    if (isEmpty(stepCategories)) {
      /*
        Ex - Kubernetes -> No nested categories -> add all the steps
      */
      count += stepsData ? stepsData.length : 0
    } else {
      /**
        Ex - Utilities -> nested categories -> add all steps of each category
      */
      stepCategories?.forEach((category: StepCategory) => {
        count += category.stepsData ? category.stepsData.length : 0
      })
    }
  })
  return count
}
 
const primaryTypes = {
  SHOW_ALL: 'show_all',
  RECENTLY_USED: 'recently_used'
}
 
enum FilterContext {
  NAV = 'NAV',
  SEARCH = 'SEARCH'
}
 
export interface StepPaletteProps {
  onSelect: (item: FactoryStepData) => void
  stepsFactory: AbstractStepFactory
  stepPaletteModuleInfos: StepPalleteModuleInfo[]
  stageType: StageType
  isProvisioner?: boolean
}
export function StepPalette({ onSelect, stepsFactory, stepPaletteModuleInfos }: StepPaletteProps): React.ReactElement {
  const [stepCategories, setStepsCategories] = useState<StepCategory[]>([])
  const [originalData, setOriginalCategories] = useState<StepCategory[]>([])
  const [selectedCategory, setSelectedCategory] = useState(primaryTypes.SHOW_ALL)
  const { trackEvent } = useTelemetry()
  // Need this when we have same names for category and sub category
  const [selectedLevel, setSelectedLevel] = useState<string | null>(null)
  const { accountId } = useParams<{ module: string; accountId: string }>()
 
  function Message({ stepsDataLoading }: { stepsDataLoading: boolean }): React.ReactElement | null {
    const message = stepsDataLoading
      ? getString('stepPalette.loadingSteps')
      : isEmpty(stepCategories)
      ? getString('stepPalette.noSearchResultsFound')
      : ''
    // Only render this section if we're loading or if we do not have any steps
    return message ? (
      <section style={{ paddingTop: '50%', justifyContent: 'center', textAlign: 'center' }}>{message}</section>
    ) : null
  }
 
  const { data: stepsData, loading: stepsDataLoading } = useMutateAsGet(useGetStepsV2, {
    queryParams: {
      accountId
    },
    body: { stepPalleteModuleInfos: stepPaletteModuleInfos }
  })
 
  const { getString } = useStrings()
  useEffect(() => {
    const fromApi = stepsData?.data?.stepCategories
    const toShow: StepCategory[] = []
    fromApi?.forEach(stepCat => {
      Eif (stepCat?.stepCategories?.length) {
        toShow.push(...stepCat?.stepCategories)
      }
    })
    Eif (toShow) {
      setStepsCategories(toShow)
      setOriginalCategories(toShow)
    }
  }, [stepsData?.data?.stepCategories])
 
  const filterSteps = (stepName: string, context = FilterContext.NAV): void => {
    const filteredData: StepCategory[] = []
    const name = stepName.toLowerCase()
    const cloneOriginalData = cloneDeep(originalData)
    Eif (name !== primaryTypes.SHOW_ALL) {
      cloneOriginalData.forEach((k: StepCategory) => {
        if (k.name?.toLowerCase() === name) {
          filteredData.push(k)
        } else if (k.stepCategories && k.stepCategories.length > 0) {
          const _stepCategories: StepCategory[] = []
          k.stepCategories.forEach((v: StepCategory) => {
            if (v.name?.toLowerCase() === name) {
              _stepCategories.push(v)
            }
          })
          if (_stepCategories?.length) {
            k.stepCategories = _stepCategories
 
            filteredData.push(k)
          } else {
            const _stepsData: StepData[] = []
            // Each category has steps data inside it
            k.stepCategories.forEach((v: StepCategory) => {
              v?.stepsData?.forEach((m: StepData) => {
                Iif (m.name?.toLowerCase().indexOf(name) !== -1) {
                  _stepsData.push(m)
                }
              })
 
              Iif (_stepsData?.length) {
                // v.stepsData = _stepsData
                filteredData.push(k)
              }
            })
          }
        }
 
        if (context === FilterContext.SEARCH && k.stepsData) {
          const _stepsData: StepData[] = []
          k.stepsData.forEach((m: StepData) => {
            Iif (m.name?.toLowerCase().indexOf(name) !== -1) {
              _stepsData.push(m)
            }
          })
          Iif (_stepsData?.length) {
            k.stepsData = _stepsData
            filteredData.push(k)
          }
        }
      })
      const uniqueData: StepCategory[] = uniqBy(filteredData, 'name')
      setStepsCategories(uniqueData)
      setSelectedCategory(stepName)
    } else {
      setStepsCategories(originalData)
      setSelectedCategory(stepName)
    }
  }
 
  return (
    <div className={css.stepPalette}>
      <div className={css.stepInside}>
        <section className={css.stepsRenderer}>
          <Layout.Vertical padding="xlarge" spacing="large">
            <Layout.Horizontal spacing="medium" className={css.paletteCardHeader}>
              <Layout.Vertical>
                <Heading level={2} color={Color.GREY_800} font={{ weight: 'bold' }} className={css.title}>
                  {getString('stepPalette.title')}
                </Heading>
              </Layout.Vertical>
 
              <ExpandingSearchInput
                flip
                autoFocus
                width={232}
                throttle={200}
                onChange={(text: string) => filterSteps(text, FilterContext.SEARCH)}
              />
            </Layout.Horizontal>
 
            <Message stepsDataLoading={stepsDataLoading} />
 
            {stepCategories?.map((stepCategory: StepCategory, i) => {
              const categorySteps: JSX.Element[] = []
              /* istanbul ignore else */ if (stepCategory?.stepsData) {
                stepCategory.stepsData.forEach((stepData: StepData) => {
                  categorySteps.push(
                    <section
                      className={css.step}
                      key={`${stepData.name}-${i}`}
                      onClick={() => {
                        Eif (stepData.type !== 'Placeholder' && !stepData.disabled) {
                          onSelect({
                            name: stepData.name || '',
                            type: stepData.type || '',
                            icon: stepsFactory.getStepIcon(stepData.type || '')
                          })
                          trackEvent(StepActions.SelectStep, { name: stepData.name || '', type: stepData.type || '' })
                        }
                      }}
                    >
                      <StepPopover stepData={stepData} stepsFactory={stepsFactory} />
                      <section className={css.stepName}>{stepData.name}</section>
                    </section>
                  )
                })
              }
 
              if (stepCategory?.stepCategories && stepCategory.stepCategories.length > 0) {
                stepCategory.stepCategories.forEach((subStepData: StepCategory, j) => {
                  subStepData?.stepsData?.map((stepData: StepData) => {
                    categorySteps.push(
                      <section
                        className={css.step}
                        key={`${stepData.name}-${j}`}
                        onClick={() => {
                          /* istanbul ignore else */ Iif (stepData.type !== 'Placeholder') {
                            onSelect({
                              name: stepData.name || /* istanbul ignore next */ '',
                              type: stepData.type || /* istanbul ignore next */ '',
                              icon: stepsFactory.getStepIcon(stepData.type || '')
                            })
                            trackEvent(StepActions.SelectStep, { name: stepData.name || '', type: stepData.type || '' })
                          }
                        }}
                      >
                        <StepPopover stepData={stepData} stepsFactory={stepsFactory} />
                        <section className={css.stepName}>{stepData.name}</section>
                      </section>
                    )
                  })
                })
              }
 
              return (
                <section className={css.categorySteps} key={stepCategory.name}>
                  <section className={cx(css.categoryName)}>{stepCategory.name}</section>
                  <section className={cx(css.steps)}>{[...categorySteps]}</section>
                </section>
              )
            })}
          </Layout.Vertical>
        </section>
        <section className={css.categoriesRenderer}>
          <section className={css.headerContainer}>
            <Layout.Horizontal flex>
              <Container flex className={css.libraryHeader}>
                <Icon size={14} name="library" className={`${css.paletteIcon} ${css.library}`} />
                <Text color={Color.WHITE} style={{ fontSize: 14 }}>
                  {getString('stepPalette.library')}
                </Text>
              </Container>
            </Layout.Horizontal>
 
            <section
              onClick={() => {
                filterSteps(primaryTypes.SHOW_ALL)
              }}
              key={primaryTypes.SHOW_ALL}
              className={css.showAllBtn}
            >
              <Text color={Color.WHITE} style={{ fontSize: 11, fontWeight: 'bold' }}>
                {getString('stepPalette.showAllSteps')} ({getAllStepsCountForPalette(originalData)})
              </Text>
            </section>
          </section>
          <hr className={css.separator} />
 
          <section className={css.secCategories}>
            <Layout.Vertical>
              {originalData?.map((category: StepCategory) => {
                const stepRenderer = []
                if (category?.stepCategories && category.stepCategories.length === 0) {
                  stepRenderer.push(
                    <section
                      className={cx(
                        css.category,
                        selectedCategory === category.name && selectedLevel === 'category' && css.active,
                        !iconMapByName[category.name || '']?.keepOriginal && css.fillWhite
                      )}
                      onClick={() => {
                        setSelectedLevel('category')
                        filterSteps(category.name || /* istanbul ignore next */ '')
                      }}
                      key={category.name}
                    >
                      <Icon
                        size={14}
                        name={iconMapByName[category.name || /* istanbul ignore next */ '']?.icon}
                        className={css.paletteIcon}
                      />
                      {category.name} ({category.stepsData?.length})
                    </section>
                  )
                }
                if (category?.stepCategories && category.stepCategories.length > 0) {
                  const subCategory = category.stepCategories
                  stepRenderer.push(
                    <section
                      className={cx(
                        css.category,
                        selectedCategory === category.name && selectedLevel === 'category' && css.active,
                        subCategory.length && css.hasSubCategories,
                        !iconMapByName[category.name || '']?.keepOriginal && css.fillWhite
                      )}
                      onClick={() => {
                        setSelectedLevel('category')
                        filterSteps(category.name || '')
                      }}
                      key={category.name}
                    >
                      <Icon
                        size={14}
                        name={iconMapByName[category.name || /* istanbul ignore next */ '']?.icon}
                        className={css.paletteIcon}
                      />
                      {category.name}({subCategory.length})
                    </section>
                  )
                  subCategory.forEach((subCat: StepCategory, k) =>
                    stepRenderer.push(
                      <section
                        className={cx(
                          css.category,
                          css.subCategory,
                          css.offset,
                          selectedCategory === subCat.name && selectedLevel === 'subCategory' && css.active,
                          k === subCategory.length - 1 && css.lastSubCategory
                        )}
                        onClick={() => {
                          setSelectedLevel('subCategory')
                          filterSteps(subCat.name || /* istanbul ignore next */ '')
                        }}
                        key={`${subCat.name}-${k}`}
                      >
                        {subCat.name} ({subCat.stepsData?.length})
                      </section>
                    )
                  )
                }
                return [...stepRenderer]
              })}
            </Layout.Vertical>
          </section>
        </section>
      </div>
    </div>
  )
}