All files / modules/70-pipeline/components/PipelineStudio/TemplateBar TemplateBar.tsx

98% Statements 49/50
60.98% Branches 25/41
90% Functions 9/10
98% Lines 49/50

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              28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x   28x 28x 28x 28x   28x 28x                               28x 8x 8x 8x 8x 8x 8x 8x           8x                         8x   8x               1x 1x         8x 1x 1x                       1x       8x                                           8x 8x                                                     8x                             2x                       1x 1x     1x   32x         3x 3x 3x 3x                              
/*
 * 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 { defaultTo } from 'lodash-es'
import { useParams } from 'react-router-dom'
import { Container, Icon, IconName, Layout, Popover, Text, useConfirmationDialog } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useModalHook } from '@harness/use-modal'
import { Classes, Dialog, Intent, Menu, Position } from '@blueprintjs/core'
import cx from 'classnames'
import { useStrings } from 'framework/strings'
import { getTemplateNameWithLabel } from '@pipeline/utils/templateUtils'
import { useFeature } from '@common/hooks/useFeatures'
import { FeatureIdentifier } from 'framework/featureStore/FeatureIdentifier'
import routes from '@common/RouteDefinitions'
import type { PipelineType, ProjectPathProps, GitQueryParams } from '@common/interfaces/RouteInterfaces'
import { useGetTemplate } from 'services/template-ng'
import { getIdentifierFromValue, getScopeFromValue } from '@common/components/EntityReference/EntityReference'
import { TemplateYaml } from '@pipeline/components/PipelineStudio/TemplateYaml/TemplateYaml'
import { Scope } from '@common/interfaces/SecretsInterface'
import type { TemplateLinkConfig } from 'services/pipeline-ng'
import { useQueryParams } from '@common/hooks'
import css from './TemplateBar.module.scss'
 
interface TemplateMenuItem {
  icon?: IconName
  label: string
  disabled?: boolean
  onClick: () => void
}
 
export interface TemplateBarProps {
  templateLinkConfig: TemplateLinkConfig
  onOpenTemplateSelector: () => void
  onRemoveTemplate: () => Promise<void>
  className?: string
}
 
export function TemplateBar(props: TemplateBarProps): JSX.Element {
  const { templateLinkConfig, onOpenTemplateSelector, onRemoveTemplate, className = '' } = props
  const [menuOpen, setMenuOpen] = React.useState(false)
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier, module } = useParams<PipelineType<ProjectPathProps>>()
  const { branch, repoIdentifier } = useQueryParams<GitQueryParams>()
  const scope = getScopeFromValue(templateLinkConfig.templateRef)
  const { enabled: templatesEnabled } = useFeature({
    featureRequest: {
      featureName: FeatureIdentifier.TEMPLATE_SERVICE
    }
  })
 
  const { data } = useGetTemplate({
    templateIdentifier: getIdentifierFromValue(templateLinkConfig.templateRef),
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier: scope === Scope.PROJECT ? projectIdentifier : undefined,
      orgIdentifier: scope === Scope.PROJECT || scope === Scope.ORG ? orgIdentifier : undefined,
      versionLabel: defaultTo(templateLinkConfig.versionLabel, ''),
      repoIdentifier,
      branch,
      getDefaultFromOtherRepo: true
    }
  })
 
  const selectedTemplate = data?.data
 
  const { openDialog: openRemoveTemplateDialog } = useConfirmationDialog({
    intent: Intent.DANGER,
    buttonIntent: Intent.DANGER,
    cancelButtonText: getString('cancel'),
    contentText: getString('pipeline.removeTemplate'),
    titleText: `${getString('common.remove')} ${getTemplateNameWithLabel(selectedTemplate)}?`,
    confirmButtonText: getString('common.remove'),
    onCloseDialog: async isConfirmed => {
      Eif (isConfirmed) {
        await onRemoveTemplate()
      }
    }
  })
 
  const openTemplateInNewTab = () => {
    Eif (selectedTemplate) {
      const templateStudioPath = 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
      })
 
      window.open(`${window.location.origin}${window.location.pathname}#${templateStudioPath}`, '_blank')
    }
  }
 
  const [showTemplateYAMLPreviewModal, hideTemplateYAMLPreviewModal] = useModalHook(
    () => (
      <Dialog
        isOpen
        enforceFocus={false}
        canEscapeKeyClose
        canOutsideClickClose
        onClose={hideTemplateYAMLPreviewModal}
        title={'template.yaml'}
        isCloseButtonShown
        className={cx(Classes.DIALOG, css.templateYamlPreviewDialog)}
        usePortal
        backdropClassName={css.templateYamlPreviewDialogBackdrop}
      >
        <Container className={css.templateYamlPreviewContainer}>
          <TemplateYaml templateYaml={defaultTo(selectedTemplate?.yaml, '')} withoutHeader />
        </Container>
      </Dialog>
    ),
    [selectedTemplate?.yaml]
  )
 
  const getItems = (): TemplateMenuItem[] => {
    return [
      {
        icon: 'command-switch',
        label: getString('pipeline.changeTemplateLabel'),
        disabled: !templatesEnabled,
        onClick: onOpenTemplateSelector
      },
      {
        icon: 'main-trash',
        label: getString('pipeline.removeTemplateLabel'),
        onClick: openRemoveTemplateDialog
      },
      {
        icon: 'main-share',
        label: getString('pipeline.openTemplateInNewTabLabel'),
        disabled: !selectedTemplate,
        onClick: openTemplateInNewTab
      },
      {
        icon: 'main-view',
        label: getString('pipeline.previewTemplateLabel'),
        disabled: !selectedTemplate,
        onClick: showTemplateYAMLPreviewModal
      }
    ]
  }
 
  return (
    <Container
      padding={{ top: 'small', right: 'medium', bottom: 'small', left: 'medium' }}
      background={Color.PRIMARY_6}
      border={{ radius: 4 }}
      className={cx(css.container, className)}
    >
      <Layout.Horizontal spacing={'small'} flex={{ alignItems: 'center', justifyContent: 'flex-start' }}>
        <Icon size={11} color={Color.WHITE} name={'template-library'} />
        <Text style={{ flexGrow: 1 }} font={{ size: 'small' }} color={Color.WHITE}>
          {selectedTemplate ? `Using Template: ${getTemplateNameWithLabel(selectedTemplate)}` : getString('loading')}
        </Text>
        <Popover
          isOpen={menuOpen}
          onInteraction={nextOpenState => {
            setMenuOpen(nextOpenState)
          }}
          position={Position.BOTTOM_RIGHT}
          className={css.main}
          disabled={!selectedTemplate}
          portalClassName={css.popover}
        >
          <Icon
            name={'more'}
            color={Color.WHITE}
            className={css.actionButton}
            onClick={e => {
              e.stopPropagation()
              setMenuOpen(true)
            }}
          />
          <Menu style={{ minWidth: 'unset' }} onClick={e => e.stopPropagation()}>
            {getItems()?.map(item => {
              return (
                <li
                  key={item.label}
                  className={cx(css.menuItem, { [css.disabled]: item.disabled })}
                  onClick={e => {
                    e.stopPropagation()
                    Eif (!item.disabled) {
                      item.onClick()
                      setMenuOpen(false)
                    }
                  }}
                >
                  {item.icon && <Icon name={item.icon} size={12} />}
                  <Text lineClamp={1}>{item.label}</Text>
                </li>
              )
            })}
          </Menu>
        </Popover>
      </Layout.Horizontal>
    </Container>
  )
}