import React , { useCallback } from 'react' ; import { LegendColorPicker , Position } from '@elastic/charts' ; import { PopoverAnchorPosition , EuiPopover , EuiOutsideClickDetector } from '@elastic/eui' ; import type { PersistedState } from '../../../../visualizations/public' ; import { ColorPicker } from '../../../../charts/public' ; const KEY_CODE_ENTER = 13 ; function getAnchorPosition ( legendPosition ) { switch ( legendPosition ) { case Position . Bottom : return 'upCenter' ; case Position . Top : return 'downCenter' ; case Position . Left : return 'rightCenter' ; default : return 'leftCenter' ; } } export const getColorPicker = ( legendPosition , setColor , uiState ) : LegendColorPicker => ( { anchor , color , onClose , onChange , seriesIdentifiers : [ seriesIdentifier ] } ) => { const seriesName = seriesIdentifier . key ; const overwriteColors = uiState ?. get ( 'vis.colors' , { } ) ?? { } ; const colorIsOverwritten = seriesName . toString ( ) in overwriteColors ; let keyDownEventOn = false ; const handleChange = ( newColor ) => { if ( newColor ) { onChange ( newColor ) ; } setColor ( newColor , seriesName ) ; if ( ! newColor || ! keyDownEventOn ) { onClose ( ) ; } } ; const onKeyDown = ( e ) => { if ( e . keyCode === KEY_CODE_ENTER ) { onClose ?. ( ) ; } keyDownEventOn = true ; } ; const handleOutsideClick = useCallback ( ( ) => { onClose ?. ( ) ; } , [ onClose ] ) ; return ( < EuiOutsideClickDetector onOutsideClick = { handleOutsideClick } > < EuiPopover isOpen ownFocus display = "block" button = { anchor } anchorPosition = { getAnchorPosition ( legendPosition ) } closePopover = { onClose } panelPaddingSize = "s" > < ColorPicker color = { color } onChange = { handleChange } label = { seriesName } useLegacyColors = { false } colorIsOverwritten = { colorIsOverwritten } onKeyDown = { onKeyDown } / > < /EuiPopover> < /EuiOutsideClickDetector>); } ;