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

82.46% Statements 47/57
67.44% Branches 29/43
77.78% Functions 7/9
83.64% Lines 46/55

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              503x 503x 503x 503x 503x 503x 503x 503x 503x     503x   503x         1x 1x           1x                       503x 75x                 75x   75x 75x   75x         75x       75x   75x 59x 15x         75x 59x 18x     41x 41x   41x 36x 36x         75x                                         43x 43x 43x 43x             1x 1x 1x 1x         1x   1x                                     1x                   503x  
/*
 * 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, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import cx from 'classnames'
import { noop } from 'lodash-es'
import { SimpleTagInput, Text, Icon } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useToaster } from '@common/exports'
import { useStrings } from 'framework/strings'
import { useGetDelegateSelectorsUpTheHierarchy } from 'services/portal'
 
import type { AccountPathProps, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import css from './DelegateSelectors.module.scss'
 
const isValidExpression = (
  tag: string,
  showError: (message: React.ReactNode, timeout?: number, key?: string) => void,
  errorMsg: string
): boolean => {
  let validExpression = true
  Iif (tag.includes('${')) {
    validExpression = tag.includes('${') && tag.includes('}')
    if (!validExpression) {
      showError(errorMsg, 5000)
    }
  }
  return validExpression
}
 
export interface DelegateSelectorsProps
  extends Partial<React.ComponentProps<typeof SimpleTagInput>>,
    Partial<ProjectPathProps> {
  placeholder?: string
  pollingInterval?: number
  wrapperClassName?: string
  onTagInputChange?: (tags: string[]) => void
}
 
export const DelegateSelectors = (props: DelegateSelectorsProps): React.ReactElement | null => {
  const { accountId } = useParams<AccountPathProps>()
  const {
    orgIdentifier,
    projectIdentifier,
    pollingInterval = null,
    onTagInputChange = noop,
    wrapperClassName,
    placeholder,
    ...rest
  } = props
 
  const { getString } = useStrings()
  const { showError } = useToaster()
 
  const queryParams = { accountId, orgId: orgIdentifier, projectId: projectIdentifier }
  const {
    data: apiData,
    loading,
    refetch
  } = useGetDelegateSelectorsUpTheHierarchy({
    queryParams
  })
 
  const [data, setData] = useState(apiData)
 
  useEffect(() => {
    if (apiData) {
      setData(apiData)
    }
  }, [apiData])
 
  // polling logic
  useEffect(() => {
    if (pollingInterval === null) {
      return
    }
    let id: number | null
    Eif (!loading) {
      id = window.setTimeout(() => refetch(), pollingInterval)
    }
    return () => {
      Eif (id) {
        window.clearTimeout(id)
      }
    }
  }, [data, loading, refetch, pollingInterval])
 
  return (
    <div className={cx(css.wrapper, wrapperClassName)} data-name="DelegateSelectors">
      {loading && !data ? (
        <div className={css.loader}>
          <Icon margin="medium" name="spinner" size={15} color={Color.PRIMARY_8} />
          <span>{getString('loading')}</span>
        </div>
      ) : (
        <SimpleTagInput
          fill
          popoverProps={{
            usePortal: false,
            minimal: true,
            position: 'bottom-left',
            className: css.delegatePopover
          }}
          items={data?.resource || []}
          onChange={onTagInputChange}
          {...rest}
          allowNewTag
          getTagProps={(value, _index, _selectedItems, createdItems, items) => {
            const _value = value as string
            const isItemNewlyCreated = createdItems.includes(_value) || !items.includes(_value)
            const isExpression = isItemNewlyCreated && _value.startsWith('${') && _value.endsWith('}')
            return isExpression
              ? { intent: 'none', minimal: true }
              : isItemNewlyCreated
              ? { intent: 'danger', minimal: true }
              : { intent: 'primary', minimal: true }
          }}
          validateNewTag={(tag: string) => {
            const pattern = new RegExp('^[a-z0-9-${}]+$', 'i')
            const validTag = new RegExp('^[a-z0-9-${}._<>+]+$', 'i').test(tag)
            const tagChars = tag.split('')
            const validExpression = isValidExpression(
              tag,
              showError,
              getString('delegate.DelegateSelectorErrorMessage')
            )
            const invalidChars = new Set()
 
            Iif (!validTag) {
              const errorMsg = (
                <Text>
                  {getString('delegate.DelegateSelector')}
                  <>
                    {tagChars.map((item: string) => {
                      if (!pattern.test(item)) {
                        invalidChars.add(item)
                        return <strong style={{ color: 'red' }}>{item}</strong>
                      } else {
                        return item
                      }
                    })}
                  </>
                  {getString('delegate.DelegateSelectorErrMsgSplChars')}: {Array.from(invalidChars).join(',')}
                </Text>
              )
              showError(errorMsg, 5000)
            }
            return validTag && validExpression
          }}
          placeholder={placeholder || getString('delegate.Delegate_Selector_placeholder')}
          className={css.delegateInput}
        />
      )}
    </div>
  )
}
 
export default DelegateSelectors