All files / modules/10-common/modals/GitDiffEditor useGitDiffEditorDialog.tsx

70.97% Statements 44/62
47.56% Branches 39/82
50% Functions 5/10
70.97% Lines 44/62

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              274x 274x 274x 274x 274x 274x   274x 274x 274x 274x   274x   274x   274x 274x                               274x         274x 899x 899x 899x 899x 899x 899x 899x 899x                       899x 899x 899x                   899x                   899x 158x 158x               899x 158x                           899x 1x           1x                                                                                           899x   1x 1x                 1x 1x       1x 1x 1x                  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useState } from 'react'
import { useParams } from 'react-router-dom'
import { omit } from 'lodash-es'
import { parse } from 'yaml'
import { Button, Layout, Icon, Text, ModalErrorHandlerBinding, ModalErrorHandler } from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
 
import { Dialog, IDialogProps } from '@blueprintjs/core'
import { useStrings } from 'framework/strings'
import { PageSpinner } from '@common/components'
import { GitDiffEditor } from '@common/components/GitDiffEditor/GitDiffEditor'
import type { SaveToGitFormInterface } from '@common/components/SaveToGitForm/SaveToGitForm'
import { EntityGitDetails, useGetFileContent } from 'services/cd-ng'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { sanitize } from '@common/utils/JSONUtils'
 
import { yamlStringify } from '@common/utils/YamlHelperMethods'
import css from './useGitDiffEditorDialog.module.scss'
 
export interface UseGitDiffEditorDialogProps<T> {
  onSuccess: (payload: T, objectId: EntityGitDetails['objectId'], gitDetails?: SaveToGitFormInterface) => void
  onClose: () => void
}
 
export interface GitData extends SaveToGitFormInterface {
  resolvedConflictCommitId: string
}
 
export interface UseGitDiffEditorDialogReturn<T> {
  openGitDiffDialog: (entity: T, gitDetails?: GitData, _modalProps?: IDialogProps) => void
  hideGitDiffDialog: () => void
}
 
const FORMATTING_OPTIONS = {
  indent: 4,
  sortMapEntries: (a: any, b: any) => (a.key < b.key ? 1 : a.key > b.key ? -1 : 0)
}
 
export function useGitDiffEditorDialog<T>(props: UseGitDiffEditorDialogProps<T>): UseGitDiffEditorDialogReturn<T> {
  const { onSuccess, onClose } = props
  const { getString } = useStrings()
  const [modalErrorHandler, setModalErrorHandler] = React.useState<ModalErrorHandlerBinding>()
  const [entityAsYaml, setEntityAsYaml] = useState<string>()
  const [gitDetails, setGitDetails] = useState<GitData>()
  const [showGitDiff, setShowGitDiff] = useState<boolean>(false)
  const [remoteVersion, setRemoteVersion] = useState<string>('')
  const defaultModalProps: IDialogProps = {
    isOpen: true,
    enforceFocus: false,
    style: {
      minWidth: 500,
      minHeight: 170,
      borderLeft: 0,
      paddingBottom: 0,
      position: 'relative',
      overflow: 'hidden'
    }
  }
  const [modalProps, setModalProps] = useState<IDialogProps>(defaultModalProps)
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
  const commonParams = {
    accountIdentifier: accountId,
    projectIdentifier,
    orgIdentifier
  }
  const {
    data,
    loading,
    refetch: fetchRemoteFileContent,
    error
  } = useGetFileContent({
    queryParams: {
      ...commonParams,
      yamlGitConfigIdentifier: '',
      filePath: '',
      branch: ''
    },
    lazy: true
  })
 
  React.useEffect(() => {
    try {
      Iif (data?.data?.content) {
        setRemoteVersion(yamlStringify(sanitize(parse(data.data.content)), FORMATTING_OPTIONS))
      }
    } catch (e) {
      //ignore error
    }
  }, [data?.data?.content])
 
  React.useEffect(() => {
    Iif (showGitDiff) {
      const { isOpen, style } = defaultModalProps
      const expandedModalProps: IDialogProps = {
        isOpen,
        enforceFocus: false,
        style: Object.assign(omit(style, 'minHeight'), { width: 'calc(100vw - 100px)', height: 'calc(100vh - 100px)' })
      }
      setModalProps(expandedModalProps)
      if (error?.message) {
        modalErrorHandler?.showDanger(error.message || '')
      }
    }
  }, [showGitDiff, error?.message])
 
  const [showModal, hideModal] = useModalHook(() => {
    const closeHandler = (): void => {
      onClose()
      hideModal()
      setShowGitDiff(false)
      setModalProps(defaultModalProps)
    }
    return (
      <Dialog {...modalProps}>
        <ModalErrorHandler bind={setModalErrorHandler} />
        <Button minimal icon="cross" iconProps={{ size: 18 }} className={css.crossIcon} onClick={closeHandler} />
        {!error && loading ? (
          <PageSpinner />
        ) : showGitDiff ? (
          <GitDiffEditor
            remote={{ branch: gitDetails?.branch || '', content: remoteVersion }}
            local={{ branch: getString('common.local'), content: entityAsYaml || '' }}
            onSave={_data => {
              try {
                onSuccess(parse(_data) as T, data?.data?.objectId, gitDetails)
                hideModal()
              } catch (e) {
                //ignore e
              }
            }}
            onCancel={closeHandler}
            width={'calc(100vw - 100px)'}
            height={error ? 'calc(100vh - 265px)' : 'calc(100vh - 210px)'}
          />
        ) : (
          <Layout.Horizontal padding={{ top: 'xlarge', left: 'xxlarge' }} spacing="large">
            <Layout.Vertical>
              <Icon name="cross" size={25} className={css.error} padding="medium" />
            </Layout.Vertical>
            <Layout.Vertical padding={{ left: 'medium' }}>
              <Text style={{ fontWeight: 'bold' }} padding={{ bottom: 'medium' }}>
                {getString('common.newVersion')}
              </Text>
              <Text>{getString('common.confictOccured', { name: 'Someone' })}</Text>
              <Text padding={{ bottom: 'large' }}>{getString('common.resolveConflict')}</Text>
              <Button
                intent="primary"
                text={getString('common.seeWhatChanged')}
                onClick={() => setShowGitDiff(true)}
                width="fit-content"
                padding={{ left: 'small' }}
              />
            </Layout.Vertical>
          </Layout.Horizontal>
        )}
      </Dialog>
    )
  }, [showGitDiff, modalProps, remoteVersion])
  return {
    openGitDiffDialog: (_entity: T, _gitDetails?: GitData, _modalProps?: IDialogProps) => {
      const { repoIdentifier = '', filePath = '', rootFolder = '', branch = '' } = _gitDetails || {}
      fetchRemoteFileContent({
        queryParams: {
          ...commonParams,
          yamlGitConfigIdentifier: repoIdentifier,
          filePath: rootFolder?.concat(filePath) || '',
          branch,
          commitId: _gitDetails?.resolvedConflictCommitId
        }
      })
      try {
        setEntityAsYaml(yamlStringify(sanitize(_entity), FORMATTING_OPTIONS))
      } catch (e) {
        //ignore error
      }
      setGitDetails(_gitDetails)
      setModalProps(_modalProps || modalProps)
      showModal()
    },
    hideGitDiffDialog: () => {
      hideModal()
      setShowGitDiff(false)
      setModalProps(defaultModalProps)
    }
  }
}