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

95.24% Statements 160/168
87.92% Branches 211/240
83.87% Functions 26/31
95.18% Lines 158/166

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              3x 3x   3x 3x 3x                       3x 3x 3x     3x                               3x 3x             3x 3x 3x 3x   3x   3x 3x 3x 3x   3x 3x 3x 3x 3x           3x                         3x       1x                                         3x                 3x                         3x     3x             68x 68x 68x 68x 68x 68x           68x   68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 12x                             68x                   68x       68x                     68x                                 68x                       68x 12x 1x   11x 11x 11x 2x 2x                             9x                           68x   68x 12x 1x   11x       68x 12x 1x   11x       68x 12x 10x     68x 13x 36x 24x                   13x     68x 12x 6x 6x 6x 6x   6x 6x 6x       68x 12x     68x         68x       68x   5x 1x 1x   1x 1x 1x 1x 1x   5x         68x 5x 5x     68x         5x 5x 5x 5x                     5x                     3x   3x 2x       2x 2x       3x 2x     2x 2x 2x     2x 1x   1x     4x           68x           2x     68x   5x 5x 5x 5x 5x 5x 2x                     3x                                 68x 15x     68x 4x 4x             68x 68x                 68x                   68x 26x     68x 12x                             68x             2x                     5x                                     3x             80x                                                                                                         1x                                                                                                       2x   2x                                          
/*
 * 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, { useMemo } from 'react'
import { defaultTo, isNull, isUndefined, omit, omitBy } from 'lodash-es'
import type { MutateRequestOptions } from 'restful-react/dist/Mutate'
import { Classes, Dialog, IDialogProps } from '@blueprintjs/core'
import * as Yup from 'yup'
import {
  Button,
  ButtonVariation,
  Formik,
  FormikForm,
  Layout,
  Text,
  PageSpinner,
  VisualYamlSelectedView as SelectedView,
  VisualYamlToggle,
  Heading
} from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import { parse } from 'yaml'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import type { PipelineInfoConfig } from 'services/cd-ng'
 
import {
  OverlayInputSetResponse,
  useGetPipeline,
  Failure,
  useGetInputSetsListForPipeline,
  useGetOverlayInputSetForPipeline,
  useCreateOverlayInputSetForPipeline,
  useUpdateOverlayInputSetForPipeline,
  ResponseOverlayInputSetResponse,
  useGetSchemaYaml,
  EntityGitDetails,
  UpdateOverlayInputSetForPipelineQueryParams,
  UpdateOverlayInputSetForPipelinePathParams,
  CreateOverlayInputSetForPipelineQueryParams
} from 'services/pipeline-ng'
 
import { useToaster } from '@common/exports'
import { NameSchema } from '@common/utils/Validation'
import type {
  YamlBuilderHandlerBinding,
  YamlBuilderProps,
  InvocationMapFunction,
  CompletionItemInterface
} from '@common/interfaces/YAMLBuilderProps'
import YAMLBuilder from '@common/components/YAMLBuilder/YamlBuilder'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import { NameIdDescriptionTags } from '@common/components'
import { useStrings } from 'framework/strings'
import type { GitQueryParams } from '@common/interfaces/RouteInterfaces'
import { UseSaveSuccessResponse, useSaveToGitDialog } from '@common/modals/SaveToGitDialog/useSaveToGitDialog'
import type { SaveToGitFormInterface } from '@common/components/SaveToGitForm/SaveToGitForm'
import GitContextForm, { GitContextProps } from '@common/components/GitContextForm/GitContextForm'
import { useQueryParams } from '@common/hooks'
import { AppStoreContext } from 'framework/AppStore/AppStoreContext'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import type { CreateUpdateInputSetsReturnType, InputSetDTO } from '@pipeline/utils/types'
import { yamlStringify } from '@common/utils/YamlHelperMethods'
import { getOverlayErrors } from '@pipeline/utils/runPipelineUtils'
import { ErrorsStrip } from '../ErrorsStrip/ErrorsStrip'
import { InputSetSelector, InputSetSelectorProps } from '../InputSetSelector/InputSetSelector'
import {
  anyOneOf,
  constructInputSetYamlObject,
  getCreateUpdateRequestBodyOptions,
  getInputSetReference
} from './OverlayInputSetUtils'
import css from './OverlayInputSetForm.module.scss'
 
export interface OverlayInputSetDTO extends Omit<OverlayInputSetResponse, 'identifier'> {
  pipeline?: PipelineInfoConfig
  identifier?: string
  repo?: string
  branch?: string
}
 
interface SaveOverlayInputSetDTO {
  overlayInputSet: OverlayInputSetDTO
}
 
const getDefaultInputSet = (
  orgIdentifier: string,
  projectIdentifier: string,
  pipelineIdentifier: string
): OverlayInputSetDTO => ({
  name: undefined,
  identifier: '',
  description: undefined,
  orgIdentifier,
  projectIdentifier,
  pipelineIdentifier,
  inputSetReferences: [],
  tags: {},
  repo: '',
  branch: ''
})
 
export interface OverlayInputSetFormProps {
  hideForm: () => void
  identifier?: string
  isReadOnly?: boolean
  overlayInputSetRepoIdentifier?: string
  overlayInputSetBranch?: string
}
 
const dialogProps: Omit<IDialogProps, 'isOpen'> = {
  usePortal: true,
  autoFocus: true,
  canEscapeKeyClose: true,
  canOutsideClickClose: true,
  enforceFocus: false,
  style: { minWidth: 700 }
}
 
const yamlBuilderReadOnlyModeProps: YamlBuilderProps = {
  fileName: `overlay-input-set.yaml`,
  entityType: 'Pipelines',
  width: 620,
  height: 360,
  showSnippetSection: false,
  yamlSanityConfig: {
    removeEmptyString: false,
    removeEmptyObject: false,
    removeEmptyArray: false
  }
}
 
const clearNullUndefined = /* istanbul ignore next */ (data: OverlayInputSetDTO): OverlayInputSetDTO =>
  omitBy(omitBy(data, isUndefined), isNull)
 
export function OverlayInputSetForm({
  hideForm,
  identifier,
  isReadOnly = false,
  overlayInputSetRepoIdentifier,
  overlayInputSetBranch
}: OverlayInputSetFormProps): React.ReactElement {
  const { getString } = useStrings()
  const [isOpen, setIsOpen] = React.useState(true)
  const [isEdit, setIsEdit] = React.useState(false)
  const [savedInputSetObj, setSavedInputSetObj] = React.useState<OverlayInputSetDTO>({})
  const { isGitSyncEnabled } = React.useContext(AppStoreContext)
  const { projectIdentifier, orgIdentifier, accountId, pipelineIdentifier } = useParams<{
    projectIdentifier: string
    orgIdentifier: string
    accountId: string
    pipelineIdentifier: string
  }>()
  const { repoIdentifier, branch } = useQueryParams<GitQueryParams>()
 
  const [initialGitDetails, setInitialGitDetails] = React.useState<EntityGitDetails>({ repoIdentifier, branch })
  const [selectedView, setSelectedView] = React.useState<SelectedView>(SelectedView.VISUAL)
  const [yamlHandler, setYamlHandler] = React.useState<YamlBuilderHandlerBinding | undefined>()
  const [selectedRepo, setSelectedRepo] = React.useState<string>(overlayInputSetRepoIdentifier || repoIdentifier || '')
  const [selectedBranch, setSelectedBranch] = React.useState<string>(overlayInputSetBranch || branch || '')
  const [selectedInputSets, setSelectedInputSets] = React.useState<InputSetSelectorProps['value']>()
  const { showSuccess, showError, clear } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const [formErrors, setFormErrors] = React.useState<Record<string, any>>({})
  const commonQueryParams = useMemo(() => {
    return {
      accountIdentifier: accountId,
      orgIdentifier,
      pipelineIdentifier,
      projectIdentifier,
      repoIdentifier,
      branch
    }
  }, [accountId, orgIdentifier, pipelineIdentifier, projectIdentifier, repoIdentifier, branch])
 
  const {
    data: overlayInputSetResponse,
    refetch: refetchOverlay,
    loading: loadingOverlayInputSet,
    error: errorOverlayInputSet
  } = useGetOverlayInputSetForPipeline({
    queryParams: {
      ...commonQueryParams,
      repoIdentifier: overlayInputSetRepoIdentifier,
      branch: overlayInputSetBranch
    },
    inputSetIdentifier: defaultTo(identifier, ''),
    lazy: true
  })
 
  const { mutate: createOverlayInputSet, loading: createOverlayInputSetLoading } = useCreateOverlayInputSetForPipeline({
    queryParams: commonQueryParams,
    requestOptions: { headers: { 'content-type': 'application/yaml' } }
  })
  const { mutate: updateOverlayInputSet, loading: updateOverlayInputSetLoading } = useUpdateOverlayInputSetForPipeline({
    queryParams: commonQueryParams,
    inputSetIdentifier: '',
    requestOptions: { headers: { 'content-type': 'application/yaml' } }
  })
 
  const {
    data: inputSetList,
    refetch: refetchInputSetList,
    loading: loadingInputSetList,
    error: errorInputSetList
  } = useGetInputSetsListForPipeline({
    queryParams: {
      ...commonQueryParams,
      inputSetType: 'INPUT_SET',
      repoIdentifier: selectedRepo,
      branch: selectedBranch,
      getDefaultFromOtherRepo: true
    },
    debounce: 300,
    lazy: true
  })
 
  const {
    data: pipeline,
    loading: loadingPipeline,
    refetch: refetchPipeline,
    error: errorPipeline
  } = useGetPipeline({
    pipelineIdentifier,
    lazy: true,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      repoIdentifier,
      branch
    }
  })
 
  const inputSet = React.useMemo(() => {
    if (!overlayInputSetResponse?.data) {
      return getDefaultInputSet(orgIdentifier, projectIdentifier, pipelineIdentifier)
    }
    const inputSetObj = overlayInputSetResponse.data
    const parsedInputSetObj = parse(defaultTo(inputSetObj?.overlayInputSetYaml, ''))
    if (isGitSyncEnabled && parsedInputSetObj?.overlayInputSet) {
      const parsedOverlayInputSet = parsedInputSetObj.overlayInputSet as OverlayInputSetDTO
      return {
        name: parsedOverlayInputSet.name as string,
        tags: parsedOverlayInputSet.tags as {
          [key: string]: string
        },
        identifier: parsedOverlayInputSet.identifier as string,
        description: parsedOverlayInputSet.description as string,
        orgIdentifier: parsedOverlayInputSet.orgIdentifier as string,
        projectIdentifier: parsedOverlayInputSet.projectIdentifier as string,
        pipelineIdentifier: parsedOverlayInputSet.pipelineIdentifier as string,
        inputSetReferences: defaultTo(parsedOverlayInputSet.inputSetReferences, []),
        gitDetails: defaultTo(inputSetObj.gitDetails, {}),
        entityValidityDetails: defaultTo(inputSetObj.entityValidityDetails, {})
      }
    }
    return {
      name: inputSetObj.name,
      tags: inputSetObj.tags,
      identifier: inputSetObj.identifier,
      description: inputSetObj.description,
      orgIdentifier,
      projectIdentifier,
      pipelineIdentifier,
      inputSetReferences: defaultTo(inputSetObj?.inputSetReferences, []),
      gitDetails: defaultTo(inputSetObj.gitDetails, {}),
      entityValidityDetails: defaultTo(inputSetObj.entityValidityDetails, {})
    }
  }, [overlayInputSetResponse?.data, isGitSyncEnabled])
 
  const [disableVisualView, setDisableVisualView] = React.useState(inputSet.entityValidityDetails?.valid === false)
 
  React.useEffect(() => {
    if (inputSet.entityValidityDetails?.valid === false || selectedView === SelectedView.YAML) {
      setSelectedView(SelectedView.YAML)
    } else {
      setSelectedView(SelectedView.VISUAL)
    }
  }, [inputSet, inputSet.entityValidityDetails?.valid])
 
  React.useEffect(() => {
    if (inputSet.entityValidityDetails?.valid === false) {
      setDisableVisualView(true)
    } else {
      setDisableVisualView(false)
    }
  }, [inputSet.entityValidityDetails?.valid])
 
  const inputSetListYaml: CompletionItemInterface[] = React.useMemo(() => {
    if (!inputSetList?.data?.content) return []
    return inputSetList.data.content.map(constructInputSetYamlObject)
  }, [inputSetList?.data?.content])
 
  React.useEffect(() => {
    const inputSetsToSelect = inputSet.inputSetReferences?.map(inputSetRef => {
      const foundInputSet = inputSetList?.data?.content?.find(currInputSet => currInputSet.identifier === inputSetRef)
      return {
        ...foundInputSet,
        label: defaultTo(foundInputSet?.name, ''),
        value: defaultTo(foundInputSet?.identifier, ''),
        type: foundInputSet?.inputSetType,
        gitDetails: defaultTo(foundInputSet?.gitDetails, {}),
        inputSetErrorDetails: foundInputSet?.inputSetErrorDetails,
        overlaySetErrorDetails: foundInputSet?.overlaySetErrorDetails
      }
    })
    setSelectedInputSets(inputSetsToSelect)
  }, [inputSetList?.data?.content, inputSet.inputSetReferences])
 
  React.useEffect(() => {
    if (identifier) {
      setIsEdit(true)
      refetchPipeline()
      refetchInputSetList()
      refetchOverlay({ pathParams: { inputSetIdentifier: identifier } })
    } else {
      refetchPipeline()
      refetchInputSetList()
      setIsEdit(false)
    }
  }, [identifier])
 
  React.useEffect(() => {
    refetchInputSetList()
  }, [selectedRepo, selectedBranch])
 
  const onRepoChange = (gitDetails: EntityGitDetails) => {
    setSelectedRepo(defaultTo(gitDetails.repoIdentifier, ''))
    setSelectedBranch(defaultTo(gitDetails.branch, ''))
  }
 
  const onBranchChange = (gitDetails: EntityGitDetails) => {
    setSelectedBranch(defaultTo(gitDetails.branch, ''))
  }
 
  const handleModeSwitch = React.useCallback(
    (view: SelectedView) => {
      if (view === SelectedView.VISUAL) {
        const yaml = defaultTo(yamlHandler?.getLatestYaml(), '')
        const inputSetYamlVisual = parse(yaml).overlayInputSet as OverlayInputSetDTO
 
        inputSet.name = inputSetYamlVisual.name
        inputSet.identifier = inputSetYamlVisual.identifier
        inputSet.description = inputSetYamlVisual.description
        inputSet.pipeline = inputSetYamlVisual.pipeline
        inputSet.inputSetReferences = inputSetYamlVisual.inputSetReferences
      }
      setSelectedView(view)
    },
    [yamlHandler?.getLatestYaml, inputSet]
  )
 
  const closeForm = React.useCallback(() => {
    setIsOpen(false)
    hideForm()
  }, [hideForm])
 
  const createUpdateOverlayInputSet = async (
    inputSetObj: InputSetDTO,
    gitDetails?: SaveToGitFormInterface,
    objectId = ''
  ): CreateUpdateInputSetsReturnType => {
    let response: ResponseOverlayInputSetResponse | null = null
    try {
      const requestData = yamlStringify({ overlayInputSet: clearNullUndefined(inputSetObj) }) as any
      const requestOptions = getCreateUpdateRequestBodyOptions({
        isEdit,
        initialGitDetails,
        inputSetObj,
        orgIdentifier,
        accountId,
        projectIdentifier,
        pipelineIdentifier,
        gitDetails,
        objectId
      })
      response = isEdit
        ? await updateOverlayInputSet(requestData, {
            ...(requestOptions as MutateRequestOptions<
              UpdateOverlayInputSetForPipelineQueryParams,
              UpdateOverlayInputSetForPipelinePathParams
            >)
          })
        : await createOverlayInputSet(requestData, {
            ...(requestOptions as MutateRequestOptions<CreateOverlayInputSetForPipelineQueryParams, void>)
          })
 
      Eif (response) {
        // This is done because when git sync is enabled, errors are displayed in a modal
        if (!isGitSyncEnabled) {
          Iif (response.data?.errorResponse) {
            clear()
            showError(getString('inputSets.overlayInputSetSavedError'), undefined, 'pipeline.overlayinputset.error')
          } else {
            clear()
            showSuccess(getString('inputSets.overlayInputSetSaved'))
          }
        }
      }
      if (!isGitSyncEnabled) {
        closeForm()
      }
    } catch (e) {
      const invaliderrors = getOverlayErrors(e?.data?.metadata?.invalidReferences)
      Eif (Object.keys(invaliderrors).length) {
        setFormErrors(invaliderrors)
      }
      // This is done because when git sync is enabled, errors are displayed in a modal
      if (!isGitSyncEnabled) {
        showError(getRBACErrorMessage(e), undefined, 'pipeline.common.error')
      } else {
        throw e
      }
    }
    return {
      status: response?.status,
      nextCallback: () => closeForm()
    }
  }
 
  const { openSaveToGitDialog } = useSaveToGitDialog<SaveOverlayInputSetDTO>({
    onSuccess: (
      gitData: SaveToGitFormInterface,
      payload?: SaveOverlayInputSetDTO,
      objectId?: string
    ): Promise<UseSaveSuccessResponse> =>
      createUpdateOverlayInputSet(defaultTo(payload?.overlayInputSet, savedInputSetObj), gitData, objectId)
  })
 
  const handleSubmit = React.useCallback(
    async (inputSetObjWithGitInfo: OverlayInputSetDTO, gitDetails?: EntityGitDetails) => {
      const inputSetObj = omit(inputSetObjWithGitInfo, 'repo', 'branch')
      setSavedInputSetObj(inputSetObj)
      setInitialGitDetails(gitDetails as EntityGitDetails)
      Eif (inputSetObj) {
        delete inputSetObj.pipeline
        if (isGitSyncEnabled) {
          openSaveToGitDialog({
            isEditing: isEdit,
            resource: {
              type: 'InputSets',
              name: inputSetObj.name as string,
              identifier: inputSetObj.identifier as string,
              gitDetails: isEdit ? overlayInputSetResponse?.data?.gitDetails : gitDetails
            },
            payload: { overlayInputSet: inputSetObj }
          })
        } else {
          createUpdateOverlayInputSet(inputSetObj)
        }
      }
    },
    [
      isEdit,
      showSuccess,
      closeForm,
      showError,
      createOverlayInputSet,
      updateOverlayInputSet,
      isGitSyncEnabled,
      overlayInputSetResponse,
      pipeline
    ]
  )
 
  const hasAnyApiError = useMemo(() => {
    return anyOneOf([errorPipeline, errorOverlayInputSet, errorInputSetList])
  }, [errorPipeline, errorOverlayInputSet, errorInputSetList])
 
  if (hasAnyApiError) {
    clear()
    showError(
      defaultTo((hasAnyApiError.data as Failure)?.message, getString('commonError')),
      undefined,
      'pipeline.common.error'
    )
  }
 
  const invocationMap: YamlBuilderProps['invocationMap'] = new Map<RegExp, InvocationMapFunction>()
  invocationMap.set(
    /^.+\.inputSetReferences$/,
    (_matchingPath: string, _currentYaml: string): Promise<CompletionItemInterface[]> => {
      return new Promise(resolve => {
        resolve(inputSetListYaml)
      })
    }
  )
 
  const { loading, data: pipelineSchema } = useGetSchemaYaml({
    queryParams: {
      entityType: 'Pipelines',
      projectIdentifier,
      orgIdentifier,
      accountIdentifier: accountId,
      scope: getScopeFromDTO({ accountIdentifier: accountId, orgIdentifier, projectIdentifier })
    }
  })
 
  const selectedInputSetReferences: string[] | undefined = React.useMemo(() => {
    return selectedInputSets?.map(getInputSetReference)
  }, [selectedInputSets])
 
  const anyApiLoading = useMemo(() => {
    return anyOneOf([
      loadingPipeline,
      createOverlayInputSetLoading,
      updateOverlayInputSetLoading,
      loadingInputSetList,
      loadingOverlayInputSet
    ])
  }, [
    loadingPipeline,
    createOverlayInputSetLoading,
    updateOverlayInputSetLoading,
    loadingInputSetList,
    loadingOverlayInputSet
  ])
 
  return (
    <Dialog
      title={
        isEdit
          ? getString('inputSets.editOverlayTitle', { name: inputSet.name })
          : getString('inputSets.newOverlayInputSet')
      }
      onClose={() => closeForm()}
      isOpen={isOpen}
      {...dialogProps}
    >
      {anyApiLoading && <PageSpinner />}
      <div className={Classes.DIALOG_BODY}>
        <Layout.Vertical spacing="medium">
          <div className={css.optionBtns}>
            <VisualYamlToggle
              selectedView={selectedView}
              onChange={nextMode => {
                handleModeSwitch(nextMode)
              }}
              disableToggle={disableVisualView}
            />
          </div>
 
          <Formik<OverlayInputSetDTO & GitContextProps>
            initialValues={{
              ...omit(inputSet, 'gitDetails', 'entityValidityDetails'),
              repo: defaultTo(repoIdentifier, ''),
              branch: defaultTo(branch, '')
            }}
            formName="overlayInputSet"
            enableReinitialize={true}
            validationSchema={Yup.object().shape({
              name: NameSchema({ requiredErrorMsg: getString('common.validation.nameIsRequired') }),
              inputSetReferences: Yup.array().of(Yup.string().required(getString('inputSets.inputSetIsRequired')))
            })}
            onSubmit={values => {
              handleSubmit(
                { ...values, inputSetReferences: selectedInputSetReferences },
                { repoIdentifier: values.repo, branch: values.branch }
              )
            }}
          >
            {formikProps => {
              return (
                <>
                  {selectedView === SelectedView.VISUAL ? (
                    <>
                      <ErrorsStrip formErrors={formErrors} />
                      <FormikForm>
                        <div className={css.inputSetForm}>
                          <NameIdDescriptionTags
                            className={css.inputSetName}
                            identifierProps={{
                              inputLabel: getString('name'),
                              isIdentifierEditable: !isEdit && !isReadOnly,
                              inputGroupProps: {
                                disabled: isReadOnly
                              }
                            }}
                            descriptionProps={{ disabled: isReadOnly }}
                            tagsProps={{
                              disabled: isReadOnly
                            }}
                            formikProps={formikProps}
                          />
                          {isGitSyncEnabled && (
                            <GitSyncStoreProvider>
                              <GitContextForm
                                formikProps={formikProps}
                                gitDetails={
                                  isEdit
                                    ? { ...overlayInputSetResponse?.data?.gitDetails, getDefaultFromOtherRepo: false }
                                    : {
                                        repoIdentifier,
                                        branch,
                                        getDefaultFromOtherRepo: true
                                      }
                                }
                                onRepoChange={onRepoChange}
                                onBranchChange={onBranchChange}
                              />
                            </GitSyncStoreProvider>
                          )}
                          <Layout.Vertical padding={{ top: 'large', bottom: 'xxxlarge' }} spacing="small">
                            <Heading level={5}>{getString('inputSets.selectInputSets')}</Heading>
                            <Text
                              icon="info-sign"
                              iconProps={{ intent: 'primary', size: 16, padding: { left: 0, right: 'small' } }}
                            >
                              {getString('inputSets.selectInputSetsHelp')}
                            </Text>
                            {inputSet && (
                              <GitSyncStoreProvider>
                                <InputSetSelector
                                  pipelineIdentifier={pipelineIdentifier}
                                  onChange={inputsets => {
                                    setSelectedInputSets(inputsets)
                                  }}
                                  value={selectedInputSets}
                                  selectedRepo={selectedRepo}
                                  selectedBranch={selectedBranch}
                                  isOverlayInputSet={true}
                                  selectedValueClass={css.selectedInputSetsContainer}
                                />
                              </GitSyncStoreProvider>
                            )}
                          </Layout.Vertical>
                        </div>
                        <Layout.Horizontal padding={{ top: 'medium' }}>
                          <Button
                            variation={ButtonVariation.PRIMARY}
                            type="submit"
                            text={getString('save')}
                            disabled={isReadOnly}
                          />
                          &nbsp; &nbsp;
                          <Button variation={ButtonVariation.TERTIARY} onClick={closeForm} text={getString('cancel')} />
                        </Layout.Horizontal>
                      </FormikForm>
                    </>
                  ) : (
                    <div className={css.editor}>
                      <ErrorsStrip formErrors={formErrors} />
                      {loading ? (
                        <PageSpinner />
                      ) : (
                        <YAMLBuilder
                          {...yamlBuilderReadOnlyModeProps}
                          existingJSON={{
                            overlayInputSet: {
                              ...omit(formikProps?.values, 'pipeline', 'repo', 'branch'),
                              inputSetReferences: selectedInputSetReferences
                            }
                          }}
                          invocationMap={invocationMap}
                          bind={setYamlHandler}
                          schema={pipelineSchema?.data}
                          isReadOnlyMode={isReadOnly}
                          showSnippetSection={false}
                          isEditModeSupported={!isReadOnly}
                        />
                      )}
                      <Layout.Horizontal padding={{ top: 'medium' }}>
                        <Button
                          variation={ButtonVariation.PRIMARY}
                          type="submit"
                          text={getString('save')}
                          onClick={() => {
                            const latestYaml = defaultTo(yamlHandler?.getLatestYaml(), '')
 
                            handleSubmit(parse(latestYaml)?.overlayInputSet, {
                              repoIdentifier: formikProps.values.repo,
                              branch: formikProps.values.branch
                            })
                          }}
                          disabled={isReadOnly}
                        />
                        &nbsp; &nbsp;
                        <Button variation={ButtonVariation.TERTIARY} onClick={closeForm} text={getString('cancel')} />
                      </Layout.Horizontal>
                    </div>
                  )}
                </>
              )
            }}
          </Formik>
        </Layout.Vertical>
      </div>
    </Dialog>
  )
}