All files / modules/72-templates-library/components/TemplateDetails TemplateDetails.tsx

90.59% Statements 77/85
74.32% Branches 55/74
70.59% Functions 12/17
92.41% Lines 73/79

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              23x 23x                         23x 23x 23x 23x 23x 23x 23x 23x         23x 23x 23x 23x 23x 23x 23x 23x 23x 23x   23x 23x 23x 23x 23x                 23x 23x 23x 23x     23x 23x 23x     23x   23x 18x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x             17x                                 17x                       17x 9x 4x       17x 9x 5x         9x 9x     9x     17x 5x 4x 4x 1x 1x 1x   4x       17x 1x 1x                               17x       17x             17x 11x       17x   17x                                                                                                                                                                                                                                                                                                                            
/*
 * 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, { useContext, useMemo } from 'react'
import {
  ButtonSize,
  ButtonVariation,
  Container,
  DropDown,
  Icon,
  Layout,
  PageError,
  SelectOption,
  Tab,
  Tabs,
  Text
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useHistory, useParams } from 'react-router-dom'
import { defaultTo, isEmpty } from 'lodash-es'
import { useStrings } from 'framework/strings'
import routes from '@common/RouteDefinitions'
import { TemplateTags } from '@templates-library/components/TemplateTags/TemplateTags'
import { PageSpinner } from '@common/components'
import {
  getIconForTemplate,
  getTypeForTemplate,
  TemplateListType
} from '@templates-library/pages/TemplatesPage/TemplatesPageUtils'
import { useMutateAsGet } from '@common/hooks'
import { TemplateSummaryResponse, useGetTemplateList } from 'services/template-ng'
import RbacButton from '@rbac/components/Button/Button'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import GitPopover from '@pipeline/components/GitPopover/GitPopover'
import { TemplateYaml } from '@pipeline/components/PipelineStudio/TemplateYaml/TemplateYaml'
import NoResultsView from '@templates-library/pages/TemplatesPage/views/NoResultsView/NoResultsView'
import templateDoesNotExistSvg from '@templates-library/pages/TemplatesPage/images/template-does-not-exist.svg'
import type { ModulePathParams, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { getVersionLabelText } from '@templates-library/utils/templatesUtils'
import { TemplateInputs } from '@templates-library/components/TemplateInputs/TemplateInputs'
import { TemplateContext } from '../TemplateStudio/TemplateContext/TemplateContext'
import { TemplateActivityLog } from '../TemplateActivityLog/TemplateActivityLog'
import css from './TemplateDetails.module.scss'
 
export interface TemplateDetailsProps {
  template: TemplateSummaryResponse
  defaultVersionLabel?: string
  allowStableSelection?: boolean
  setTemplate?: (template: TemplateSummaryResponse) => void
}
 
export enum TemplateTabs {
  INPUTS = 'INPUTS',
  YAML = 'YAML',
  REFERENCEDBY = 'REFERENCEDBY'
}
 
export enum ParentTemplateTabs {
  BASIC = 'BASIC',
  ACTVITYLOG = 'ACTVITYLOG'
}
 
const DefaultStableVersionValue = '-1'
 
export const TemplateDetails: React.FC<TemplateDetailsProps> = props => {
  const { template, defaultVersionLabel, allowStableSelection = false, setTemplate } = props
  const { getString } = useStrings()
  const history = useHistory()
  const [versionOptions, setVersionOptions] = React.useState<SelectOption[]>([])
  const { isReadonly } = useContext(TemplateContext)
  const { isGitSyncEnabled } = useAppStore()
  const [templates, setTemplates] = React.useState<TemplateSummaryResponse[]>([])
  const [selectedTemplate, setSelectedTemplate] = React.useState<TemplateSummaryResponse>()
  const [selectedParentTab, setSelectedParentTab] = React.useState<ParentTemplateTabs>(ParentTemplateTabs.BASIC)
  const [selectedTab, setSelectedTab] = React.useState<TemplateTabs>(TemplateTabs.INPUTS)
  const { module } = useParams<ProjectPathProps & ModulePathParams>()
 
  const {
    data: templateData,
    refetch: reloadTemplates,
    loading,
    error: templatesError
  } = useMutateAsGet(useGetTemplateList, {
    body: {
      filterType: 'Template',
      templateIdentifiers: [template.identifier]
    },
    queryParams: {
      accountIdentifier: template.accountId,
      orgIdentifier: template.orgIdentifier,
      projectIdentifier: template.projectIdentifier,
      templateListType: TemplateListType.All,
      module,
      repoIdentifier: template.gitDetails?.repoIdentifier,
      branch: template.gitDetails?.branch
    },
    queryParamStringifyOptions: { arrayFormat: 'comma' }
  })
 
  const onChange = React.useCallback(
    (option: SelectOption): void => {
      const version = defaultTo(option.value?.toString(), '')
      if (version === DefaultStableVersionValue) {
        setSelectedTemplate(templates.find(item => !item.versionLabel))
      } else {
        setSelectedTemplate(templates.find(item => item.versionLabel === version))
      }
    },
    [templates]
  )
 
  React.useEffect(() => {
    if (selectedTemplate) {
      setTemplate?.(selectedTemplate)
    }
  }, [selectedTemplate])
 
  React.useEffect(() => {
    const newVersionOptions: SelectOption[] = templates.map(item => {
      return {
        label: getVersionLabelText(item, getString),
        value: defaultTo(item.versionLabel, DefaultStableVersionValue)
      } as SelectOption
    })
    setVersionOptions(newVersionOptions)
    const selectedVersionLabel = allowStableSelection
      ? defaultVersionLabel
      : defaultTo(defaultVersionLabel, template.versionLabel)
    setSelectedTemplate(templates.find(item => item.versionLabel === selectedVersionLabel))
  }, [templates])
 
  React.useEffect(() => {
    if (templateData?.data?.content) {
      const allVersions = [...templateData.data.content]
      if (allowStableSelection) {
        const stableVersion = { ...allVersions.find(item => item.stableTemplate) }
        delete stableVersion.versionLabel
        allVersions.unshift(stableVersion)
      }
      setTemplates(allVersions)
    }
  }, [templateData])
 
  const goToTemplateStudio = () => {
    Eif (selectedTemplate) {
      history.push(
        routes.toTemplateStudio({
          projectIdentifier: selectedTemplate.projectIdentifier,
          orgIdentifier: selectedTemplate.orgIdentifier,
          accountId: defaultTo(selectedTemplate.accountId, ''),
          module,
          templateType: selectedTemplate.templateEntityType,
          templateIdentifier: selectedTemplate.identifier,
          versionLabel: selectedTemplate.versionLabel,
          repoIdentifier: selectedTemplate.gitDetails?.repoIdentifier,
          branch: selectedTemplate.gitDetails?.branch
        })
      )
    }
  }
 
  const handleTabChange = React.useCallback((tab: TemplateTabs) => {
    setSelectedTab(tab)
  }, [])
 
  const handleParentTabChange = React.useCallback(
    (tab: ParentTemplateTabs) => {
      setSelectedParentTab(tab)
    },
    [setSelectedParentTab]
  )
 
  const showNoResultsView = useMemo(
    () => !loading && !templatesError && isEmpty(selectedTemplate),
    [loading, templatesError, selectedTemplate]
  )
 
  const templateIcon = React.useMemo(() => getIconForTemplate(getString, selectedTemplate), [selectedTemplate])
 
  return (
    <Container height={'100%'} className={css.container} data-template-id={template.identifier}>
      <Layout.Vertical flex={{ align: 'center-center' }} height={'100%'}>
        {loading && <PageSpinner />}
        {!loading && templatesError && (
          <PageError
            message={defaultTo((templatesError.data as Error)?.message, templatesError.message)}
            onClick={reloadTemplates}
          />
        )}
        {showNoResultsView && (
          <NoResultsView
            text={getString('templatesLibrary.templateHasBeenDeleted')}
            minimal={true}
            customImgSrc={templateDoesNotExistSvg}
          />
        )}
        {!templatesError && selectedTemplate && (
          <Container height={'100%'} width={'100%'}>
            <Layout.Vertical height={'100%'}>
              <Layout.Horizontal
                flex={{ alignItems: 'center' }}
                spacing={'huge'}
                padding={{ top: 'large', left: 'xxlarge', bottom: 'large', right: 'xxlarge' }}
                border={{ bottom: true }}
              >
                <Layout.Horizontal className={css.shrink} spacing={'small'}>
                  <Text lineClamp={2} font={{ size: 'medium', weight: 'bold' }} color={Color.GREY_800}>
                    {selectedTemplate.name}
                  </Text>
                  {isGitSyncEnabled && (
                    <GitPopover
                      data={defaultTo(selectedTemplate.gitDetails, {})}
                      iconProps={{ margin: { left: 'small', top: 'xsmall' } }}
                    />
                  )}
                </Layout.Horizontal>
                <RbacButton
                  text={getString('templatesLibrary.openInTemplateStudio')}
                  variation={ButtonVariation.SECONDARY}
                  size={ButtonSize.SMALL}
                  className={css.openInStudio}
                  onClick={goToTemplateStudio}
                  permission={{
                    permission: PermissionIdentifier.VIEW_TEMPLATE,
                    resource: {
                      resourceType: ResourceType.TEMPLATE
                    }
                  }}
                />
              </Layout.Horizontal>
              <Container background={Color.FORM_BG} className={css.tabsContainer}>
                <Tabs id="template-details-parent" selectedTabId={selectedParentTab} onChange={handleParentTabChange}>
                  <Tab
                    id={ParentTemplateTabs.BASIC}
                    title={getString('details')}
                    panel={
                      <Layout.Vertical>
                        <Container>
                          <Layout.Vertical
                            className={css.topContainer}
                            spacing={'large'}
                            padding={{ top: 'xlarge', right: 'xxlarge', bottom: 'xlarge', left: 'xxlarge' }}
                          >
                            <Container>
                              <Layout.Vertical spacing={'small'}>
                                <Text font={{ weight: 'semi-bold' }} color={Color.BLACK}>
                                  {getString('typeLabel')}
                                </Text>
                                <Container>
                                  <Layout.Horizontal
                                    spacing={'small'}
                                    flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
                                  >
                                    {templateIcon && <Icon name={templateIcon} size={20} />}
                                    <Text color={Color.GREY_900}>
                                      {getTypeForTemplate(selectedTemplate, getString)}
                                    </Text>
                                  </Layout.Horizontal>
                                </Container>
                              </Layout.Vertical>
                            </Container>
                            <Container>
                              <Layout.Vertical spacing={'small'}>
                                <Text font={{ weight: 'semi-bold' }} color={Color.BLACK}>
                                  {getString('description')}
                                </Text>
                                <Text color={Color.GREY_900}>{defaultTo(selectedTemplate.description, '-')}</Text>
                              </Layout.Vertical>
                            </Container>
                            <Container>
                              <Layout.Vertical spacing={'small'}>
                                <Text font={{ weight: 'semi-bold' }} color={Color.BLACK}>
                                  {getString('tagsLabel')}
                                </Text>
                                {selectedTemplate.tags && !isEmpty(selectedTemplate.tags) ? (
                                  <Container>
                                    <TemplateTags tags={selectedTemplate.tags} />
                                  </Container>
                                ) : (
                                  <Text color={Color.GREY_900}>-</Text>
                                )}
                              </Layout.Vertical>
                            </Container>
                            <Container>
                              <Layout.Vertical spacing={'small'}>
                                <Text font={{ weight: 'semi-bold' }} color={Color.BLACK}>
                                  {getString('templatesLibrary.createNewModal.versionLabel')}
                                </Text>
                                <DropDown
                                  filterable={false}
                                  items={versionOptions}
                                  value={defaultTo(selectedTemplate.versionLabel, DefaultStableVersionValue)}
                                  onChange={onChange}
                                  disabled={isReadonly}
                                  width={300}
                                  popoverClassName={css.dropdown}
                                />
                              </Layout.Vertical>
                            </Container>
                          </Layout.Vertical>
                        </Container>
                        <Container className={css.innerTabsContainer}>
                          <Tabs id="template-details" selectedTabId={selectedTab} onChange={handleTabChange}>
                            <Tab
                              id={TemplateTabs.INPUTS}
                              title={getString('templatesLibrary.templateInputs')}
                              panel={<TemplateInputs template={selectedTemplate} />}
                            />
                            <Tab
                              id={TemplateTabs.YAML}
                              title={getString('yaml')}
                              panel={<TemplateYaml templateYaml={defaultTo(selectedTemplate.yaml, '')} />}
                            />
                            <Tab
                              id={TemplateTabs.REFERENCEDBY}
                              disabled={true}
                              title={getString('templatesLibrary.referencedBy')}
                            />
                          </Tabs>
                        </Container>
                      </Layout.Vertical>
                    }
                  />
                  <Tab
                    id={ParentTemplateTabs.ACTVITYLOG}
                    title={getString('activityLog')}
                    panel={<TemplateActivityLog template={selectedTemplate} />}
                  />
                </Tabs>
              </Container>
            </Layout.Vertical>
          </Container>
        )}
      </Layout.Vertical>
    </Container>
  )
}