All files / modules/10-common/components/Wizard WizardFooter.tsx

58.18% Statements 32/55
49.38% Branches 40/81
71.43% Functions 5/7
58.49% Lines 31/53

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              5x 5x 5x   5x 5x 5x   5x 5x                                                     5x                                               243x 243x   243x                 2x 2x 2x 2x 2x                   1x 1x             1x 1x 1x 1x                       9x   9x     23x     2x 2x   9x 8x   3x                                                                                                                                  
/*
 * 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, { RefObject, Dispatch, SetStateAction } from 'react'
import { Layout, Button, ButtonVariation } from '@wings-software/uicore'
import cx from 'classnames'
import type { FormikErrors, FormikProps } from 'formik'
import { parse } from 'yaml'
import { isEmpty } from 'lodash-es'
import { useStrings } from 'framework/strings'
import type { YamlBuilderHandlerBinding, YamlBuilderProps } from '@common/interfaces/YAMLBuilderProps'
import { setNewTouchedPanel } from './WizardUtils'
import css from './Wizard.module.scss'
 
interface WizardFooterProps {
  isYamlView: boolean
  selectedTabIndex: number
  onHide: () => void
  submitLabel?: string
  disableSubmit?: boolean
  setValidateOnChange: Dispatch<SetStateAction<boolean>>
  lastTab: boolean
  onYamlSubmit?: (val: any) => void
  yamlObjectKey?: string
  yamlHandler?: YamlBuilderHandlerBinding
  elementsRef: { current: RefObject<HTMLSpanElement>[] }
  showError: (str: string) => void
  yamlBuilderReadOnlyModeProps?: YamlBuilderProps
  formikProps: FormikProps<any>
  setSelectedTabId: Dispatch<SetStateAction<string>>
  setSelectedTabIndex: Dispatch<SetStateAction<number>>
  setTouchedPanels: Dispatch<SetStateAction<number[]>>
  touchedPanels: number[]
  tabsMap: string[]
  loadingYamlView?: boolean
  validate?: (arg?: { latestYaml?: string }) => Promise<FormikErrors<any>> | FormikErrors<any>
  setSubmittedForm: Dispatch<SetStateAction<boolean>>
}
 
export const WizardFooter = ({
  isYamlView,
  selectedTabIndex,
  onHide,
  submitLabel,
  disableSubmit,
  setValidateOnChange,
  lastTab,
  onYamlSubmit,
  yamlObjectKey,
  yamlHandler,
  elementsRef,
  showError,
  formikProps,
  yamlBuilderReadOnlyModeProps,
  setSelectedTabId,
  setSelectedTabIndex,
  tabsMap,
  setTouchedPanels,
  touchedPanels,
  loadingYamlView,
  validate,
  setSubmittedForm
}: WizardFooterProps): JSX.Element => {
  const { getString } = useStrings()
  const invalidYamlString = getString('common.validation.invalidYamlText')
 
  return (
    <Layout.Horizontal className={cx(css.footer, !isYamlView && css.nonYamlViewFooter)}>
      {!isYamlView && selectedTabIndex !== 0 && (
        <Button
          variation={ButtonVariation.SECONDARY}
          text={getString('back')}
          icon="chevron-left"
          minimal
          onClick={() => {
            const upcomingTabIndex = selectedTabIndex - 1
            setSelectedTabId(tabsMap[upcomingTabIndex])
            setSelectedTabIndex(upcomingTabIndex)
            setNewTouchedPanel({ selectedTabIndex, upcomingTabIndex, touchedPanels, setTouchedPanels })
            formikProps.validateForm()
          }}
        />
      )}
      {!isYamlView && !lastTab && (
        <Button
          text={getString('continue')}
          variation={ButtonVariation.PRIMARY}
          rightIcon="chevron-right"
          onClick={async () => {
            const formErrors = await formikProps.validateForm()
            Iif (!isEmpty(formErrors)) {
              formikProps.setErrors(formErrors)
              const errorKeys = Object.keys(formErrors)
              const newTouchedObj: { [key: string]: boolean } = {}
              errorKeys.forEach(k => (newTouchedObj[k] = true))
              formikProps.setTouched({ ...formikProps.touched, ...newTouchedObj }) // required to display
            }
            const upcomingTabIndex = selectedTabIndex + 1
            setSelectedTabId(tabsMap[upcomingTabIndex])
            setSelectedTabIndex(upcomingTabIndex)
            setNewTouchedPanel({ selectedTabIndex, upcomingTabIndex, touchedPanels, setTouchedPanels })
          }}
        />
      )}
      {!isYamlView && lastTab && (
        <Button
          text={submitLabel || getString('submit')}
          variation={ButtonVariation.PRIMARY}
          rightIcon="chevron-right"
          type="submit"
          disabled={disableSubmit}
          onClick={async () => {
            setSubmittedForm(true)
 
            if (
              elementsRef.current.some(
                (element): boolean =>
                  !!element?.current?.firstElementChild?.classList?.contains('bp3-icon-warning-sign')
              )
            ) {
              setValidateOnChange(true)
              showError(getString('addressErrorFields'))
            }
            const validateErrors = await validate?.()
            if (isEmpty(validateErrors)) {
              // submit form if given validate is empty
              formikProps.submitForm()
            }
          }}
        />
      )}
      {!isYamlView && (
        <Button
          className={css.cancel}
          variation={ButtonVariation.TERTIARY}
          onClick={onHide}
          text={getString('cancel')}
        />
      )}
      {isYamlView && yamlBuilderReadOnlyModeProps && !loadingYamlView && (
        <>
          <Button
            text={submitLabel || getString('submit')}
            variation={ButtonVariation.PRIMARY}
            rightIcon="chevron-right"
            onClick={async () => {
              setSubmittedForm(true)
              const latestYaml = yamlHandler?.getLatestYaml() || /* istanbul ignore next */ ''
              const errorsYaml =
                (yamlHandler?.getYAMLValidationErrorMap() as unknown as Map<number, string>) ||
                /* istanbul ignore next */ ''
              if (errorsYaml?.size > 0) {
                showError(invalidYamlString)
                return
              }
 
              if (!isEmpty(await validate?.({ latestYaml }))) {
                return
              } else {
                formikProps.setSubmitting(true)
              }
 
              try {
                const parsedYaml = parse(latestYaml)
                const processedFormik = yamlObjectKey ? parsedYaml?.[yamlObjectKey] : parsedYaml
                if (!parsedYaml) {
                  /* istanbul ignore next */
                  showError(invalidYamlString)
                  return
                }
                formikProps.setSubmitting(true)
                onYamlSubmit?.(processedFormik)
              } catch (e) {
                /* istanbul ignore next */
                showError(invalidYamlString)
                return
              }
            }}
            disabled={disableSubmit}
          />
          <Button
            className={css.cancel}
            variation={ButtonVariation.TERTIARY}
            onClick={onHide}
            text={getString('cancel')}
          />
        </>
      )}
    </Layout.Horizontal>
  )
}