import chroma from 'chroma-js' ; import { clamp } from '../utils/common' ; import { Logger } from '../utils/logger' ; import { Color , Colors } from './colors' ; import { LRUCache } from './data_structures' ; public export type RGB = number ; public export type A = number ; internal export type RgbTuple = [ r : RGB , g : RGB , b : RGB , alpha ? : A ] ; public export type RgbaTuple = [ r : RGB , g : RGB , b : RGB , alpha : A ] ; internal export type OpacityFn = ( opacity : number ) => number ; internal export function overrideOpacity ( [ r , g , b , o ] , opacity ? ) { const opacityOverride = opacity === undefined ? o : typeof opacity === 'number' ? opacity : opacity ( o ) ; if ( r === 0 && b === 0 && g === 0 && o === 0 ) { return Colors . Transparent . rgba ; } return [ r , g , b , clamp ( Number . isFinite ( opacityOverride ) ? opacityOverride : o , 0 , 1 ) ] ; } internal export function RGBATupleToString ( rgba ) { return `rgba(${ rgba [ 0 ] }, ${ rgba [ 1 ] }, ${ rgba [ 2 ] }, ${ rgba [ 3 ] ?? 1 })` ; } internal export function isValid ( color ) { try { return chroma ( color === Colors . Transparent . keyword ? 'rgba(0,0,0,0)' : color ) ; } catch { return false ; } } internal export function getChromaColor ( color ) { return chroma ( ... color ) ; } internal export function getGreensColorScale ( gamma , domain ) { const scale = chroma . scale ( chroma . brewer . Greens ) . gamma ( gamma ) . domain ( domain ) ; return ( value ) => scale ( value ) . css ( ) ; } const rgbaCache = new LRUCache < Color , RgbaTuple > ( 200 ) ; internal export function colorToRgba ( color ) { const cachedValue = rgbaCache . get ( color ) ; if ( cachedValue === undefined ) { const chromaColor = isValid ( color ) ; if ( chromaColor === false ) Logger . warn ( `The provided color is not a valid CSS color, using RED as fallback` , color ) ; const newValue = chromaColor ? chromaColor . rgba ( ) : Colors . Red . rgba ; rgbaCache . set ( color , newValue ) ; return newValue ; } return cachedValue ; }