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

94.55% Statements 52/55
78.38% Branches 58/74
78.57% Functions 11/14
94.12% Lines 48/51

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              5x 5x                   5x 5x 5x 5x 5x           5x             5x 5x 5x                                                                                                         5x                                     134x 134x 402x 134x 134x 134x 134x 134x 134x 134x 134x                       134x 134x 134x 402x 134x   134x 46x 18x 18x 18x               134x 134x 134x     134x 33x 5x   28x       134x                                             243x     9x       243x         1x                                                                                   717x 717x                                                                                                                                                         5x  
/*
 * 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, { useEffect, useRef, createRef, RefObject } from 'react'
import {
  Layout,
  Tabs,
  Tab,
  Formik,
  FormikForm,
  Icon,
  VisualYamlSelectedView as SelectedView
} from '@wings-software/uicore'
import type { IconName } from '@wings-software/uicore'
import { useHistory } from 'react-router-dom'
import cx from 'classnames'
import { isEqual } from 'lodash-es'
import { NavigationCheck } from '@common/components/NavigationCheck/NavigationCheck'
import { useToaster } from '@common/exports'
import type {
  YamlBuilderHandlerBinding,
  YamlBuilderProps,
  InvocationMapFunction
} from '@common/interfaces/YAMLBuilderProps'
import {
  renderTitle,
  setNewTouchedPanel,
  shouldBlockNavigation,
  renderYamlBuilder,
  FormikPropsInterface
} from './WizardUtils'
import { WizardHeader } from './WizardHeader'
import { WizardFooter } from './WizardFooter'
import css from './Wizard.module.scss'
 
export interface PanelInterface {
  id: string
  tabTitle?: string
  tabTitleComponent?: JSX.Element
  iconName?: IconName
  requiredFields?: string[]
  checkValidPanel?: ({
    formikValues,
    formikErrors
  }: {
    formikValues: { [key: string]: any }
    formikErrors: { [key: string]: any }
  }) => boolean
}
export interface WizardMapInterface {
  wizardLabel?: string
  panels: PanelInterface[]
}
 
interface VisualYamlPropsInterface {
  showVisualYaml: boolean
  schema?: Record<string, any>
  invocationMap?: Map<RegExp, InvocationMapFunction>
  handleModeSwitch: (mode: SelectedView, yamlHandler?: YamlBuilderHandlerBinding) => void
  convertFormikValuesToYaml: (formikPropsValues: any) => any
  onYamlSubmit: (val: any) => void
  yamlObjectKey?: string
  loading?: boolean
  yamlBuilderReadOnlyModeProps: YamlBuilderProps
  positionInHeader?: boolean
}
interface WizardProps {
  wizardMap: WizardMapInterface
  formikInitialProps: FormikPropsInterface
  onHide: () => void
  defaultTabId?: string
  tabWidth?: string
  tabChevronOffset?: string
  submitLabel?: string
  isEdit?: boolean
  children?: JSX.Element[]
  disableSubmit?: boolean
  errorToasterMessage?: string
  rightNav?: JSX.Element
  leftNav?: ({ selectedView }: { selectedView: SelectedView }) => JSX.Element
  visualYamlProps?: VisualYamlPropsInterface
  wizardType?: string // required for dataTooltip to be unique
  className?: string
  renderErrorsStrip?: () => JSX.Element // component currently only allowed for pipeline components
}
 
const Wizard: React.FC<WizardProps> = ({
  wizardMap,
  onHide,
  submitLabel,
  tabWidth,
  tabChevronOffset,
  defaultTabId,
  formikInitialProps,
  children,
  isEdit = false,
  disableSubmit,
  errorToasterMessage,
  rightNav,
  leftNav,
  visualYamlProps = { showVisualYaml: false },
  className = '',
  wizardType,
  renderErrorsStrip
}) => {
  const { wizardLabel } = wizardMap
  const defaultWizardTabId = wizardMap.panels[0].id
  const tabsMap = wizardMap?.panels?.map(panel => panel.id)
  const initialIndex = defaultTabId ? tabsMap.findIndex(tabsId => defaultTabId === tabsId) : 0
  const [selectedTabId, setSelectedTabId] = React.useState<string>(defaultTabId || defaultWizardTabId)
  const [touchedPanels, setTouchedPanels] = React.useState<number[]>([])
  const [validateOnChange, setValidateOnChange] = React.useState<boolean>(formikInitialProps.validateOnChange || false)
  const [selectedTabIndex, setSelectedTabIndex] = React.useState<number>(initialIndex)
  const [selectedView, setSelectedView] = React.useState<SelectedView>(SelectedView.VISUAL)
  const layoutRef = useRef<HTMLDivElement>(null)
  const lastTab = selectedTabIndex === tabsMap.length - 1
  const {
    showVisualYaml,
    handleModeSwitch,
    yamlBuilderReadOnlyModeProps,
    loading: loadingYamlView,
    schema,
    convertFormikValuesToYaml,
    onYamlSubmit,
    yamlObjectKey,
    invocationMap,
    positionInHeader
  } = visualYamlProps
  const isYamlView = selectedView === SelectedView.YAML
  const [yamlHandler, setYamlHandler] = React.useState<YamlBuilderHandlerBinding | undefined>()
  const elementsRef: { current: RefObject<HTMLSpanElement>[] } = useRef(wizardMap.panels?.map(() => createRef()))
  const [submittedForm, setSubmittedForm] = React.useState<boolean>(false)
 
  const handleTabChange = (data: string): void => {
    const tabsIndex = tabsMap.findIndex(tab => tab === data)
    setSelectedTabId(data)
    setSelectedTabIndex(tabsIndex)
    setNewTouchedPanel({
      upcomingTabIndex: tabsIndex,
      selectedTabIndex,
      touchedPanels,
      setTouchedPanels,
      includeSkippedIndexes: true
    })
  }
  const history = useHistory()
  const { showError, clear } = useToaster()
  const getIsDirtyForm = (parsedYaml: any): boolean =>
    !isEqual(convertFormikValuesToYaml?.(formikInitialProps?.initialValues), parsedYaml)
 
  useEffect(() => {
    if (errorToasterMessage) {
      showError(errorToasterMessage)
    } else {
      clear()
    }
  }, [showError, errorToasterMessage])
 
  return (
    <section className={cx(css.wizardShell, className)} ref={layoutRef}>
      <WizardHeader
        yamlHandler={yamlHandler}
        showError={showError}
        leftNav={leftNav}
        selectedView={selectedView}
        rightNav={rightNav}
        showVisualYaml={showVisualYaml}
        handleModeSwitch={handleModeSwitch}
        setSelectedView={setSelectedView}
        positionInHeader={positionInHeader}
        wizardLabel={wizardLabel}
      />
      {submittedForm && renderErrorsStrip?.()}
      <Layout.Horizontal spacing="large" className={css.tabsContainer}>
        <Formik
          {...formikInitialProps}
          validateOnChange={validateOnChange}
          formName={`wizardForm${wizardType ? `_${wizardType}` : ''}`}
        >
          {formikProps => {
            const additionalWizardFooterProps =
              typeof formikInitialProps.validate !== 'undefined'
                ? {
                    validate: (arg?: { latestYaml?: string }) =>
                      formikInitialProps?.validate?.({ formikProps, latestYaml: arg?.latestYaml })
                  }
                : {}
 
            return (
              <FormikForm className={isYamlView ? css.yamlContainer : ''}>
                <NavigationCheck
                  when={true}
                  shouldBlockNavigation={() =>
                    shouldBlockNavigation({
                      isSubmitting: formikProps.isSubmitting,
                      isValid: formikProps.isValid,
                      isYamlView,
                      yamlHandler,
                      dirty: formikProps.dirty,
                      getIsDirtyForm
                    })
                  }
                  navigate={newPath => {
                    history.push(newPath)
                  }}
                />
                {isYamlView && yamlBuilderReadOnlyModeProps ? (
                  // loadingYamlView ?
                  renderYamlBuilder({
                    loadingYamlView,
                    yamlBuilderReadOnlyModeProps,
                    convertFormikValuesToYaml,
                    formikProps,
                    setYamlHandler,
                    invocationMap,
                    schema
                  })
                ) : (
                  // (
                  //   <div style={{ position: 'relative', height: 'calc(100vh - 128px)' }}>
                  //     <PageSpinner />
                  //   </div>
                  // ) : (
                  //   <YAMLBuilder
                  //     {...yamlBuilderReadOnlyModeProps}
                  //     existingJSON={convertFormikValuesToYaml?.(formikProps.values)}
                  //     isReadOnlyMode={false}
                  //     showSnippetSection={false}
                  //     bind={setYamlHandler}
                  //     invocationMap={invocationMap}
                  //     schema={schema}
                  //   />
                  // )
                  <Tabs id="Wizard" onChange={handleTabChange} selectedTabId={selectedTabId}>
                    {wizardMap.panels.map((_panel, panelIndex) => {
                      const { id, tabTitle, tabTitleComponent, requiredFields = [], checkValidPanel } = _panel
                      return (
                        <Tab
                          key={id}
                          id={id}
                          style={{ width: tabWidth ? tabWidth : 'auto' }}
                          title={renderTitle({
                            tabTitle,
                            tabTitleComponent,
                            requiredFields,
                            checkValidPanel,
                            panelIndex,
                            touchedPanels,
                            isEdit,
                            selectedTabIndex,
                            formikVals: formikProps.values,
                            formikErrs: formikProps.errors,
                            ref: elementsRef.current[panelIndex]
                          })}
                          panel={
                            children?.[panelIndex] && React.cloneElement(children[panelIndex], { formikProps, isEdit })
                          }
                        >
                          {panelIndex !== wizardMap.panels.length - 1 && (
                            <Icon
                              data-name="chevron-right-tab"
                              name="chevron-right"
                              height={20}
                              size={20}
                              margin={{ right: 'small', left: 'small' }}
                              color={'grey400'}
                              style={{
                                position: tabChevronOffset ? 'absolute' : 'initial',
                                left: tabChevronOffset || 'auto',
                                cursor: 'auto'
                              }}
                              onClick={e => e.preventDefault()}
                            />
                          )}
                        </Tab>
                      )
                    })}
                  </Tabs>
                )}
                <WizardFooter
                  isYamlView={isYamlView}
                  selectedTabIndex={selectedTabIndex}
                  onHide={onHide}
                  submitLabel={submitLabel}
                  disableSubmit={disableSubmit}
                  setValidateOnChange={setValidateOnChange}
                  lastTab={lastTab}
                  onYamlSubmit={onYamlSubmit}
                  yamlObjectKey={yamlObjectKey}
                  yamlHandler={yamlHandler}
                  elementsRef={elementsRef}
                  showError={showError}
                  formikProps={formikProps}
                  yamlBuilderReadOnlyModeProps={yamlBuilderReadOnlyModeProps}
                  setSelectedTabId={setSelectedTabId}
                  setSelectedTabIndex={setSelectedTabIndex}
                  tabsMap={tabsMap}
                  touchedPanels={touchedPanels}
                  setTouchedPanels={setTouchedPanels}
                  loadingYamlView={loadingYamlView}
                  setSubmittedForm={setSubmittedForm}
                  {...additionalWizardFooterProps}
                />
              </FormikForm>
            )
          }}
        </Formik>
      </Layout.Horizontal>
      <div className={css.footerLine}></div>
    </section>
  )
}
 
export default Wizard