All files / framework/Templates/TemplateConfigModal TemplateConfigModal.tsx

96.2% Statements 76/79
78.26% Branches 54/69
91.67% Functions 11/12
96.15% Lines 75/78

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              32x 32x 32x   32x                     32x 32x 32x 32x 32x 32x   32x 32x 32x   32x 32x 32x 32x 32x   32x 32x   32x 32x 32x 32x 32x 32x 32x 32x                                                                                 32x   32x 28x                 28x 28x 28x 28x 28x 28x 28x 28x   28x 14x 14x     28x 1x   1x 1x 1x           1x 1x 1x 1x                     28x 39x 30x 1x   29x   9x     28x   28x                         12x                                                                             39x                                                                                                                                                                                                 32x 26x 26x 26x 26x 26x 26x   26x 7x                                   7x     26x 14x       26x                                 26x    
/*
 * 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, { Dispatch, useState, SetStateAction, useContext } from 'react'
import * as Yup from 'yup'
import { isEmpty, omit, defaultTo } from 'lodash-es'
import type { FormikProps } from 'formik'
import {
  Formik,
  Layout,
  FormikForm,
  FormInput,
  Text,
  Button,
  ButtonVariation,
  Container,
  Icon
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useStrings } from 'framework/strings'
import { NameIdDescriptionTags } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import RbacButton from '@rbac/components/Button/Button'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import type { EntityGitDetails, NGTemplateInfoConfig } from 'services/template-ng'
import { TemplatePreview } from '@templates-library/components/TemplatePreview/TemplatePreview'
import { TemplateContext } from '@templates-library/components/TemplateStudio/TemplateContext/TemplateContext'
import { PageSpinner } from '@common/components'
import type { UseSaveSuccessResponse } from '@common/modals/SaveToGitDialog/useSaveToGitDialog'
import GitContextForm, { IGitContextFormProps } from '@common/components/GitContextForm/GitContextForm'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import { IdentifierSchema, NameSchema } from '@common/utils/Validation'
import { regexVersionLabel } from '@common/utils/StringUtils'
import type { Error } from 'services/cd-ng'
import { DefaultNewTemplateId, DefaultNewVersionLabel } from '../templates'
import css from './TemplateConfigModal.module.scss'
 
export enum Fields {
  Name = 'name',
  Identifier = 'identifier',
  Description = 'description',
  Tags = 'tags',
  VersionLabel = 'versionLabel',
  Repo = 'repo',
  Branch = 'branch'
}
 
export interface PromiseExtraArgs {
  isEdit?: boolean
  updatedGitDetails?: EntityGitDetails
  comment?: string
}
 
export interface ModalProps {
  title: string
  disabledFields?: Fields[]
  emptyFields?: Fields[]
  shouldGetComment?: boolean
  promise: (values: NGTemplateInfoConfig, extraInfo: PromiseExtraArgs) => Promise<UseSaveSuccessResponse>
  onSuccess?: (values: NGTemplateInfoConfig) => void
  onFailure?: (error: Error) => void
  lastPublishedVersion?: string
}
 
export interface TemplateConfigValues extends NGTemplateInfoConfigWithGitDetails {
  comment: string
}
 
export interface NGTemplateInfoConfigWithGitDetails extends NGTemplateInfoConfig {
  repo: string
  branch: string
}
 
export interface ConfigModalProps {
  initialValues: NGTemplateInfoConfigWithGitDetails
  onClose: () => void
  modalProps: ModalProps
  showGitFields?: boolean
  gitDetails?: IGitContextFormProps
}
 
interface BasicDetailsInterface extends ConfigModalProps {
  setPreviewValues: Dispatch<SetStateAction<NGTemplateInfoConfigWithGitDetails>>
}
 
const MAX_VERSION_LABEL_LENGTH = 63
 
const BasicTemplateDetails = (props: BasicDetailsInterface): JSX.Element => {
  const { initialValues, setPreviewValues, onClose, modalProps, showGitFields, gitDetails } = props
  const {
    title,
    disabledFields = [],
    shouldGetComment = false,
    promise,
    onSuccess,
    onFailure,
    lastPublishedVersion
  } = modalProps
  const { getString } = useStrings()
  const [isEdit, setIsEdit] = React.useState<boolean>()
  const { isGitSyncEnabled } = useAppStore()
  const currentTemplateType = initialValues.type
  const formName = `create${currentTemplateType}Template`
  const [loading, setLoading] = React.useState<boolean>()
  const { isReadonly } = useContext(TemplateContext)
 
  React.useEffect(() => {
    const edit = initialValues.identifier !== DefaultNewTemplateId
    setIsEdit(edit)
  }, [initialValues])
 
  const onSubmit = React.useCallback((values: TemplateConfigValues) => {
    setLoading(true)
    const formGitDetails =
      values.repo && values.repo.trim().length > 0 ? { repoIdentifier: values.repo, branch: values.branch } : undefined
    const comment = values.comment.trim()
    promise(omit(values, 'repo', 'branch', 'comment'), {
      isEdit: false,
      updatedGitDetails: formGitDetails,
      ...(comment.length > 0 && { comment: values.comment })
    })
      .then(response => {
        setLoading(false)
        Eif (response && response.status === 'SUCCESS') {
          onSuccess?.(values)
          onClose()
        } else {
          throw response
        }
      })
      .catch(error => {
        setLoading(false)
        onFailure?.(error)
      })
  }, [])
 
  const getSaveButtonText = React.useCallback((): string => {
    if (isEdit) {
      if (isGitSyncEnabled) {
        return getString('continue')
      }
      return getString('save')
    }
    return getString('start')
  }, [isEdit, isGitSyncEnabled, getString])
 
  const versionLabelText = getString('templatesLibrary.createNewModal.versionLabel')
 
  return (
    <Container width={'55%'} className={css.basicDetails} background={Color.FORM_BG} padding={'huge'}>
      {loading && <PageSpinner />}
      <Text
        color={Color.GREY_800}
        font={{ weight: 'bold', size: 'medium' }}
        margin={{ bottom: 'xlarge', left: 0, right: 0 }}
      >
        {defaultTo(title, '')}
      </Text>
      <Formik<TemplateConfigValues>
        initialValues={{ ...initialValues, comment: '' }}
        onSubmit={onSubmit}
        validate={values => setPreviewValues(values)}
        formName={formName}
        enableReinitialize={true}
        validationSchema={Yup.object().shape({
          name: NameSchema({
            requiredErrorMsg: getString('common.validation.fieldIsRequired', {
              name: getString('templatesLibrary.createNewModal.nameError')
            })
          }),
          identifier: IdentifierSchema(),
          versionLabel: Yup.string()
            .trim()
            .required(
              getString('common.validation.fieldIsRequired', {
                name: versionLabelText
              })
            )
            .matches(
              regexVersionLabel,
              getString('common.validation.fieldMustStartWithAlphanumericAndCanNotHaveSpace', {
                name: versionLabelText
              })
            )
            .max(
              MAX_VERSION_LABEL_LENGTH,
              getString('common.validation.fieldCannotbeLongerThanN', {
                name: versionLabelText,
                n: MAX_VERSION_LABEL_LENGTH
              })
            ),
          ...(isGitSyncEnabled && showGitFields
            ? {
                repo: Yup.string().trim().required(getString('common.git.validation.repoRequired')),
                branch: Yup.string().trim().required(getString('common.git.validation.branchRequired'))
              }
            : {})
        })}
      >
        {(formik: FormikProps<TemplateConfigValues>) => {
          return (
            <FormikForm>
              <Layout.Vertical spacing={'huge'}>
                <Container>
                  <Layout.Vertical spacing={'small'}>
                    <Container>
                      <Layout.Vertical>
                        <NameIdDescriptionTags
                          tooltipProps={{ dataTooltipId: formName }}
                          formikProps={formik}
                          identifierProps={{
                            isIdentifierEditable: !disabledFields.includes(Fields.Identifier) && !isReadonly,
                            inputGroupProps: { disabled: disabledFields.includes(Fields.Name) || isReadonly }
                          }}
                          className={css.nameIdDescriptionTags}
                          descriptionProps={{
                            disabled: disabledFields.includes(Fields.Description) || isReadonly
                          }}
                          tagsProps={{
                            disabled: disabledFields.includes(Fields.Tags) || isReadonly
                          }}
                        />
                        <FormInput.Text
                          name="versionLabel"
                          placeholder={getString('templatesLibrary.createNewModal.versionPlaceholder')}
                          label={versionLabelText}
                          disabled={disabledFields.includes(Fields.VersionLabel) || isReadonly}
                        />
                        {lastPublishedVersion && (
                          <Container
                            border={{ radius: 4, color: Color.BLUE_100 }}
                            background={Color.BLUE_100}
                            flex={{ alignItems: 'center' }}
                            padding={'small'}
                            margin={{ bottom: 'medium' }}
                          >
                            <Layout.Horizontal spacing="small" flex={{ justifyContent: 'start' }}>
                              <Icon name="info-messaging" size={18} />
                              <Text color={Color.BLACK} font={{ weight: 'semi-bold', size: 'small' }}>
                                {getString('templatesLibrary.createNewModal.lastPublishedVersion')}
                              </Text>
                              <Text
                                lineClamp={1}
                                color={Color.BLACK}
                                font={{ size: 'small' }}
                                margin={{ left: 'none' }}
                              >
                                {lastPublishedVersion}
                              </Text>
                            </Layout.Horizontal>
                          </Container>
                        )}
                        {shouldGetComment && (
                          <FormInput.TextArea
                            name="comment"
                            label={getString('optionalField', {
                              name: getString('common.commentModal.commentLabel')
                            })}
                            textArea={{
                              className: css.comment
                            }}
                          />
                        )}
                      </Layout.Vertical>
                    </Container>
                    {isGitSyncEnabled && showGitFields && (
                      <GitSyncStoreProvider>
                        <GitContextForm formikProps={formik} gitDetails={gitDetails} />
                      </GitSyncStoreProvider>
                    )}
                  </Layout.Vertical>
                </Container>
                <Container>
                  <Layout.Horizontal spacing="small" flex={{ alignItems: 'flex-end', justifyContent: 'flex-start' }}>
                    <RbacButton
                      text={getSaveButtonText()}
                      type="submit"
                      variation={ButtonVariation.PRIMARY}
                      permission={{
                        permission: PermissionIdentifier.EDIT_TEMPLATE,
                        resource: {
                          resourceType: ResourceType.TEMPLATE
                        }
                      }}
                    />
                    <Button text={getString('cancel')} variation={ButtonVariation.TERTIARY} onClick={onClose} />
                  </Layout.Horizontal>
                </Container>
              </Layout.Vertical>
            </FormikForm>
          )
        }}
      </Formik>
    </Container>
  )
}
 
export const TemplateConfigModal = (props: ConfigModalProps): JSX.Element => {
  const { initialValues, modalProps, ...rest } = props
  const { emptyFields = [] } = modalProps
  const [previewValues, setPreviewValues] = useState(props.initialValues)
  const [formInitialValues, setFormInitialValues] = React.useState(initialValues)
  const { isGitSyncEnabled } = useAppStore()
  const { getString } = useStrings()
 
  React.useEffect(() => {
    const newInitialValues = {
      ...initialValues,
      ...((emptyFields.includes(Fields.Name) || isEmpty(initialValues.name)) && {
        name: getString('templatesLibrary.createNewModal.namePlaceholder', { entity: initialValues.type })
      }),
      ...((emptyFields.includes(Fields.Identifier) || initialValues.identifier === DefaultNewTemplateId) && {
        identifier: getString('templatesLibrary.createNewModal.identifierPlaceholder', {
          entity: initialValues.type.toLowerCase()
        })
      }),
      ...((emptyFields.includes(Fields.VersionLabel) || initialValues.versionLabel === DefaultNewVersionLabel) && {
        versionLabel: undefined
      }),
      ...(emptyFields.includes(Fields.Description) && { description: undefined }),
      ...(emptyFields.includes(Fields.Tags) && { tags: undefined }),
      ...(emptyFields.includes(Fields.Repo) && { repo: undefined }),
      ...(emptyFields.includes(Fields.Branch) && { branch: undefined })
    }
    setFormInitialValues(newInitialValues)
  }, [initialValues, JSON.stringify(emptyFields)])
 
  React.useEffect(() => {
    setPreviewValues(formInitialValues)
  }, [formInitialValues])
 
  const content = (
    <Layout.Horizontal>
      <BasicTemplateDetails
        initialValues={formInitialValues}
        modalProps={modalProps}
        setPreviewValues={setPreviewValues}
        {...rest}
      />
      <TemplatePreview previewValues={previewValues} />
      <Button
        className={css.closeIcon}
        iconProps={{ size: 24, color: Color.GREY_500 }}
        icon="cross"
        variation={ButtonVariation.ICON}
        onClick={props.onClose}
      />
    </Layout.Horizontal>
  )
  return isGitSyncEnabled ? <GitSyncStoreProvider>{content}</GitSyncStoreProvider> : content
}