import _ from 'lodash' ; import Color from 'color' ; import { CoreSetup } from 'opensearch-dashboards/public' ; import { COLOR_MAPPING_SETTING } from '../../../common' ; import { createColorPalette } from './color_palette' ; const standardizeColor = ( color ) => new Color ( color ) . hex ( ) . toLowerCase ( ) ; /**
 * Maintains a lookup table that associates the value (key) with a hex color (value)
 * across the visualizations.
 * Provides functions to interact with the lookup table
 */ export class MappedColors { private _oldMap : any ; private _mapping : any ; constructor ( private uiSettings ) { this . _oldMap = { } ; this . _mapping = { } ; } private getConfigColorMapping ( ) { return _ . mapValues ( this . uiSettings . get ( COLOR_MAPPING_SETTING ) , standardizeColor ) ; } public get oldMap ( ) : any { return this . _oldMap ; } public get mapping ( ) : any { return this . _mapping ; } get ( key ) { return this . getConfigColorMapping ( ) [ key as any ] || this . _mapping [ key ] ; } flush ( ) { this . _oldMap = _ . clone ( this . _mapping ) ; this . _mapping = { } ; } purge ( ) { this . _oldMap = { } ; this . _mapping = { } ; } mapKeys ( keys ) { const configMapping = this . getConfigColorMapping ( ) ; const configColors = _ . values ( configMapping ) ; const oldColors = _ . values ( this . _oldMap ) ; const keysToMap = [ ] ; _ . each ( keys , ( key ) => { if ( configMapping [ key as any ] ) delete this . _mapping [ key ] ; if ( _ . includes ( configColors , this . _mapping [ key ] ) ) keysToMap . push ( key ) ; if ( this . _oldMap [ key ] ) this . _mapping [ key ] = this . _oldMap [ key ] ; if ( this . get ( key ) == null ) keysToMap . push ( key ) ; } ) ; const allColors = _ ( this . _mapping ) . values ( ) . union ( configColors ) . union ( oldColors ) . value ( ) ; const colorPalette = createColorPalette ( allColors . length + keysToMap . length ) ; let newColors = _ . difference ( colorPalette , allColors ) ; while ( keysToMap . length > newColors . length ) { newColors = newColors . concat ( _ . sampleSize ( allColors , keysToMap . length - newColors . length ) ) ; } _ . merge ( this . _mapping , _ . zipObject ( keysToMap , newColors ) ) ; } }