From 451836a86a10a60cf020a40943dcb8da287ed6ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Wed, 14 Oct 2020 10:21:45 +0200 Subject: [PATCH] NamedColors: Named colors refactors (#28235) * NamedColors: Refactoring, performance improvements, and simplifications * More simplifification * Updated to use new function * Updates * Updates * Updated BarGauge to use fallback color intead of magic string * Updates * Fixed unused import --- .../grafana-data/src/field/fieldColor.test.ts | 4 +- packages/grafana-data/src/field/fieldColor.ts | 66 ++++++-------- packages/grafana-data/src/types/fieldColor.ts | 2 - .../src/utils/namedColorsPalette.test.ts | 43 +-------- .../src/utils/namedColorsPalette.ts | 88 +++++++++---------- .../grafana-ui/src/components/Badge/Badge.tsx | 4 +- .../src/components/BarGauge/BarGauge.tsx | 24 ++--- .../components/BigValue/BigValueLayout.tsx | 4 +- .../components/ColorPicker/ColorPicker.tsx | 4 +- .../ColorPicker/ColorPickerPopover.test.tsx | 34 +++---- .../ColorPicker/ColorPickerPopover.tsx | 8 +- .../ColorPicker/NamedColorsGroup.tsx | 6 +- .../ColorPicker/NamedColorsPalette.story.tsx | 24 ----- .../ColorPicker/NamedColorsPalette.tsx | 4 +- .../ColorPicker/SpectrumPalette.tsx | 4 +- .../grafana-ui/src/components/Gauge/Gauge.tsx | 8 +- .../src/components/Graph/utils.test.ts | 6 +- .../src/components/OptionsUI/color.tsx | 4 +- .../src/components/OptionsUI/fieldColor.tsx | 4 +- .../uPlot/geometries/configGetters.ts | 4 +- .../components/uPlot/plugins/LegendPlugin.tsx | 6 +- .../app/plugins/panel/graph/data_processor.ts | 4 +- public/app/plugins/panel/graph/graph.ts | 2 +- public/app/plugins/panel/graph/module.ts | 4 +- .../graph/specs/threshold_manager.test.ts | 2 + .../plugins/panel/graph/threshold_manager.ts | 11 +-- .../panel/graph/time_region_manager.ts | 19 ++-- .../app/plugins/panel/heatmap/color_legend.ts | 11 +-- public/app/plugins/panel/heatmap/rendering.ts | 9 +- public/app/plugins/panel/singlestat/module.ts | 8 +- public/app/plugins/panel/table-old/module.ts | 2 +- .../app/plugins/panel/table-old/renderer.ts | 10 +-- .../panel/table-old/specs/renderer.test.ts | 21 +++-- 33 files changed, 186 insertions(+), 268 deletions(-) diff --git a/packages/grafana-data/src/field/fieldColor.test.ts b/packages/grafana-data/src/field/fieldColor.test.ts index 42846325f84..638f4beb9b8 100644 --- a/packages/grafana-data/src/field/fieldColor.test.ts +++ b/packages/grafana-data/src/field/fieldColor.test.ts @@ -3,7 +3,7 @@ import { fieldColorModeRegistry, FieldValueColorCalculator } from './fieldColor' describe('fieldColorModeRegistry', () => { interface GetCalcOptions { - mode: FieldColorModeId; + mode: string; seriesIndex?: number; } @@ -16,7 +16,7 @@ describe('fieldColorModeRegistry', () => { } it('Schemes should interpolate', () => { - const calcFn = getCalculator({ mode: FieldColorModeId.ContinousGrYlRd }); + const calcFn = getCalculator({ mode: 'continuous-GrYlRd' }); expect(calcFn(70, 0.5, undefined)).toEqual('rgb(226, 192, 61)'); }); diff --git a/packages/grafana-data/src/field/fieldColor.ts b/packages/grafana-data/src/field/fieldColor.ts index c11a988c34e..efadedd148c 100644 --- a/packages/grafana-data/src/field/fieldColor.ts +++ b/packages/grafana-data/src/field/fieldColor.ts @@ -1,5 +1,5 @@ import { FALLBACK_COLOR, Field, FieldColorModeId, GrafanaTheme, Threshold } from '../types'; -import { classicColors, getColorFromHexRgbOrName, RegistryItem } from '../utils'; +import { classicColors, getColorForTheme, RegistryItem } from '../utils'; import { Registry } from '../utils/Registry'; import { interpolateRgbBasis } from 'd3-interpolate'; import { fallBackTreshold } from './thresholds'; @@ -23,64 +23,56 @@ export const fieldColorModeRegistry = new Registry(() => { }, { id: FieldColorModeId.Thresholds, - name: 'Color by thresholds', + name: 'From thresholds', description: 'Derive colors from thresholds', getCalculator: (_field, theme) => { return (_value, _percent, threshold) => { const thresholdSafe = threshold ?? fallBackTreshold; - return getColorFromHexRgbOrName(thresholdSafe.color, theme.type); + return getColorForTheme(thresholdSafe.color, theme); }; }, }, - new FieldColorSchemeMode({ - id: FieldColorModeId.PaletteSaturated, - name: 'Color by series / Saturated palette', - //description: 'Assigns color based on series or field index', - isContinuous: false, - isByValue: false, - colors: [ - 'blue', - 'red', - 'green', - 'yellow', - 'purple', - 'orange', - 'dark-blue', - 'dark-red', - 'dark-yellow', - 'dark-purple', - 'dark-orange', - ], - }), + // new FieldColorSchemeMode({ + // id: FieldColorModeId.PaletteSaturated, + // name: 'By series / Saturated palette', + // //description: 'Assigns color based on series or field index', + // isContinuous: false, + // isByValue: false, + // colors: [ + // 'blue', + // 'red', + // 'green', + // 'yellow', + // 'purple', + // 'orange', + // 'dark-blue', + // 'dark-red', + // 'dark-yellow', + // 'dark-purple', + // 'dark-orange', + // ], + // }), new FieldColorSchemeMode({ id: FieldColorModeId.PaletteClassic, - name: 'Color by series / Classic palette', + name: 'By series / Classic palette', //description: 'Assigns color based on series or field index', isContinuous: false, isByValue: false, colors: classicColors, }), new FieldColorSchemeMode({ - id: FieldColorModeId.ContinousGrYlRd, - name: 'Color by value / Green-Yellow-Red / Continouous', + id: 'continuous-GrYlRd', + name: 'By value / Green Yellow Red (gradient)', //description: 'Interpolated colors based value, min and max', isContinuous: true, isByValue: true, colors: ['green', 'yellow', 'red'], }), - new FieldColorSchemeMode({ - id: FieldColorModeId.ContinousBlGrOr, - name: 'Color by value / Blue-Green-Orange / Continouous', - //description: 'Interpolated colors based value, min and max', - isContinuous: true, - isByValue: true, - colors: ['blue', 'green', 'orange'], - }), ]; }); interface FieldColorSchemeModeOptions { - id: FieldColorModeId; + id: string; name: string; description?: string; colors: string[]; @@ -112,7 +104,7 @@ export class FieldColorSchemeMode implements FieldColorMode { return this.colorCache; } - this.colorCache = this.colors.map(c => getColorFromHexRgbOrName(c, theme.type)); + this.colorCache = this.colors.map(c => getColorForTheme(c, theme)); return this.colorCache; } @@ -157,6 +149,6 @@ export function getFieldColorMode(mode?: FieldColorModeId): FieldColorMode { function getFixedColor(field: Field, theme: GrafanaTheme) { return () => { - return getColorFromHexRgbOrName(field.config.color?.fixedColor ?? FALLBACK_COLOR, theme.type); + return getColorForTheme(field.config.color?.fixedColor ?? FALLBACK_COLOR, theme); }; } diff --git a/packages/grafana-data/src/types/fieldColor.ts b/packages/grafana-data/src/types/fieldColor.ts index f419196281d..f0929679574 100644 --- a/packages/grafana-data/src/types/fieldColor.ts +++ b/packages/grafana-data/src/types/fieldColor.ts @@ -1,7 +1,5 @@ export enum FieldColorModeId { Thresholds = 'thresholds', - ContinousGrYlRd = 'continuous-GrYlRd', - ContinousBlGrOr = 'continuous-BlGrOr', PaletteClassic = 'palette-classic', PaletteSaturated = 'palette-saturated', Fixed = 'fixed', diff --git a/packages/grafana-data/src/utils/namedColorsPalette.test.ts b/packages/grafana-data/src/utils/namedColorsPalette.test.ts index 9e24d840307..3cfc68c9e40 100644 --- a/packages/grafana-data/src/utils/namedColorsPalette.test.ts +++ b/packages/grafana-data/src/utils/namedColorsPalette.test.ts @@ -1,48 +1,9 @@ -import { - getColorName, - getColorDefinition, - getColorByName, - getColorFromHexRgbOrName, - getColorDefinitionByName, -} from './namedColorsPalette'; +import { getColorFromHexRgbOrName, getColorDefinitionByName } from './namedColorsPalette'; import { GrafanaThemeType } from '../types/theme'; describe('colors', () => { const SemiDarkBlue = getColorDefinitionByName('semi-dark-blue'); - describe('getColorDefinition', () => { - it('returns undefined for unknown hex', () => { - expect(getColorDefinition('#ff0000', GrafanaThemeType.Light)).toBeUndefined(); - expect(getColorDefinition('#ff0000', GrafanaThemeType.Dark)).toBeUndefined(); - }); - - it('returns definition for known hex', () => { - expect(getColorDefinition(SemiDarkBlue.variants.light, GrafanaThemeType.Light)).toEqual(SemiDarkBlue); - expect(getColorDefinition(SemiDarkBlue.variants.dark, GrafanaThemeType.Dark)).toEqual(SemiDarkBlue); - }); - }); - - describe('getColorName', () => { - it('returns undefined for unknown hex', () => { - expect(getColorName('#ff0000')).toBeUndefined(); - }); - - it('returns name for known hex', () => { - expect(getColorName(SemiDarkBlue.variants.light, GrafanaThemeType.Light)).toEqual(SemiDarkBlue.name); - expect(getColorName(SemiDarkBlue.variants.dark, GrafanaThemeType.Dark)).toEqual(SemiDarkBlue.name); - }); - }); - - describe('getColorByName', () => { - it('returns undefined for unknown color', () => { - expect(getColorByName('aruba-sunshine')).toBeUndefined(); - }); - - it('returns color definition for known color', () => { - expect(getColorByName(SemiDarkBlue.name)).toBe(SemiDarkBlue); - }); - }); - describe('getColorFromHexRgbOrName', () => { it('returns black for unknown color', () => { expect(getColorFromHexRgbOrName('aruba-sunshine')).toBe('#000000'); @@ -57,7 +18,7 @@ describe('colors', () => { }); it('returns color if specified as hex or rgb/a', () => { - expect(getColorFromHexRgbOrName('ff0000')).toBe('ff0000'); + expect(getColorFromHexRgbOrName('ff0000')).toBe('#ff0000'); expect(getColorFromHexRgbOrName('#ff0000')).toBe('#ff0000'); expect(getColorFromHexRgbOrName('#FF0000')).toBe('#FF0000'); expect(getColorFromHexRgbOrName('#CCC')).toBe('#CCC'); diff --git a/packages/grafana-data/src/utils/namedColorsPalette.ts b/packages/grafana-data/src/utils/namedColorsPalette.ts index 6ee5ff8604e..19795150259 100644 --- a/packages/grafana-data/src/utils/namedColorsPalette.ts +++ b/packages/grafana-data/src/utils/namedColorsPalette.ts @@ -1,6 +1,6 @@ import flatten from 'lodash/flatten'; import tinycolor from 'tinycolor2'; -import { GrafanaThemeType } from '../types/theme'; +import { GrafanaTheme, GrafanaThemeType } from '../types/theme'; type Hue = 'green' | 'yellow' | 'red' | 'blue' | 'orange' | 'purple'; @@ -49,6 +49,8 @@ export type ColorDefinition = { }; let colorsPaletteInstance: Map; +let colorsMap: Record | undefined; +let colorsMapTheme: GrafanaTheme | undefined; const buildColorDefinition = ( hue: Hue, @@ -65,61 +67,59 @@ const buildColorDefinition = ( isPrimary: !!isPrimary, }); -export const getColorDefinitionByName = (name: Color): ColorDefinition => { +export function getColorDefinitionByName(name: Color): ColorDefinition { return flatten(Array.from(getNamedColorPalette().values())).filter(definition => definition.name === name)[0]; -}; +} -export const getColorDefinition = (hex: string, theme: GrafanaThemeType): ColorDefinition | undefined => { - return flatten(Array.from(getNamedColorPalette().values())).filter( - definition => definition.variants[theme] === hex - )[0]; -}; +export function buildColorsMapForTheme(theme: GrafanaTheme): Record { + theme = theme ?? GrafanaThemeType.Dark; -const isHex = (color: string) => { - const hexRegex = /^((0x){0,1}|#{0,1})([0-9A-F]{8}|[0-9A-F]{6}|[0-9A-F]{3})$/gi; - return hexRegex.test(color); -}; + colorsMap = {} as Record; -export const getColorName = (color?: string, theme?: GrafanaThemeType): Color | undefined => { + for (const def of getNamedColorPalette().values()) { + for (const c of def) { + colorsMap[c.name] = c.variants[theme.type]; + } + } + + return colorsMap; +} + +export function getColorForTheme(color: string, theme: GrafanaTheme): string { if (!color) { - return undefined; + return 'gray'; + } + + // check if we need to rebuild cache + if (!colorsMap || colorsMapTheme !== theme) { + colorsMap = buildColorsMapForTheme(theme); + colorsMapTheme = theme; + } + + let realColor = colorsMap[color as Color]; + if (realColor) { + return realColor; + } + + if (color[0] === '#') { + return (colorsMap[color as Color] = color); } if (color.indexOf('rgb') > -1) { - return undefined; - } - if (isHex(color)) { - const definition = getColorDefinition(color, theme || GrafanaThemeType.Dark); - return definition ? definition.name : undefined; + return (colorsMap[color as Color] = color); } - return color as Color; -}; + return (colorsMap[color as Color] = tinycolor(color).toHexString()); +} -export const getColorByName = (colorName: string) => { - const definition = flatten(Array.from(getNamedColorPalette().values())).filter( - definition => definition.name === colorName - ); - return definition.length > 0 ? definition[0] : undefined; -}; +/** + * @deprecated use getColorForTheme + */ +export function getColorFromHexRgbOrName(color: string, type?: GrafanaThemeType): string { + const themeType = type ?? GrafanaThemeType.Dark; -export const getColorFromHexRgbOrName = (color: string, theme?: GrafanaThemeType): string => { - if (color.indexOf('rgb') > -1 || isHex(color)) { - return color; - } - - const colorDefinition = getColorByName(color); - - if (!colorDefinition) { - return new tinycolor(color).toHexString(); - } - - return theme ? colorDefinition.variants[theme] : colorDefinition.variants.dark; -}; - -export const getColorForTheme = (color: ColorDefinition, theme?: GrafanaThemeType) => { - return theme ? color.variants[theme] : color.variants.dark; -}; + return getColorForTheme(color, ({ type: themeType } as unknown) as GrafanaTheme); +} const buildNamedColorsPalette = () => { const palette = new Map(); diff --git a/packages/grafana-ui/src/components/Badge/Badge.tsx b/packages/grafana-ui/src/components/Badge/Badge.tsx index abe7ab23699..c51f22e460a 100644 --- a/packages/grafana-ui/src/components/Badge/Badge.tsx +++ b/packages/grafana-ui/src/components/Badge/Badge.tsx @@ -4,7 +4,7 @@ import { useTheme } from '../../themes/ThemeContext'; import { stylesFactory } from '../../themes/stylesFactory'; import { IconName } from '../../types'; import { Tooltip } from '../Tooltip/Tooltip'; -import { getColorFromHexRgbOrName, GrafanaTheme } from '@grafana/data'; +import { getColorForTheme, GrafanaTheme } from '@grafana/data'; import tinycolor from 'tinycolor2'; import { css } from 'emotion'; import { HorizontalGroup } from '..'; @@ -42,7 +42,7 @@ export const Badge = React.memo(({ icon, color, text, tooltip }) => Badge.displayName = 'Badge'; const getStyles = stylesFactory((theme: GrafanaTheme, color: BadgeColor) => { - let sourceColor = getColorFromHexRgbOrName(color); + let sourceColor = getColorForTheme(color, theme); let borderColor = ''; let bgColor = ''; let textColor = ''; diff --git a/packages/grafana-ui/src/components/BarGauge/BarGauge.tsx b/packages/grafana-ui/src/components/BarGauge/BarGauge.tsx index e28cea73641..1616cab9522 100644 --- a/packages/grafana-ui/src/components/BarGauge/BarGauge.tsx +++ b/packages/grafana-ui/src/components/BarGauge/BarGauge.tsx @@ -12,6 +12,8 @@ import { FieldConfig, FieldColorModeId, getFieldColorMode, + getColorForTheme, + FALLBACK_COLOR, } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors'; @@ -19,7 +21,6 @@ import { selectors } from '@grafana/e2e-selectors'; import { FormattedValueDisplay } from '../FormattedValueDisplay/FormattedValueDisplay'; // Utils -import { getColorFromHexRgbOrName } from '@grafana/data'; import { measureText, calculateFontSize } from '../../utils/measureText'; // Types @@ -131,8 +132,8 @@ export class BarGauge extends PureComponent { const { value, display } = this.props; if (positionValue === null) { return { - background: 'gray', - border: 'gray', + background: FALLBACK_COLOR, + border: FALLBACK_COLOR, }; } @@ -165,8 +166,8 @@ export class BarGauge extends PureComponent { } return { - background: 'gray', - border: 'gray', + background: FALLBACK_COLOR, + border: FALLBACK_COLOR, }; } @@ -526,7 +527,7 @@ export function getBarGradient(props: Props, maxSize: number): string { for (let i = 0; i < thresholds.steps.length; i++) { const threshold = thresholds.steps[i]; - const color = getColorFromHexRgbOrName(threshold.color); + const color = getColorForTheme(threshold.color, props.theme); const valuePercent = getValuePercent(threshold.value, minValue, maxValue); const pos = valuePercent * maxSize; const offset = Math.round(pos - (pos - lastpos) / 2); @@ -545,7 +546,7 @@ export function getBarGradient(props: Props, maxSize: number): string { } if (mode.colors) { - const scheme = mode.colors.map(item => getColorFromHexRgbOrName(item, theme.type)); + const scheme = mode.colors.map(item => getColorForTheme(item, theme)); for (let i = 0; i < scheme.length; i++) { const color = scheme[i]; @@ -560,18 +561,19 @@ export function getBarGradient(props: Props, maxSize: number): string { return gradient + ')'; } - return 'gray'; + return value.color ?? FALLBACK_COLOR; } /** * Only exported to for unit test */ export function getValueColor(props: Props): string { - const { theme, value } = props; + const { value } = props; if (value.color) { return value.color; } - return getColorFromHexRgbOrName('gray', theme.type); + + return FALLBACK_COLOR; } function getValueStyles( @@ -582,7 +584,7 @@ function getValueStyles( orientation: VizOrientation ): CSSProperties { const styles: CSSProperties = { - color: color, + color, height: `${height}px`, width: `${width}px`, display: 'flex', diff --git a/packages/grafana-ui/src/components/BigValue/BigValueLayout.tsx b/packages/grafana-ui/src/components/BigValue/BigValueLayout.tsx index c7dba399c28..9aac2e88d04 100644 --- a/packages/grafana-ui/src/components/BigValue/BigValueLayout.tsx +++ b/packages/grafana-ui/src/components/BigValue/BigValueLayout.tsx @@ -4,7 +4,7 @@ import tinycolor from 'tinycolor2'; import { Chart, Geom } from 'bizcharts'; // Utils -import { getColorFromHexRgbOrName, formattedValueToString, DisplayValue } from '@grafana/data'; +import { formattedValueToString, DisplayValue, getColorForTheme } from '@grafana/data'; import { calculateFontSize } from '../../utils/measureText'; // Types @@ -30,7 +30,7 @@ export abstract class BigValueLayout { constructor(private props: Props) { const { width, height, value, theme } = props; - this.valueColor = getColorFromHexRgbOrName(value.color || 'green', theme.type); + this.valueColor = getColorForTheme(value.color || 'green', theme); this.panelPadding = height > 100 ? 12 : 8; this.textValues = getTextValues(props); this.justifyCenter = shouldJustifyCenter(props.justifyMode, this.textValues.title); diff --git a/packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx b/packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx index b9f66b9d62b..5c6743564c7 100644 --- a/packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx +++ b/packages/grafana-ui/src/components/ColorPicker/ColorPicker.tsx @@ -3,7 +3,7 @@ import omit from 'lodash/omit'; import { PopoverController } from '../Tooltip/PopoverController'; import { Popover } from '../Tooltip/Popover'; import { ColorPickerPopover, ColorPickerProps, ColorPickerChangeHandler } from './ColorPickerPopover'; -import { getColorFromHexRgbOrName } from '@grafana/data'; +import { getColorForTheme } from '@grafana/data'; import { SeriesColorPickerPopover } from './SeriesColorPickerPopover'; import { withTheme } from '../../themes/ThemeContext'; @@ -74,7 +74,7 @@ export const colorPickerFactory = ( ref={this.pickerTriggerRef} onClick={showPopper} onMouseLeave={hidePopper} - color={getColorFromHexRgbOrName(this.props.color || '#000000', theme.type)} + color={getColorForTheme(this.props.color || '#000000', theme)} /> )} diff --git a/packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.test.tsx b/packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.test.tsx index 8f96b2412d9..0beb1f4fcc0 100644 --- a/packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.test.tsx +++ b/packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.test.tsx @@ -4,18 +4,16 @@ import { ColorPickerPopover } from './ColorPickerPopover'; import { ColorSwatch } from './NamedColorsGroup'; import flatten from 'lodash/flatten'; import { getTheme } from '../../themes'; -import { GrafanaThemeType, getColorDefinitionByName, getNamedColorPalette } from '@grafana/data'; +import { GrafanaThemeType, getNamedColorPalette, getColorFromHexRgbOrName } from '@grafana/data'; const allColors = flatten(Array.from(getNamedColorPalette().values())); describe('ColorPickerPopover', () => { - const BasicGreen = getColorDefinitionByName('green'); - const BasicBlue = getColorDefinitionByName('blue'); - describe('rendering', () => { it('should render provided color as selected if color provided by name', () => { - const wrapper = mount( {}} theme={getTheme()} />); - const selectedSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === BasicGreen.name); + const theme = getTheme(); + const wrapper = mount( {}} theme={theme} />); + const selectedSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === 'green'); const notSelectedSwatches = wrapper.find(ColorSwatch).filterWhere(node => node.prop('isSelected') === false); expect(selectedSwatch.length).toBe(1); @@ -24,10 +22,10 @@ describe('ColorPickerPopover', () => { }); it('should render provided color as selected if color provided by hex', () => { - const wrapper = mount( - {}} theme={getTheme()} /> - ); - const selectedSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === BasicGreen.name); + const theme = getTheme(); + const wrapper = mount( {}} theme={theme} />); + + const selectedSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === 'green'); const notSelectedSwatches = wrapper.find(ColorSwatch).filterWhere(node => node.prop('isSelected') === false); expect(selectedSwatch.length).toBe(1); @@ -47,35 +45,31 @@ describe('ColorPickerPopover', () => { it('should pass hex color value to onChange prop by default', () => { wrapper = mount( - + ); - const basicBlueSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === BasicBlue.name); + const basicBlueSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === 'green'); basicBlueSwatch.simulate('click'); expect(onChangeSpy).toBeCalledTimes(1); - expect(onChangeSpy).toBeCalledWith(BasicBlue.variants.light); + expect(onChangeSpy).toBeCalledWith(getColorFromHexRgbOrName('green', GrafanaThemeType.Light)); }); it('should pass color name to onChange prop when named colors enabled', () => { wrapper = mount( ); - const basicBlueSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === BasicBlue.name); + const basicBlueSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === 'green'); basicBlueSwatch.simulate('click'); expect(onChangeSpy).toBeCalledTimes(1); - expect(onChangeSpy).toBeCalledWith(BasicBlue.name); + expect(onChangeSpy).toBeCalledWith('green'); }); }); }); diff --git a/packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.tsx b/packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.tsx index 2395698837f..5a9efb1835c 100644 --- a/packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.tsx +++ b/packages/grafana-ui/src/components/ColorPicker/ColorPickerPopover.tsx @@ -4,7 +4,7 @@ import { PopoverContentProps } from '../Tooltip/Tooltip'; import SpectrumPalette from './SpectrumPalette'; import { Themeable } from '../../types/theme'; import { warnAboutColorPickerPropsDeprecation } from './warnAboutColorPickerPropsDeprecation'; -import { GrafanaThemeType, getColorName, getColorFromHexRgbOrName } from '@grafana/data'; +import { GrafanaThemeType, getColorForTheme } from '@grafana/data'; export type ColorPickerChangeHandler = (color: string) => void; @@ -57,7 +57,7 @@ export class ColorPickerPopover extends React if (enableNamedColors) { return changeHandler(color); } - changeHandler(getColorFromHexRgbOrName(color, theme.type)); + changeHandler(getColorForTheme(color, theme)); }; onTabChange = (tab: PickerType | keyof T) => { @@ -72,9 +72,7 @@ export class ColorPickerPopover extends React case 'spectrum': return ; case 'palette': - return ( - - ); + return ; default: return this.renderCustomPicker(activePicker); } diff --git a/packages/grafana-ui/src/components/ColorPicker/NamedColorsGroup.tsx b/packages/grafana-ui/src/components/ColorPicker/NamedColorsGroup.tsx index dc61b1e44a4..7ced267e804 100644 --- a/packages/grafana-ui/src/components/ColorPicker/NamedColorsGroup.tsx +++ b/packages/grafana-ui/src/components/ColorPicker/NamedColorsGroup.tsx @@ -1,6 +1,6 @@ import React, { FunctionComponent } from 'react'; import { Themeable } from '../../types'; -import { ColorDefinition, getColorForTheme } from '@grafana/data'; +import { ColorDefinition } from '@grafana/data'; import { Color } from 'csstype'; import upperFirst from 'lodash/upperFirst'; import find from 'lodash/find'; @@ -86,7 +86,7 @@ const NamedColorsGroup: FunctionComponent = ({ key={primaryColor.name} isSelected={primaryColor.name === selectedColor} variant={ColorSwatchVariant.Large} - color={getColorForTheme(primaryColor, theme.type)} + color={primaryColor.variants[theme.type]} label={upperFirst(primaryColor.hue)} onClick={() => onColorSelect(primaryColor)} theme={theme} @@ -105,7 +105,7 @@ const NamedColorsGroup: FunctionComponent = ({ onColorSelect(color)} theme={theme} /> diff --git a/packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.story.tsx b/packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.story.tsx index 1e04b4446d7..16017a910b4 100644 --- a/packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.story.tsx +++ b/packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.story.tsx @@ -1,16 +1,11 @@ import React from 'react'; import { NamedColorsPalette } from './NamedColorsPalette'; -import { getColorName, getColorDefinitionByName } from '@grafana/data'; import { select } from '@storybook/addon-knobs'; import { withCenteredStory } from '../../utils/storybook/withCenteredStory'; import { renderComponentWithTheme } from '../../utils/storybook/withTheme'; import { UseState } from '../../utils/storybook/UseState'; import mdx from './ColorPicker.mdx'; -const BasicGreen = getColorDefinitionByName('green'); -const BasicRed = getColorDefinitionByName('red'); -const LightBlue = getColorDefinitionByName('light-blue'); - export default { title: 'Pickers and Editors/ColorPicker/Palettes/NamedColorsPalette', component: NamedColorsPalette, @@ -44,22 +39,3 @@ export const namedColors = () => { ); }; - -export const hexValues = () => { - let hexVals: any = {}; - hexVals[BasicGreen.variants.dark] = BasicGreen.variants.dark; - hexVals[BasicRed.variants.dark] = BasicRed.variants.dark; - hexVals[LightBlue.variants.dark] = LightBlue.variants.dark; - - const selectedColor = select('Selected color', hexVals, 'red'); - return ( - - {(selectedColor, updateSelectedColor) => { - return renderComponentWithTheme(NamedColorsPalette, { - color: getColorName(selectedColor), - onChange: updateSelectedColor, - }); - }} - - ); -}; diff --git a/packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.tsx b/packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.tsx index 65f7f890255..57f5ea42211 100644 --- a/packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.tsx +++ b/packages/grafana-ui/src/components/ColorPicker/NamedColorsPalette.tsx @@ -1,10 +1,10 @@ import React from 'react'; -import { Color, getNamedColorPalette } from '@grafana/data'; +import { getNamedColorPalette } from '@grafana/data'; import { Themeable } from '../../types/index'; import NamedColorsGroup from './NamedColorsGroup'; export interface NamedColorsPaletteProps extends Themeable { - color?: Color; + color?: string; onChange: (colorName: string) => void; } diff --git a/packages/grafana-ui/src/components/ColorPicker/SpectrumPalette.tsx b/packages/grafana-ui/src/components/ColorPicker/SpectrumPalette.tsx index f6e3e5cfbd1..bd22d22b6ad 100644 --- a/packages/grafana-ui/src/components/ColorPicker/SpectrumPalette.tsx +++ b/packages/grafana-ui/src/components/ColorPicker/SpectrumPalette.tsx @@ -6,7 +6,7 @@ import tinycolor from 'tinycolor2'; import ColorInput from './ColorInput'; import { Themeable } from '../../types'; import SpectrumPalettePointer, { SpectrumPalettePointerProps } from './SpectrumPalettePointer'; -import { GrafanaTheme, getColorFromHexRgbOrName } from '@grafana/data'; +import { GrafanaTheme, getColorForTheme } from '@grafana/data'; export interface SpectrumPaletteProps extends Themeable { color: string; @@ -86,7 +86,7 @@ const SpectrumPalette: React.FunctionComponent = ({ color, return (
{ onChange(tinycolor(a.rgb).toString()); }} diff --git a/packages/grafana-ui/src/components/Gauge/Gauge.tsx b/packages/grafana-ui/src/components/Gauge/Gauge.tsx index 4f4f8f24694..e37b139987f 100644 --- a/packages/grafana-ui/src/components/Gauge/Gauge.tsx +++ b/packages/grafana-ui/src/components/Gauge/Gauge.tsx @@ -2,12 +2,12 @@ import React, { PureComponent } from 'react'; import $ from 'jquery'; import { DisplayValue, - getColorFromHexRgbOrName, formattedValueToString, FieldConfig, ThresholdsMode, getActiveThreshold, Threshold, + getColorForTheme, } from '@grafana/data'; import { Themeable } from '../../types'; import { selectThemeVariant } from '../../themes'; @@ -67,7 +67,7 @@ export class Gauge extends PureComponent { const first = getActiveThreshold(min, steps); const last = getActiveThreshold(max, steps); const formatted: Threshold[] = []; - formatted.push({ value: +min.toFixed(decimals), color: getColorFromHexRgbOrName(first.color, theme.type) }); + formatted.push({ value: +min.toFixed(decimals), color: getColorForTheme(first.color, theme) }); let skip = true; for (let i = 0; i < steps.length; i++) { const step = steps[i]; @@ -78,12 +78,12 @@ export class Gauge extends PureComponent { continue; } const prev = steps[i - 1]; - formatted.push({ value: step.value, color: getColorFromHexRgbOrName(prev!.color, theme.type) }); + formatted.push({ value: step.value, color: getColorForTheme(prev!.color, theme) }); if (step === last) { break; } } - formatted.push({ value: +max.toFixed(decimals), color: getColorFromHexRgbOrName(last.color, theme.type) }); + formatted.push({ value: +max.toFixed(decimals), color: getColorForTheme(last.color, theme) }); return formatted; } diff --git a/packages/grafana-ui/src/components/Graph/utils.test.ts b/packages/grafana-ui/src/components/Graph/utils.test.ts index 8acb71102c9..4925ecac157 100644 --- a/packages/grafana-ui/src/components/Graph/utils.test.ts +++ b/packages/grafana-ui/src/components/Graph/utils.test.ts @@ -4,10 +4,10 @@ import { FieldType, FieldCache, FieldColorModeId, - getColorFromHexRgbOrName, - GrafanaThemeType, Field, + getColorForTheme, } from '@grafana/data'; +import { getTheme } from '../../themes'; import { getMultiSeriesGraphHoverInfo, findHoverIndexFromData, graphTimeFormat } from './utils'; const mockResult = ( @@ -63,7 +63,7 @@ const cSeries = toDataFrame({ }); function getFixedThemedColor(field: Field): string { - return getColorFromHexRgbOrName(field.config.color!.fixedColor!, GrafanaThemeType.Dark); + return getColorForTheme(field.config.color!.fixedColor!, getTheme()); } describe('Graph utils', () => { diff --git a/packages/grafana-ui/src/components/OptionsUI/color.tsx b/packages/grafana-ui/src/components/OptionsUI/color.tsx index 60b0a696ecc..1b638a94193 100644 --- a/packages/grafana-ui/src/components/OptionsUI/color.tsx +++ b/packages/grafana-ui/src/components/OptionsUI/color.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import { GrafanaTheme, getColorFromHexRgbOrName } from '@grafana/data'; +import { getColorForTheme, GrafanaTheme } from '@grafana/data'; import { ColorPicker } from '../ColorPicker/ColorPicker'; import { stylesFactory, useTheme } from '../../themes'; import { css } from 'emotion'; @@ -25,7 +25,7 @@ export const ColorValueEditor: React.FC = ({ value, onChange }) => { ref={ref} onClick={showColorPicker} onMouseLeave={hideColorPicker} - color={value ? getColorFromHexRgbOrName(value, theme.type) : theme.colors.formInputBorder} + color={value ? getColorForTheme(value, theme) : theme.colors.formInputBorder} />
{/*
diff --git a/packages/grafana-ui/src/components/OptionsUI/fieldColor.tsx b/packages/grafana-ui/src/components/OptionsUI/fieldColor.tsx index d0c953759a8..2e7b0061a3c 100644 --- a/packages/grafana-ui/src/components/OptionsUI/fieldColor.tsx +++ b/packages/grafana-ui/src/components/OptionsUI/fieldColor.tsx @@ -7,7 +7,7 @@ import { fieldColorModeRegistry, FieldColorMode, GrafanaTheme, - getColorFromHexRgbOrName, + getColorForTheme, } from '@grafana/data'; import { Select } from '../Select/Select'; import { ColorValueEditor } from './color'; @@ -70,7 +70,7 @@ const FieldColorModeViz: FC = ({ mode, theme }) => { return null; } - const colors = mode.colors.map(item => getColorFromHexRgbOrName(item, theme.type)); + const colors = mode.colors.map(item => getColorForTheme(item, theme)); const style: CSSProperties = { height: '8px', width: '100%', diff --git a/packages/grafana-ui/src/components/uPlot/geometries/configGetters.ts b/packages/grafana-ui/src/components/uPlot/geometries/configGetters.ts index 9f67671c915..2de6c14795a 100644 --- a/packages/grafana-ui/src/components/uPlot/geometries/configGetters.ts +++ b/packages/grafana-ui/src/components/uPlot/geometries/configGetters.ts @@ -1,10 +1,10 @@ import { AreaProps, LineProps, PointProps } from './types'; import tinycolor from 'tinycolor2'; -import { getColorFromHexRgbOrName } from '@grafana/data'; export const getAreaConfig = (props: AreaProps) => { + // TODO can we pass therem here? or make sure color is already correct? const fill = props.fill - ? tinycolor(getColorFromHexRgbOrName(props.color)) + ? tinycolor(props.color) .setAlpha(props.fill) .toRgbString() : undefined; diff --git a/packages/grafana-ui/src/components/uPlot/plugins/LegendPlugin.tsx b/packages/grafana-ui/src/components/uPlot/plugins/LegendPlugin.tsx index 32cbf65385d..bb4684b88af 100644 --- a/packages/grafana-ui/src/components/uPlot/plugins/LegendPlugin.tsx +++ b/packages/grafana-ui/src/components/uPlot/plugins/LegendPlugin.tsx @@ -1,8 +1,9 @@ import React from 'react'; import { GraphCustomFieldConfig, GraphLegend, LegendDisplayMode, LegendItem } from '../..'; import { usePlotData } from '../context'; -import { FieldType, getColorFromHexRgbOrName, getFieldDisplayName } from '@grafana/data'; +import { FieldType, getColorForTheme, getFieldDisplayName } from '@grafana/data'; import { colors } from '../../../utils'; +import { useTheme } from '../../../themes'; export type LegendPlacement = 'top' | 'bottom' | 'left' | 'right'; @@ -13,6 +14,7 @@ interface LegendPluginProps { export const LegendPlugin: React.FC = ({ placement, displayMode = LegendDisplayMode.List }) => { const { data } = usePlotData(); + const theme = useTheme(); const legendItems: LegendItem[] = []; @@ -27,7 +29,7 @@ export const LegendPlugin: React.FC = ({ placement, displayMo legendItems.push({ color: field.config.color && field.config.color.fixedColor - ? getColorFromHexRgbOrName(field.config.color.fixedColor) + ? getColorForTheme(field.config.color.fixedColor, theme) : colors[seriesIdx], label: getFieldDisplayName(field, data), isVisible: true, diff --git a/public/app/plugins/panel/graph/data_processor.ts b/public/app/plugins/panel/graph/data_processor.ts index cff76a35978..d17b43dd2a0 100644 --- a/public/app/plugins/panel/graph/data_processor.ts +++ b/public/app/plugins/panel/graph/data_processor.ts @@ -1,7 +1,6 @@ import _ from 'lodash'; import { colors } from '@grafana/ui'; import { - getColorFromHexRgbOrName, TimeRange, FieldType, Field, @@ -9,6 +8,7 @@ import { getTimeField, dateTime, getFieldDisplayName, + getColorForTheme, } from '@grafana/data'; import TimeSeries from 'app/core/time_series2'; import config from 'app/core/config'; @@ -84,7 +84,7 @@ export class DataProcessor { const series = new TimeSeries({ datapoints: datapoints || [], alias: alias, - color: getColorFromHexRgbOrName(color, config.theme.type), + color: getColorForTheme(color, config.theme), unit: field.config ? field.config.unit : undefined, dataFrameIndex, fieldIndex, diff --git a/public/app/plugins/panel/graph/graph.ts b/public/app/plugins/panel/graph/graph.ts index 43b2c85b753..96d5287ec99 100644 --- a/public/app/plugins/panel/graph/graph.ts +++ b/public/app/plugins/panel/graph/graph.ts @@ -75,7 +75,7 @@ class GraphElement { this.panelWidth = 0; this.eventManager = new EventManager(this.ctrl); this.thresholdManager = new ThresholdManager(this.ctrl); - this.timeRegionManager = new TimeRegionManager(this.ctrl, config.theme.type); + this.timeRegionManager = new TimeRegionManager(this.ctrl); // @ts-ignore this.tooltip = new GraphTooltip(this.elem, this.ctrl.dashboard, this.scope, () => { return this.sortedSeries; diff --git a/public/app/plugins/panel/graph/module.ts b/public/app/plugins/panel/graph/module.ts index 8c43a1e88be..35b20f494da 100644 --- a/public/app/plugins/panel/graph/module.ts +++ b/public/app/plugins/panel/graph/module.ts @@ -12,7 +12,7 @@ import { axesEditorComponent } from './axes_editor'; import config from 'app/core/config'; import TimeSeries from 'app/core/time_series2'; import { getProcessedDataFrames } from 'app/features/dashboard/state/runRequest'; -import { getColorFromHexRgbOrName, PanelEvents, PanelPlugin, DataFrame, FieldConfigProperty } from '@grafana/data'; +import { PanelEvents, PanelPlugin, DataFrame, FieldConfigProperty, getColorForTheme } from '@grafana/data'; import { GraphContextMenuCtrl } from './GraphContextMenuCtrl'; import { graphPanelMigrationHandler } from './GraphMigrations'; @@ -327,7 +327,7 @@ export class GraphCtrl extends MetricsPanelCtrl { } onColorChange = (series: any, color: string) => { - series.setColor(getColorFromHexRgbOrName(color, config.theme.type)); + series.setColor(getColorForTheme(color, config.theme)); this.panel.aliasColors[series.alias] = color; this.render(); }; diff --git a/public/app/plugins/panel/graph/specs/threshold_manager.test.ts b/public/app/plugins/panel/graph/specs/threshold_manager.test.ts index 9f3d77a6ee3..0b0d0b251b1 100644 --- a/public/app/plugins/panel/graph/specs/threshold_manager.test.ts +++ b/public/app/plugins/panel/graph/specs/threshold_manager.test.ts @@ -1,4 +1,5 @@ import angular from 'angular'; +import { config } from 'app/core/config'; import TimeSeries from 'app/core/time_series2'; import { ThresholdManager } from '../threshold_manager'; @@ -31,6 +32,7 @@ describe('ThresholdManager', () => { describe('When creating plot markings', () => { plotOptionsScenario('for simple gt threshold', (ctx: any) => { + console.log('config', config.theme); ctx.setup([{ op: 'gt', value: 300, fill: true, line: true, colorMode: 'critical' }]); it('should add fill for threshold with fill: true', () => { diff --git a/public/app/plugins/panel/graph/threshold_manager.ts b/public/app/plugins/panel/graph/threshold_manager.ts index a988a0336d3..d6e24a3db5c 100644 --- a/public/app/plugins/panel/graph/threshold_manager.ts +++ b/public/app/plugins/panel/graph/threshold_manager.ts @@ -1,9 +1,10 @@ import 'vendor/flot/jquery.flot'; import $ from 'jquery'; import _ from 'lodash'; -import { getColorFromHexRgbOrName } from '@grafana/data'; +import { getColorForTheme } from '@grafana/data'; import { CoreEvents } from 'app/types'; import { PanelCtrl } from 'app/features/panel/panel_ctrl'; +import { config } from 'app/core/config'; export class ThresholdManager { plot: any; @@ -228,12 +229,12 @@ export class ThresholdManager { if (threshold.yaxis === 'right' && this.hasSecondYAxis) { options.grid.markings.push({ y2axis: { from: threshold.value, to: limit }, - color: getColorFromHexRgbOrName(fillColor), + color: getColorForTheme(fillColor, config.theme), }); } else { options.grid.markings.push({ yaxis: { from: threshold.value, to: limit }, - color: getColorFromHexRgbOrName(fillColor), + color: getColorForTheme(fillColor, config.theme), }); } } @@ -241,12 +242,12 @@ export class ThresholdManager { if (threshold.yaxis === 'right' && this.hasSecondYAxis) { options.grid.markings.push({ y2axis: { from: threshold.value, to: threshold.value }, - color: getColorFromHexRgbOrName(lineColor), + color: getColorForTheme(lineColor, config.theme), }); } else { options.grid.markings.push({ yaxis: { from: threshold.value, to: threshold.value }, - color: getColorFromHexRgbOrName(lineColor), + color: getColorForTheme(lineColor, config.theme), }); } } diff --git a/public/app/plugins/panel/graph/time_region_manager.ts b/public/app/plugins/panel/graph/time_region_manager.ts index 31eb4ce7814..ccf0f18b6fe 100644 --- a/public/app/plugins/panel/graph/time_region_manager.ts +++ b/public/app/plugins/panel/graph/time_region_manager.ts @@ -1,6 +1,7 @@ import 'vendor/flot/jquery.flot'; import _ from 'lodash'; -import { GrafanaThemeType, getColorFromHexRgbOrName, dateTime, DateTime, AbsoluteTimeRange } from '@grafana/data'; +import { getColorForTheme, dateTime, DateTime, AbsoluteTimeRange, GrafanaTheme } from '@grafana/data'; +import { config } from 'app/core/config'; type TimeRegionColorDefinition = { fill: string | null; @@ -42,27 +43,27 @@ export function getColorModes() { }); } -function getColor(timeRegion: any, theme: GrafanaThemeType): TimeRegionColorDefinition { +function getColor(timeRegion: any, theme: GrafanaTheme): TimeRegionColorDefinition { if (Object.keys(colorModes).indexOf(timeRegion.colorMode) === -1) { timeRegion.colorMode = 'red'; } if (timeRegion.colorMode === 'custom') { return { - fill: timeRegion.fill && timeRegion.fillColor ? getColorFromHexRgbOrName(timeRegion.fillColor, theme) : null, - line: timeRegion.line && timeRegion.lineColor ? getColorFromHexRgbOrName(timeRegion.lineColor, theme) : null, + fill: timeRegion.fill && timeRegion.fillColor ? getColorForTheme(timeRegion.fillColor, theme) : null, + line: timeRegion.line && timeRegion.lineColor ? getColorForTheme(timeRegion.lineColor, theme) : null, }; } const colorMode = colorModes[timeRegion.colorMode]; if (colorMode.themeDependent === true) { - return theme === GrafanaThemeType.Light ? colorMode.lightColor : colorMode.darkColor; + return theme.isLight ? colorMode.lightColor : colorMode.darkColor; } return { - fill: timeRegion.fill ? getColorFromHexRgbOrName(colorMode.color.fill, theme) : null, - line: timeRegion.fill ? getColorFromHexRgbOrName(colorMode.color.line, theme) : null, + fill: timeRegion.fill ? getColorForTheme(colorMode.color.fill, theme) : null, + line: timeRegion.fill ? getColorForTheme(colorMode.color.line, theme) : null, }; } @@ -70,7 +71,7 @@ export class TimeRegionManager { plot: any; timeRegions: any; - constructor(private panelCtrl: any, private theme: GrafanaThemeType = GrafanaThemeType.Dark) {} + constructor(private panelCtrl: any) {} draw(plot: any) { this.timeRegions = this.panelCtrl.panel.timeRegions; @@ -204,7 +205,7 @@ export class TimeRegionManager { fromStart.add(24, 'hours'); } - timeRegionColor = getColor(timeRegion, this.theme); + timeRegionColor = getColor(timeRegion, config.theme); for (let j = 0; j < regions.length; j++) { const r = regions[j]; diff --git a/public/app/plugins/panel/heatmap/color_legend.ts b/public/app/plugins/panel/heatmap/color_legend.ts index ff46d051364..05b074d00a7 100644 --- a/public/app/plugins/panel/heatmap/color_legend.ts +++ b/public/app/plugins/panel/heatmap/color_legend.ts @@ -5,7 +5,8 @@ import { contextSrv } from 'app/core/core'; import { tickStep } from 'app/core/utils/ticks'; import { getColorScale, getOpacityScale } from './color_scale'; import coreModule from 'app/core/core_module'; -import { PanelEvents, GrafanaThemeType, getColorFromHexRgbOrName } from '@grafana/data'; +import { PanelEvents, getColorForTheme } from '@grafana/data'; +import { config } from 'app/core/config'; const LEGEND_HEIGHT_PX = 6; const LEGEND_WIDTH_PX = 100; @@ -272,13 +273,7 @@ function drawSimpleOpacityLegend(elem: JQuery, options: { colorScale: string; ex .attr('width', rangeStep) .attr('height', legendHeight) .attr('stroke-width', 0) - .attr( - 'fill', - getColorFromHexRgbOrName( - options.cardColor, - contextSrv.user.lightTheme ? GrafanaThemeType.Light : GrafanaThemeType.Dark - ) - ) + .attr('fill', getColorForTheme(options.cardColor, config.theme)) .style('opacity', d => legendOpacityScale(d)); } } diff --git a/public/app/plugins/panel/heatmap/rendering.ts b/public/app/plugins/panel/heatmap/rendering.ts index 48264645bdf..7c7fe30b929 100644 --- a/public/app/plugins/panel/heatmap/rendering.ts +++ b/public/app/plugins/panel/heatmap/rendering.ts @@ -9,14 +9,14 @@ import { getColorScale, getOpacityScale } from './color_scale'; import { toUtc, PanelEvents, - GrafanaThemeType, - getColorFromHexRgbOrName, getValueFormat, formattedValueToString, dateTimeFormat, + getColorForTheme, } from '@grafana/data'; import { graphTimeFormat } from '@grafana/ui'; import { CoreEvents } from 'app/types'; +import { config } from 'app/core/config'; const MIN_CARD_SIZE = 1, CARD_PADDING = 1, @@ -682,10 +682,7 @@ export class HeatmapRenderer { getCardColor(d: { count: any }) { if (this.panel.color.mode === 'opacity') { - return getColorFromHexRgbOrName( - this.panel.color.cardColor, - contextSrv.user.lightTheme ? GrafanaThemeType.Light : GrafanaThemeType.Dark - ); + return getColorForTheme(this.panel.color.cardColor, config.theme); } else { return this.colorScale(d.count); } diff --git a/public/app/plugins/panel/singlestat/module.ts b/public/app/plugins/panel/singlestat/module.ts index e9f336eca5e..9b13f5fd77d 100644 --- a/public/app/plugins/panel/singlestat/module.ts +++ b/public/app/plugins/panel/singlestat/module.ts @@ -19,11 +19,11 @@ import { LegacyResponseData, getFlotPairs, getDisplayProcessor, - getColorFromHexRgbOrName, PanelEvents, formattedValueToString, locationUtil, getFieldDisplayName, + getColorForTheme, } from '@grafana/data'; import { convertOldAngularValueMapping } from '@grafana/ui'; @@ -542,7 +542,7 @@ class SingleStatCtrl extends MetricsPanelCtrl { show: true, fill: 1, lineWidth: 1, - fillColor: getColorFromHexRgbOrName(panel.sparkline.fillColor, config.theme.type), + fillColor: getColorForTheme(panel.sparkline.fillColor, config.theme), zero: false, }, }, @@ -564,7 +564,7 @@ class SingleStatCtrl extends MetricsPanelCtrl { const plotSeries = { data: data.sparkline, - color: getColorFromHexRgbOrName(panel.sparkline.lineColor, config.theme.type), + color: getColorForTheme(panel.sparkline.lineColor, config.theme), }; $.plot(plotCanvas, [plotSeries], options); @@ -585,7 +585,7 @@ class SingleStatCtrl extends MetricsPanelCtrl { // Map panel colors to hex or rgb/a values if (panel.colors) { - data.colorMap = panel.colors.map((color: string) => getColorFromHexRgbOrName(color, config.theme.type)); + data.colorMap = panel.colors.map((color: string) => getColorForTheme(color, config.theme)); } const body = panel.gauge.show ? '' : getBigValueHtml(); diff --git a/public/app/plugins/panel/table-old/module.ts b/public/app/plugins/panel/table-old/module.ts index b6b7a24d84a..2b3660c99d5 100644 --- a/public/app/plugins/panel/table-old/module.ts +++ b/public/app/plugins/panel/table-old/module.ts @@ -129,7 +129,7 @@ export class TablePanelCtrl extends MetricsPanelCtrl { this.dashboard.getTimezone(), this.$sanitize, this.templateSrv, - config.theme.type + config.theme ); return super.render(this.table); diff --git a/public/app/plugins/panel/table-old/renderer.ts b/public/app/plugins/panel/table-old/renderer.ts index 61f79fcb6f6..7cf5f4b1191 100644 --- a/public/app/plugins/panel/table-old/renderer.ts +++ b/public/app/plugins/panel/table-old/renderer.ts @@ -2,9 +2,7 @@ import _ from 'lodash'; import { escapeStringForRegex, formattedValueToString, - getColorFromHexRgbOrName, getValueFormat, - GrafanaThemeType, ScopedVars, stringStartsAsRegEx, stringToJsRegex, @@ -13,6 +11,8 @@ import { TimeZone, dateTimeFormatISO, dateTimeFormat, + getColorForTheme, + GrafanaTheme, } from '@grafana/data'; import { getTemplateSrv, TemplateSrv } from '@grafana/runtime'; import { ColumnRender, TableRenderModel, ColumnStyle } from './types'; @@ -28,7 +28,7 @@ export class TableRenderer { private timeZone: TimeZone, private sanitize: (v: any) => any, private templateSrv: TemplateSrv = getTemplateSrv(), - private theme?: GrafanaThemeType + private theme: GrafanaTheme ) { this.initColumns(); } @@ -75,10 +75,10 @@ export class TableRenderer { } for (let i = style.thresholds.length; i > 0; i--) { if (value >= style.thresholds[i - 1]) { - return getColorFromHexRgbOrName(style.colors[i], this.theme); + return getColorForTheme(style.colors[i], this.theme); } } - return getColorFromHexRgbOrName(_.first(style.colors), this.theme); + return getColorForTheme(_.first(style.colors), this.theme); } defaultCellFormatter(v: any, style: ColumnStyle) { diff --git a/public/app/plugins/panel/table-old/specs/renderer.test.ts b/public/app/plugins/panel/table-old/specs/renderer.test.ts index ffe3a050f5a..caca84f279b 100644 --- a/public/app/plugins/panel/table-old/specs/renderer.test.ts +++ b/public/app/plugins/panel/table-old/specs/renderer.test.ts @@ -1,8 +1,9 @@ import _ from 'lodash'; import TableModel from 'app/core/table_model'; import { TableRenderer } from '../renderer'; -import { getColorDefinitionByName, ScopedVars, TimeZone } from '@grafana/data'; +import { ScopedVars, TimeZone } from '@grafana/data'; import { ColumnRender } from '../types'; +import { config } from 'app/core/config'; const utc: TimeZone = 'utc'; @@ -23,8 +24,6 @@ const templateSrv = { }; describe('when rendering table', () => { - const SemiDarkOrange = getColorDefinitionByName('semi-dark-orange'); - describe('given 13 columns', () => { const table = new TableModel(); table.columns = [ @@ -87,7 +86,7 @@ describe('when rendering table', () => { decimals: 1, colorMode: 'value', thresholds: [50, 80], - colors: ['#00ff00', SemiDarkOrange.name, 'rgb(1,0,0)'], + colors: ['#00ff00', 'semi-dark-orange', 'rgb(1,0,0)'], }, { pattern: 'String', @@ -178,7 +177,7 @@ describe('when rendering table', () => { ], colorMode: 'value', thresholds: [1, 2], - colors: ['#00ff00', SemiDarkOrange.name, 'rgb(1,0,0)'], + colors: ['#00ff00', 'semi-dark-orange', 'rgb(1,0,0)'], }, { pattern: 'RangeMappingColored', @@ -198,7 +197,7 @@ describe('when rendering table', () => { ], colorMode: 'value', thresholds: [2, 5], - colors: ['#00ff00', SemiDarkOrange.name, 'rgb(1,0,0)'], + colors: ['#00ff00', 'semi-dark-orange', 'rgb(1,0,0)'], }, { pattern: 'HiddenType', @@ -212,7 +211,7 @@ describe('when rendering table', () => { }; //@ts-ignore - const renderer = new TableRenderer(panel, table, utc, sanitize, templateSrv); + const renderer = new TableRenderer(panel, table, utc, sanitize, templateSrv, config.theme); it('time column should be formatted', () => { const html = renderer.renderCell(0, 0, 1388556366666); @@ -271,7 +270,7 @@ describe('when rendering table', () => { it('colored cell should have style (handles named color values', () => { const html = renderer.renderCell(2, 0, 55); - expect(html).toBe(`55.0`); + expect(html).toBe(`55.0`); }); it('colored cell should have style handles(rgb color values)', () => { @@ -368,12 +367,12 @@ describe('when rendering table', () => { it('value should be mapped to text and colored cell should have style', () => { const html = renderer.renderCell(11, 0, 1); - expect(html).toBe(`on`); + expect(html).toBe(`on`); }); it('value should be mapped to text and colored cell should have style', () => { const html = renderer.renderCell(11, 0, '1'); - expect(html).toBe(`on`); + expect(html).toBe(`on`); }); it('value should be mapped to text and colored cell should have style', () => { @@ -403,7 +402,7 @@ describe('when rendering table', () => { it('value should be mapped to text (range) and colored cell should have style', () => { const html = renderer.renderCell(12, 0, 4); - expect(html).toBe(`off`); + expect(html).toBe(`off`); }); it('value should be mapped to text (range) and colored cell should have style', () => {