All files / modules/30-delegates/components/DelegateTokens/modals useCreateTokenModal.tsx

91.89% Statements 34/37
73.33% Branches 22/30
83.33% Functions 5/6
91.67% Lines 33/36

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              14x 14x                       14x 14x 14x   14x   14x 14x 14x 14x 14x 14x   14x                                 14x 24x 24x 24x                 24x   24x                 24x   24x 1x 1x       1x                 1x 1x         1x     24x   2x                               15x                                                                                                               24x 2x     24x          
/*
 * 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, { useCallback } from 'react'
import {
  Dialog,
  Button,
  Layout,
  FormInput,
  Container,
  Text,
  Formik,
  FormikForm,
  PageSpinner,
  ButtonVariation
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useModalHook } from '@harness/use-modal'
import { useParams } from 'react-router-dom'
import type { FormikActions } from 'formik'
import * as Yup from 'yup'
import type { IDialogProps } from '@blueprintjs/core'
import { NameSchema } from '@common/utils/Validation'
import CopyToClipboard from '@common/components/CopyToClipBoard/CopyToClipBoard'
import { useStrings } from 'framework/strings'
import { useCreateDelegateToken, CreateDelegateTokenQueryParams } from 'services/cd-ng'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { Category, DelegateActions } from '@common/constants/TrackingConstants'
 
import css from '../DelegateTokens.module.scss'
 
export interface CreateTokenModalProps {
  onSuccess?: () => void
  onUserAdded?: () => void
}
 
export interface CreateTokenModalReturn {
  openCreateTokenModal: () => void
  closeCreateTokenModal: () => void
}
 
interface FormikProps {
  name: string
  tokenValue: string
}
 
export const useCreateTokenModal = ({ onSuccess }: CreateTokenModalProps): CreateTokenModalReturn => {
  const { getString } = useStrings()
  const { accountId, projectIdentifier, orgIdentifier } = useParams<Record<string, string>>()
  const modalProps: IDialogProps = {
    isOpen: true,
    title: getString('rbac.token.createLabel'),
    enforceFocus: false,
    style: {
      width: 416,
      height: 368
    }
  }
  const { trackEvent } = useTelemetry()
 
  const { mutate: createToken, loading } = useCreateDelegateToken({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      tokenName: ''
    } as CreateDelegateTokenQueryParams
  })
 
  const generatedValuePlaceholder = getString('delegates.tokens.generatedValuePlaceholder')
 
  const onSubmit = async (values: FormikProps, formikActions: FormikActions<any>) => {
    try {
      trackEvent(DelegateActions.SaveCreateToken, {
        category: Category.DELEGATE,
        data: values
      })
      const createTokenResponse = await createToken(undefined, {
        headers: { 'content-type': 'application/json' },
        queryParams: {
          accountIdentifier: accountId,
          orgIdentifier,
          projectIdentifier,
          tokenName: values?.name?.trim?.()
        } as CreateDelegateTokenQueryParams
      })
      formikActions.setFieldValue('tokenValue', createTokenResponse?.resource?.value || '')
      onSuccess?.()
    } catch (e) {
      /* istanbul ignore next */
      formikActions.setFieldError('name', e.data?.message || e.data?.responseMessages?.[0]?.message)
    }
    return values
  }
 
  const [showModal, hideModal] = useModalHook(
    () => (
      <Dialog onClose={hideModal} {...modalProps} style={{ height: '100%' }}>
        <>
          {loading ? <PageSpinner /> : null}
          <Formik
            initialValues={{
              name: '',
              tokenValue: generatedValuePlaceholder
            }}
            onSubmit={onSubmit}
            formName="createTokenForm"
            validationSchema={Yup.object().shape({
              name: NameSchema({ requiredErrorMsg: getString('delegates.tokens.tokenNameRequired') }),
              tokenValue: Yup.string()
            })}
          >
            {form => {
              return (
                <FormikForm className={css.addTokenModalForm}>
                  <div className={css.addTokenModalContainer}>
                    <Layout.Vertical>
                      <FormInput.Text name="name" label={getString('name')} />
                      <Container
                        intent="primary"
                        padding="small"
                        font={{
                          align: 'center'
                        }}
                        flex
                        className={css.tokenField}
                      >
                        <Text margin={{ right: 'large' }} font="small" color={Color.BLACK} className={css.tokenValue}>
                          {form.values.tokenValue}
                        </Text>
                        <span className={css.copyContainer}>
                          <CopyToClipboard content={form.values.tokenValue} />
                        </span>
                      </Container>
                    </Layout.Vertical>
                    <Layout.Horizontal spacing="small" className={css.addTokenModalActionContainer}>
                      <Button
                        intent="primary"
                        type="submit"
                        variation={ButtonVariation.PRIMARY}
                        disabled={generatedValuePlaceholder !== form.values.tokenValue}
                      >
                        {getString('common.apply')}
                      </Button>
                      <Button
                        onClick={e => {
                          e.preventDefault()
                          hideModal()
                          trackEvent(DelegateActions.CloseCreateToken, {
                            category: Category.DELEGATE
                          })
                        }}
                        variation={ButtonVariation.TERTIARY}
                      >
                        {generatedValuePlaceholder === form.values.tokenValue
                          ? getString('cancel')
                          : getString('close')}
                      </Button>
                    </Layout.Horizontal>
                  </div>
                </FormikForm>
              )
            }}
          </Formik>
        </>
      </Dialog>
    ),
    [onSuccess]
  )
  const open = useCallback(() => {
    showModal()
  }, [showModal])
 
  return {
    openCreateTokenModal: open,
    closeCreateTokenModal: hideModal
  }
}