All files / modules/70-pipeline/components/ErrorsStrip ErrorsStrip.tsx

83.1% Statements 59/71
64% Branches 64/100
73.33% Functions 11/15
82.61% Lines 57/69

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              52x 52x 52x 52x   52x 52x 52x 52x   52x 52x 52x             52x                                             52x 424x 424x   424x 424x   424x 424x 424x 424x           424x   39x 39x 39x   39x 32x   39x 7x   32x             424x 191x 191x 176x       424x 102x 102x 1x 1x 1x     102x 102x     424x 360x           360x 360x   360x 345x           424x 149x 28x 28x       424x 375x     49x         98x                         57x                                                                                          
/*
 * Copyright 2021 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 { Icon, Layout, Text, Utils, Button, ButtonVariation } from '@wings-software/uicore'
import { FontVariation, Color } from '@harness/design-system'
import { Intent, PopoverPosition } from '@blueprintjs/core'
import type { FormikErrors } from 'formik'
import cx from 'classnames'
import { defaultTo, isEmpty } from 'lodash-es'
import { getErrorsList } from '@pipeline/components/PipelineStudio/StepUtil'
import { useStrings } from 'framework/strings'
import type { StringsMap } from 'stringTypes'
import { useDeepCompareEffect } from '@common/hooks'
import { focusOnNode } from '@common/utils/utils'
import css from './ErrorsStrip.module.scss'
 
interface ErrorStripProps {
  formErrors: FormikErrors<unknown>
  domRef?: React.MutableRefObject<HTMLElement | undefined>
}
 
const onNextHandler = (
  offset: number,
  inputsList: string[],
  highlighted: number,
  setHighlighted: React.Dispatch<React.SetStateAction<number>>,
  domRef?: React.MutableRefObject<HTMLElement | undefined>
): void => {
  const nextElementName = inputsList[highlighted + offset]
  if (nextElementName) {
    let element = domRef?.current?.querySelector(`[name="${nextElementName}"]`) as HTMLInputElement | undefined
    if (element) {
      element.focus()
    } else {
      element = domRef?.current?.querySelector(`[data-name="${nextElementName}"]`)?.parentElement
        ?.previousElementSibling as HTMLInputElement | undefined
 
      // element.scrollIntoView was breaking the UI
      element && focusOnNode(element)
    }
    setHighlighted(highlighted + offset)
  }
}
 
export function ErrorsStrip(props: ErrorStripProps): React.ReactElement {
  const { errorStrings, errorCount } = getErrorsList(props.formErrors)
  const { getString } = useStrings()
 
  const [highlighted, setHighlighted] = React.useState(-1)
  const [inputsList, setInputsList] = React.useState<string[]>([])
 
  const tabList = document.getElementsByClassName('bp3-tab-list')
  const [stickyErrors, setStickyErrors] = React.useState(false)
  const [stickyWidth, setStickyWidth] = React.useState('100%')
  const errorStripRef = React.useRef<HTMLDivElement | undefined>()
  function handleIntersection(entries: IntersectionObserverEntry[]): void {
    const [entry] = entries
    setStickyErrors(!entry.isIntersecting)
  }
 
  const clickHandler = React.useCallback(
    (e: Event) => {
      Eif (e.target && !errorStripRef.current?.contains(e.target as Node)) {
        const target = e.target as HTMLDivElement
        let element = defaultTo(target.getAttribute('name'), '')
 
        if (isEmpty(element)) {
          element = defaultTo(target.closest('.bp3-form-group')?.querySelector('.bp3-label')?.getAttribute('for'), '')
        }
        if (!isEmpty(element)) {
          setHighlighted(inputsList.indexOf(element))
        } else {
          setHighlighted(-1)
        }
      }
    },
    [inputsList]
  )
 
  React.useEffect(() => {
    props.domRef?.current?.addEventListener('click', clickHandler)
    return () => {
      props.domRef?.current?.removeEventListener('click', clickHandler)
    }
  }, [props.domRef, errorStripRef, clickHandler])
 
  useDeepCompareEffect(() => {
    const totalElements: string[] = []
    props.domRef?.current?.querySelectorAll('.bp3-form-helper-text [data-name]').forEach(element => {
      const name = element.getAttribute('data-name')
      Eif (name && !isEmpty(name)) {
        totalElements.push(name)
      }
    })
    setHighlighted(-1)
    setInputsList(totalElements)
  }, [errorCount, props.domRef, props.formErrors])
 
  React.useEffect(() => {
    const options = {
      root: null,
      rootMargin: '0px',
      threshold: 0
    }
 
    const observer = new IntersectionObserver(handleIntersection, options)
    if (tabList[0]) observer.observe(tabList[0])
 
    return () => {
      if (tabList[0]) observer.unobserve(tabList[0])
    }
  }, [tabList])
 
  // Set the width of error strip width using js since it is position:fixed
  // and out of normal flow of the document
  React.useEffect(() => {
    if (errorStripRef.current?.parentElement) {
      const { width } = getComputedStyle(errorStripRef.current?.parentElement)
      width !== stickyWidth && setStickyWidth(width)
    }
  }, [props.formErrors, stickyWidth])
 
  if (!errorCount) {
    return <></>
  }
 
  return (
    <Layout.Horizontal
      className={cx(css.errorHeader, { [css.sticky]: stickyErrors })}
      flex={{ distribution: 'space-between' }}
      ref={ref => {
        errorStripRef.current = ref as HTMLDivElement
      }}
      style={{
        width: stickyErrors ? stickyWidth : ''
      }}
    >
      <Layout.Horizontal>
        <Icon name="warning-sign" intent={Intent.DANGER} margin={{ right: 'small' }} />
        <Text intent="danger">{getString('common.errorCount' as keyof StringsMap, { count: errorCount })}</Text>
        <Utils.WrapOptionalTooltip
          tooltip={
            <div className={css.runPipelineErrorDesc}>
              {errorStrings.map((errorMessage, index) => (
                <Text
                  intent="danger"
                  key={index}
                  font={{ variation: FontVariation.SMALL_BOLD }}
                  className={css.runPipelineErrorLine}
                >
                  {errorMessage}
                </Text>
              ))}
            </div>
          }
          tooltipProps={{
            position: PopoverPosition.BOTTOM,
            inheritDarkTheme: true,
            popoverClassName: css.runPipelineErrorPopover
          }}
        >
          <Text font={{ variation: FontVariation.TINY_SEMI }} color={Color.GREY_600} margin={{ left: 'small' }}>
            {getString('common.seeDetails')}
          </Text>
        </Utils.WrapOptionalTooltip>
      </Layout.Horizontal>
      {inputsList.length > 0 ? (
        <Layout.Horizontal>
          <Button
            intent="danger"
            disabled={highlighted === inputsList.length - 1}
            onClick={() => onNextHandler(1, inputsList, highlighted, setHighlighted, props.domRef)}
            variation={ButtonVariation.ICON}
            iconProps={{ size: 10 }}
            icon="main-chevron-down"
          />
          <Button
            intent="danger"
            disabled={highlighted <= 0}
            onClick={() => onNextHandler(-1, inputsList, highlighted, setHighlighted, props.domRef)}
            iconProps={{ size: 10 }}
            variation={ButtonVariation.ICON}
            icon="main-chevron-up"
          />
        </Layout.Horizontal>
      ) : null}
    </Layout.Horizontal>
  )
}