All files / modules/70-pipeline/components/PipelineStudio/PipelineCanvas PipelineCanvas.tsx

46.37% Statements 134/289
35.48% Branches 182/513
35% Functions 14/40
46.69% Lines 134/287

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 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917              8x 8x 8x 8x                           8x 8x 8x 8x 8x   8x 8x 8x 8x                     8x 8x 8x 8x 8x             8x   8x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x                                   8x                                             8x         14x                                           14x                         14x 14x                           14x   14x 14x                 14x   14x                       14x   14x 14x 14x                             14x 14x 14x 14x 14x 14x 14x 14x 14x   14x   14x                                                         14x                                                   14x                   14x                               14x                                                                                     14x 14x   14x                                                                                         14x                                 14x   14x 9x 5x     5x         14x 14x     14x       14x 14x 14x             14x     14x                             14x 14x 14x         14x                                             14x                                                                                       1x 1x     1x 1x             1x 1x 1x     14x   14x                             14x                                   14x 14x             14x 14x                     14x 14x         14x                                                                                               14x 14x                                                   14x 1x               13x 12x 7x 3x     3x   4x     4x   5x     13x 1x               12x       12x         8x           1x 1x           1x                                     1x 1x                                                                                                                               1x                                                                                                                                                              
/*
 * 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, { useState } from 'react'
import { Classes, Dialog, IDialogProps, Intent } from '@blueprintjs/core'
import cx from 'classnames'
import {
  Text,
  Icon,
  Layout,
  Button,
  SelectOption,
  Container,
  ButtonVariation,
  useToaster,
  PageSpinner,
  VisualYamlSelectedView as SelectedView,
  VisualYamlToggle,
  useConfirmationDialog
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { useHistory, useParams, matchPath } from 'react-router-dom'
import { parse } from 'yaml'
import { defaultTo, isEmpty, isEqual, merge, omit, set } from 'lodash-es'
import produce from 'immer'
import type { PipelineInfoConfig } from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import { AppStoreContext } from 'framework/AppStore/AppStoreContext'
import { NavigationCheck } from '@common/components/NavigationCheck/NavigationCheck'
import { accountPathProps, pipelinePathProps, pipelineModuleParams } from '@common/utils/routeUtils'
import type {
  PipelinePathProps,
  ProjectPathProps,
  PathFn,
  PipelineType,
  GitQueryParams,
  PipelineStudioQueryParams,
  RunPipelineQueryParams,
  UseTemplateQueryParams
} from '@common/interfaces/RouteInterfaces'
import RbacButton from '@rbac/components/Button/Button'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import routes from '@common/RouteDefinitions'
import {
  EntityGitDetails,
  GovernanceMetadata,
  useGetTemplateFromPipeline,
  InputSetSummaryResponse,
  useGetInputsetYaml
} from 'services/pipeline-ng'
import { useGlobalEventListener, useMutateAsGet, useQueryParams, useUpdateQueryParams } from '@common/hooks'
import type { GitFilterScope } from '@common/components/GitFilters/GitFilters'
import { TagsPopover } from '@common/components'
import type { IGitContextFormProps } from '@common/components/GitContextForm/GitContextForm'
import { useDocumentTitle } from '@common/hooks/useDocumentTitle'
import { PipelineVariablesContextProvider } from '@pipeline/components/PipelineVariablesContext/PipelineVariablesContext'
import { useFeatureFlags } from '@common/hooks/useFeatureFlag'
import GenericErrorHandler from '@common/pages/GenericErrorHandler/GenericErrorHandler'
import NoEntityFound from '@pipeline/pages/utils/NoEntityFound/NoEntityFound'
import { getFeaturePropsForRunPipelineButton } from '@pipeline/utils/runPipelineUtils'
import { RunPipelineForm } from '@pipeline/components/RunPipelineModal/RunPipelineForm'
import { EvaluationModal } from '@governance/EvaluationModal'
import { createTemplate, getScopeBasedTemplateRef } from '@pipeline/utils/templateUtils'
import { getStepFromStage } from '@pipeline/components/PipelineStudio/StepUtil'
import { updateStepWithinStage } from '@pipeline/components/PipelineStudio/RightDrawer/RightDrawer'
import type { TemplateSummaryResponse } from 'services/template-ng'
import StageBuilder from '@pipeline/components/PipelineStudio/StageBuilder/StageBuilder'
import { TemplatePipelineBuilder } from '@pipeline/components/PipelineStudio/PipelineTemplateBuilder/TemplatePipelineBuilder/TemplatePipelineBuilder'
import { SavePipelinePopover } from '@pipeline/components/PipelineStudio/SavePipelinePopover/SavePipelinePopover'
import { useTemplateSelector } from '@pipeline/utils/useTemplateSelector'
import { usePipelineContext } from '../PipelineContext/PipelineContext'
import CreatePipelines from '../CreateModal/PipelineCreate'
import { DefaultNewPipelineId, DrawerTypes } from '../PipelineContext/PipelineActions'
import PipelineYamlView from '../PipelineYamlView/PipelineYamlView'
import { RightBar } from '../RightBar/RightBar'
import StudioGitPopover from '../StudioGitPopover'
import css from './PipelineCanvas.module.scss'
 
interface OtherModalProps {
  onSubmit?: (values: PipelineInfoConfig) => void
  initialValues?: PipelineInfoConfig
  onClose?: () => void
}
 
interface PipelineWithGitContextFormProps extends PipelineInfoConfig {
  repo?: string
  branch?: string
}
 
interface InputSetValue extends SelectOption {
  type: InputSetSummaryResponse['inputSetType']
  gitDetails?: EntityGitDetails
}
 
const runModalProps: IDialogProps = {
  isOpen: true,
  // usePortal: true,
  autoFocus: true,
  canEscapeKeyClose: true,
  canOutsideClickClose: false,
  enforceFocus: false,
  className: css.runPipelineDialog,
  style: { width: 872, height: 'fit-content', overflow: 'auto' },
  isCloseButtonShown: false
}
 
export interface PipelineCanvasProps {
  toPipelineStudio: PathFn<PipelineType<PipelinePathProps> & PipelineStudioQueryParams>
  toPipelineDetail: PathFn<PipelineType<PipelinePathProps>>
  toPipelineList: PathFn<PipelineType<ProjectPathProps>>
  toPipelineProject: PathFn<PipelineType<ProjectPathProps>>
  getOtherModal?: (
    onSubmit: (values: PipelineInfoConfig, gitDetails?: EntityGitDetails) => void,
    onClose: () => void
  ) => React.ReactElement<OtherModalProps>
}
 
export function PipelineCanvas({
  toPipelineList,
  toPipelineStudio,
  getOtherModal
}: PipelineCanvasProps): React.ReactElement {
  const { isGitSyncEnabled } = React.useContext(AppStoreContext)
  const {
    state,
    state: {
      selectionState: { selectedStageId },
      templateTypes,
      pipelineView: { drawerData },
      templateView: { isTemplateDrawerOpened }
    },
    updatePipeline,
    updateGitDetails,
    deletePipelineCache,
    fetchPipeline,
    view,
    setView,
    isReadonly,
    updateStage,
    updatePipelineView,
    setSelectedStageId,
    setSelectedSectionId,
    getStageFromPipeline,
    setTemplateTypes
  } = usePipelineContext()
  const {
    repoIdentifier,
    branch,
    runPipeline,
    executionId,
    inputSetType,
    inputSetValue,
    inputSetLabel,
    inputSetRepoIdentifier,
    inputSetBranch,
    stagesExecuted,
    useTemplate
  } = useQueryParams<GitQueryParams & RunPipelineQueryParams & UseTemplateQueryParams>()
  const { updateQueryParams, replaceQueryParams } = useUpdateQueryParams<PipelineStudioQueryParams>()
  const {
    pipeline,
    isUpdated,
    pipelineView: { isYamlEditable },
    pipelineView,
    isLoading,
    isInitialized,
    originalPipeline,
    yamlHandler,
    isBEPipelineUpdated,
    gitDetails,
    entityValidityDetails,
    templateError
  } = state
 
  const { getString } = useStrings()
  const { accountId, projectIdentifier, orgIdentifier, pipelineIdentifier, module } = useParams<
    PipelineType<{
      orgIdentifier: string
      projectIdentifier: string
      pipelineIdentifier: string
      accountId: string
    }> &
      GitQueryParams
  >()
  const { getTemplate } = useTemplateSelector()
 
  const { data: template } = useMutateAsGet(useGetTemplateFromPipeline, {
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      pipelineIdentifier,
      projectIdentifier,
      repoIdentifier,
      branch
    },
    body: {}
  })
 
  const { showError, clear } = useToaster()
 
  useDocumentTitle([parse(pipeline?.name || getString('pipelines'))])
  const [discardBEUpdateDialog, setDiscardBEUpdate] = React.useState(false)
  const { openDialog: openConfirmBEUpdateError } = useConfirmationDialog({
    cancelButtonText: getString('cancel'),
    contentText: getString('pipelines-studio.pipelineUpdatedError'),
    titleText: getString('pipelines-studio.pipelineUpdated'),
    confirmButtonText: getString('update'),
    intent: Intent.WARNING,
    onCloseDialog: isConfirmed => {
      if (isConfirmed) {
        fetchPipeline({ forceFetch: true, forceUpdate: true })
      } else {
        setDiscardBEUpdate(true)
      }
    }
  })
 
  const history = useHistory()
  const isYaml = view === SelectedView.YAML
  const [isYamlError, setYamlError] = React.useState(false)
  const [blockNavigation, setBlockNavigation] = React.useState(false)
  const [selectedBranch, setSelectedBranch] = React.useState(branch || '')
  const [savedTemplate, setSavedTemplate] = React.useState<TemplateSummaryResponse>()
  const [disableVisualView, setDisableVisualView] = React.useState(entityValidityDetails?.valid === false)
  const { OPA_PIPELINE_GOVERNANCE } = useFeatureFlags()
  const [governanceMetadata, setGovernanceMetadata] = useState<GovernanceMetadata>()
  const shouldShowGovernanceEvaluation =
    OPA_PIPELINE_GOVERNANCE && (governanceMetadata?.status === 'error' || governanceMetadata?.status === 'warning')
 
  const { openDialog: openUnsavedChangesDialog } = useConfirmationDialog({
    cancelButtonText: getString('cancel'),
    contentText: isYamlError ? getString('navigationYamlError') : getString('navigationCheckText'),
    titleText: isYamlError ? getString('navigationYamlErrorTitle') : getString('navigationCheckTitle'),
    confirmButtonText: getString('confirm'),
    intent: Intent.WARNING,
    onCloseDialog: async isConfirmed => {
      if (isConfirmed) {
        deletePipelineCache(gitDetails).then(() => {
          history.push(
            routes.toPipelineStudio({
              projectIdentifier,
              orgIdentifier,
              pipelineIdentifier: pipeline?.identifier || '-1',
              accountId,
              module,
              branch: selectedBranch,
              repoIdentifier: repoIdentifier
            })
          )
          location.reload()
        })
      } else {
        setSelectedBranch(branch || '')
      }
      setBlockNavigation(false)
    }
  })
 
  const isValidYaml = function (): boolean {
    if (yamlHandler) {
      try {
        const parsedYaml = parse(yamlHandler.getLatestYaml())
        if (!parsedYaml) {
          clear()
          showError(getString('invalidYamlText'))
          return false
        }
        if (yamlHandler.getYAMLValidationErrorMap()?.size > 0) {
          clear()
          setYamlError(true)
          showError(getString('invalidYamlText'))
          return false
        }
        updatePipeline(parsedYaml.pipeline)
      } catch (e) {
        clear()
        setYamlError(true)
        showError(e.message || getString('invalidYamlText'))
        return false
      }
    }
    return true
  }
 
  useGlobalEventListener('TEMPLATE_SAVED', event => {
    const { detail: newTemplate } = event
    if (newTemplate) {
      setSavedTemplate(newTemplate)
      window.requestAnimationFrame(() => {
        openUseTemplateDialog()
      })
    }
  })
 
  const { openDialog: openUseTemplateDialog } = useConfirmationDialog({
    intent: Intent.WARNING,
    cancelButtonText: getString('no'),
    contentText: getString('pipeline.templateSaved', {
      name: savedTemplate?.name,
      entity: savedTemplate?.templateEntityType?.toLowerCase()
    }),
    titleText: `Use Template ${savedTemplate?.name}?`,
    confirmButtonText: getString('yes'),
    onCloseDialog: async isConfirmed => {
      if (isConfirmed) {
        onUseTemplateConfirm()
      }
    }
  })
 
  const onUseTemplateConfirm = async () => {
    if (savedTemplate?.templateEntityType === 'Pipeline') {
      const processNode = createTemplate(pipeline, savedTemplate)
      await updatePipeline(processNode)
    } else if (selectedStageId) {
      const { stage: selectedStage } = getStageFromPipeline(selectedStageId)
      if (savedTemplate?.templateEntityType === 'Stage') {
        if (selectedStage?.stage) {
          const processNode = createTemplate(selectedStage.stage, savedTemplate)
          await updateStage(processNode)
        }
      } else if (savedTemplate?.templateEntityType === 'Step') {
        const selectedStepId = drawerData.data?.stepConfig?.node.identifier
        if (selectedStepId) {
          const selectedStep = getStepFromStage(selectedStepId, [
            ...defaultTo(selectedStage?.stage?.spec?.execution?.steps, []),
            ...defaultTo(selectedStage?.stage?.spec?.execution?.rollbackSteps, [])
          ])
          if (selectedStep?.step) {
            const processNode = createTemplate(selectedStep?.step, savedTemplate)
            const newPipelineView = produce(pipelineView, draft => {
              set(draft, 'drawerData.data.stepConfig.node', processNode)
            })
            updatePipelineView(newPipelineView)
            const stageData = produce(selectedStage, draft => {
              if (draft?.stage?.spec?.execution) {
                updateStepWithinStage(draft.stage.spec.execution, selectedStepId, processNode as any)
              }
            })
            if (stageData?.stage) {
              await updateStage(stageData.stage)
            }
            drawerData.data?.stepConfig?.onUpdate?.(processNode)
          }
        }
      }
      if (savedTemplate?.identifier && savedTemplate?.childType) {
        templateTypes[savedTemplate.identifier] = savedTemplate.childType
        setTemplateTypes(templateTypes)
      }
    }
  }
 
  const [usingTemplate, setUsingTemplate] = React.useState<TemplateSummaryResponse>()
  const [copyingTemplate, setCopyingTemplate] = React.useState<TemplateSummaryResponse>()
 
  const [showModal, hideModal] = useModalHook(() => {
    if (getOtherModal) {
      pipeline.identifier = ''
      updatePipeline(pipeline)
      return (
        <PipelineVariablesContextProvider pipeline={pipeline}>
          {getOtherModal(onSubmit, onCloseCreate)}
        </PipelineVariablesContextProvider>
      )
    } else {
      return (
        <PipelineVariablesContextProvider pipeline={pipeline}>
          <Dialog
            style={{
              width: isGitSyncEnabled ? '614px' : '385px',
              background: 'var(--form-bg)',
              paddingTop: '36px'
            }}
            enforceFocus={false}
            isOpen={true}
            className={'padded-dialog'}
            onClose={onCloseCreate}
            title={
              pipelineIdentifier === DefaultNewPipelineId
                ? getString('moduleRenderer.newPipeLine')
                : getString('editPipeline')
            }
          >
            <CreatePipelines
              afterSave={onSubmit}
              initialValues={merge(pipeline, {
                repo: gitDetails.repoIdentifier || '',
                branch: gitDetails.branch || ''
              })}
              closeModal={onCloseCreate}
              gitDetails={gitDetails as IGitContextFormProps}
              usingTemplate={usingTemplate}
              copyingTemplate={copyingTemplate}
            />
          </Dialog>
        </PipelineVariablesContextProvider>
      )
    }
  }, [pipeline?.identifier, pipeline, usingTemplate, copyingTemplate])
 
  const addTemplate = async () => {
    if (!isTemplateDrawerOpened && !usingTemplate && !copyingTemplate) {
      try {
        const { template: newTemplate, isCopied } = await getTemplate({ templateType: 'Pipeline' })
        if (isCopied) {
          setCopyingTemplate(newTemplate)
        } else {
          setUsingTemplate(newTemplate)
        }
        showModal()
      } catch (_) {
        // user cancelled template selection
        onCloseCreate()
      }
    }
  }
 
  React.useEffect(() => {
    // for new pipeline always use UI as default view
    if (pipelineIdentifier === DefaultNewPipelineId) {
      setView(SelectedView.VISUAL)
    } else Iif (entityValidityDetails?.valid === false || view === SelectedView.YAML) {
      setView(SelectedView.YAML)
    } else {
      setView(SelectedView.VISUAL)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pipelineIdentifier, entityValidityDetails?.valid])
 
  React.useEffect(() => {
    Iif (entityValidityDetails?.valid === false) {
      setDisableVisualView(true)
    } else {
      setDisableVisualView(false)
    }
  }, [entityValidityDetails?.valid])
 
  React.useEffect(() => {
    Eif (isInitialized) {
      Iif (pipeline?.identifier === DefaultNewPipelineId) {
        if (useTemplate) {
          addTemplate()
        } else {
          showModal()
        }
      }
      Iif (isBEPipelineUpdated && !discardBEUpdateDialog) {
        openConfirmBEUpdateError()
      }
      Iif (blockNavigation && isUpdated) {
        openUnsavedChangesDialog()
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    // eslint-disable-next-line react-hooks/exhaustive-deps
    pipeline?.identifier,
    showModal,
    isInitialized,
    isBEPipelineUpdated,
    discardBEUpdateDialog,
    blockNavigation
  ])
 
  React.useEffect(() => {
    Eif (pipeline?.name) {
      window.dispatchEvent(new CustomEvent('RENAME_PIPELINE', { detail: pipeline?.name }))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pipeline?.name])
 
  const onCloseCreate = React.useCallback(() => {
    if (pipelineIdentifier === DefaultNewPipelineId || getOtherModal) {
      if (getOtherModal) {
        deletePipelineCache(gitDetails)
      }
      history.push(toPipelineList({ orgIdentifier, projectIdentifier, accountId, module }))
    }
    hideModal()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    accountId,
    hideModal,
    history,
    module,
    orgIdentifier,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    pipeline?.identifier,
    projectIdentifier,
    toPipelineList,
    getOtherModal,
    deletePipelineCache
  ])
 
  const onSubmit = React.useCallback(
    (
      values: PipelineInfoConfig,
      updatedGitDetails?: EntityGitDetails,
      using?: TemplateSummaryResponse,
      copying?: TemplateSummaryResponse
    ) => {
      pipeline.name = values.name
      pipeline.description = values.description
      pipeline.identifier = values.identifier
      pipeline.tags = values.tags ?? {}
      if (using) {
        set(pipeline, 'template.templateRef', getScopeBasedTemplateRef(using))
        if (using.versionLabel) {
          set(pipeline, 'template.versionLabel', using.versionLabel)
        }
      } else if (copying) {
        merge(pipeline, parse(copying?.yaml || '')?.template.spec)
      }
      delete (pipeline as PipelineWithGitContextFormProps).repo
      delete (pipeline as PipelineWithGitContextFormProps).branch
      updatePipeline(pipeline)
      if (updatedGitDetails) {
        if (gitDetails?.objectId) {
          updatedGitDetails = { ...gitDetails, ...updatedGitDetails }
        }
        updateGitDetails(updatedGitDetails).then(() => {
          if (updatedGitDetails) {
            updateQueryParams(
              { repoIdentifier: updatedGitDetails.repoIdentifier, branch: updatedGitDetails.branch },
              { skipNulls: true }
            )
          }
        })
      }
      hideModal()
      setUsingTemplate(undefined)
      setCopyingTemplate(undefined)
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [hideModal, pipeline, updatePipeline]
  )
 
  function handleViewChange(newView: SelectedView): boolean {
    Iif (newView === view) return false
    Iif (newView === SelectedView.VISUAL && yamlHandler && isYamlEditable) {
      if (!isValidYaml()) return false
    }
    setView(newView)
    updatePipelineView({
      splitViewData: {},
      isDrawerOpened: false,
      isYamlEditable: false,
      isSplitViewOpen: false,
      drawerData: { type: DrawerTypes.AddStep }
    })
    setSelectedStageId(undefined)
    setSelectedSectionId(undefined)
    return true
  }
 
  const [inputSetYaml, setInputSetYaml] = React.useState('')
 
  const { data, refetch, loading } = useGetInputsetYaml({
    planExecutionId: executionId ?? '',
    queryParams: {
      orgIdentifier,
      projectIdentifier,
      accountIdentifier: accountId
    },
    lazy: true,
    requestOptions: {
      headers: {
        'content-type': 'application/yaml'
      }
    }
  })
 
  const getInputSetSelected = (): InputSetValue[] => {
    if (inputSetType) {
      const inputSetSelected: InputSetValue[] = [
        {
          type: inputSetType as InputSetSummaryResponse['inputSetType'],
          value: inputSetValue ?? '',
          label: inputSetLabel ?? '',
          gitDetails: {
            repoIdentifier: inputSetRepoIdentifier,
            branch: inputSetBranch
          }
        }
      ]
      return inputSetSelected
    }
    return []
  }
 
  React.useEffect(() => {
    Iif (data) {
      ;(data as unknown as Response).text().then(str => {
        setInputSetYaml(str)
      })
    }
  }, [data])
 
  React.useEffect(() => {
    Iif (executionId && executionId !== null) {
      refetch()
    }
  }, [executionId])
 
  function onCloseRunPipelineModal(): void {
    closeRunPipelineModal()
    setInputSetYaml('')
    replaceQueryParams({ repoIdentifier: repoIdentifier, branch: branch }, { skipNulls: true }, true)
  }
 
  React.useEffect(() => {
    Iif (runPipeline) {
      openRunPipelineModal()
    }
  }, [runPipeline])
 
  const [openRunPipelineModal, closeRunPipelineModal] = useModalHook(
    () =>
      loading ? (
        <PageSpinner />
      ) : (
        <Dialog {...runModalProps}>
          <Layout.Vertical className={css.modalCard}>
            <RunPipelineForm
              pipelineIdentifier={pipelineIdentifier}
              orgIdentifier={orgIdentifier}
              projectIdentifier={projectIdentifier}
              accountId={accountId}
              module={module}
              inputSetYAML={inputSetYaml || ''}
              inputSetSelected={getInputSetSelected()}
              repoIdentifier={repoIdentifier}
              branch={branch}
              onClose={() => {
                onCloseRunPipelineModal()
              }}
              stagesExecuted={stagesExecuted}
            />
            <Button
              aria-label="close modal"
              icon="cross"
              variation={ButtonVariation.ICON}
              onClick={() => {
                onCloseRunPipelineModal()
              }}
              className={css.crossIcon}
            />
          </Layout.Vertical>
        </Dialog>
      ),
    [
      loading,
      inputSetYaml,
      inputSetRepoIdentifier,
      inputSetBranch,
      branch,
      repoIdentifier,
      inputSetType,
      inputSetValue,
      inputSetLabel,
      pipelineIdentifier
    ]
  )
 
  const onGitBranchChange = React.useMemo(
    () => (selectedFilter: GitFilterScope) => {
      setSelectedBranch(selectedFilter.branch as string)
      if (isUpdated && branch !== selectedFilter.branch) {
        setBlockNavigation(true)
      } else if (branch !== selectedFilter.branch) {
        deletePipelineCache({ repoIdentifier: selectedFilter.repo || '', branch: selectedFilter.branch || '' }).then(
          () => {
            history.push(
              routes.toPipelineStudio({
                projectIdentifier,
                orgIdentifier,
                pipelineIdentifier: pipelineIdentifier || '-1',
                accountId,
                module,
                branch: selectedFilter.branch,
                repoIdentifier: selectedFilter.repo
              })
            )
            location.reload()
          }
        )
      }
    },
    [repoIdentifier, branch, isUpdated, pipelineIdentifier]
  )
 
  if (isLoading) {
    return (
      <React.Fragment>
        <PageSpinner fixed />
        <div /> {/* this empty div is required for rendering layout correctly */}
      </React.Fragment>
    )
  }
 
  const getPipelineNameTextContainerWidth = (): number | undefined => {
    if (isGitSyncEnabled) {
      if (pipelineIdentifier === DefaultNewPipelineId) {
        Iif (!isEmpty(pipeline?.tags)) {
          return 150
        }
        return 175
      }
      Iif (!isEmpty(pipeline?.tags)) {
        return 125
      }
      return 155
    }
    return 400
  }
 
  if (templateError?.data && !isGitSyncEnabled) {
    return (
      <GenericErrorHandler
        errStatusCode={templateError?.status}
        errorMessage={(templateError?.data as Error)?.message}
      />
    )
  }
 
  Iif (templateError?.data && isEmpty(pipeline) && isGitSyncEnabled) {
    return <NoEntityFound identifier={pipelineIdentifier} entityType={'pipeline'} />
  }
 
  return (
    <PipelineVariablesContextProvider pipeline={pipeline}>
      <div
        className={cx(Classes.POPOVER_DISMISS, css.content)}
        onClick={e => {
          e.stopPropagation()
        }}
      >
        <NavigationCheck
          when={getOtherModal && pipeline.identifier !== ''}
          shouldBlockNavigation={nextLocation => {
            let localUpdated = isUpdated
            const matchDefault = matchPath(nextLocation.pathname, {
              path: toPipelineStudio({ ...accountPathProps, ...pipelinePathProps, ...pipelineModuleParams }),
              exact: true
            })
 
            // This is special handler when user update yaml and immediately click on run
            Iif (isYaml && yamlHandler && isYamlEditable && !localUpdated) {
              try {
                const parsedYaml = parse(yamlHandler.getLatestYaml())
                if (!parsedYaml) {
                  clear()
                  showError(getString('invalidYamlText'), undefined, 'pipeline.parse.yaml.error')
                  return true
                }
                if (yamlHandler.getYAMLValidationErrorMap()?.size > 0) {
                  setYamlError(true)
                  return true
                }
                localUpdated = !isEqual(omit(originalPipeline, 'repo', 'branch'), parsedYaml.pipeline)
                updatePipeline(parsedYaml.pipeline)
              } catch (e) {
                setYamlError(true)
                return true
              }
            }
            setYamlError(false)
            return (
              !matchDefault?.isExact &&
              localUpdated &&
              !isReadonly &&
              !(pipelineIdentifier === DefaultNewPipelineId && isEmpty(pipeline?.name))
            )
          }}
          textProps={{
            contentText: isYamlError ? getString('navigationYamlError') : getString('navigationCheckText'),
            titleText: isYamlError ? getString('navigationYamlErrorTitle') : getString('navigationCheckTitle')
          }}
          navigate={newPath => {
            const isPipeline = matchPath(newPath, {
              path: toPipelineStudio({ ...accountPathProps, ...pipelinePathProps, ...pipelineModuleParams }),
              exact: true
            })
            !isPipeline?.isExact && deletePipelineCache(gitDetails)
            history.push(newPath)
          }}
        />
        <div>
          <div className={css.titleBar}>
            <div className={css.breadcrumbsMenu}>
              <div className={css.pipelineMetadataContainer}>
                <Layout.Horizontal className={css.pipelineNameContainer}>
                  <Icon className={css.pipelineIcon} padding={{ right: 'small' }} name="pipeline" size={32} />
                  <Text
                    className={css.pipelineName}
                    style={{
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                      maxWidth: getPipelineNameTextContainerWidth()
                    }}
                    tooltip={pipeline?.name}
                  >
                    {pipeline?.name}
                  </Text>
                  {!isEmpty(pipeline?.tags) && pipeline.tags && (
                    <Container className={css.tagsContainer}>
                      <TagsPopover tags={pipeline.tags} />
                    </Container>
                  )}
                  {isGitSyncEnabled && (
                    <StudioGitPopover
                      gitDetails={gitDetails}
                      identifier={pipelineIdentifier}
                      isReadonly={isReadonly}
                      entityData={{ ...pipeline, versionLabel: '', type: 'Step' }} // Just to avoid type issues
                      onGitBranchChange={onGitBranchChange}
                      entityType={'Pipeline'}
                    />
                  )}
                  {isYaml || isReadonly ? null : (
                    <Button variation={ButtonVariation.ICON} icon="Edit" onClick={showModal} />
                  )}
                </Layout.Horizontal>
              </div>
            </div>
            <VisualYamlToggle
              className={css.visualYamlToggle}
              selectedView={isYaml || disableVisualView ? SelectedView.YAML : SelectedView.VISUAL}
              disableToggle={disableVisualView}
              onChange={nextMode => {
                handleViewChange(nextMode)
              }}
            />
            <div>
              <div className={css.savePublishContainer}>
                {isReadonly && (
                  <div className={css.readonlyAccessTag}>
                    <Icon name="eye-open" size={16} />
                    <div className={css.readonlyAccessText}>{getString('common.readonlyPermissions')}</div>
                  </div>
                )}
                {isUpdated && !isReadonly && <div className={css.tagRender}>{getString('unsavedChanges')}</div>}
                <SavePipelinePopover
                  toPipelineStudio={toPipelineStudio}
                  setGovernanceMetadata={setGovernanceMetadata}
                  isValidYaml={isValidYaml}
                />
                {pipelineIdentifier !== DefaultNewPipelineId && !isReadonly && (
                  <Button
                    disabled={!isUpdated}
                    onClick={() => {
                      updatePipelineView({ ...pipelineView, isYamlEditable: false })
                      fetchPipeline({ forceFetch: true, forceUpdate: true })
                    }}
                    className={css.discardBtn}
                    variation={ButtonVariation.SECONDARY}
                    text={getString('pipeline.discard')}
                  />
                )}
                <RbacButton
                  data-testid="card-run-pipeline"
                  variation={ButtonVariation.PRIMARY}
                  icon="run-pipeline"
                  intent="success"
                  disabled={isUpdated || entityValidityDetails?.valid === false}
                  className={css.runPipelineBtn}
                  text={getString('runPipelineText')}
                  tooltip={
                    entityValidityDetails?.valid === false
                      ? getString('pipeline.cannotRunInvalidPipeline')
                      : isUpdated
                      ? 'Please click Save and then run the pipeline.'
                      : ''
                  }
                  onClick={e => {
                    e.stopPropagation()
                    openRunPipelineModal()
                  }}
                  featuresProps={getFeaturePropsForRunPipelineButton({ modules: template?.data?.modules, getString })}
                  permission={{
                    resourceScope: {
                      accountIdentifier: accountId,
                      orgIdentifier,
                      projectIdentifier
                    },
                    resource: {
                      resourceType: ResourceType.PIPELINE,
                      resourceIdentifier: pipeline?.identifier as string
                    },
                    permission: PermissionIdentifier.EXECUTE_PIPELINE
                  }}
                />
              </div>
            </div>
          </div>
        </div>
        {isYaml ? <PipelineYamlView /> : pipeline.template ? <TemplatePipelineBuilder /> : <StageBuilder />}
        {shouldShowGovernanceEvaluation && (
          <EvaluationModal
            accountId={accountId}
            metadata={governanceMetadata}
            headingErrorMessage={getString('pipeline.policyEvaluations.failedToSavePipeline')}
          />
        )}
      </div>
      <RightBar />
    </PipelineVariablesContextProvider>
  )
}