All files / modules/75-ci/pages/get-started-with-ci/InfraProvisioningWizard SelectGitProvider.tsx

93.22% Statements 55/59
80.7% Branches 46/57
100% Functions 14/14
93.1% Lines 54/58

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              4x 4x   4x 4x                               4x 4x 4x 4x   4x   4x                                           4x       13x 13x 13x 13x 13x 13x   13x 7x 1x       13x                     37x 24x   13x       13x 13x             13x 12x 12x             13x 11x     6x             2x 1x   1x           4x                 1x                         13x                               1x     25x 25x       25x                       75x                                   2x 2x                                                 1x   6x   1x       1x 1x               1x 1x 1x                                                                                                       4x  
/*
 * 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, useRef, useState } from 'react'
import * as Yup from 'yup'
import type { FormikContext } from 'formik'
import cx from 'classnames'
import {
  Text,
  FontVariation,
  Layout,
  CardSelect,
  Icon,
  Container,
  Button,
  Formik,
  FormikForm as Form,
  FormInput,
  ButtonVariation,
  ButtonSize,
  Color,
  FormError
} from '@harness/uicore'
import { useStrings } from 'framework/strings'
import { OAuthProviders, OAuthProviderType } from '@common/constants/OAuthProviders'
import { TestStatus } from '@common/components/TestConnectionWidget/TestConnectionWidget'
import { AllGitProviders, GitAuthenticationMethod, GitProvider } from './Constants'
 
import css from './InfraProvisioningWizard.module.scss'
 
const OAUTH_REDIRECT_URL_PREFIX = `${location.protocol}//${location.host}/gateway/`
 
export interface SelectGitProviderRef {
  values: SelectGitProviderInterface
  setFieldTouched(field: keyof SelectGitProviderInterface & string, isTouched?: boolean, shouldValidate?: boolean): void
}
 
export type SelectGitProviderForwardRef =
  | ((instance: SelectGitProviderRef | null) => void)
  | React.MutableRefObject<SelectGitProviderRef | null>
  | null
 
interface SelectGitProviderProps {
  selectedGitProvider?: GitProvider
}
 
export interface SelectGitProviderInterface {
  accessToken: string
  gitAuthenticationMethod?: GitAuthenticationMethod
  gitProvider?: GitProvider
}
 
const SelectGitProviderRef = (
  props: SelectGitProviderProps,
  forwardRef: SelectGitProviderForwardRef
): React.ReactElement => {
  const { selectedGitProvider } = props
  const { getString } = useStrings()
  const [gitProvider, setGitProvider] = useState<GitProvider>()
  const [authMethod, setAuthMethod] = useState<GitAuthenticationMethod>()
  const [testConnectionStatus, setTestConnectionStatus] = useState<TestStatus>(TestStatus.NOT_INITIATED)
  const formikRef = useRef<FormikContext<SelectGitProviderInterface>>()
 
  useEffect(() => {
    if (authMethod === GitAuthenticationMethod.AccessToken) {
      setTestConnectionStatus(TestStatus.NOT_INITIATED)
    }
  }, [authMethod])
 
  const setForwardRef = ({
    values,
    setFieldTouched
  }: {
    values: SelectGitProviderInterface
    setFieldTouched(
      field: keyof SelectGitProviderInterface & string,
      isTouched?: boolean,
      shouldValidate?: boolean
    ): void
  }): void => {
    if (!forwardRef) {
      return
    }
    Iif (typeof forwardRef === 'function') {
      return
    }
 
    Eif (values) {
      forwardRef.current = {
        values: values,
        setFieldTouched: setFieldTouched
      }
    }
  }
 
  useEffect(() => {
    Eif (formikRef.current?.values && formikRef.current?.setFieldTouched) {
      setForwardRef({
        values: formikRef.current.values,
        setFieldTouched: formikRef.current.setFieldTouched
      })
    }
  })
 
  const TestConnection = (): React.ReactElement => {
    switch (testConnectionStatus) {
      case TestStatus.FAILED:
      case TestStatus.NOT_INITIATED:
        return (
          <Button
            variation={ButtonVariation.SECONDARY}
            text={getString('common.smtp.testConnection')}
            size={ButtonSize.SMALL}
            type="submit"
            onClick={() => {
              if (formikRef.current?.values?.accessToken) {
                setTestConnectionStatus(TestStatus.IN_PROGRESS)
                //TODO remove this when api will available for integration
                setTimeout(() => setTestConnectionStatus(TestStatus.SUCCESS), 3000)
              }
            }}
          />
        )
      case TestStatus.IN_PROGRESS:
        return (
          <Layout.Horizontal flex spacing="small">
            <Icon name="steps-spinner" color={Color.PRIMARY_7} />
            <Text font={{ variation: FontVariation.BODY2 }} color={Color.PRIMARY_7}>
              {getString('common.test.inProgress')}
            </Text>
          </Layout.Horizontal>
        )
      case TestStatus.SUCCESS:
        return (
          <Layout.Horizontal flex spacing="small">
            <Icon name="success-tick" />
            <Text font={{ variation: FontVariation.BODY2 }} color={Color.GREEN_700}>
              {getString('common.test.connectionSuccessful')}
            </Text>
          </Layout.Horizontal>
        )
      default:
        return <></>
    }
  }
 
  return (
    <Layout.Vertical width="70%">
      <Text font={{ variation: FontVariation.H4 }}>{getString('ci.getStartedWithCI.codeRepo')}</Text>
      <Formik<SelectGitProviderInterface>
        initialValues={{
          accessToken: '',
          gitProvider: selectedGitProvider,
          gitAuthenticationMethod: undefined
        }}
        formName="ciInfraProvisiong-gitProvider"
        validationSchema={Yup.object().shape({
          accessToken: Yup.string()
            .trim()
            .required(getString('fieldRequired', { field: getString('ci.getStartedWithCI.accessTokenLabel') }))
        })}
        validateOnChange={true}
        onSubmit={(values: SelectGitProviderInterface) => Promise.resolve(values)}
      >
        {formikProps => {
          formikRef.current = formikProps
          setForwardRef({
            values: formikProps.values,
            setFieldTouched: formikProps.setFieldTouched
          })
          return (
            <Form>
              <Container
                padding={{ top: 'xxlarge', bottom: 'xxxlarge' }}
                className={cx({ [css.borderBottom]: selectedGitProvider })}
              >
                <CardSelect
                  data={AllGitProviders}
                  cornerSelected={true}
                  className={css.icons}
                  cardClassName={css.gitProviderCard}
                  renderItem={(item: GitProvider) => (
                    <Layout.Vertical flex>
                      <Icon
                        name={item.icon}
                        size={30}
                        flex
                        className={cx(
                          { [css.githubIcon]: item.icon === 'github' },
                          { [css.gitlabIcon]: item.icon === 'gitlab' },
                          { [css.bitbucketIcon]: item.icon === 'bitbucket-blue' }
                        )}
                      />
                      <Text font={{ variation: FontVariation.BODY2 }} padding={{ top: 'small' }}>
                        {getString(item.label)}
                      </Text>
                    </Layout.Vertical>
                  )}
                  selected={gitProvider}
                  onChange={(item: GitProvider) => {
                    formikProps.setFieldValue('gitProvider', item.type)
                    setGitProvider(item)
                  }}
                />
                {formikProps.touched.gitProvider && !formikProps.values.gitProvider ? (
                  <Container padding={{ top: 'xsmall' }}>
                    <FormError
                      name={'gitProvider'}
                      errorMessage={getString('fieldRequired', {
                        field: getString('ci.getStartedWithCI.codeRepoLabel')
                      })}
                    />
                  </Container>
                ) : null}
              </Container>
              {selectedGitProvider ? (
                <>
                  <Text font={{ variation: FontVariation.H5 }} padding={{ top: 'xlarge', bottom: 'small' }}>
                    {getString('ci.getStartedWithCI.authMethod')}
                  </Text>
                  <Layout.Vertical padding={{ top: 'medium' }}>
                    <Layout.Horizontal spacing="small">
                      <Button
                        round
                        text={getString('ci.getStartedWithCI.oAuthLabel')}
                        onClick={() => {
                          const oAuthProviderDetails = OAuthProviders.filter(
                            (oAuthProvider: OAuthProviderType) =>
                              gitProvider && gitProvider.type.toUpperCase() === oAuthProvider.name.toUpperCase()
                          )[0]
                          Iif (oAuthProviderDetails) {
                            const redirectionUrl = `${OAUTH_REDIRECT_URL_PREFIX}api/users/${oAuthProviderDetails.url}`
                            window.open(redirectionUrl, '_blank')
                          }
                          formikProps.setFieldValue('gitAuthenticationMethod', GitAuthenticationMethod.OAuth)
                          setAuthMethod(GitAuthenticationMethod.OAuth)
                        }}
                        intent={authMethod === GitAuthenticationMethod.OAuth ? 'primary' : 'none'}
                      />
                      <Button
                        round
                        text={getString('ci.getStartedWithCI.accessTokenLabel')}
                        onClick={() => {
                          formikProps.setFieldValue('accessToken', '')
                          formikProps.setFieldValue('gitAuthenticationMethod', GitAuthenticationMethod.AccessToken)
                          setAuthMethod(GitAuthenticationMethod.AccessToken)
                        }}
                        intent={authMethod === GitAuthenticationMethod.AccessToken ? 'primary' : 'none'}
                      />
                    </Layout.Horizontal>
                    {formikProps.touched.gitAuthenticationMethod && !formikProps.values.gitAuthenticationMethod ? (
                      <Container padding={{ top: 'xsmall' }}>
                        <FormError
                          name={'gitAuthenticationMethod'}
                          errorMessage={getString('fieldRequired', {
                            field: getString('ci.getStartedWithCI.authMethodLabel')
                          })}
                        />
                      </Container>
                    ) : null}
                  </Layout.Vertical>
                  {authMethod === GitAuthenticationMethod.AccessToken ? (
                    <Container padding={{ top: 'xlarge' }}>
                      <Layout.Horizontal flex={{ justifyContent: 'flex-start' }} spacing="large">
                        <FormInput.Text
                          style={{ width: '40%' }}
                          name="accessToken"
                          label={
                            <Text font={{ variation: FontVariation.FORM_LABEL }}>
                              {getString('ci.getStartedWithCI.accessTokenLabel')}
                            </Text>
                          }
                          tooltipProps={{ dataTooltipId: 'accessToken' }}
                          disabled={[TestStatus.FAILED, TestStatus.IN_PROGRESS].includes(testConnectionStatus)}
                        />
                        <Container
                          padding={{ top: 'small', left: 'small' }}
                          className={cx({
                            [css.testConnectionBtnWithError]:
                              formikProps.touched.accessToken && formikProps.errors.accessToken
                          })}
                        >
                          <TestConnection />
                        </Container>
                      </Layout.Horizontal>
                    </Container>
                  ) : null}
                </>
              ) : null}
            </Form>
          )
        }}
      </Formik>
    </Layout.Vertical>
  )
}
 
export const SelectGitProvider = React.forwardRef(SelectGitProviderRef)