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
This commit is contained in:
Torkel Ödegaard
2020-10-14 10:21:45 +02:00
committed by GitHub
parent 66def25c6d
commit 451836a86a
33 changed files with 186 additions and 268 deletions

View File

@@ -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<BadgeProps>(({ 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 = '';

View File

@@ -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<Props> {
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<Props> {
}
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',

View File

@@ -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);

View File

@@ -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 = <T extends ColorPickerProps>(
ref={this.pickerTriggerRef}
onClick={showPopper}
onMouseLeave={hidePopper}
color={getColorFromHexRgbOrName(this.props.color || '#000000', theme.type)}
color={getColorForTheme(this.props.color || '#000000', theme)}
/>
)}
</>

View File

@@ -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(<ColorPickerPopover color={BasicGreen.name} onChange={() => {}} theme={getTheme()} />);
const selectedSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === BasicGreen.name);
const theme = getTheme();
const wrapper = mount(<ColorPickerPopover color={'green'} onChange={() => {}} 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(
<ColorPickerPopover color={BasicGreen.variants.dark} onChange={() => {}} theme={getTheme()} />
);
const selectedSwatch = wrapper.find(ColorSwatch).findWhere(node => node.key() === BasicGreen.name);
const theme = getTheme();
const wrapper = mount(<ColorPickerPopover color={'green'} onChange={() => {}} 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(
<ColorPickerPopover
color={BasicGreen.variants.dark}
onChange={onChangeSpy}
theme={getTheme(GrafanaThemeType.Light)}
/>
<ColorPickerPopover color={'green'} onChange={onChangeSpy} theme={getTheme(GrafanaThemeType.Light)} />
);
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(
<ColorPickerPopover
enableNamedColors
color={BasicGreen.variants.dark}
color={'green'}
onChange={onChangeSpy}
theme={getTheme(GrafanaThemeType.Light)}
/>
);
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');
});
});
});

View File

@@ -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<T extends CustomPickersDescriptor> 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<T extends CustomPickersDescriptor> extends React
case 'spectrum':
return <SpectrumPalette color={color} onChange={this.handleChange} theme={theme} />;
case 'palette':
return (
<NamedColorsPalette color={getColorName(color, theme.type)} onChange={this.handleChange} theme={theme} />
);
return <NamedColorsPalette color={color} onChange={this.handleChange} theme={theme} />;
default:
return this.renderCustomPicker(activePicker);
}

View File

@@ -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<NamedColorsGroupProps> = ({
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<NamedColorsGroupProps> = ({
<ColorSwatch
key={color.name}
isSelected={color.name === selectedColor}
color={getColorForTheme(color, theme.type)}
color={color.variants[theme.type]}
onClick={() => onColorSelect(color)}
theme={theme}
/>

View File

@@ -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 = () => {
</UseState>
);
};
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 (
<UseState initialState={selectedColor}>
{(selectedColor, updateSelectedColor) => {
return renderComponentWithTheme(NamedColorsPalette, {
color: getColorName(selectedColor),
onChange: updateSelectedColor,
});
}}
</UseState>
);
};

View File

@@ -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;
}

View File

@@ -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<SpectrumPaletteProps> = ({ color,
return (
<div>
<SpectrumPicker
color={tinycolor(getColorFromHexRgbOrName(color)).toRgb()}
color={tinycolor(getColorForTheme(color, theme)).toRgb()}
onChange={(a: ColorResult) => {
onChange(tinycolor(a.rgb).toString());
}}

View File

@@ -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<Props> {
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<Props> {
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;
}

View File

@@ -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', () => {

View File

@@ -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<Props> = ({ 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}
/>
</div>
{/* <div className={styles.colorText} onClick={showColorPicker}>

View File

@@ -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<ModeProps> = ({ 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%',

View File

@@ -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;

View File

@@ -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<LegendPluginProps> = ({ placement, displayMode = LegendDisplayMode.List }) => {
const { data } = usePlotData();
const theme = useTheme();
const legendItems: LegendItem[] = [];
@@ -27,7 +29,7 @@ export const LegendPlugin: React.FC<LegendPluginProps> = ({ 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,