import React , { useContext , useMemo , useState } from 'react' ; import { TRANSFORM_STATE } from '../../../../../../common/constants' ; import { TransformListAction , TransformListRow } from '../../../../common' ; import { useDeleteIndexAndTargetIndex , useDeleteTransforms } from '../../../../hooks' ; import { AuthorizationContext } from '../../../../lib/authorization' ; import { deleteActionNameText , isDeleteActionDisabled , DeleteActionName , } from './delete_action_name' ; export type DeleteAction = ReturnType < typeof useDeleteAction > ; export const useDeleteAction = ( forceDisable ) => { const { canDeleteTransform } = useContext ( AuthorizationContext ) . capabilities ; const deleteTransforms = useDeleteTransforms ( ) ; const [ isModalVisible , setModalVisible ] = useState ( false ) ; const [ items , setItems ] = useState < TransformListRow [ ] > ( [ ] ) ; const isBulkAction = items . length > 1 ; const shouldForceDelete = useMemo ( ( ) => items . some ( ( i ) => i . stats . state === TRANSFORM_STATE . FAILED ) , [ items ] ) ; const closeModal = ( ) => setModalVisible ( false ) ; const { userCanDeleteIndex , userCanDeleteDataView , deleteDestIndex , indexPatternExists , deleteIndexPattern , toggleDeleteIndex , toggleDeleteIndexPattern , } = useDeleteIndexAndTargetIndex ( items ) ; const deleteAndCloseModal = ( ) => { setModalVisible ( false ) ; const shouldDeleteDestIndex = userCanDeleteIndex && deleteDestIndex ; const shouldDeleteDestIndexPattern = userCanDeleteIndex && userCanDeleteDataView && indexPatternExists && deleteIndexPattern ; const forceDelete = isBulkAction ? shouldForceDelete : items [ 0 ] && items [ 0 ] && items [ 0 ] . stats . state === TRANSFORM_STATE . FAILED ; deleteTransforms ( { transformsInfo : items . map ( ( i ) => ( { id : i . config . id , state : i . stats . state , } ) ) , deleteDestIndex : shouldDeleteDestIndex , deleteDestIndexPattern : shouldDeleteDestIndexPattern , forceDelete , } ) ; } ; const openModal = ( newItems ) => { if ( Array . isArray ( newItems ) ) { setItems ( newItems ) ; setModalVisible ( true ) ; } } ; const action = useMemo ( ( ) => ( { name : ( item ) => ( < DeleteActionName { ... { canDeleteTransform , disabled : isDeleteActionDisabled ( [ item ] , forceDisable ) , isBulkAction : false , } } / > ) , enabled : ( item ) => ! isDeleteActionDisabled ( [ item ] , forceDisable ) && canDeleteTransform , description : deleteActionNameText , icon : 'trash' , type : 'icon' , onClick : ( item ) => openModal ( [ item ] ) , 'data-test-subj' : 'transformActionDelete' , } ) , [ canDeleteTransform , forceDisable ] ) ; return { action , closeModal , deleteAndCloseModal , deleteDestIndex , deleteIndexPattern , indexPatternExists , isModalVisible , items , openModal , shouldForceDelete , toggleDeleteIndex , toggleDeleteIndexPattern , userCanDeleteIndex , userCanDeleteDataView , } ; } ;