All files / modules/75-cd/components/PipelineStudio/DeployStage/EditStageView EditStageView.tsx

88.57% Statements 62/70
73.81% Branches 124/168
77.78% Functions 7/9
88.24% Lines 60/68

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              5x 5x                         5x 5x 5x 5x   5x 5x         5x 5x 5x   5x 5x 5x 5x 5x 5x 5x     5x   5x 5x 5x 5x                                     5x                         10x 10x 10x                                                   10x 10x 10x 10x 10x 10x 10x   10x   10x 2x       10x 6x 6x       10x                                           10x   1x 1x     1x 1x 1x       1x 1x   1x     1x     1x         10x                                                 1x 1x     1x     1x         12x 12x 12x                                                                                                                                                                                                                                                      
/*
 * 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 from 'react'
import {
  Text,
  Container,
  Formik,
  FormikForm,
  Button,
  Card,
  Accordion,
  HarnessDocTooltip,
  ThumbnailSelect,
  ButtonVariation
} from '@wings-software/uicore'
import type { Item } from '@wings-software/uicore/dist/components/ThumbnailSelect/ThumbnailSelect'
import { Color } from '@harness/design-system'
import cx from 'classnames'
import * as Yup from 'yup'
import { omit, set } from 'lodash-es'
import type { FormikProps } from 'formik'
import { useStrings } from 'framework/strings'
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import type {
  CustomVariablesData,
  CustomVariableEditableExtraProps
} from '@pipeline/components/PipelineSteps/Steps/CustomVariables/CustomVariableEditable'
import { StepWidget } from '@pipeline/components/AbstractSteps/StepWidget'
import { StepViewType } from '@pipeline/components/AbstractSteps/Step'
import { usePipelineContext } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import type { AllNGVariables } from '@pipeline/utils/types'
import { NameId, NameIdDescriptionTags } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import { isDuplicateStageId } from '@pipeline/components/PipelineStudio/StageBuilder/StageBuilderUtil'
import { usePipelineVariables } from '@pipeline/components/PipelineVariablesContext/PipelineVariablesContext'
import { StageErrorContext } from '@pipeline/context/StageErrorContext'
import { DeployTabs } from '@cd/components/PipelineStudio/DeployStageSetupShell/DeployStageSetupShellUtils'
import DeployServiceErrors from '@cd/components/PipelineStudio/DeployServiceSpecifications/DeployServiceErrors'
import { useValidationErrors } from '@pipeline/components/PipelineStudio/PiplineHooks/useValidationErrors'
import type { DeploymentStageElementConfig, StageElementWrapper } from '@pipeline/utils/pipelineTypes'
import type { StringNGVariable } from 'services/cd-ng'
import { getNameAndIdentifierSchema } from '@pipeline/utils/tempates'
import type { TemplateSummaryResponse } from 'services/template-ng'
import { createTemplate, getTemplateNameWithLabel } from '@pipeline/utils/templateUtils'
import { isContextTypeNotStageTemplate } from '@pipeline/components/PipelineStudio/PipelineUtils'
import css from './EditStageView.module.scss'
import stageCss from '../../DeployStageSetupShell/DeployStage.module.scss'
 
export interface EditStageViewProps {
  data?: StageElementWrapper<DeploymentStageElementConfig>
  template?: TemplateSummaryResponse
  onSubmit?: (values: StageElementWrapper<DeploymentStageElementConfig>, identifier?: string) => void
  onChange?: (values: DeploymentStageElementConfig) => void
  context?: string
  isReadonly: boolean
}
 
interface Values {
  identifier: string
  name: string
  description?: string
  tags?: { [key: string]: string }
  serviceType: string
}
 
export const EditStageView: React.FC<EditStageViewProps> = ({
  data,
  template,
  onSubmit,
  context,
  onChange,
  isReadonly,
  children
}): JSX.Element => {
  const {
    state: {
      pipeline: { stages = [] }
    }
  } = usePipelineContext()
  const { getString } = useStrings()
  const newStageData: Item[] = [
    {
      label: getString('service'),
      value: 'service',
      icon: 'service',
      disabled: false
    },
    {
      label: getString('multipleService'),
      value: 'multiple-service',
      icon: 'multi-service',
      disabled: true
    },
    {
      label: getString('functions'),
      value: 'functions',
      icon: 'functions',
      disabled: true
    },
    {
      label: getString('otherWorkloads'),
      value: 'other-workloads',
      icon: 'other-workload',
      disabled: true
    }
  ]
  const { stepsFactory, getStageFromPipeline, contextType, allowableTypes } = usePipelineContext()
  const { variablesPipeline, metadataMap } = usePipelineVariables()
  const scrollRef = React.useRef<HTMLDivElement | null>(null)
  const allNGVariables = (data?.stage?.variables || []) as AllNGVariables[]
  const { errorMap } = useValidationErrors()
  const { subscribeForm, unSubscribeForm, submitFormsForTab } = React.useContext(StageErrorContext)
  const formikRef = React.useRef<FormikProps<unknown> | null>(null)
 
  React.useEffect(() => {
    /* istanbul ignore else */
    if (errorMap.size > 0) {
      submitFormsForTab(DeployTabs.OVERVIEW)
    }
  }, [errorMap])
 
  React.useEffect(() => {
    subscribeForm({ tab: DeployTabs.OVERVIEW, form: formikRef })
    return () => unSubscribeForm({ tab: DeployTabs.OVERVIEW, form: formikRef })
  }, [])
 
  const whatToDeploy = (
    <>
      {context ? (
        <div className={stageCss.tabSubHeading}>{getString('whatToDeploy')}</div>
      ) : (
        <Text
          color={Color.GREY_700}
          font={{ size: 'normal', weight: 'semi-bold' }}
          tooltipProps={{ dataTooltipId: 'whatToDeploy' }}
        >
          {getString('whatToDeploy')}
        </Text>
      )}
 
      <ThumbnailSelect
        name="serviceType"
        items={newStageData}
        className={context ? stageCss.thumbnailSelect : css.stageTypeThumbnail}
        isReadonly={isReadonly}
      />
    </>
  )
 
  const handleSubmit = (values: Values): void => {
    /* istanbul ignore else */
    if (data?.stage) {
      Iif (template) {
        onSubmit?.({ stage: createTemplate(values, template) }, values.identifier)
      } else {
        data.stage.identifier = values.identifier
        data.stage.name = values.name
        Iif (values.description) {
          data.stage.description = values.description
        }
        /* istanbul ignore else */
        if (values.tags) {
          data.stage.tags = values.tags
        }
        Iif (!data.stage.spec?.serviceConfig) {
          set(data, 'stage.spec.serviceConfig', {})
        }
        Iif (!data.stage.spec?.infrastructure) {
          set(data, 'stage.spec.infrastructure', {})
        }
        onSubmit?.(data, values.identifier)
      }
    }
  }
 
  return (
    <div className={stageCss.serviceOverrides}>
      <DeployServiceErrors domRef={scrollRef as React.MutableRefObject<HTMLElement | undefined>} />
      <div className={context ? stageCss.contentSection : css.contentSection} ref={scrollRef}>
        {context ? (
          <div className={stageCss.tabHeading} id="stageOverview">
            {getString('stageOverview')}
          </div>
        ) : (
          <Text icon="cd-main" iconProps={{ size: 16 }} className={css.addStageHeading}>
            {getString('pipelineSteps.build.create.aboutYourStage')}
          </Text>
        )}
        <Container>
          <Formik<Values>
            initialValues={{
              identifier: data?.stage?.identifier || '',
              name: data?.stage?.name || '',
              description: data?.stage?.description,
              tags: data?.stage?.tags || {},
              serviceType: newStageData[0].value
            }}
            formName="cdEditStage"
            onSubmit={handleSubmit}
            validate={values => {
              const errors: { name?: string } = {}
              Iif (isDuplicateStageId(values.identifier || '', stages, !!context)) {
                errors.name = getString('validation.identifierDuplicate')
              }
              Iif (context && data) {
                onChange?.(omit(values as unknown as DeploymentStageElementConfig, 'serviceType'))
              }
              return errors
            }}
            validationSchema={Yup.object().shape(getNameAndIdentifierSchema(getString, contextType))}
          >
            {formikProps => {
              window.dispatchEvent(new CustomEvent('UPDATE_ERRORS_STRIP', { detail: DeployTabs.OVERVIEW }))
              formikRef.current = formikProps
              return (
                <FormikForm>
                  {isContextTypeNotStageTemplate(contextType) && (
                    <>
                      {context ? (
                        <Card className={stageCss.sectionCard}>
                          <NameIdDescriptionTags
                            formikProps={formikProps}
                            identifierProps={{
                              inputLabel: getString('stageNameLabel'),
                              isIdentifierEditable: !context,
                              inputGroupProps: { disabled: isReadonly }
                            }}
                            descriptionProps={{ disabled: isReadonly }}
                            tagsProps={{ disabled: isReadonly }}
                            className={css.nameIdDescriptionTags}
                          />
                        </Card>
                      ) : template ? (
                        <NameId
                          identifierProps={{
                            inputLabel: getString('stageNameLabel'),
                            isIdentifierEditable: !context && !isReadonly,
                            inputGroupProps: { disabled: isReadonly }
                          }}
                        />
                      ) : (
                        <NameIdDescriptionTags
                          formikProps={formikProps}
                          identifierProps={{
                            inputLabel: getString('stageNameLabel'),
                            isIdentifierEditable: !context && !isReadonly,
                            inputGroupProps: { disabled: isReadonly }
                          }}
                          descriptionProps={{ disabled: isReadonly }}
                          tagsProps={{ disabled: isReadonly }}
                        />
                      )}
                    </>
                  )}
 
                  {template ? (
                    <Text
                      icon={'template-library'}
                      margin={{ top: 'medium', bottom: 'medium' }}
                      font={{ size: 'small' }}
                      iconProps={{ size: 12, margin: { right: 'xsmall' } }}
                      color={Color.BLACK}
                    >
                      {`Using Template: ${getTemplateNameWithLabel(template)}`}
                    </Text>
                  ) : !context ? (
                    whatToDeploy
                  ) : (
                    <Card className={stageCss.sectionCard}>{whatToDeploy}</Card>
                  )}
 
                  {!context && (
                    <Button
                      margin={{ top: 'medium' }}
                      type="submit"
                      variation={ButtonVariation.PRIMARY}
                      text={getString('pipelineSteps.build.create.setupStage')}
                    />
                  )}
                </FormikForm>
              )
            }}
          </Formik>
        </Container>
        {context && (
          <>
            <Accordion activeId={allNGVariables.length > 0 ? 'advanced' : ''} className={stageCss.accordion}>
              <Accordion.Panel
                id="advanced"
                addDomId={true}
                summary={<div className={stageCss.tabHeading}>{getString('common.advanced')}</div>}
                details={
                  <Card className={stageCss.sectionCard} id="variables">
                    <div
                      className={cx(stageCss.tabSubHeading, 'ng-tooltip-native')}
                      data-tooltip-id="overviewStageVariables"
                    >
                      {getString('pipeline.stageVariables')}
                      <HarnessDocTooltip tooltipId="overviewStageVariables" useStandAlone={true} />
                    </div>
                    <StepWidget<CustomVariablesData, CustomVariableEditableExtraProps>
                      factory={stepsFactory}
                      initialValues={{
                        variables: allNGVariables,
                        canAddVariable: true
                      }}
                      readonly={isReadonly}
                      type={StepType.CustomVariable}
                      stepViewType={StepViewType.StageVariable}
                      allowableTypes={allowableTypes}
                      onUpdate={({ variables }: CustomVariablesData) => {
                        onChange?.({ ...(data?.stage as DeploymentStageElementConfig), variables })
                      }}
                      customStepProps={{
                        tabName: DeployTabs.OVERVIEW,
                        formName: 'addEditStageCustomVariableForm',
                        yamlProperties:
                          getStageFromPipeline(
                            data?.stage?.identifier || '',
                            variablesPipeline
                          )?.stage?.stage?.variables?.map?.(
                            variable => metadataMap[(variable as StringNGVariable).value || '']?.yamlProperties || {}
                          ) || [],
                        enableValidation: true
                      }}
                    />
                  </Card>
                }
              />
            </Accordion>
            <Container margin={{ top: 'xxlarge' }}>{children}</Container>
          </>
        )}
      </div>
    </div>
  )
}