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

67.21% Statements 207/308
48.32% Branches 518/1072
62.5% Functions 25/40
67.91% Lines 201/296

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              23x 23x 23x 23x 23x 23x 23x 23x             23x 23x               23x 23x 23x 23x 23x 23x     23x 23x 23x   23x           23x 23x 23x 23x 23x 23x   23x 23x 23x 23x   23x   23x                   23x         8x 8x 6x 6x 6x 12x       6x             8x     23x           2x 2x             2x                     2x   2x     2x         23x 3x 3x 3x 3x 3x 3x       23x         3x   3x     3x               3x         3x 3x   3x   3x             3x     3x 3x         23x                 3x   3x 2x 2x 2x 2x       2x   2x       2x 2x     2x 1x                                           23x                   3x 3x   3x 3x                         23x                 5x     5x 5x     5x             5x 5x         5x                                                 23x                               3x 3x 3x     3x         3x       3x 1x 1x     2x 1x 1x 1x     1x         1x 1x     23x                                 61x 59x 59x 59x   59x 59x   59x     59x 59x 59x 59x 59x 59x 59x 59x 59x 59x       59x 1x             1x     59x 10x     10x 10x             5x         49x     59x 33x   6x   6x 6x 6x 6x   6x     6x       6x                                     6x                     59x 2x 2x 1x             1x     1x       1x 1x   1x         1x 1x 1x 1x 1x   1x     1x 1x 1x 1x 1x 1x       1x   1x 1x     1x             59x                         59x   59x 2x 2x 1x 1x               1x     1x             1x 1x               1x 1x   1x                                   1x   1x     59x                                 59x                                                                     59x                   59x 2x                 59x 3x                                   59x                                                                     2x                                                                                                                                                       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, { SyntheticEvent } from 'react'
import { Drawer, Intent, Position } from '@blueprintjs/core'
import { Button, useConfirmationDialog } from '@wings-software/uicore'
import { cloneDeep, defaultTo, get, isEmpty, isEqual, isNil, set } from 'lodash-es'
import cx from 'classnames'
import produce from 'immer'
import { parse } from 'yaml'
import { useStrings, UseStringsReturn } from 'framework/strings'
import type {
  ExecutionElementConfig,
  StepElementConfig,
  StepGroupElementConfig,
  StageElementConfig
} from 'services/cd-ng'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { StepActions } from '@common/constants/TrackingConstants'
import type { StageType } from '@pipeline/utils/stageHelpers'
import type {
  BuildStageElementConfig,
  DeploymentStageElementConfig,
  StageElementWrapper
} from '@pipeline/utils/pipelineTypes'
import type { DependencyElement } from 'services/ci'
import { usePipelineVariables } from '@pipeline/components/PipelineVariablesContext/PipelineVariablesContext'
import { PipelineGovernanceView } from '@governance/PipelineGovernanceView'
import { getStepPaletteModuleInfosFromStage } from '@pipeline/utils/stepUtils'
import { getIdentifierFromValue } from '@common/components/EntityReference/EntityReference'
import { useTemplateSelector } from '@pipeline/utils/useTemplateSelector'
import { createTemplate } from '@pipeline/utils/templateUtils'
import type { TemplateStepNode } from 'services/pipeline-ng'
import type { StringsMap } from 'stringTypes'
import { usePipelineContext } from '../PipelineContext/PipelineContext'
import { DrawerData, DrawerSizes, DrawerTypes, PipelineViewData } from '../PipelineContext/PipelineActions'
import { StepCommandsWithRef as StepCommands, StepFormikRef } from '../StepCommands/StepCommands'
 
import {
  StepCommandsViews,
  StepOrStepGroupOrTemplateStepData,
  TabTypes,
  Values
} from '../StepCommands/StepCommandTypes'
import { StepPalette } from '../StepPalette/StepPalette'
import { addService, addStepOrGroup, generateRandomString, getStepFromId } from '../ExecutionGraph/ExecutionGraphUtil'
import PipelineVariables, { PipelineVariablesRef } from '../PipelineVariables/PipelineVariables'
import { PipelineNotifications, PipelineNotificationsRef } from '../PipelineNotifications/PipelineNotifications'
import { PipelineTemplates } from '../PipelineTemplates/PipelineTemplates'
import { ExecutionStrategy, ExecutionStrategyRefInterface } from '../ExecutionStrategy/ExecutionStrategy'
import type { StepData } from '../../AbstractSteps/AbstractStepFactory'
import { StepType } from '../../PipelineSteps/PipelineStepInterface'
import { FlowControlWithRef as FlowControl, FlowControlRef } from '../FlowControl/FlowControl'
import { AdvancedOptions } from '../AdvancedOptions/AdvancedOptions'
import { RightDrawerTitle } from './RightDrawerTitle'
 
import css from './RightDrawer.module.scss'
 
export const FullscreenDrawers: DrawerTypes[] = [
  DrawerTypes.PipelineVariables,
  DrawerTypes.PipelineNotifications,
  DrawerTypes.FlowControl,
  DrawerTypes.AdvancedOptions,
  DrawerTypes.PolicySets
]
 
type TrackEvent = (eventName: string, properties: Record<string, string>) => void
 
const checkDuplicateStep = (
  formikRef: React.MutableRefObject<StepFormikRef | null>,
  data: DrawerData['data'],
  getString: UseStringsReturn['getString']
): boolean => {
  const values = formikRef.current?.getValues() as Values
  if (values && data?.stepConfig?.stepsMap && formikRef.current?.setFieldError) {
    const stepsMap = data.stepConfig.stepsMap
    let duplicate = false
    stepsMap.forEach((_step, key) => {
      Iif (key === values.identifier && values.identifier !== data?.stepConfig?.node?.identifier) {
        duplicate = true
      }
    })
    Iif (duplicate) {
      setTimeout(() => {
        formikRef.current?.setFieldError('identifier', getString('pipelineSteps.duplicateStep'))
      }, 300)
      return true
    }
  }
  return false
}
 
export const updateStepWithinStage = (
  execution: ExecutionElementConfig,
  processingNodeIdentifier: string,
  processedNode: StepElementConfig
): void => {
  // Finds the step in the stage, and updates with the processed node
  execution?.steps?.forEach(stepWithinStage => {
    Iif (stepWithinStage.stepGroup) {
      // If stage has a step group, loop over the step group steps and update the matching identifier with node
      if (stepWithinStage.stepGroup?.identifier === processingNodeIdentifier) {
        stepWithinStage.stepGroup = processedNode as any
      } else {
        updateStepWithinStage(stepWithinStage.stepGroup, processingNodeIdentifier, processedNode)
      }
    } else Iif (stepWithinStage.parallel) {
      // If stage has a parallel steps, loop over and update the matching identifier with node
      stepWithinStage.parallel.forEach(parallelStep => {
        if (parallelStep?.stepGroup?.identifier === processingNodeIdentifier) {
          parallelStep.stepGroup = processedNode as any
        } else if (parallelStep.step?.identifier === processingNodeIdentifier) {
          parallelStep.step = processedNode as any
        } else if (parallelStep?.stepGroup) {
          updateStepWithinStage(parallelStep?.stepGroup, processingNodeIdentifier, processedNode)
        }
      })
    } else Eif (stepWithinStage.step?.identifier === processingNodeIdentifier) {
      // Else simply find the matching step ad update the node
      stepWithinStage.step = processedNode as any
    }
  })
  Iif (execution?.rollbackSteps) {
    updateStepWithinStage({ steps: execution.rollbackSteps }, processingNodeIdentifier, processedNode)
  }
}
 
const addReplace = (item: Partial<Values>, node: any): void => {
  Eif (item.name && item.tab !== TabTypes.Advanced) node.name = item.name
  Eif (item.identifier && item.tab !== TabTypes.Advanced) node.identifier = item.identifier
  Eif ((item as StepElementConfig).description && item.tab !== TabTypes.Advanced)
    node.description = (item as StepElementConfig).description
  Iif (item.when && item.tab === TabTypes.Advanced) node.when = item.when
  Iif ((item as StepElementConfig).timeout && item.tab !== TabTypes.Advanced)
    node.timeout = (item as StepElementConfig).timeout
}
 
const processNodeImpl = (
  item: Partial<Values>,
  data: any,
  trackEvent: TrackEvent
): StepElementConfig & TemplateStepNode => {
  return produce(data.stepConfig.node as StepElementConfig & TemplateStepNode, node => {
    // Add/replace values only if they are presented
    addReplace(item, node)
 
    // default strategies can be present without having the need to click on Advanced Tab. For eg. in CV step.
    Iif (Array.isArray(item.failureStrategies)) {
      node.failureStrategies = item.failureStrategies
      const telemetryData = item.failureStrategies.map(strategy => ({
        onError: strategy.onFailure?.errors?.join(', '),
        action: strategy.onFailure?.action?.type
      }))
      telemetryData.length && trackEvent(StepActions.AddEditFailureStrategy, { data: JSON.stringify(telemetryData) })
    }
    Iif (item.delegateSelectors && item.tab === TabTypes.Advanced) {
      set(node, 'spec.delegateSelectors', item.delegateSelectors)
    }
 
    // Delete values if they were already added and now removed
    Iif (node.timeout && !(item as StepElementConfig).timeout && item.tab !== TabTypes.Advanced) delete node.timeout
    Iif (node.description && !(item as StepElementConfig).description && item.tab !== TabTypes.Advanced)
      delete node.description
    Iif (node.failureStrategies && !item.failureStrategies && item.tab === TabTypes.Advanced)
      delete node.failureStrategies
    Iif (
      node.spec?.delegateSelectors &&
      (!item.delegateSelectors || item.delegateSelectors?.length === 0) &&
      item.tab === TabTypes.Advanced
    ) {
      delete node.spec.delegateSelectors
    }
    Iif (item.template) {
      node.template = item.template
    }
    Eif ((item as StepElementConfig).spec && item.tab !== TabTypes.Advanced) {
      node.spec = { ...(item as StepElementConfig).spec }
    }
  })
}
 
const updateWithNodeIdentifier = async (
  selectedStage: StageElementWrapper<StageElementConfig> | undefined,
  drawerType: DrawerTypes,
  processNode: StepElementConfig & TemplateStepNode,
  updatePipelineView: (data: PipelineViewData) => void,
  updateStage: (stage: StageElementConfig) => Promise<void>,
  data: any,
  pipelineView: PipelineViewData
): Promise<void> => {
  const provisioner = (selectedStage?.stage as DeploymentStageElementConfig)?.spec?.infrastructure
    ?.infrastructureDefinition?.provisioner
  if (drawerType === DrawerTypes.StepConfig && selectedStage?.stage?.spec?.execution) {
    const processingNodeIdentifier = data?.stepConfig?.node?.identifier
    const stageData = produce(selectedStage, draft => {
      Eif (draft.stage?.spec?.execution) {
        updateStepWithinStage(draft.stage.spec.execution, processingNodeIdentifier, processNode)
      }
    })
    // update view data before updating pipeline because its async
    updatePipelineView(
      produce(pipelineView, draft => {
        set(draft, 'drawerData.data.stepConfig.node', processNode)
      })
    )
 
    Eif (stageData.stage) {
      await updateStage(stageData.stage)
    }
 
    data?.stepConfig?.onUpdate?.(processNode)
  } else Iif (drawerType === DrawerTypes.ProvisionerStepConfig && provisioner) {
    const processingNodeIdentifier = data?.stepConfig?.node?.identifier
    const stageData = produce(selectedStage, draft => {
      const provisionerInternal = (draft?.stage as DeploymentStageElementConfig)?.spec?.infrastructure
        ?.infrastructureDefinition?.provisioner
      if (provisionerInternal) {
        updateStepWithinStage(provisionerInternal, processingNodeIdentifier, processNode)
      }
    })
    // update view data before updating pipeline because its async
    updatePipelineView(
      produce(pipelineView, draft => {
        set(draft, 'drawerData.data.stepConfig.node', processNode)
      })
    )
    if (stageData?.stage) {
      await updateStage(stageData.stage)
    }
    data?.stepConfig?.onUpdate?.(processNode)
  }
}
 
const onSubmitStep = async (
  item: Partial<Values>,
  drawerType: DrawerTypes,
  data: any,
  trackEvent: TrackEvent,
  selectedStage: StageElementWrapper<StageElementConfig> | undefined,
  updatePipelineView: (data: PipelineViewData) => void,
  updateStage: (stage: StageElementConfig) => Promise<void>,
  pipelineView: PipelineViewData
): Promise<void> => {
  Eif (data?.stepConfig?.node) {
    const processNode = processNodeImpl(item, data, trackEvent)
 
    Eif (data?.stepConfig?.node?.identifier) {
      updateWithNodeIdentifier(
        selectedStage,
        drawerType,
        processNode,
        updatePipelineView,
        updateStage,
        data,
        pipelineView
      )
    }
  }
}
 
const applyChanges = async (
  formikRef: React.MutableRefObject<StepFormikRef<unknown> | null>,
  data: any,
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string,
  updatePipelineView: (data: PipelineViewData) => void,
  pipelineView: PipelineViewData,
  setSelectedStepId: (selectedStepId: string | undefined) => void,
  trackEvent: TrackEvent
): Promise<void> => {
  Iif (checkDuplicateStep(formikRef, data, getString)) {
    return
  }
  await formikRef?.current?.submitForm()
  Iif (!isEmpty(formikRef.current?.getErrors())) {
    return
  } else {
    updatePipelineView({
      ...pipelineView,
      isDrawerOpened: false,
      drawerData: {
        type: DrawerTypes.AddStep
      }
    })
    setSelectedStepId(undefined)
    Iif (data?.stepConfig?.isStepGroup) {
      trackEvent(StepActions.AddEditStepGroup, {
        name: defaultTo((formikRef?.current?.getValues?.() as Values).name, '')
      })
    } else {
      trackEvent(StepActions.AddEditStep, {
        name: defaultTo(data?.stepConfig?.node?.name, ''),
        type: defaultTo((data?.stepConfig?.node as StepElementConfig)?.type, '')
      })
    }
  }
}
 
export interface CloseDrawerArgs {
  e?: SyntheticEvent<Element, Event> | undefined
  formikRef: React.MutableRefObject<StepFormikRef | null>
  data: any
  getString: (key: keyof StringsMap, vars?: Record<string, any> | undefined) => string
  openConfirmBEUpdateError: () => void
  updatePipelineView: (data: PipelineViewData) => void
  pipelineView: PipelineViewData
  setSelectedStepId: (selectedStepId: string | undefined) => void
  type: DrawerTypes
  onSearchInputChange?: (value: string) => void
  executionStrategyRef: React.MutableRefObject<ExecutionStrategyRefInterface | null>
  variablesRef: React.MutableRefObject<PipelineVariablesRef | null>
  flowControlRef: React.MutableRefObject<FlowControlRef | null>
  notificationsRef: React.MutableRefObject<PipelineNotificationsRef | null>
}
 
const closeDrawer = (args: CloseDrawerArgs): void => {
  const {
    e,
    formikRef,
    data,
    getString,
    openConfirmBEUpdateError,
    updatePipelineView,
    setSelectedStepId,
    pipelineView,
    type,
    onSearchInputChange,
    executionStrategyRef,
    variablesRef,
    flowControlRef,
    notificationsRef
  } = args
  e?.persist()
  Iif (checkDuplicateStep(formikRef, data, getString)) {
    return
  }
  Iif (formikRef.current?.isDirty?.()) {
    openConfirmBEUpdateError()
    return
  }
 
  Iif (type === DrawerTypes.FlowControl) {
    flowControlRef.current?.onRequestClose()
    return
  }
  if (type === DrawerTypes.ExecutionStrategy) {
    executionStrategyRef.current?.cancelExecutionStrategySelection()
    return
  }
 
  if (type === DrawerTypes.PipelineVariables) {
    onSearchInputChange?.('')
    variablesRef.current?.onRequestClose()
    return
  }
 
  Iif (type === DrawerTypes.PipelineNotifications) {
    notificationsRef.current?.onRequestClose()
    return
  }
 
  updatePipelineView({ ...pipelineView, isDrawerOpened: false, drawerData: { type: DrawerTypes.AddStep } })
  setSelectedStepId(undefined)
}
 
export function RightDrawer(): React.ReactElement {
  const {
    state: {
      templateTypes,
      pipelineView: { drawerData, isDrawerOpened, isSplitViewOpen },
      pipelineView,
      selectionState: { selectedStageId, selectedStepId },
      pipeline
    },
    allowableTypes,
    updatePipeline,
    isReadonly,
    updateStage,
    updatePipelineView,
    getStageFromPipeline,
    stepsFactory,
    setSelectedStepId
  } = usePipelineContext()
  const { type, data, ...restDrawerProps } = drawerData
  const { trackEvent } = useTelemetry()
  const { getTemplate } = useTemplateSelector()
 
  const { stage: selectedStage } = getStageFromPipeline(defaultTo(selectedStageId, ''))
  const stageType = selectedStage?.stage?.type
 
  let stepData = (data?.stepConfig?.node as StepElementConfig)?.type
    ? stepsFactory.getStepData(defaultTo((data?.stepConfig?.node as StepElementConfig)?.type, ''))
    : null
  const templateStepTemplate = (data?.stepConfig?.node as TemplateStepNode)?.template
  const formikRef = React.useRef<StepFormikRef | null>(null)
  const flowControlRef = React.useRef<FlowControlRef | null>(null)
  const variablesRef = React.useRef<PipelineVariablesRef | null>(null)
  const notificationsRef = React.useRef<PipelineNotificationsRef | null>(null)
  const executionStrategyRef = React.useRef<ExecutionStrategyRefInterface | null>(null)
  const { getString } = useStrings()
  const isFullScreenDrawer = FullscreenDrawers.includes(type)
  let title: React.ReactNode | null = null
  Iif (data?.stepConfig?.isStepGroup) {
    stepData = stepsFactory.getStepData(StepType.StepGroup)
  }
 
  const discardChanges = (): void => {
    updatePipelineView({
      ...pipelineView,
      isDrawerOpened: false,
      drawerData: {
        type: DrawerTypes.AddStep
      }
    })
    setSelectedStepId(undefined)
  }
 
  if (stepData || templateStepTemplate) {
    const stepType = stepData
      ? stepData?.type
      : get(templateTypes, getIdentifierFromValue(templateStepTemplate.templateRef))
    const toolTipType = type ? `_${type}` : ''
    title = (
      <RightDrawerTitle
        stepType={stepType}
        toolTipType={toolTipType}
        stepData={stepData}
        discardChanges={discardChanges}
        applyChanges={() =>
          applyChanges(formikRef, data, getString, updatePipelineView, pipelineView, setSelectedStepId, trackEvent)
        }
      ></RightDrawerTitle>
    )
  } else {
    title = null
  }
 
  React.useEffect(() => {
    if (selectedStepId && selectedStage && !pipelineView.isDrawerOpened && isSplitViewOpen) {
      let step
      let drawerType = DrawerTypes.StepConfig
      // 1. search for step in execution
      const execStep = getStepFromId(selectedStage?.stage?.spec?.execution, selectedStepId, false, false)
      step = execStep.node
      Eif (!step) {
        drawerType = DrawerTypes.ConfigureService
        // 2. search for step in serviceDependencies
        const depStep = (selectedStage?.stage as BuildStageElementConfig)?.spec?.serviceDependencies?.find(
          (item: DependencyElement) => item.identifier === selectedStepId
        )
        step = depStep
      }
 
      // 3. if we find step open right drawer
      Iif (step) {
        updatePipelineView({
          ...pipelineView,
          isDrawerOpened: true,
          drawerData: {
            type: drawerType,
            data: {
              stepConfig: {
                node: step as any,
                stepsMap: data?.paletteData?.stepsMap || data?.stepConfig?.stepsMap || new Map(),
                onUpdate: data?.paletteData?.onUpdate,
                isStepGroup: false,
                addOrEdit: 'edit',
                hiddenAdvancedPanels: data?.paletteData?.hiddenAdvancedPanels
              }
            }
          }
        })
      } else {
        updatePipelineView({
          ...pipelineView,
          isDrawerOpened: false,
          drawerData: {
            type: DrawerTypes.AddStep
          }
        })
      }
    }
  }, [selectedStepId, selectedStage, isSplitViewOpen])
 
  const onServiceDependencySubmit = async (item: Partial<Values>): Promise<void> => {
    const { stage: pipelineStage } = (selectedStageId && cloneDeep(getStageFromPipeline(selectedStageId))) || {}
    if (data?.stepConfig?.addOrEdit === 'add' && pipelineStage) {
      const newServiceData: DependencyElement = {
        identifier: defaultTo(item.identifier, ''),
        name: item.name,
        type: StepType.Dependency,
        ...((item as StepElementConfig).description && { description: (item as StepElementConfig).description }),
        spec: (item as StepElementConfig).spec
      }
      Iif (!(pipelineStage.stage as BuildStageElementConfig)?.spec?.serviceDependencies?.length) {
        set(pipelineStage, 'stage.spec.serviceDependencies', [])
      }
      addService(
        defaultTo((pipelineStage.stage as BuildStageElementConfig)?.spec?.serviceDependencies, []),
        newServiceData
      )
      Eif (pipelineStage.stage) {
        await updateStage(pipelineStage.stage)
      }
      updatePipelineView({
        ...pipelineView,
        isDrawerOpened: false,
        drawerData: { type: DrawerTypes.ConfigureService }
      })
      data.stepConfig?.onUpdate?.(newServiceData)
    } else Eif (data?.stepConfig?.addOrEdit === 'edit' && pipelineStage) {
      const node = data?.stepConfig?.node as DependencyElement
      Eif (node) {
        const serviceDependency = (pipelineStage.stage as BuildStageElementConfig)?.spec?.serviceDependencies?.find(
          // NOTE: "node.identifier" is used as item.identifier may contain changed identifier
          dep => dep.identifier === node.identifier
        )
 
        Eif (serviceDependency) {
          Eif (item.identifier) serviceDependency.identifier = item.identifier
          Eif (item.name) serviceDependency.name = item.name
          Eif ((item as StepElementConfig).description)
            serviceDependency.description = (item as StepElementConfig).description
          Eif ((item as StepElementConfig).spec) serviceDependency.spec = (item as StepElementConfig).spec
        }
 
        // Delete values if they were already added and now removed
        Iif (node.description && !(item as StepElementConfig).description) delete node.description
 
        Eif (pipelineStage.stage) {
          await updateStage(pipelineStage.stage)
        }
      }
      updatePipelineView({
        ...pipelineView,
        isDrawerOpened: false,
        drawerData: { type: DrawerTypes.ConfigureService }
      })
    }
  }
  const { openDialog: openConfirmBEUpdateError } = useConfirmationDialog({
    cancelButtonText: getString('cancel'),
    contentText: getString('pipeline.stepConfigHasChanges'),
    titleText: stepData?.name || getString('pipeline.closeStepConfig'),
    confirmButtonText: getString('applyChanges'),
    intent: Intent.WARNING,
    onCloseDialog: isConfirmed => {
      if (isConfirmed) {
        applyChanges(formikRef, data, getString, updatePipelineView, pipelineView, setSelectedStepId, trackEvent)
      }
    }
  })
 
  const { onSearchInputChange } = usePipelineVariables()
 
  const onStepSelection = async (item: StepData): Promise<void> => {
    const paletteData = data?.paletteData
    if (paletteData?.entity) {
      const { stage: pipelineStage } = cloneDeep(getStageFromPipeline(defaultTo(selectedStageId, '')))
      const newStepData = {
        step: {
          type: item.type,
          name: item.name,
          identifier: generateRandomString(item.name),
          spec: {}
        }
      }
      Iif (pipelineStage && !pipelineStage.stage?.spec) {
        set(pipelineStage, 'stage.spec', {})
      }
      Iif (pipelineStage && isNil(pipelineStage.stage?.spec?.execution)) {
        if (paletteData.isRollback) {
          set(pipelineStage, 'stage.spec.execution', { rollbackSteps: [] })
        } else {
          set(pipelineStage, 'stage.spec.execution', { steps: [] })
        }
      }
      data?.paletteData?.onUpdate?.(newStepData.step)
      addStepOrGroup(
        paletteData.entity,
        pipelineStage?.stage?.spec?.execution as any,
        newStepData,
        paletteData.isParallelNodeClicked,
        paletteData.isRollback
      )
 
      Eif (pipelineStage?.stage) {
        await updateStage(pipelineStage?.stage)
      }
      updatePipelineView({
        ...pipelineView,
        isDrawerOpened: true,
        drawerData: {
          type: DrawerTypes.StepConfig,
          data: {
            stepConfig: {
              node: newStepData.step,
              stepsMap: paletteData.stepsMap,
              onUpdate: data?.paletteData?.onUpdate,
              isStepGroup: false,
              addOrEdit: 'edit',
              hiddenAdvancedPanels: data?.paletteData?.hiddenAdvancedPanels
            }
          }
        }
      })
 
      return
    }
    updatePipelineView({ ...pipelineView, isDrawerOpened: false, drawerData: { type: DrawerTypes.AddStep } })
  }
 
  const updateNode = async (processNode: StepElementConfig | TemplateStepNode) => {
    const newPipelineView = produce(pipelineView, draft => {
      set(draft, 'drawerData.data.stepConfig.node', processNode)
    })
    updatePipelineView(newPipelineView)
    const processingNodeIdentifier = defaultTo(drawerData.data?.stepConfig?.node?.identifier, '')
    const stageData = produce(selectedStage, draft => {
      if (draft?.stage?.spec?.execution) {
        updateStepWithinStage(draft.stage.spec.execution, processingNodeIdentifier, processNode as any)
      }
    })
    if (stageData?.stage) {
      await updateStage(stageData.stage)
    }
    drawerData.data?.stepConfig?.onUpdate?.(processNode)
  }
 
  const addOrUpdateTemplate = async () => {
    try {
      const stepType =
        (data?.stepConfig?.node as StepElementConfig)?.type ||
        get(templateTypes, getIdentifierFromValue((data?.stepConfig?.node as TemplateStepNode).template.templateRef))
      const { template, isCopied } = await getTemplate({
        templateType: 'Step',
        selectedChildType: stepType,
        ...((data?.stepConfig?.node as TemplateStepNode)?.template && {
          selectedTemplateRef: getIdentifierFromValue(
            (data?.stepConfig?.node as TemplateStepNode).template.templateRef
          ),
          selectedVersionLabel: (data?.stepConfig?.node as TemplateStepNode).template.versionLabel
        })
      })
      const node = drawerData.data?.stepConfig?.node as StepOrStepGroupOrTemplateStepData
      if (
        !isCopied &&
        isEqual((node as TemplateStepNode)?.template?.templateRef, template.identifier) &&
        isEqual((node as TemplateStepNode)?.template?.versionLabel, template.versionLabel)
      ) {
        return
      }
      const processNode = isCopied
        ? produce(defaultTo(parse(defaultTo(template?.yaml, '')).template.spec, {}) as StepElementConfig, draft => {
            draft.name = defaultTo(node?.name, '')
            draft.identifier = defaultTo(node?.identifier, '')
          })
        : createTemplate<TemplateStepNode>(node as unknown as TemplateStepNode, template)
      await updateNode(processNode)
    } catch (_) {
      // Do nothing.. user cancelled template selection
    }
  }
 
  const removeTemplate = async () => {
    const node = drawerData.data?.stepConfig?.node as TemplateStepNode
    const processNode = produce({} as StepElementConfig, draft => {
      draft.name = node.name
      draft.identifier = node.identifier
      draft.type = get(templateTypes, getIdentifierFromValue(node.template.templateRef))
    })
    await updateNode(processNode)
  }
 
  const onDiscard = () => {
    updatePipelineView({
      ...pipelineView,
      isDrawerOpened: false,
      drawerData: {
        type: DrawerTypes.AddStep
      }
    })
  }
 
  const handleClose = (e?: React.SyntheticEvent<Element, Event>): void => {
    closeDrawer({
      e,
      formikRef,
      data,
      getString,
      openConfirmBEUpdateError,
      updatePipelineView,
      pipelineView,
      setSelectedStepId,
      type,
      onSearchInputChange,
      executionStrategyRef,
      variablesRef,
      flowControlRef,
      notificationsRef
    })
  }
 
  return (
    <Drawer
      onClose={handleClose}
      usePortal={true}
      autoFocus={true}
      canEscapeKeyClose={type !== DrawerTypes.ExecutionStrategy}
      canOutsideClickClose={type !== DrawerTypes.ExecutionStrategy}
      enforceFocus={false}
      hasBackdrop={true}
      size={DrawerSizes[type]}
      isOpen={isDrawerOpened}
      position={Position.RIGHT}
      title={title}
      data-type={type}
      className={cx(css.main, css.almostFullScreen, css.fullScreen, { [css.showRighDrawer]: isFullScreenDrawer })}
      {...restDrawerProps}
      // {...(type === DrawerTypes.FlowControl ? { style: { right: 60, top: 64 }, hasBackdrop: false } : {})}
      isCloseButtonShown={false}
      // BUG: https://github.com/palantir/blueprint/issues/4519
      // you must pass only a single classname, not even an empty string, hence passing a dummy class
      // "classnames" package cannot be used here because it returns an empty string when no classes are applied
      portalClassName={isFullScreenDrawer ? css.almostFullScreenPortal : 'pipeline-studio-right-drawer'}
    >
      <Button minimal className={css.almostFullScreenCloseBtn} icon="cross" withoutBoxShadow onClick={handleClose} />
 
      {type === DrawerTypes.StepConfig && data?.stepConfig?.node && (
        <StepCommands
          step={data.stepConfig.node as StepElementConfig | StepGroupElementConfig}
          isReadonly={isReadonly}
          ref={formikRef}
          checkDuplicateStep={checkDuplicateStep.bind(null, formikRef, data, getString)}
          isNewStep={!data.stepConfig.stepsMap.get(data.stepConfig.node.identifier)?.isSaved}
          stepsFactory={stepsFactory}
          hasStepGroupAncestor={!!data?.stepConfig?.isUnderStepGroup}
          onUpdate={value =>
            onSubmitStep(
              value,
              DrawerTypes.StepConfig,
              data,
              trackEvent,
              selectedStage,
              updatePipelineView,
              updateStage,
              pipelineView
            )
          }
          viewType={StepCommandsViews.Pipeline}
          allowableTypes={allowableTypes}
          onUseTemplate={addOrUpdateTemplate}
          onRemoveTemplate={removeTemplate}
          isStepGroup={data.stepConfig.isStepGroup}
          hiddenPanels={data.stepConfig.hiddenAdvancedPanels}
          stageType={stageType as StageType}
        />
      )}
      {type === DrawerTypes.AddStep && selectedStageId && data?.paletteData && (
        <StepPalette
          stepsFactory={stepsFactory}
          stepPaletteModuleInfos={getStepPaletteModuleInfosFromStage(stageType, selectedStage?.stage)}
          stageType={stageType as StageType}
          onSelect={onStepSelection}
        />
      )}
      {/* TODO */}
      {type === DrawerTypes.PipelineVariables && <PipelineVariables ref={variablesRef} pipeline={pipeline} />}
      {type === DrawerTypes.Templates && <PipelineTemplates />}
      {type === DrawerTypes.ExecutionStrategy && (
        <ExecutionStrategy selectedStage={defaultTo(selectedStage, {})} ref={executionStrategyRef} />
      )}
      {type === DrawerTypes.FlowControl && <FlowControl ref={flowControlRef} onDiscard={onDiscard} />}
      {type === DrawerTypes.PipelineNotifications && <PipelineNotifications ref={notificationsRef} />}
      {type === DrawerTypes.AdvancedOptions && (
        <AdvancedOptions
          pipeline={cloneDeep(pipeline)}
          onApplyChanges={async updatedPipeline => {
            await updatePipeline(updatedPipeline)
            updatePipelineView({
              ...pipelineView,
              isDrawerOpened: false,
              drawerData: {
                type: DrawerTypes.AddStep
              }
            })
          }}
          onDiscard={onDiscard}
        />
      )}
      {type === DrawerTypes.PolicySets && <PipelineGovernanceView pipelineName={pipeline.name} />}
      {type === DrawerTypes.ConfigureService && selectedStageId && data?.stepConfig && data?.stepConfig.node && (
        <StepCommands
          key={`step-form-${data.stepConfig.node.identifier}`}
          step={data.stepConfig.node as StepElementConfig}
          isReadonly={isReadonly}
          ref={formikRef}
          isNewStep={!data.stepConfig.stepsMap.get(data.stepConfig.node.identifier)?.isSaved}
          stepsFactory={stepsFactory}
          onUpdate={onServiceDependencySubmit}
          isStepGroup={false}
          allowableTypes={allowableTypes}
          withoutTabs
          stageType={stageType as StageType}
        />
      )}
 
      {type === DrawerTypes.AddProvisionerStep && selectedStageId && data?.paletteData && (
        <StepPalette
          stepsFactory={stepsFactory}
          stepPaletteModuleInfos={getStepPaletteModuleInfosFromStage(stageType, undefined, 'Provisioner')}
          stageType={stageType as StageType}
          isProvisioner={true}
          onSelect={async (item: StepData) => {
            const paletteData = data.paletteData
            Iif (paletteData?.entity) {
              const { stage: pipelineStage } = cloneDeep(getStageFromPipeline(selectedStageId))
              const newStepData = {
                step: {
                  type: item.type,
                  name: item.name,
                  identifier: generateRandomString(item.name),
                  spec: {}
                }
              }
 
              data?.paletteData?.onUpdate?.(newStepData.step)
 
              if (
                pipelineStage &&
                !get(pipelineStage?.stage, 'spec.infrastructure.infrastructureDefinition.provisioner')
              ) {
                set(pipelineStage, 'stage.spec.infrastructure.infrastructureDefinition.provisioner', {
                  steps: [],
                  rollbackSteps: []
                })
              }
 
              const provisioner = get(pipelineStage?.stage, 'spec.infrastructure.infrastructureDefinition.provisioner')
              // set empty arrays
              if (!paletteData.isRollback && !provisioner.steps) provisioner.steps = []
              if (paletteData.isRollback && !provisioner.rollbackSteps) provisioner.rollbackSteps = []
 
              addStepOrGroup(
                paletteData.entity,
                provisioner,
                newStepData,
                paletteData.isParallelNodeClicked,
                paletteData.isRollback
              )
 
              if (pipelineStage?.stage) {
                await updateStage(pipelineStage?.stage)
              }
 
              updatePipelineView({
                ...pipelineView,
                isDrawerOpened: true,
                drawerData: {
                  type: DrawerTypes.ProvisionerStepConfig,
                  data: {
                    stepConfig: {
                      node: newStepData.step,
                      stepsMap: paletteData.stepsMap,
                      onUpdate: data?.paletteData?.onUpdate,
                      isStepGroup: false,
                      addOrEdit: 'edit',
                      hiddenAdvancedPanels: data.paletteData?.hiddenAdvancedPanels
                    }
                  }
                }
              })
 
              return
            }
            updatePipelineView({ ...pipelineView, isDrawerOpened: false, drawerData: { type: DrawerTypes.AddStep } })
          }}
        />
      )}
      {type === DrawerTypes.ProvisionerStepConfig && data?.stepConfig?.node && (
        <StepCommands
          step={data.stepConfig.node as StepElementConfig}
          ref={formikRef}
          isReadonly={isReadonly}
          allowableTypes={allowableTypes}
          checkDuplicateStep={checkDuplicateStep.bind(null, formikRef, data, getString)}
          isNewStep={!data.stepConfig.stepsMap.get(data.stepConfig.node.identifier)?.isSaved}
          stepsFactory={stepsFactory}
          hasStepGroupAncestor={!!data?.stepConfig?.isUnderStepGroup}
          onUpdate={value =>
            onSubmitStep(
              value,
              DrawerTypes.ProvisionerStepConfig,
              data,
              trackEvent,
              selectedStage,
              updatePipelineView,
              updateStage,
              pipelineView
            )
          }
          isStepGroup={data.stepConfig.isStepGroup}
          hiddenPanels={data.stepConfig.hiddenAdvancedPanels}
          stageType={stageType as StageType}
        />
      )}
    </Drawer>
  )
}