All files / modules/70-pipeline/components/RunPipelineModal RunPipelineForm.tsx

74.89% Statements 173/231
61.84% Branches 188/304
71.79% Functions 28/39
75.55% Lines 173/229

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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847              31x 31x 31x                   31x 31x 31x 31x 31x   31x   31x                 31x 31x   31x             31x 31x 31x 31x 31x 31x               31x 31x 31x 31x   31x 31x 31x 31x 31x 31x 31x 31x 31x           31x 31x 31x 31x 31x 31x   31x                         31x                                                     197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x         197x 197x 197x   197x                               197x 36x 36x         36x     36x                       197x                         197x                       197x 18x       197x 18x       197x                                 197x                     197x 197x 197x                                 197x                         197x                     197x   18x           18x   18x                                       18x           18x     197x 18x     197x 33x 4x   29x       197x 19x 1x         197x   197x 18x 13x       197x 2x                                   4x 4x             197x   6x       6x 6x   2x 2x   4x 4x       4x   4x 2x                           2x                             4x 2x   2x                                                 2x                                             2x               2x     197x 36x 36x 36x                                             197x 34x 18x   18x 3x         197x                                                 197x         40x   38x 38x   37x             37x       40x 38x 37x     37x           37x   39x     197x 197x     197x 197x 40x     40x 40x           39x     197x       197x   197x 3x   194x           2x         192x 192x 192x   192x     384x                                                                                                                                                                               5x 5x     5x 5x           5x                 5x                                                 1x 1x                                                               197x                                         31x 163x   162x             31x 25x                
/*
 * 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, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Dialog, Classes } from '@blueprintjs/core'
import {
  Button,
  Formik,
  Layout,
  NestedAccordionProvider,
  ButtonVariation,
  PageSpinner,
  VisualYamlSelectedView as SelectedView,
  SelectOption
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useModalHook } from '@harness/use-modal'
import cx from 'classnames'
import { useHistory } from 'react-router-dom'
import { isEmpty, defaultTo, keyBy } from 'lodash-es'
import type { FormikErrors, FormikProps } from 'formik'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import type { PipelineConfig, PipelineInfoConfig, ResponseJsonNode } from 'services/cd-ng'
import {
  useGetPipeline,
  usePostPipelineExecuteWithInputSetYaml,
  useRePostPipelineExecuteWithInputSetYaml,
  StageExecutionResponse,
  useRunStagesWithRuntimeInputYaml,
  useRerunStagesWithRuntimeInputYaml,
  useGetStagesExecutionList
} from 'services/pipeline-ng'
import { useToaster } from '@common/exports'
import routes from '@common/RouteDefinitions'
import type { YamlBuilderHandlerBinding, YamlBuilderProps } from '@common/interfaces/YAMLBuilderProps'
import { usePermission } from '@rbac/hooks/usePermission'
import type {
  GitQueryParams,
  InputSetGitQueryParams,
  PipelinePathProps,
  PipelineType
} from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import RbacButton from '@rbac/components/Button/Button'
import {
  ALL_STAGE_VALUE,
  getAllStageData,
  getAllStageItem,
  getFeaturePropsForRunPipelineButton,
  SelectedStageData,
  StageSelectionData
} from '@pipeline/utils/runPipelineUtils'
import { useQueryParams } from '@common/hooks'
import { yamlStringify, yamlParse } from '@common/utils/YamlHelperMethods'
import { PipelineActions } from '@common/constants/TrackingConstants'
import { useTelemetry } from '@common/hooks/useTelemetry'
import type { InputSetDTO } from '@pipeline/utils/types'
import { useDeepCompareEffect } from '@common/hooks/useDeepCompareEffect'
import { clearRuntimeInput, validatePipeline, getErrorsList } from '../PipelineStudio/StepUtil'
import { PreFlightCheckModal } from '../PreFlightCheckModal/PreFlightCheckModal'
import { YamlBuilderMemo } from '../PipelineStudio/PipelineYamlView/PipelineYamlView'
import factory from '../PipelineSteps/PipelineStepFactory'
import { StepViewType } from '../AbstractSteps/Step'
import SaveAsInputSet from './SaveAsInputSet'
import ReplacedExpressionInputForm from './ReplacedExpressionInputForm'
import {
  KVPair,
  PipelineVariablesContextProvider,
  usePipelineVariables
} from '../PipelineVariablesContext/PipelineVariablesContext'
import type { InputSetSelectorProps } from '../InputSetSelector/InputSetSelector'
import { ApprovalStageInfo, ExpressionsInfo, RequiredStagesInfo } from './RunStageInfoComponents'
import { PipelineInvalidRequestContent } from './PipelineInvalidRequestContent'
import RunModalHeader from './RunModalHeader'
import CheckBoxActions from './CheckBoxActions'
import VisualView from './VisualView'
import { useInputSets } from './useInputSets'
 
import css from './RunPipelineForm.module.scss'
 
export interface RunPipelineFormProps extends PipelineType<PipelinePathProps & GitQueryParams> {
  inputSetSelected?: InputSetSelectorProps['value']
  inputSetYAML?: string
  onClose?: () => void
  executionView?: boolean
  mockData?: ResponseJsonNode
  executionInputSetTemplateYaml?: string
  stagesExecuted?: string[]
  executionIdentifier?: string
}
 
const yamlBuilderReadOnlyModeProps: YamlBuilderProps = {
  fileName: `run-pipeline.yaml`,
  entityType: 'Pipelines',
  showSnippetSection: false,
  yamlSanityConfig: {
    removeEmptyString: false,
    removeEmptyObject: false,
    removeEmptyArray: false
  }
}
 
function RunPipelineFormBasic({
  pipelineIdentifier,
  accountId,
  orgIdentifier,
  projectIdentifier,
  onClose,
  inputSetSelected,
  inputSetYAML,
  module,
  executionView,
  branch,
  repoIdentifier,
  executionInputSetTemplateYaml = '',
  stagesExecuted,
  executionIdentifier
}: RunPipelineFormProps & InputSetGitQueryParams): React.ReactElement {
  const [skipPreFlightCheck, setSkipPreFlightCheck] = useState<boolean>(false)
  const [selectedView, setSelectedView] = useState<SelectedView>(SelectedView.VISUAL)
  const [notifyOnlyMe, setNotifyOnlyMe] = useState<boolean>(false)
  const [selectedInputSets, setSelectedInputSets] = useState<InputSetSelectorProps['value']>(inputSetSelected)
  const [formErrors, setFormErrors] = useState<FormikErrors<InputSetDTO>>({})
  const { trackEvent } = useTelemetry()
  const { showError, showSuccess, showWarning } = useToaster()
  const formikRef = React.useRef<FormikProps<PipelineInfoConfig>>()
  const history = useHistory()
  const { getString } = useStrings()
  const { getRBACErrorMessage } = useRBACError()
  const { isGitSyncEnabled } = useAppStore()
  const [runClicked, setRunClicked] = useState(false)
  const [expressionFormState, setExpressionFormState] = useState<KVPair>({})
  const [selectedStageData, setSelectedStageData] = useState<StageSelectionData>({
    allStagesSelected: true,
    selectedStages: [getAllStageData(getString)],
    selectedStageItems: [getAllStageItem(getString)]
  })
  const { setPipeline: updatePipelineInVaribalesContext } = usePipelineVariables()
  const [existingProvide, setExistingProvide] = useState<'existing' | 'provide'>('existing')
  const [yamlHandler, setYamlHandler] = useState<YamlBuilderHandlerBinding | undefined>()
 
  const [canEdit] = usePermission(
    {
      resourceScope: {
        accountIdentifier: accountId,
        orgIdentifier,
        projectIdentifier
      },
      resource: {
        resourceType: ResourceType.PIPELINE,
        resourceIdentifier: pipelineIdentifier
      },
      permissions: [PermissionIdentifier.EDIT_PIPELINE]
    },
    [accountId, orgIdentifier, projectIdentifier, pipelineIdentifier]
  )
 
  const stageIdentifiers = useMemo((): string[] => {
    let stageIds: string[] = []
    stageIds = stagesExecuted?.length
      ? stagesExecuted
      : selectedStageData.allStagesSelected
      ? []
      : (selectedStageData.selectedStageItems.map(stageData => stageData.value) as string[])
    Iif (stageIds.includes(ALL_STAGE_VALUE)) {
      stageIds = []
    }
    return stageIds
  }, [stagesExecuted, selectedStageData])
 
  const {
    inputSet,
    inputSetYamlResponse,
    hasInputSets,
    parsedInputSetTemplateYaml,
    loading: loadingInputSets,
    error: inputSetsError,
    isInputSetApplied,
    refetch: getTemplateFromPipeline
  } = useInputSets({
    accountId,
    projectIdentifier,
    orgIdentifier,
    pipelineIdentifier,
    selectedStageData,
    rerunInputSetYaml: inputSetYAML,
    branch,
    repoIdentifier,
    pipelineExecutionId: executionIdentifier,
    inputSetSelected: selectedInputSets
  })
 
  const { data: pipelineResponse, loading: loadingPipeline } = useGetPipeline({
    pipelineIdentifier,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      repoIdentifier,
      branch,
      getTemplatesResolvedPipeline: true
    }
  })
 
  const pipeline: PipelineInfoConfig | undefined = React.useMemo(
    () => yamlParse<PipelineConfig>(defaultTo(pipelineResponse?.data?.yamlPipeline, ''))?.pipeline,
    [pipelineResponse?.data?.yamlPipeline]
  )
 
  const resolvedPipeline: PipelineInfoConfig | undefined = React.useMemo(
    () => yamlParse<PipelineConfig>(defaultTo(pipelineResponse?.data?.resolvedTemplatesPipelineYaml, ''))?.pipeline,
    [pipelineResponse?.data?.resolvedTemplatesPipelineYaml]
  )
 
  const { mutate: runPipeline, loading: runLoading } = usePostPipelineExecuteWithInputSetYaml({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      moduleType: module,
      repoIdentifier,
      branch
    },
    identifier: pipelineIdentifier,
    requestOptions: {
      headers: {
        'content-type': 'application/yaml'
      }
    }
  })
 
  const { mutate: runStage, loading: runStageLoading } = useRunStagesWithRuntimeInputYaml({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      moduleType: module,
      repoIdentifier,
      branch
    },
    identifier: pipelineIdentifier
  })
  const { executionId } = useQueryParams<{ executionId?: string }>()
  const pipelineExecutionId = executionIdentifier ?? executionId
  const { mutate: reRunPipeline, loading: reRunLoading } = useRePostPipelineExecuteWithInputSetYaml({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      moduleType: module,
      repoIdentifier,
      branch
    },
    identifier: pipelineIdentifier,
    originalExecutionId: defaultTo(pipelineExecutionId, ''),
    requestOptions: {
      headers: {
        'content-type': 'application/yaml'
      }
    }
  })
  const { mutate: reRunStages, loading: reRunStagesLoading } = useRerunStagesWithRuntimeInputYaml({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      moduleType: module,
      repoIdentifier,
      branch
    },
    identifier: pipelineIdentifier,
    originalExecutionId: defaultTo(pipelineExecutionId, '')
  })
 
  const { data: stageExecutionData } = useGetStagesExecutionList({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      pipelineIdentifier,
      branch,
      repoIdentifier
    }
  })
 
  const executionStageList = useMemo((): SelectOption[] => {
    const executionStages: SelectOption[] =
      stageExecutionData?.data?.map((execStage: StageExecutionResponse) => {
        return {
          label: defaultTo(execStage?.stageName, ''),
          value: defaultTo(execStage?.stageIdentifier, '')
        }
      }) || []
    executionStages.unshift(getAllStageItem(getString))
 
    Iif (stagesExecuted?.length) {
      const updatedSelectedStageList: SelectedStageData[] = []
      const updatedSelectedItems: SelectOption[] = []
      stagesExecuted.forEach(stageExecuted => {
        const selectedStage = stageExecutionData?.data?.find(stageData => stageData.stageIdentifier === stageExecuted)
        selectedStage && updatedSelectedStageList.push(selectedStage)
        selectedStage &&
          updatedSelectedItems.push({
            label: selectedStage?.stageName as string,
            value: selectedStage?.stageIdentifier as string
          })
      })
 
      setSelectedStageData({
        selectedStages: updatedSelectedStageList,
        selectedStageItems: updatedSelectedItems,
        allStagesSelected: false
      })
      setSkipPreFlightCheck(true)
    } else {
      setSelectedStageData({
        selectedStages: [getAllStageData(getString)],
        selectedStageItems: [getAllStageItem(getString)],
        allStagesSelected: true
      })
    }
    return executionStages
  }, [stageExecutionData?.data])
 
  useEffect(() => {
    setSelectedInputSets(inputSetSelected)
  }, [inputSetSelected])
 
  useEffect(() => {
    if (inputSetYAML) {
      setExistingProvide('provide')
    } else {
      setExistingProvide(hasInputSets ? 'existing' : 'provide')
    }
  }, [inputSetYAML, hasInputSets])
 
  useEffect(() => {
    if (inputSetsError) {
      showError(getRBACErrorMessage(inputSetsError))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [inputSetsError])
 
  const valuesPipelineRef = useRef<PipelineInfoConfig>()
 
  useDeepCompareEffect(() => {
    if (resolvedPipeline) {
      updatePipelineInVaribalesContext(resolvedPipeline)
    }
  }, [resolvedPipeline])
 
  const [showPreflightCheckModal, hidePreflightCheckModal] = useModalHook(() => {
    return (
      <Dialog
        className={cx(css.preFlightCheckModal, Classes.DIALOG)}
        enforceFocus={false}
        isOpen
        onClose={hidePreflightCheckModal}
      >
        <PreFlightCheckModal
          pipeline={valuesPipelineRef.current}
          module={module}
          accountId={accountId}
          orgIdentifier={orgIdentifier}
          projectIdentifier={projectIdentifier}
          pipelineIdentifier={pipelineIdentifier}
          branch={branch}
          repoIdentifier={repoIdentifier}
          onCloseButtonClick={hidePreflightCheckModal}
          onContinuePipelineClick={() => {
            hidePreflightCheckModal()
            handleRunPipeline(valuesPipelineRef.current, true)
          }}
        />
      </Dialog>
    )
  }, [])
 
  const handleRunPipeline = useCallback(
    async (valuesPipeline?: PipelineInfoConfig, forceSkipFlightCheck = false) => {
      Iif (Object.keys(formErrors).length) {
        return
      }
 
      valuesPipelineRef.current = valuesPipeline
      if (!skipPreFlightCheck && !forceSkipFlightCheck) {
        // Not skipping pre-flight check - open the new modal
        showPreflightCheckModal()
        return
      }
      const expressionValues: KVPair = {}
      Object.entries(expressionFormState).forEach(([key, value]: string[]) => {
        expressionValues[key] = value
      })
 
      try {
        let response
        if (isEmpty(pipelineExecutionId)) {
          response = selectedStageData.allStagesSelected
            ? await runPipeline(
                !isEmpty(valuesPipelineRef.current)
                  ? (yamlStringify({ pipeline: valuesPipelineRef.current }) as any)
                  : ''
              )
            : await runStage({
                runtimeInputYaml: !isEmpty(valuesPipelineRef.current)
                  ? (yamlStringify({ pipeline: valuesPipelineRef.current }) as any)
                  : '',
                stageIdentifiers: stageIdentifiers,
                expressionValues
              })
        } else {
          response = selectedStageData.allStagesSelected
            ? await reRunPipeline(
                !isEmpty(valuesPipelineRef.current)
                  ? (yamlStringify({ pipeline: valuesPipelineRef.current }) as any)
                  : ''
              )
            : await reRunStages({
                runtimeInputYaml: !isEmpty(valuesPipelineRef.current)
                  ? (yamlStringify({ pipeline: valuesPipelineRef.current }) as any)
                  : '',
                stageIdentifiers: stageIdentifiers,
                expressionValues
              })
        }
 
        const data = response.data
        const governanceMetadata = data?.planExecution?.governanceMetadata
 
        Iif (response.status === 'SUCCESS') {
          if (onClose) {
            onClose()
          }
          if (response.data) {
            showSuccess(getString('runPipelineForm.pipelineRunSuccessFully'))
            history.push({
              pathname: routes.toExecutionPipelineView({
                orgIdentifier,
                pipelineIdentifier,
                projectIdentifier,
                executionIdentifier: defaultTo(data?.planExecution?.uuid, ''),
                accountId,
                module
              }),
              state: {
                shouldShowGovernanceEvaluations:
                  governanceMetadata?.status === 'error' || governanceMetadata?.status === 'warning',
                governanceMetadata
              }
            })
            trackEvent(PipelineActions.StartedExecution, { module })
          }
        }
      } catch (error: any) {
        showWarning(defaultTo(getRBACErrorMessage(error), getString('runPipelineForm.runPipelineFailed')))
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [
      runPipeline,
      runStage,
      showWarning,
      showSuccess,
      pipelineIdentifier,
      history,
      orgIdentifier,
      module,
      projectIdentifier,
      onClose,
      accountId,
      skipPreFlightCheck,
      formErrors,
      selectedStageData
    ]
  )
 
  function handleModeSwitch(view: SelectedView): void {
    Iif (view === SelectedView.VISUAL && yamlHandler && formikRef.current) {
      const parsedYaml = yamlParse<PipelineConfig>(defaultTo(yamlHandler.getLatestYaml(), ''))
 
      if (parsedYaml.pipeline) {
        formikRef.current.setValues(parsedYaml.pipeline)
        formikRef.current.validateForm(parsedYaml.pipeline)
      }
    }
    setSelectedView(view)
  }
 
  const blockedStagesSelected = useMemo(() => {
    let areDependentStagesSelected = false
    Eif (selectedStageData.allStagesSelected) {
      return areDependentStagesSelected
    }
 
    const allRequiredStagesUpdated: string[] = []
    const stagesSelectedMap: { [key: string]: SelectedStageData } = keyBy(
      selectedStageData.selectedStages,
      'stageIdentifier'
    )
    selectedStageData.selectedStages.forEach((stage: StageExecutionResponse) => {
      if (stage.toBeBlocked) {
        allRequiredStagesUpdated.push(...(stage.stagesRequired || []))
      }
    })
 
    allRequiredStagesUpdated.forEach((stageId: string) => {
      if (!stagesSelectedMap[stageId]) {
        areDependentStagesSelected = true
      }
    })
 
    return areDependentStagesSelected
  }, [selectedStageData])
 
  useDeepCompareEffect(() => {
    if (inputSet?.pipeline && formikRef.current) {
      formikRef.current.setValues(inputSet.pipeline)
 
      if (isInputSetApplied) {
        formikRef.current.validateForm()
      }
    }
  }, [inputSet, isInputSetApplied])
 
  const updateExpressionValue = (e: React.ChangeEvent<HTMLInputElement>): void => {
    if (!e.target) {
      return
    }
 
    const keyName: string = e.target.name
    const exprValue: string = defaultTo(e.target.value, '').trim()
    setExpressionFormState(
      (oldState: KVPair): KVPair => ({
        ...oldState,
        [keyName]: exprValue
      })
    )
    if (formErrors) {
      const formErrorsUpdated = { ...formErrors }
      if (!(formErrors as any)[keyName] && isEmpty(exprValue)) {
        ;(formErrorsUpdated as any)[keyName] = getString('pipeline.expressionRequired')
      } else if ((formErrors as any)[keyName] && !isEmpty(exprValue)) {
        delete (formErrorsUpdated as any)[keyName]
      }
 
      setFormErrors(formErrorsUpdated)
    }
  }
 
  const getFormErrors = async (
    latestPipeline: { pipeline: PipelineInfoConfig },
    latestYamlTemplate: PipelineInfoConfig,
    orgPipeline: PipelineInfoConfig | undefined
  ): Promise<FormikErrors<InputSetDTO>> => {
    let errors = formErrors
    function validateErrors(): Promise<FormikErrors<InputSetDTO>> {
      return new Promise(resolve => {
        setTimeout(() => {
          const validatedErrors =
            (validatePipeline({
              pipeline: { ...clearRuntimeInput(latestPipeline.pipeline) },
              template: latestYamlTemplate,
              originalPipeline: orgPipeline,
              getString,
              viewType: StepViewType.DeploymentForm
            }) as any) || formErrors
          resolve(validatedErrors)
        }, 300)
      })
    }
    if (latestPipeline?.pipeline && latestYamlTemplate && orgPipeline) {
      errors = await validateErrors()
      const expressionErrors: KVPair = {}
 
      // vaidate replacedExpressions
      Iif (inputSetYamlResponse?.data?.replacedExpressions?.length) {
        inputSetYamlResponse.data.replacedExpressions.forEach((value: string) => {
          const currValue = defaultTo(expressionFormState[value], '')
          if (currValue.trim() === '') expressionErrors[value] = getString('pipeline.expressionRequired')
        })
      }
      setFormErrors({ ...errors, ...expressionErrors })
    }
    return errors
  }
 
  const shouldShowPageSpinner = (): boolean => {
    return loadingPipeline || runLoading || runStageLoading || reRunLoading || reRunStagesLoading || loadingInputSets
  }
 
  const formRefDom = React.useRef<HTMLElement | undefined>()
  const handleValidation = async (values: any): Promise<void> => {
    Iif (values?.pipeline) {
      values = values.pipeline
    }
    const latestPipeline = { pipeline: values as PipelineInfoConfig }
    const runPipelineFormErrors = await getFormErrors(
      latestPipeline,
      defaultTo(parsedInputSetTemplateYaml?.pipeline, {} as PipelineInfoConfig),
      pipeline
    )
    // https://github.com/formium/formik/issues/1392
    throw runPipelineFormErrors
  }
 
  Iif (shouldShowPageSpinner()) {
    return <PageSpinner />
  }
 
  let runPipelineFormContent: React.ReactElement | null = null
 
  if (inputSetsError?.message) {
    runPipelineFormContent = <PipelineInvalidRequestContent onClose={onClose} getTemplateError={inputSetsError} />
  } else {
    runPipelineFormContent = (
      <>
        <Formik<PipelineInfoConfig>
          initialValues={defaultTo(inputSet.pipeline, {} as PipelineInfoConfig)}
          formName="runPipeline"
          onSubmit={values => {
            handleRunPipeline(values, false)
          }}
          validate={handleValidation}
        >
          {formik => {
            const { submitForm, values, setValues, setFormikState } = formik
            formikRef.current = formik
            valuesPipelineRef.current = values
 
            return (
              <Layout.Vertical
                ref={ref => {
                  formRefDom.current = ref as HTMLElement
                }}
              >
                <RunModalHeader
                  pipelineExecutionId={pipelineExecutionId}
                  selectedStageData={selectedStageData}
                  setSelectedStageData={setSelectedStageData}
                  setSkipPreFlightCheck={setSkipPreFlightCheck}
                  handleModeSwitch={handleModeSwitch}
                  runClicked={runClicked}
                  selectedView={selectedView}
                  executionView={executionView}
                  pipelineResponse={pipelineResponse}
                  getTemplateFromPipeline={getTemplateFromPipeline}
                  template={inputSetYamlResponse}
                  formRefDom={formRefDom}
                  formErrors={formErrors}
                  stageExecutionData={stageExecutionData}
                  executionStageList={executionStageList}
                />
                <RequiredStagesInfo
                  selectedStageData={selectedStageData}
                  blockedStagesSelected={blockedStagesSelected}
                  getString={getString}
                />
                <ApprovalStageInfo pipeline={pipeline} selectedStageData={selectedStageData} />
                <ExpressionsInfo template={inputSetYamlResponse} getString={getString} />
                <ReplacedExpressionInputForm
                  updateExpressionValue={updateExpressionValue}
                  expressions={inputSetYamlResponse?.data?.replacedExpressions}
                />
                {selectedView === SelectedView.VISUAL ? (
                  <VisualView
                    executionView={executionView}
                    selectedInputSets={selectedInputSets}
                    existingProvide={existingProvide}
                    setExistingProvide={setExistingProvide}
                    executionInputSetTemplateYaml={executionInputSetTemplateYaml}
                    pipelineIdentifier={pipelineIdentifier}
                    template={inputSetYamlResponse}
                    pipeline={pipeline}
                    currentPipeline={{ pipeline: values }}
                    getTemplateError={inputSetsError}
                    resolvedPipeline={resolvedPipeline}
                    submitForm={submitForm}
                    setRunClicked={setRunClicked}
                    hasInputSets={hasInputSets}
                    setSelectedInputSets={setSelectedInputSets}
                    loading={false}
                    loadingMergeInputSetUpdate={false}
                  />
                ) : (
                  <div className={css.editor}>
                    <Layout.Vertical className={css.content} padding="xlarge">
                      <YamlBuilderMemo
                        {...yamlBuilderReadOnlyModeProps}
                        existingJSON={{ pipeline: values }}
                        bind={setYamlHandler}
                        schema={{}}
                        invocationMap={factory.getInvocationMap()}
                        height="55vh"
                        width="100%"
                        showSnippetSection={false}
                        isEditModeSupported={canEdit}
                      />
                    </Layout.Vertical>
                  </div>
                )}
                <CheckBoxActions
                  executionView={executionView}
                  notifyOnlyMe={notifyOnlyMe}
                  skipPreFlightCheck={skipPreFlightCheck}
                  setSkipPreFlightCheck={setSkipPreFlightCheck}
                  setNotifyOnlyMe={setNotifyOnlyMe}
                />
                {executionView ? null : (
                  <Layout.Horizontal
                    padding={{ left: 'xlarge', right: 'xlarge', top: 'large', bottom: 'large' }}
                    flex={{ justifyContent: 'space-between', alignItems: 'center' }}
                    className={css.footer}
                  >
                    <Layout.Horizontal className={cx(css.actionButtons)}>
                      <RbacButton
                        variation={ButtonVariation.PRIMARY}
                        intent="success"
                        type="submit"
                        text={getString('runPipeline')}
                        onClick={event => {
                          event.stopPropagation()
                          setRunClicked(true)
                          // _formSubmitCount is custom state var used to track submitCount.
                          // enableReinitialize prop resets the submitCount, so error checks fail.
                          setFormikState({ _formSubmitCount: 1 } as any)
                          Iif (
                            (!selectedInputSets || selectedInputSets.length === 0) &&
                            existingProvide === 'existing'
                          ) {
                            setExistingProvide('provide')
                          } else {
                            Iif (selectedView === SelectedView.YAML) {
                              const parsedYaml = yamlParse<PipelineConfig>(defaultTo(yamlHandler?.getLatestYaml(), ''))
                              if (parsedYaml.pipeline) {
                                setValues(parsedYaml.pipeline)
                                setTimeout(() => {
                                  submitForm()
                                }, 0)
                              }
                            } else {
                              submitForm()
                            }
                          }
                        }}
                        featuresProps={getFeaturePropsForRunPipelineButton({
                          modules: inputSetYamlResponse?.data?.modules,
                          getString
                        })}
                        permission={{
                          resource: {
                            resourceIdentifier: pipeline?.identifier as string,
                            resourceType: ResourceType.PIPELINE
                          },
                          permission: PermissionIdentifier.EXECUTE_PIPELINE
                        }}
                        disabled={blockedStagesSelected || (getErrorsList(formErrors).errorCount > 0 && runClicked)}
                      />
                      <div className={css.secondaryButton}>
                        <Button
                          variation={ButtonVariation.TERTIARY}
                          id="cancel-runpipeline"
                          text={getString('cancel')}
                          margin={{ left: 'medium' }}
                          background={Color.GREY_50}
                          onClick={() => {
                            Eif (onClose) {
                              onClose()
                            }
                          }}
                        />
                      </div>
                    </Layout.Horizontal>
                    <SaveAsInputSet
                      key="saveasinput"
                      pipeline={pipeline}
                      currentPipeline={{ pipeline: values }}
                      values={values}
                      template={inputSetYamlResponse?.data?.inputSetTemplateYaml}
                      canEdit={canEdit}
                      accountId={accountId}
                      projectIdentifier={projectIdentifier}
                      orgIdentifier={orgIdentifier}
                      repoIdentifier={repoIdentifier}
                      branch={branch}
                      isGitSyncEnabled={isGitSyncEnabled}
                      setFormErrors={setFormErrors}
                      refetchParentData={getTemplateFromPipeline}
                    />
                  </Layout.Horizontal>
                )}
              </Layout.Vertical>
            )
          }}
        </Formik>
      </>
    )
  }
 
  return executionView ? (
    <div className={css.runFormExecutionView}>{runPipelineFormContent}</div>
  ) : (
    <RunPipelineFormWrapper
      accountId={accountId}
      orgIdentifier={orgIdentifier}
      pipelineIdentifier={pipelineIdentifier}
      projectIdentifier={projectIdentifier}
      module={module}
      pipeline={pipeline}
    >
      {runPipelineFormContent}
    </RunPipelineFormWrapper>
  )
}
 
export interface RunPipelineFormWrapperProps extends PipelineType<PipelinePathProps> {
  children: React.ReactNode
  pipeline?: PipelineInfoConfig
}
 
export function RunPipelineFormWrapper(props: RunPipelineFormWrapperProps): React.ReactElement {
  const { children } = props
 
  return (
    <React.Fragment>
      <div className={css.runForm}>{children}</div>
    </React.Fragment>
  )
}
 
export function RunPipelineForm(props: RunPipelineFormProps & InputSetGitQueryParams): React.ReactElement {
  return (
    <NestedAccordionProvider>
      <PipelineVariablesContextProvider>
        <RunPipelineFormBasic {...props} />
      </PipelineVariablesContextProvider>
    </NestedAccordionProvider>
  )
}