All files / modules/72-templates-library/components/TemplateStudio/TemplateStudioSubHeader/views/TemplateStudioSubHeaderLeftView TemplateStudioSubHeaderLeftView.tsx

89.8% Statements 88/98
67.69% Branches 44/65
93.75% Functions 15/16
89.58% Lines 86/96

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              10x 10x                         10x 10x 10x 10x 10x 10x           10x 10x 10x             10x 10x 10x 10x   10x 10x 10x   10x 10x 10x   10x 10x                     10x       39x 39x 39x     39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x   39x                         39x   4x                                   39x 2x     2x                       39x   1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x                         1x               39x 1x 1x 1x                               39x           1x 1x         39x 1x 1x 1x 1x                     39x 17x         39x 17x 25x         17x 17x     39x 17x 4x 4x       4x       39x                                                                   2x       1x         2x                           1x                                      
/*
 * 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 {
  Button,
  ButtonSize,
  ButtonVariation,
  Container,
  DropDown,
  Icon,
  Layout,
  SelectOption,
  Text,
  VisualYamlSelectedView as SelectedView,
  useConfirmationDialog
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { Color } from '@harness/design-system'
import { useParams, useHistory } from 'react-router-dom'
import { defaultTo, isEmpty, isNil, merge } from 'lodash-es'
import { Dialog } from '@blueprintjs/core'
import {
  Fields,
  ModalProps,
  PromiseExtraArgs,
  TemplateConfigModal
} from 'framework/Templates/TemplateConfigModal/TemplateConfigModal'
import { TagsPopover, useToaster } from '@common/components'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import templateFactory from '@templates-library/components/Templates/TemplatesFactory'
import type {
  GitQueryParams,
  ModulePathParams,
  TemplateStudioPathProps,
  TemplateStudioQueryParams
} from '@common/interfaces/RouteInterfaces'
import { TemplateContext } from '@templates-library/components/TemplateStudio/TemplateContext/TemplateContext'
import routes from '@common/RouteDefinitions'
import { useUpdateStableTemplate, NGTemplateInfoConfig } from 'services/template-ng'
import { useStrings } from 'framework/strings'
import type { UseSaveSuccessResponse } from '@common/modals/SaveToGitDialog/useSaveToGitDialog'
import RbacButton from '@rbac/components/Button/Button'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import type { IGitContextFormProps } from '@common/components/GitContextForm/GitContextForm'
import { useQueryParams, useUpdateQueryParams } from '@common/hooks'
import { AppStoreContext } from 'framework/AppStore/AppStoreContext'
import { DefaultNewTemplateId, DefaultNewVersionLabel } from 'framework/Templates/templates'
import type { GitFilterScope } from '@common/components/GitFilters/GitFilters'
import StudioGitPopover from '@pipeline/components/PipelineStudio/StudioGitPopover'
import css from './TemplateStudioSubHeaderLeftView.module.scss'
 
interface TemplateWithGitContextFormProps extends NGTemplateInfoConfig {
  repo?: string
  branch?: string
}
 
export interface TemplateStudioSubHeaderLeftViewProps {
  onGitBranchChange?: (selectedFilter: GitFilterScope) => void
}
 
export const TemplateStudioSubHeaderLeftView: (props: TemplateStudioSubHeaderLeftViewProps) => JSX.Element = ({
  onGitBranchChange
}) => {
  const { state, updateTemplate, deleteTemplateCache, fetchTemplate, view, isReadonly, setLoading, updateGitDetails } =
    React.useContext(TemplateContext)
  const { template, versions, stableVersion, isUpdated, gitDetails } = state
  const { accountId, projectIdentifier, orgIdentifier, module, templateType, templateIdentifier } = useParams<
    TemplateStudioPathProps & ModulePathParams
  >()
  const { updateQueryParams } = useUpdateQueryParams<TemplateStudioQueryParams>()
  const { repoIdentifier, branch } = useQueryParams<GitQueryParams>()
  const { isGitSyncEnabled } = React.useContext(AppStoreContext)
  const iconColor = templateFactory.getTemplateColor(templateType) || Color.BLACK
  const [modalProps, setModalProps] = React.useState<ModalProps>()
  const isYaml = view === SelectedView.YAML
  const history = useHistory()
  const [versionOptions, setVersionOptions] = React.useState<SelectOption[]>([])
  const { showSuccess, showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
 
  const { mutate: updateStableTemplate, loading: updateStableTemplateLoading } = useUpdateStableTemplate({
    templateIdentifier: template.identifier,
    versionLabel: template.versionLabel,
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      repoIdentifier,
      branch
    },
    requestOptions: { headers: { 'content-type': 'application/json' } }
  })
 
  const [showConfigModal, hideConfigModal] = useModalHook(
    () => (
      <Dialog enforceFocus={false} isOpen={true} className={css.createTemplateDialog}>
        {modalProps && (
          <TemplateConfigModal
            initialValues={merge(template, {
              repo: defaultTo(gitDetails.repoIdentifier, ''),
              branch: defaultTo(gitDetails.branch, '')
            })}
            onClose={onCloseCreate}
            modalProps={modalProps}
            showGitFields={true}
            gitDetails={gitDetails as IGitContextFormProps}
          />
        )}
      </Dialog>
    ),
    [template, modalProps]
  )
 
  const onCloseCreate = React.useCallback(() => {
    Iif (template.identifier === DefaultNewTemplateId) {
      history.push(routes.toTemplates({ orgIdentifier, projectIdentifier, accountId, module }))
    }
    hideConfigModal()
  }, [
    accountId,
    hideConfigModal,
    history,
    module,
    orgIdentifier,
    template.identifier,
    projectIdentifier,
    routes.toTemplates
  ])
 
  const onSubmit = React.useCallback(
    async (data: NGTemplateInfoConfig, extraInfo: PromiseExtraArgs): Promise<UseSaveSuccessResponse> => {
      let { updatedGitDetails } = extraInfo
      template.name = data.name
      template.description = data.description
      template.identifier = data.identifier
      template.tags = data.tags ?? {}
      template.versionLabel = data.versionLabel
      delete (template as TemplateWithGitContextFormProps).repo
      delete (template as TemplateWithGitContextFormProps).branch
 
      try {
        await updateTemplate(template)
        Iif (updatedGitDetails) {
          if (gitDetails?.objectId) {
            updatedGitDetails = { ...gitDetails, ...updatedGitDetails }
          }
          updateGitDetails(updatedGitDetails).then(() => {
            if (updatedGitDetails) {
              updateQueryParams(
                { repoIdentifier: updatedGitDetails.repoIdentifier, branch: updatedGitDetails.branch },
                { skipNulls: true }
              )
            }
          })
        }
        return { status: 'SUCCESS' }
      } catch (error) {
        return { status: 'ERROR' }
      }
    },
    [template]
  )
 
  const goToTemplateVersion = async (versionLabel: string): Promise<void> => {
    Eif (versionLabel !== DefaultNewVersionLabel && versionLabel !== template.versionLabel) {
      await deleteTemplateCache()
      history.replace(
        routes.toTemplateStudio({
          projectIdentifier,
          orgIdentifier,
          accountId,
          module,
          templateType: template.type,
          templateIdentifier: template.identifier,
          versionLabel: versionLabel,
          repoIdentifier,
          branch
        })
      )
    }
  }
 
  const { openDialog: openConfirmationDialog } = useConfirmationDialog({
    cancelButtonText: getString('cancel'),
    contentText: getString('templatesLibrary.setAsStableText', { version: template.versionLabel }),
    titleText: getString('templatesLibrary.setAsStableTitle'),
    confirmButtonText: getString('confirm'),
    onCloseDialog: isConfirmed => {
      Eif (isConfirmed) {
        updateStableLabel()
      }
    }
  })
 
  const updateStableLabel = async () => {
    try {
      await updateStableTemplate()
      showSuccess(getString('common.template.updateTemplate.templateUpdated'))
      await fetchTemplate({ forceFetch: true, forceUpdate: true })
    } catch (error) {
      showError(
        getRBACErrorMessage(error) || getString('common.template.updateTemplate.errorWhileUpdating'),
        undefined,
        'template.save.template.error'
      )
      setLoading(false)
    }
  }
 
  React.useEffect(() => {
    Iif (updateStableTemplateLoading) {
      setLoading(true)
    }
  }, [updateStableTemplateLoading])
 
  React.useEffect(() => {
    const newVersionOption: SelectOption[] = versions.map(item => {
      return {
        label: item === stableVersion ? item + ' (Stable)' : item,
        value: item
      }
    })
    newVersionOption.sort((a, b) => a.label.localeCompare(b.label))
    setVersionOptions(newVersionOption)
  }, [versions])
 
  React.useEffect(() => {
    if (template.identifier === DefaultNewTemplateId && !isEmpty(template.type)) {
      hideConfigModal()
      setModalProps({
        title: getString('templatesLibrary.createNewModal.heading', { entity: template.type }),
        promise: onSubmit
      })
      showConfigModal()
    }
  }, [template.identifier, showConfigModal, template.type, onSubmit])
 
  return (
    <Container className={css.subHeaderLeftView}>
      <Layout.Horizontal spacing={'medium'} padding={{ right: 'medium' }} flex={{ alignItems: 'center' }}>
        <Container>
          <Layout.Horizontal spacing={'small'} flex={{ alignItems: 'center' }}>
            <Icon color={iconColor} name="template-library" size={20} />
            <Text
              className={css.templateName}
              color={Color.GREY_700}
              font={{ weight: 'bold' }}
              tooltip={template?.name}
            >
              {template.name}
            </Text>
            {!isNil(template?.tags) && !isEmpty(template?.tags) && <TagsPopover tags={template.tags} />}
            {isGitSyncEnabled && onGitBranchChange && (
              <StudioGitPopover
                gitDetails={gitDetails}
                identifier={templateIdentifier}
                isReadonly={isReadonly}
                entityData={template}
                onGitBranchChange={onGitBranchChange}
                entityType={getString('common.template.label')}
              />
            )}
            {!isYaml && !isReadonly && (
              <RbacButton
                variation={ButtonVariation.ICON}
                icon="Edit"
                iconProps={{
                  color: Color.GREY_800
                }}
                withoutCurrentColor
                onClick={() => {
                  setModalProps({
                    title: getString('templatesLibrary.createNewModal.editHeading', { entity: template.type }),
                    promise: onSubmit,
                    onSuccess: () => {
                      hideConfigModal()
                    },
                    disabledFields:
                      templateIdentifier === DefaultNewTemplateId ? [] : [Fields.VersionLabel, Fields.Identifier]
                  })
                  showConfigModal()
                }}
                permission={{
                  permission: PermissionIdentifier.EDIT_TEMPLATE,
                  resource: {
                    resourceType: ResourceType.TEMPLATE
                  }
                }}
              />
            )}
          </Layout.Horizontal>
        </Container>
        {templateIdentifier !== DefaultNewTemplateId && (
          <DropDown
            onChange={item => goToTemplateVersion(item.value.toString())}
            items={versionOptions}
            value={template.versionLabel}
            filterable={false}
            className={css.versionDropDown}
          />
        )}
        {template.versionLabel !== stableVersion && !isUpdated && !isReadonly && (
          <Button
            onClick={openConfirmationDialog}
            variation={ButtonVariation.LINK}
            size={ButtonSize.SMALL}
            text={getString('common.setAsStable')}
          />
        )}
      </Layout.Horizontal>
    </Container>
  )
}