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

79.8% Statements 79/99
56.49% Branches 87/154
61.54% Functions 16/26
79.38% Lines 77/97

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              121x 121x 121x 121x 121x 121x   121x 121x 121x 121x 121x   121x 121x                                               121x             121x 2x 4x               121x               33x 33x 33x 33x 33x 33x   33x         33x         33x 33x 33x 33x 33x 33x           33x         33x 28x 24x 3x             33x 13x 13x     33x 14x 14x 2x 2x 1x 1x   2x   10x                       33x 13x 3x 3x                         10x 10x         33x                           33x 14x 11x 22x           11x         33x                                                                                                     33x 15x   9x     3x     3x       33x                     33x                       32x         1x     1x   1x                                   40x             87x 87x                                             121x  
/*
 * Copyright 2022 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, { useEffect, useState } from 'react'
import { SelectOption, Layout, Icon, Select, Button, Text, Container } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useModalHook } from '@harness/use-modal'
import { useParams } from 'react-router-dom'
import { isEmpty } from 'lodash-es'
 
import cx from 'classnames'
import { Menu, Dialog } from '@blueprintjs/core'
import { useStrings } from 'framework/strings'
import { GitBranchDTO, GitSyncConfig, syncGitBranchPromise, useGetListOfBranchesWithStatus } from 'services/cd-ng'
import { useGitSyncStore } from 'framework/GitRepoStore/GitSyncStoreContext'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useToaster } from '@common/exports'
import css from './GitFilters.module.scss'
 
export interface GitFilterScope {
  repo: string
  branch: GitBranchDTO['branchName']
  getDefaultFromOtherRepo?: boolean
}
 
export interface GitFiltersProps {
  defaultValue?: GitFilterScope
  onChange: (value: GitFilterScope) => void
  className?: string
  branchSelectClassName?: string
  showRepoSelector?: boolean
  showBranchSelector?: boolean
  showBranchIcon?: boolean
  shouldAllowBranchSync?: boolean
  getDisabledOptionTitleText?: () => string
}
 
interface BranchSelectOption extends SelectOption {
  branchSyncStatus?: GitBranchDTO['branchSyncStatus']
}
 
const branchSyncStatus: Record<string, GitBranchDTO['branchSyncStatus']> = {
  SYNCED: 'SYNCED',
  SYNCING: 'SYNCING',
  UNSYNCED: 'UNSYNCED'
}
 
//Select 1st in response as fallback, if default should be slected and it is not availble in response
const getBranchToBePreselected = (list: GitBranchDTO[], defaultBranch?: string): string => {
  Eif (list.length > 0 && defaultBranch) {
    return list.findIndex(item => item.branchName === defaultBranch) > -1
      ? defaultBranch
      : (list[0].branchName as string)
  } else {
    return ''
  }
}
 
const GitFilters: React.FC<GitFiltersProps> = props => {
  const {
    defaultValue = { repo: '', branch: '' },
    showRepoSelector = true,
    showBranchSelector = true,
    showBranchIcon = true,
    shouldAllowBranchSync = true,
    getDisabledOptionTitleText
  } = props
  const { showSuccess } = useToaster()
  const { getString } = useStrings()
  const { gitSyncRepos, loadingRepos } = useGitSyncStore()
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const [page] = React.useState<number>(0)
 
  const defaultRepoSelect: SelectOption = {
    label: getString('common.gitSync.allRepositories'),
    value: ''
  }
 
  const defaultBranchSelect: BranchSelectOption = {
    label: getString('common.gitSync.defaultBranches'),
    value: ''
  }
 
  const [repoSelectOptions, setRepoSelectOptions] = React.useState<SelectOption[]>([defaultRepoSelect])
  const [selectedGitRepo, setSelectedGitRepo] = useState<string>(defaultValue.repo || '')
  const [selectedGitBranch, setSelectedGitBranch] = useState<string>(defaultValue.branch || '')
  const [branchSelectOptions, setBranchSelectOptions] = React.useState<BranchSelectOption[]>([defaultBranchSelect])
  const [unSyncedSelectedBranch, setUnSyncedSelectedBranch] = React.useState<BranchSelectOption | null>(null)
  const [searchTerm, setSearchTerm] = React.useState<string>('')
 
  const {
    data: response,
    loading,
    refetch: getListOfBranchesWithStatus
  } = useGetListOfBranchesWithStatus({
    lazy: true,
    debounce: 500
  })
 
  React.useEffect(() => {
    const isSelectedBranchExist = !!branchSelectOptions.filter(item => item.value === selectedGitBranch)[0]
    if (!isSelectedBranchExist) {
      branchSelectOptions.push({
        label: selectedGitBranch,
        value: selectedGitBranch
      })
    }
  }, [branchSelectOptions, selectedGitBranch])
 
  useEffect(() => {
    setSelectedGitRepo(defaultValue.repo)
    setSelectedGitBranch(defaultValue.branch || '')
  }, [defaultValue.repo, defaultValue.branch])
 
  useEffect(() => {
    const branchList = response?.data?.branches?.content
    if (!loading && branchList?.length) {
      const defaultBranch = getBranchToBePreselected(branchList, response?.data?.defaultBranch?.branchName)
      if (isEmpty(selectedGitBranch)) {
        props.onChange({ repo: selectedGitRepo, branch: defaultBranch })
        setSelectedGitBranch(defaultBranch)
      }
      setBranchSelectOptions(
        branchList.map((branch: GitBranchDTO) => {
          return {
            label: branch.branchName || '',
            value: branch.branchName || '',
            branchSyncStatus: branch.branchSyncStatus
          }
        })
      )
    }
 
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [response])
 
  useEffect(() => {
    if (selectedGitRepo) {
      Eif (!unSyncedSelectedBranch) {
        getListOfBranchesWithStatus({
          queryParams: {
            accountIdentifier: accountId,
            orgIdentifier,
            projectIdentifier,
            yamlGitConfigIdentifier: selectedGitRepo,
            page,
            size: 100,
            searchTerm
          }
        })
      }
    } else {
      setBranchSelectOptions([defaultBranchSelect])
      setSelectedGitBranch('')
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchTerm, selectedGitRepo, unSyncedSelectedBranch])
 
  const startBranchSync = (): void => {
    syncGitBranchPromise({
      queryParams: {
        accountIdentifier: accountId,
        orgIdentifier,
        projectIdentifier,
        repoIdentifier: selectedGitRepo,
        branch: unSyncedSelectedBranch?.value as string
      },
      body: undefined
    }).then(() => showSuccess(getString('common.gitSync.syncStartSuccess', { branch: unSyncedSelectedBranch?.value })))
    setUnSyncedSelectedBranch(null)
  }
 
  useEffect(() => {
    if (projectIdentifier && gitSyncRepos?.length) {
      const reposAvailable = gitSyncRepos?.map((gitRepo: GitSyncConfig) => {
        return {
          label: gitRepo.name || '',
          value: gitRepo.identifier || ''
        }
      })
 
      setRepoSelectOptions([defaultRepoSelect].concat(reposAvailable))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [gitSyncRepos, projectIdentifier])
 
  const [showModal, hideModal] = useModalHook(
    () => (
      <Dialog
        isOpen={!!unSyncedSelectedBranch?.value}
        enforceFocus={false}
        onClose={() => {
          hideModal()
          setUnSyncedSelectedBranch(null)
          response?.data?.defaultBranch?.branchSyncStatus === branchSyncStatus.SYNCED
            ? setSelectedGitBranch(response?.data?.defaultBranch?.branchName || '')
            : setSelectedGitRepo('')
        }}
      >
        {unSyncedSelectedBranch?.branchSyncStatus === branchSyncStatus.UNSYNCED ? (
          <Container padding="xlarge">
            <Layout.Horizontal flex={{ distribution: 'space-between' }}>
              <Text font={{ weight: 'bold', size: 'medium' }} color={Color.GREY_800}>
                {getString('common.gitSync.unSynced.header')}
              </Text>
              <Icon size={24} name="refresh" />
            </Layout.Horizontal>
            <Text margin={{ top: 'medium' }}>
              {getString('common.gitSync.unSynced.message1', { branch: unSyncedSelectedBranch?.value })}
            </Text>
            <Text margin={{ bottom: 'medium', top: 'small' }}>{getString('common.gitSync.unSynced.message2')}</Text>
            <div className={css.btnConatiner}>
              <Button minimal margin={{ right: 'small' }} onClick={() => setUnSyncedSelectedBranch(null)}>
                {getString('cancel')}
              </Button>
              <Button intent="primary" onClick={() => startBranchSync()}>
                {getString('common.gitSync.sync')}
              </Button>
            </div>
          </Container>
        ) : (
          <Container padding="large" className={css.syncModal}>
            <Icon size={24} margin="large" name="spinner"></Icon>
            <Text color={Color.GREY_800} font={{ weight: 'bold', size: 'medium' }} margin={{ bottom: 'small' }}>
              {getString('common.gitSync.syncing.header')}
            </Text>
            <Text>{getString('common.gitSync.syncing.message')}</Text>
            <Button margin={{ top: 'medium' }} intent="primary" onClick={() => setUnSyncedSelectedBranch(null)}>
              {getString('common.ok')}
            </Button>
          </Container>
        )}
      </Dialog>
    ),
    [unSyncedSelectedBranch]
  )
 
  const getSyncIcon = (syncStatus: GitBranchDTO['branchSyncStatus']): JSX.Element | void => {
    switch (syncStatus) {
      case branchSyncStatus.SYNCED:
        return <Icon size={20} name="synced" />
 
      case branchSyncStatus.SYNCING:
        return <Icon className={'rotate'} name="syncing" />
 
      case branchSyncStatus.UNSYNCED:
        return <Icon name="not-synced" />
    }
  }
 
  const handleBranchClick = (branch: BranchSelectOption): void => {
    if (branch.branchSyncStatus === branchSyncStatus.SYNCED) {
      const newSelected = branch.value as string
      setSelectedGitBranch(newSelected)
      props.onChange({ repo: selectedGitRepo, branch: newSelected })
    } else {
      setUnSyncedSelectedBranch(branch)
      showModal()
    }
  }
 
  return (
    <Layout.Horizontal
      spacing="xsmall"
      margin={{ right: 'small' }}
      className={cx(props.className, css.gitFilterContainer)}
    >
      {showRepoSelector && (
        <>
          <Icon padding={{ top: 'small' }} name="repository" color={Color.GREY_600}></Icon>
          <Select
            name={'repo'}
            className={css.repoSelectDefault}
            value={repoSelectOptions.find(repoOption => repoOption.value === selectedGitRepo)}
            disabled={loadingRepos}
            data-id="gitRepoSelect"
            items={repoSelectOptions}
            onChange={(selected: SelectOption) => {
              Iif (selected.value === selectedGitRepo) {
                return
              }
              setSelectedGitRepo(selected.value as string)
              // Default branch will be selected after loading branches for new repo and event will be dispatched
              selected.value ? setSelectedGitBranch('') : props.onChange({ repo: '', branch: '' })
            }}
          ></Select>
        </>
      )}
 
      {showBranchSelector && (
        <>
          {showBranchIcon && (
            <Icon
              padding={{ top: 'small' }}
              margin={{ left: 'large' }}
              name="git-new-branch"
              color={Color.GREY_600}
            ></Icon>
          )}
          <Select
            name={'branch'}
            value={branchSelectOptions.find(branchOption => branchOption.value === selectedGitBranch)}
            items={branchSelectOptions}
            disabled={!selectedGitBranch}
            data-id="gitBranchSelect"
            className={cx(props.branchSelectClassName)}
            onQueryChange={(query: string) => setSearchTerm(query)}
            itemRenderer={(item: BranchSelectOption): React.ReactElement => {
              const isDisabled = !shouldAllowBranchSync && item.branchSyncStatus === branchSyncStatus.UNSYNCED
              return (
                <Menu.Item
                  key={item.value as string}
                  active={item.value === selectedGitBranch}
                  disabled={isDisabled}
                  title={isDisabled && getDisabledOptionTitleText ? getDisabledOptionTitleText?.() : undefined}
                  onClick={() => handleBranchClick(item)}
                  text={
                    <Layout.Horizontal flex={{ distribution: 'space-between' }}>
                      <Text lineClamp={1}>{item.label}</Text>
                      {item.branchSyncStatus && getSyncIcon(item.branchSyncStatus)}
                    </Layout.Horizontal>
                  }
                />
              )
            }}
          ></Select>
        </>
      )}
    </Layout.Horizontal>
  )
}
 
export default GitFilters