All files / modules/72-templates-library/pages/TemplatesPage TemplatesPage.tsx

83.13% Statements 69/83
65.08% Branches 41/63
50% Functions 8/16
83.13% Lines 69/83

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              1x 1x                   1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 15x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 98x     14x             14x                                             14x 5x 5x     14x 5x     14x           14x   1x                 1x             14x   1x                           14x                               14x                                                                                                                                                                       1x 1x     1x 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, { useState } from 'react'
import {
  Container,
  DropDown,
  ExpandingSearchInput,
  ExpandingSearchInputHandle,
  GridListToggle,
  HarnessDocTooltip,
  Layout,
  Views
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { useHistory, useParams } from 'react-router-dom'
import { Dialog } from '@blueprintjs/core'
import { TemplateSettingsModal } from '@templates-library/components/TemplateSettingsModal/TemplateSettingsModal'
import { Page } from '@common/exports'
import { useStrings } from 'framework/strings'
import { Sort, SortFields, TemplateListType } from '@templates-library/pages/TemplatesPage/TemplatesPageUtils'
import { TemplateDetailsDrawer } from '@templates-library/components/TemplateDetailDrawer/TemplateDetailDrawer'
import {
  Failure,
  Error,
  PageTemplateSummaryResponse,
  TemplateSummaryResponse,
  useGetTemplateList
} from 'services/template-ng'
import type { ModulePathParams, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import { NewTemplatePopover } from '@templates-library/pages/TemplatesPage/views/NewTemplatePopover/NewTemplatePopover'
import { DeleteTemplateModal } from '@templates-library/components/DeleteTemplateModal/DeleteTemplateModal'
import routes from '@common/RouteDefinitions'
import { useMutateAsGet } from '@common/hooks'
import NoResultsView from '@templates-library/pages/TemplatesPage/views/NoResultsView/NoResultsView'
import TemplatesView from '@templates-library/pages/TemplatesPage/views/TemplatesView'
import ResultsViewHeader from '@templates-library/pages/TemplatesPage/views/ResultsViewHeader/ResultsViewHeader'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import GitFilters, { GitFilterScope } from '@common/components/GitFilters/GitFilters'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import { getAllowedTemplateTypes, TemplateType } from '@templates-library/utils/templatesUtils'
import { getLinkForAccountResources } from '@common/utils/BreadcrumbUtils'
import { useDocumentTitle } from '@common/hooks/useDocumentTitle'
import { useFeatureFlag } from '@common/hooks/useFeatureFlag'
import { FeatureFlag } from '@common/featureFlags'
import css from './TemplatesPage.module.scss'
 
export default function TemplatesPage(): React.ReactElement {
  const { getString } = useStrings()
  const history = useHistory()
  const [page, setPage] = useState(0)
  const [view, setView] = useState<Views>(Views.GRID)
  const [sort, setSort] = useState<string[]>([SortFields.LastUpdatedAt, Sort.DESC])
  const [type, setType] = useState<keyof typeof TemplateType | null>(null)
  const [searchParam, setSearchParam] = useState('')
  const [templateToDelete, setTemplateToDelete] = React.useState<TemplateSummaryResponse>({})
  const [templateList, setTemplateListList] = useState<PageTemplateSummaryResponse>()
  const [localError, setLocalError] = useState<Error | Failure | null>(null)
  const [templateIdentifierToSettings, setTemplateIdentifierToSettings] = React.useState<string>()
  const [selectedTemplate, setSelectedTemplate] = React.useState<TemplateSummaryResponse | undefined>()
  const [gitFilter, setGitFilter] = useState<GitFilterScope | null>(null)
  const searchRef = React.useRef<ExpandingSearchInputHandle>({} as ExpandingSearchInputHandle)
  const { projectIdentifier, orgIdentifier, accountId, module } = useParams<ProjectPathProps & ModulePathParams>()
  const { isGitSyncEnabled } = useAppStore()
  const scope = getScopeFromDTO({ projectIdentifier, orgIdentifier, accountIdentifier: accountId })
  const pipelineTemplatesFeatureFlagEnabled = useFeatureFlag(FeatureFlag.NG_PIPELINE_TEMPLATE)
  const allowedTemplateTypes = getAllowedTemplateTypes(getString, module, pipelineTemplatesFeatureFlagEnabled).filter(
    item => !item.disabled
  )
 
  useDocumentTitle([getString('common.templates')])
 
  const {
    data: templateData,
    refetch: reloadTemplates,
    loading,
    error
  } = useMutateAsGet(useGetTemplateList, {
    body: {
      filterType: 'Template',
      ...(type && { templateEntityTypes: [type] })
    },
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      templateListType: TemplateListType.LastUpdated,
      searchTerm: searchParam,
      page,
      sort,
      size: 20,
      ...(gitFilter?.repo &&
        gitFilter.branch && {
          repoIdentifier: gitFilter.repo,
          branch: gitFilter.branch
        })
    },
    queryParamStringifyOptions: { arrayFormat: 'comma' }
  })
 
  React.useEffect(() => {
    setTemplateListList(templateData?.data)
    setLocalError(null)
  }, [templateData])
 
  React.useEffect(() => {
    setLocalError(error as Error)
  }, [error])
 
  const reset = React.useCallback((): void => {
    searchRef.current.clear()
    setType(null)
    setGitFilter(null)
  }, [searchRef.current, setType, setGitFilter])
 
  const [showDeleteTemplatesModal, hideDeleteTemplatesModal] = useModalHook(() => {
    const content = (
      <DeleteTemplateModal
        template={templateToDelete}
        onClose={hideDeleteTemplatesModal}
        onSuccess={() => {
          hideDeleteTemplatesModal()
          reloadTemplates()
        }}
      />
    )
    return (
      <Dialog enforceFocus={false} isOpen={true} className={css.deleteTemplateDialog}>
        {isGitSyncEnabled ? <GitSyncStoreProvider>{content}</GitSyncStoreProvider> : content}
      </Dialog>
    )
  }, [templateToDelete, reloadTemplates, isGitSyncEnabled])
 
  const [showTemplateSettingsModal, hideTemplateSettingsModal] = useModalHook(
    () => (
      <Dialog enforceFocus={false} isOpen={true} className={css.updateTemplateSettingsDialog}>
        <TemplateSettingsModal
          templateIdentifier={templateIdentifierToSettings || ''}
          onClose={hideTemplateSettingsModal}
          onSuccess={() => {
            hideTemplateSettingsModal()
            reloadTemplates()
          }}
        />
      </Dialog>
    ),
    [templateIdentifierToSettings, reloadTemplates]
  )
 
  const goToTemplateStudio = (template: TemplateSummaryResponse): void => {
    history.push(
      routes.toTemplateStudio({
        projectIdentifier,
        orgIdentifier,
        accountId,
        module,
        templateType: template.templateEntityType,
        templateIdentifier: template.identifier || '',
        versionLabel: template.versionLabel,
        repoIdentifier: template.gitDetails?.repoIdentifier,
        branch: template.gitDetails?.branch
      })
    )
  }
 
  return (
    <>
      <Page.Header
        title={
          <div className="ng-tooltip-native">
            <h2 data-tooltip-id="templatesPageHeading"> {getString('common.templates')}</h2>
            <HarnessDocTooltip tooltipId="templatePageHeading" useStandAlone={true} />
          </div>
        }
        breadcrumbs={
          <NGBreadcrumbs
            links={getLinkForAccountResources({ accountId, orgIdentifier, projectIdentifier, getString })}
          />
        }
      />
      <Page.SubHeader>
        <Layout.Horizontal spacing={'medium'}>
          <NewTemplatePopover />
          <DropDown
            onChange={item => {
              setType(item.value as TemplateType)
            }}
            value={type}
            filterable={false}
            addClearBtn={true}
            items={allowedTemplateTypes}
            placeholder={getString('all')}
            popoverClassName={css.dropdownPopover}
          />
          {isGitSyncEnabled && (
            <GitSyncStoreProvider>
              <GitFilters
                onChange={filter => {
                  setGitFilter(filter)
                  setPage(0)
                }}
                className={css.gitFilter}
                defaultValue={gitFilter || undefined}
              />
            </GitSyncStoreProvider>
          )}
        </Layout.Horizontal>
        <Layout.Horizontal spacing="small" style={{ alignItems: 'center' }}>
          <ExpandingSearchInput
            alwaysExpanded
            width={200}
            placeholder={getString('search')}
            onChange={(text: string) => {
              setPage(0)
              setSearchParam(text)
            }}
            ref={searchRef}
            defaultValue={searchParam}
            className={css.expandSearch}
          />
          <GridListToggle initialSelectedView={view} onViewToggle={setView} />
        </Layout.Horizontal>
      </Page.SubHeader>
      <Page.Body
        loading={loading}
        error={localError?.message}
        className={css.pageBody}
        retryOnError={/* istanbul ignore next */ () => reloadTemplates()}
      >
        <Container height={'100%'} style={{ overflow: 'auto' }}>
          {!templateList?.content?.length && (
            <NoResultsView
              hasSearchParam={!!searchParam || !!type}
              onReset={reset}
              text={getString('templatesLibrary.templatesPage.noTemplates', { scope })}
            />
          )}
          {!!templateList?.content?.length && (
            <Layout.Vertical height={'100%'} margin={{ left: 'xlarge', right: 'xlarge' }}>
              <ResultsViewHeader templateData={templateList} setPage={setPage} setSort={setSort} />
              <Container style={{ flexGrow: 1 }} padding={{ bottom: 'large' }}>
                <TemplatesView
                  gotoPage={setPage}
                  data={templateList}
                  onSelect={setSelectedTemplate}
                  selectedIdentifier={selectedTemplate?.identifier}
                  onPreview={setSelectedTemplate}
                  onOpenEdit={goToTemplateStudio}
                  onOpenSettings={identifier => {
                    setTemplateIdentifierToSettings(identifier)
                    showTemplateSettingsModal()
                  }}
                  onDelete={template => {
                    setTemplateToDelete(template)
                    showDeleteTemplatesModal()
                  }}
                  view={view}
                />
              </Container>
            </Layout.Vertical>
          )}
        </Container>
      </Page.Body>
      {selectedTemplate && (
        <TemplateDetailsDrawer
          template={selectedTemplate}
          onClose={() => {
            setSelectedTemplate(undefined)
          }}
        />
      )}
    </>
  )
}