Skip to content

Commit

Permalink
[Lens] Allow setting custom colours to collapsed by slices pie's mult…
Browse files Browse the repository at this point in the history
…iple metrics (#160592)

Fixes #159808 

It was working before, the only missing point was you couldn't color
when all groups were collaped by.


1. Moved dimension editor code to separate file.
2. Removed StaticColorValue component and used `ColorPicker` that we use
for other places in the code
3. Fixed the issue for pie (hopefully tested everything now)
4. Fixed the issue for xy chart. To reproduce - create a date histogram
xy chart, assign color to the Count of records. Then create a breakdown
dimension and collapse it. Open dimension panel for count of records -
the displayed color is the default one, not the one we assigned.
  • Loading branch information
mbondyra authored Jun 29, 2023
1 parent 04922bf commit 0a1b516
Show file tree
Hide file tree
Showing 11 changed files with 245 additions and 224 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,34 +26,32 @@ const tooltipContent = {
custom: i18n.translate('visualizationUiComponents.colorPicker.tooltip.custom', {
defaultMessage: 'Clear the custom color to return to “Auto” mode.',
}),
disabled: i18n.translate('visualizationUiComponents.colorPicker.tooltip.disabled', {
defaultMessage:
'You are unable to apply custom colors to individual series when the layer includes a "Break down by" field.',
}),
};

export const ColorPicker = ({
overwriteColor,
defaultColor,
setConfig,
label,
disableHelpTooltip,
disabled,
setConfig,
defaultColor,
overwriteColor,
disabledMessage,
showAlpha,
}: {
overwriteColor?: string | null;
defaultColor?: string | null;
setConfig: (config: { color?: string }) => void;
label?: string;
disableHelpTooltip?: boolean;
disabled?: boolean;
disabledMessage?: string;
showAlpha?: boolean;
}) => {
const [colorText, setColorText] = useState(overwriteColor || defaultColor);
const [validatedColor, setValidatedColor] = useState(overwriteColor || defaultColor);
const [currentColorAlpha, setCurrentColorAlpha] = useState(getColorAlpha(colorText));
const unflushedChanges = useRef(false);

const isDisabled = Boolean(disabledMessage);

useEffect(() => {
// only the changes from outside the color picker should be applied
if (!unflushedChanges.current) {
Expand Down Expand Up @@ -97,8 +95,8 @@ export const ColorPicker = ({
compressed
isClearable={Boolean(overwriteColor)}
onChange={handleColor}
color={disabled ? '' : colorText}
disabled={disabled}
color={isDisabled ? '' : colorText}
disabled={isDisabled}
placeholder={
defaultColor?.toUpperCase() ||
i18n.translate('visualizationUiComponents.colorPicker.seriesColor.auto', {
Expand All @@ -123,7 +121,7 @@ export const ColorPicker = ({
<TooltipWrapper
delay="long"
position="top"
tooltipContent={colorText && !disabled ? tooltipContent.custom : tooltipContent.auto}
tooltipContent={colorText && !isDisabled ? tooltipContent.custom : tooltipContent.auto}
condition={!disableHelpTooltip}
>
<span>
Expand All @@ -142,10 +140,10 @@ export const ColorPicker = ({
</TooltipWrapper>
}
>
{disabled ? (
{isDisabled ? (
<EuiToolTip
position="top"
content={tooltipContent.disabled}
content={disabledMessage}
delay="long"
anchorClassName="eui-displayBlock"
>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import './toolbar.scss';
import React from 'react';
import { i18n } from '@kbn/i18n';
import type { PaletteRegistry } from '@kbn/coloring';
import { ColorPicker, useDebouncedValue } from '@kbn/visualization-ui-components/public';
import { PieVisualizationState } from '../../../common/types';
import { VisualizationDimensionEditorProps } from '../../types';
import { PalettePicker } from '../../shared_components';
import { CollapseSetting } from '../../shared_components/collapse_setting';
import {
getDefaultColorForMultiMetricDimension,
hasNonCollapsedSliceBy,
isCollapsed,
} from './visualization';

type DimensionEditorProps = VisualizationDimensionEditorProps<PieVisualizationState> & {
paletteService: PaletteRegistry;
};

export function DimensionEditor(props: DimensionEditorProps) {
const { inputValue: localState, handleInputChange: setLocalState } =
useDebouncedValue<PieVisualizationState>({
value: props.state,
onChange: props.setState,
});

const currentLayer = localState.layers.find((layer) => layer.layerId === props.layerId);

const setConfig = React.useCallback(
({ color }) => {
if (!currentLayer) {
return;
}
const newColorsByDimension = { ...currentLayer.colorsByDimension };

if (color) {
newColorsByDimension[props.accessor] = color;
} else {
delete newColorsByDimension[props.accessor];
}

setLocalState({
...localState,
layers: localState.layers.map((layer) =>
layer.layerId === currentLayer.layerId
? {
...layer,
colorsByDimension: newColorsByDimension,
}
: layer
),
});
},
[currentLayer, localState, props.accessor, setLocalState]
);

if (!currentLayer) {
return null;
}

const firstNonCollapsedColumnId = currentLayer.primaryGroups.find(
(id) => !isCollapsed(id, currentLayer)
);

const showColorPicker =
currentLayer.metrics.includes(props.accessor) && currentLayer.allowMultipleMetrics;

const colorPickerDisabledMessage = hasNonCollapsedSliceBy(currentLayer)
? ['pie', 'donut'].includes(props.state.shape)
? i18n.translate('xpack.lens.pieChart.colorPicker.disabledBecauseSliceBy', {
defaultMessage:
'You are unable to apply custom colors to individual slices when the layer includes one or more "Slice by" dimensions.',
})
: i18n.translate('xpack.lens.pieChart.colorPicker.disabledBecauseGroupBy', {
defaultMessage:
'You are unable to apply custom colors to individual slices when the layer includes one or more "Group by" dimensions.',
})
: undefined;

return (
<>
{props.accessor === firstNonCollapsedColumnId && (
<PalettePicker
palettes={props.paletteService}
activePalette={props.state.palette}
setPalette={(newPalette) => {
setLocalState({ ...props.state, palette: newPalette });
}}
/>
)}
{showColorPicker && (
<ColorPicker
{...props}
overwriteColor={currentLayer.colorsByDimension?.[props.accessor]}
defaultColor={getDefaultColorForMultiMetricDimension({
layer: currentLayer,
columnId: props.accessor,
paletteService: props.paletteService,
datasource: props.datasource,
palette: props.state.palette,
})}
disabledMessage={colorPickerDisabledMessage}
setConfig={setConfig}
/>
)}
</>
);
}

export function DimensionDataExtraEditor(
props: VisualizationDimensionEditorProps<PieVisualizationState> & {
paletteService: PaletteRegistry;
}
) {
const currentLayer = props.state.layers.find((layer) => layer.layerId === props.layerId);

if (!currentLayer) {
return null;
}

return (
<>
{[...currentLayer.primaryGroups, ...(currentLayer.secondaryGroups ?? [])].includes(
props.accessor
) && (
<CollapseSetting
value={currentLayer?.collapseFns?.[props.accessor] || ''}
onChange={(collapseFn) => {
props.setState({
...props.state,
layers: props.state.layers.map((layer) =>
layer.layerId !== props.layerId
? layer
: {
...layer,
collapseFns: {
...layer.collapseFns,
[props.accessor]: collapseFn,
},
}
),
});
}}
/>
)}
</>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import {
PieChartTypes,
} from '../../../common/constants';
import { getDefaultVisualValuesForLayer } from '../../shared_components/datasource_default_values';
import { isCollapsed } from './visualization';
import { hasNonCollapsedSliceBy, isCollapsed } from './visualization';

interface Attributes {
isPreview: boolean;
Expand Down Expand Up @@ -110,7 +110,7 @@ const generateCommonLabelsAstArgs: GenerateLabelsAstArguments = (
layer.numberDisplay !== NumberDisplay.HIDDEN ? (layer.numberDisplay as ValueFormats) : [];
const percentDecimals = layer.percentDecimals ?? DEFAULT_PERCENT_DECIMALS;
const colorOverrides =
layer.allowMultipleMetrics && !layer.primaryGroups.length
layer.allowMultipleMetrics && !hasNonCollapsedSliceBy(layer)
? Object.entries(columnToLabelMap).reduce<Record<string, string>>(
(acc, [columnId, label]) => {
const color = layer.colorsByDimension?.[columnId];
Expand Down
Loading

0 comments on commit 0a1b516

Please sign in to comment.