All files / modules/10-common/components/EntityReference EntityReference.tsx

92.56% Statements 112/121
74.73% Branches 68/91
81.48% Functions 22/27
93.22% Lines 110/118

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 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402              726x 726x 726x                               726x 726x 726x 726x 726x 726x   726x   726x 726x 726x 726x               726x 731x 159x 572x 73x   499x     726x                     726x 2226x 245x 1981x 273x   1708x   726x 470x 470x   60x 60x   262x 262x   78x 78x     470x     726x 851x 851x 183x   668x                                                                             145x 44x 101x     101x     726x 726x 726x 726x       126x     726x 127x                           126x 126x 126x     126x         126x 126x 126x 126x 126x 126x   126x 19x     126x   126x 126x   126x 19x 19x 19x 18x 18x     16x 16x           1x     1x 1x 1x 1x 1x     1x 1x               2x       126x 19x 18x   1x 1x       126x 19x 19x           126x 1x 1x     126x       126x   126x 208x                                                                                 126x               378x           1x                                                   126x 126x 19x           126x                                           10x 10x                                                       726x  
/*
 * 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, useEffect, useRef } from 'react'
import cx from 'classnames'
import {
  Container,
  TextInput,
  Button,
  Layout,
  Text,
  Tabs,
  Tab,
  Icon,
  IconName,
  ButtonVariation,
  PageError,
  NoDataCard,
  NoDataCardProps,
  PaginationProps
} from '@harness/uicore'
import { FontVariation, Color } from '@harness/design-system'
import { Classes } from '@blueprintjs/core'
import { debounce, isEmpty } from 'lodash-es'
import { useParams } from 'react-router-dom'
import { Scope } from '@common/interfaces/SecretsInterface'
import { useStrings, UseStringsReturn } from 'framework/strings'
import type { StringKeys } from 'framework/strings'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import type { AccountPathProps, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { Category, StageActions } from '@common/constants/TrackingConstants'
import { CollapsableList } from '../CollapsableList/CollapsableList'
import css from './EntityReference.module.scss'
 
export interface ScopedObjectDTO {
  accountIdentifier?: string
  orgIdentifier?: string
  projectIdentifier?: string
}
 
export function getScopeFromDTO<T extends ScopedObjectDTO>(obj: T): Scope {
  if (obj.projectIdentifier) {
    return Scope.PROJECT
  } else if (obj.orgIdentifier) {
    return Scope.ORG
  }
  return Scope.ACCOUNT
}
 
export const getScopeBasedProjectPathParams = (
  { accountId, projectIdentifier, orgIdentifier }: ProjectPathProps,
  scope: Scope
) => {
  return {
    accountIdentifier: accountId,
    projectIdentifier: scope === Scope.PROJECT ? projectIdentifier : undefined,
    orgIdentifier: scope === Scope.PROJECT || scope === Scope.ORG ? orgIdentifier : undefined
  }
}
 
export function getScopeFromValue(value: string): Scope {
  if (typeof value === 'string' && value.startsWith(`${Scope.ACCOUNT}.`)) {
    return Scope.ACCOUNT
  } else if (typeof value === 'string' && value.startsWith(`${Scope.ORG}.`)) {
    return Scope.ORG
  }
  return Scope.PROJECT
}
export function getScopeLabelfromScope(scope: Scope, getString: UseStringsReturn['getString']): string {
  let label = ''
  switch (scope) {
    case Scope.ACCOUNT:
      label += getString('account')
      break
    case Scope.PROJECT:
      label += getString('projectLabel')
      break
    case Scope.ORG:
      label += getString('orgLabel')
      break
    default:
  }
  return label
}
 
export function getIdentifierFromValue(value: string): string {
  const scope = getScopeFromValue(value)
  if ((typeof value === 'string' && scope === Scope.ACCOUNT) || scope === Scope.ORG) {
    return value.replace(`${scope}.`, '')
  }
  return value
}
 
export type EntityReferenceResponse<T> = {
  name: string
  identifier: string
  record: T
}
 
export interface EntityReferenceProps<T> {
  onSelect: (reference: T, scope: Scope) => void
  fetchRecords: (
    scope: Scope,
    done: (records: EntityReferenceResponse<T>[]) => void,
    searchTerm: string,
    page: number
  ) => void
  recordRender: (args: { item: EntityReferenceResponse<T>; selectedScope: Scope; selected?: boolean }) => JSX.Element
  collapsedRecordRender?: (args: {
    item: EntityReferenceResponse<T>
    selectedScope: Scope
    selected?: boolean
  }) => JSX.Element
  recordClassName?: string
  className?: string
  projectIdentifier?: string
  noRecordsText?: string
  noDataCard?: NoDataCardProps
  orgIdentifier?: string
  defaultScope?: Scope
  searchInlineComponent?: JSX.Element
  onCancel?: () => void
  renderTabSubHeading?: boolean
  pagination: PaginationProps
  disableCollapse?: boolean
  input?: any
}
 
function getDefaultScope(orgIdentifier?: string, projectIdentifier?: string): Scope {
  if (!isEmpty(projectIdentifier)) {
    return Scope.PROJECT
  } else Iif (!isEmpty(orgIdentifier)) {
    return Scope.ORG
  }
  return Scope.ACCOUNT
}
 
const enum TAB_ID {
  PROJECT = 'project',
  ORGANIZATION = 'organization',
  ACCOUNT = 'account'
}
 
function getDefaultTab(projectIdentifier: string | undefined, orgIdentifier: string | undefined) {
  return projectIdentifier ? TAB_ID.PROJECT : orgIdentifier ? TAB_ID.ORGANIZATION : TAB_ID.ACCOUNT
}
 
export function EntityReference<T>(props: EntityReferenceProps<T>): JSX.Element {
  const { getString } = useStrings()
  const {
    defaultScope,
    projectIdentifier,
    orgIdentifier,
    fetchRecords,
    className = '',
    recordRender,
    collapsedRecordRender,
    searchInlineComponent,
    noDataCard,
    renderTabSubHeading = false,
    disableCollapse,
    input
  } = props
  const [searchTerm, setSearchTerm] = useState<string>('')
  const [selectedScope, setSelectedScope] = useState<Scope>(
    defaultScope || getDefaultScope(orgIdentifier, projectIdentifier)
  )
  const { accountId } = useParams<AccountPathProps>()
  const {
    selectedProject,
    selectedOrg,
    currentUserInfo: { accounts = [] }
  } = useAppStore()
  const selectedAccount = accounts.find(account => account.uuid === accountId)
  const [data, setData] = useState<EntityReferenceResponse<T>[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<string | null>()
  const [selectedRecord, setSelectedRecord] = useState<T>()
 
  React.useEffect(() => {
    setSelectedScope(getDefaultScope(orgIdentifier, projectIdentifier))
  }, [projectIdentifier, orgIdentifier])
 
  const delayedFetchRecords = useRef(debounce((fn: () => void) => fn(), 300)).current
 
  const inputRef = useRef()
  const firstUpdate = useRef(true)
 
  const fetchData = (resetPageIndex: boolean, inputChange = false) => {
    try {
      setError(null)
      if (!searchTerm && !inputChange) {
        setLoading(true)
        fetchRecords(
          selectedScope,
          records => {
            setData(records)
            setLoading(false)
          },
          searchTerm,
          props.pagination.pageIndex as number
        )
      } else {
        Iif (resetPageIndex && props.pagination.pageIndex !== 0) {
          props.pagination.gotoPage?.(0)
        }
        const pageNo = resetPageIndex ? 0 : props.pagination.pageIndex
        delayedFetchRecords(() => {
          setLoading(true)
          setSelectedRecord(undefined)
          fetchRecords(
            selectedScope,
            records => {
              setData(records)
              setLoading(false)
            },
            searchTerm,
            pageNo as number
          )
        })
      }
    } catch (msg) {
      setError(msg)
    }
  }
 
  useEffect(() => {
    if (inputRef.current === input) {
      fetchData(true)
    } else {
      fetchData(true, true)
      inputRef.current = input
    }
  }, [selectedScope, delayedFetchRecords, searchTerm, input])
 
  useEffect(() => {
    Eif (firstUpdate.current) {
      firstUpdate.current = false
    } else {
      fetchData(false)
    }
  }, [props.pagination.pageIndex])
 
  const onScopeChange = (scope: Scope): void => {
    setSelectedRecord(undefined)
    setSelectedScope(scope)
  }
 
  const iconProps = {
    size: 14
  }
 
  const defaultTab = getDefaultTab(projectIdentifier, orgIdentifier)
 
  const RenderList = () => {
    return (
      <Layout.Vertical spacing="large">
        <div className={css.searchBox}>
          <TextInput
            wrapperClassName={css.search}
            placeholder={getString('search')}
            leftIcon="search"
            value={searchTerm}
            autoFocus
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchTerm(e.target.value)}
          />
          {searchInlineComponent}
        </div>
        {loading ? (
          <Container flex={{ align: 'center-center' }} padding="small">
            <Icon name="spinner" size={24} color={Color.PRIMARY_7} />
          </Container>
        ) : error ? (
          <Container>
            <PageError message={error} onClick={() => fetchData(true)} />
          </Container>
        ) : data.length ? (
          <CollapsableList<T>
            selectedRecord={selectedRecord}
            setSelectedRecord={setSelectedRecord}
            data={data}
            recordRender={recordRender}
            collapsedRecordRender={collapsedRecordRender}
            selectedScope={selectedScope}
            pagination={props.pagination}
            disableCollapse={disableCollapse}
          />
        ) : (
          <Container padding={{ top: 'xlarge' }} flex={{ align: 'center-center' }} className={css.noDataContainer}>
            <NoDataCard {...noDataCard} containerClassName={css.noDataCardImg} />
          </Container>
        )}
      </Layout.Vertical>
    )
  }
 
  const renderTab = (
    show: boolean,
    id: string,
    scope: Scope,
    icon: IconName,
    title: StringKeys,
    tabDesc = ''
  ): React.ReactElement | null => {
    return show ? (
      <Tab
        className={css.tabClass}
        id={id}
        title={
          <Layout.Horizontal
            onClick={() => onScopeChange(scope)}
            flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
            padding={{ left: 'xsmall', right: 'xsmall' }}
          >
            <Icon name={icon} {...iconProps} className={css.tabIcon} />
 
            <Text lineClamp={1} font={{ variation: FontVariation.H6, weight: 'light' }}>
              {getString(title)}
            </Text>
            {renderTabSubHeading && tabDesc && (
              <Text
                lineClamp={1}
                font={{ variation: FontVariation.FORM_LABEL, weight: 'light' }}
                padding={{ left: 'xsmall' }}
                className={css.tabValue}
              >
                {`[${tabDesc}]`}
              </Text>
            )}
          </Layout.Horizontal>
        }
        panel={RenderList()}
      />
    ) : null
  }
 
  const { trackEvent } = useTelemetry()
  useEffect(() => {
    trackEvent(StageActions.LoadCreateOrSelectConnectorView, {
      category: Category.STAGE
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  return (
    <Container className={cx(css.container, className)}>
      <div className={css.tabsContainer}>
        <Tabs id={'selectScope'} defaultSelectedTabId={defaultTab}>
          {renderTab(
            !!projectIdentifier,
            TAB_ID.PROJECT,
            Scope.PROJECT,
            'projects-wizard',
            'projectLabel',
            selectedProject?.name
          )}
          {renderTab(!!orgIdentifier, TAB_ID.ORGANIZATION, Scope.ORG, 'diagram-tree', 'orgLabel', selectedOrg?.name)}
          {renderTab(true, TAB_ID.ACCOUNT, Scope.ACCOUNT, 'layers', 'account', selectedAccount?.accountName)}
        </Tabs>
      </div>
 
      <Layout.Horizontal spacing="medium" padding={{ top: 'medium' }}>
        <Button
          variation={ButtonVariation.PRIMARY}
          text={getString('entityReference.apply')}
          onClick={() => {
            props.onSelect(selectedRecord as T, selectedScope)
            trackEvent(StageActions.ApplySelectedConnector, {
              category: Category.STAGE,
              selectedRecord,
              selectedScope
            })
          }}
          disabled={!selectedRecord}
          className={cx(Classes.POPOVER_DISMISS)}
        />
        {props.onCancel && (
          <Button
            variation={ButtonVariation.TERTIARY}
            text={getString('cancel')}
            onClick={() => {
              props.onCancel?.()
              trackEvent(StageActions.CancelSelectConnector, {
                category: Category.STAGE,
                selectedRecord,
                selectedScope
              })
            }}
          />
        )}
      </Layout.Horizontal>
    </Container>
  )
}
 
export default EntityReference