import colorJS from 'color' ; import { Theme , LIGHT_THEME , DARK_THEME } from '@elastic/charts' ; function computeRelativeLuminosity ( rgb ) { return colorJS ( rgb ) . luminosity ( ) ; } function computeContrast ( rgb1 , rgb2 ) { return colorJS ( rgb1 ) . contrast ( colorJS ( rgb2 ) ) ; } function getAAARelativeLum ( bgColor , fgColor , ratio = 7 ) { const relLum1 = computeRelativeLuminosity ( bgColor ) ; const relLum2 = computeRelativeLuminosity ( fgColor ) ; if ( relLum1 > relLum2 ) { return ( relLum1 + 0.05 - ratio * 0.05 ) / ratio ; } else { return Math . min ( ratio * ( relLum1 + 0.05 ) - 0.05 , 1 ) ; } } function getGrayFromRelLum ( relLum ) { if ( relLum <= 0.0031308 ) { return relLum * 12.92 ; } else { return ( 1.0 + 0.055 ) * Math . pow ( relLum , 1.0 / 2.4 ) - 0.055 ; } } function getGrayRGBfromGray ( gray ) { const g = Math . round ( gray * 255 ) ; return `rgb(${ g },${ g },${ g })` ; } function getAAAGray ( bgColor , fgColor , ratio = 7 ) { const relLum = getAAARelativeLum ( bgColor , fgColor , ratio ) ; const gray = getGrayFromRelLum ( relLum ) ; return getGrayRGBfromGray ( gray ) ; } function findBestContrastColor ( bgColor , lightFgColor , darkFgColor , ratio = 4.5 ) { const lc = computeContrast ( bgColor , lightFgColor ) ; const dc = computeContrast ( bgColor , darkFgColor ) ; if ( lc >= dc ) { if ( lc >= ratio ) { return lightFgColor ; } return getAAAGray ( bgColor , lightFgColor , ratio ) ; } if ( dc >= ratio ) { return darkFgColor ; } return getAAAGray ( bgColor , darkFgColor , ratio ) ; } function isValidColor ( color ) { if ( typeof color !== 'string' ) { return false ; } if ( color . length === 0 ) { return false ; } try { colorJS ( color ) ; return true ; } catch { return false ; } } param baseTheme param bgColor export function getBaseTheme ( baseTheme , bgColor ? ) { if ( ! isValidColor ( bgColor ) ) { return baseTheme ; } const bgLuminosity = computeRelativeLuminosity ( bgColor ) ; const mainTheme = bgLuminosity <= 0.179 ? DARK_THEME : LIGHT_THEME ; const color = findBestContrastColor ( bgColor , LIGHT_THEME . axes . axisTitle . fill , DARK_THEME . axes . axisTitle . fill ) ; return { ... mainTheme , axes : { ... mainTheme . axes , axisTitle : { ... mainTheme . axes . axisTitle , fill : color , } , tickLabel : { ... mainTheme . axes . tickLabel , fill : color , } , axisLine : { ... mainTheme . axes . axisLine , stroke : color , } , tickLine : { ... mainTheme . axes . tickLine , stroke : color , } , } , } ; } export function getChartClasses ( bgColor ? ) { if ( typeof bgColor !== 'string' ) { return ; } const bgLuminosity = computeRelativeLuminosity ( bgColor ) ; return bgLuminosity <= 0.179 ? 'tvbVisTimeSeriesDark' : 'tvbVisTimeSeriesLight' ; }