import { i18n } from '@osd/i18n' ; import _ from 'lodash' ; import uuid from 'uuid' ; import { ActionByType , IncompatibleActionError } from '../../ui_actions_plugin' ; import { ViewMode , PanelState , IEmbeddable } from '../../embeddable_plugin' ; import { PanelNotFoundError , EmbeddableInput , isReferenceOrValueEmbeddable , isErrorEmbeddable , } from '../../../../embeddable/public' ; import { DashboardPanelState , DASHBOARD_CONTAINER_TYPE , DashboardContainer } from '..' ; export const ACTION_ADD_TO_LIBRARY = 'addToFromLibrary' ; export interface AddToLibraryActionContext { embeddable : IEmbeddable ; } export class AddToLibraryAction implements ActionByType < typeof ACTION_ADD_TO_LIBRARY > { public readonly type = ACTION_ADD_TO_LIBRARY ; public readonly id = ACTION_ADD_TO_LIBRARY ; public order = 15 ; constructor ( ) { } public getDisplayName ( { embeddable } ) { if ( ! embeddable . getRoot ( ) || ! embeddable . getRoot ( ) . isContainer ) { throw new IncompatibleActionError ( ) ; } return i18n . translate ( 'dashboard.panel.AddToLibrary' , { defaultMessage : 'Add to library' , } ) ; } public getIconType ( { embeddable } ) { if ( ! embeddable . getRoot ( ) || ! embeddable . getRoot ( ) . isContainer ) { throw new IncompatibleActionError ( ) ; } return 'folderCheck' ; } public async isCompatible ( { embeddable } ) { return Boolean ( ! isErrorEmbeddable ( embeddable ) && embeddable . getInput ( ) ?. viewMode !== ViewMode . VIEW && embeddable . getRoot ( ) && embeddable . getRoot ( ) . isContainer && embeddable . getRoot ( ) . type === DASHBOARD_CONTAINER_TYPE && isReferenceOrValueEmbeddable ( embeddable ) && ! embeddable . inputIsRefType ( embeddable . getInput ( ) ) ) ; } public async execute ( { embeddable } ) { if ( ! isReferenceOrValueEmbeddable ( embeddable ) ) { throw new IncompatibleActionError ( ) ; } const newInput = await embeddable . getInputAsRefType ( ) ; embeddable . updateInput ( newInput ) ; const dashboard = embeddable . getRoot ( ) as DashboardContainer ; const panelToReplace = dashboard . getInput ( ) . panels [ embeddable . id ] as DashboardPanelState ; if ( ! panelToReplace ) { throw new PanelNotFoundError ( ) ; } const newPanel = { type : embeddable . type , explicitInput : { ... newInput , id : uuid . v4 ( ) } , } ; dashboard . replacePanel ( panelToReplace , newPanel ) ; } }