[Lens] Make reference lines use the correct formatter when configured (#158266)

## Summary

Fixes #156771 

This PR add the correct logic to extract the table column formatter,
when set, and use it within a reference line context. If no formatter is
set then the group/axis formatter is used.

Included required changes directly in this PR to make it reviewable.

<img width="1227" alt="Screenshot 2023-05-31 at 14 53 40"
src="3615ca3a-f9d3-4b0a-b8f1-4c47dcf953dd">



### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces&mdash;unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes&mdash;Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: Stratoula Kalafateli <efstratia.kalafateli@elastic.co>
Co-authored-by: Peter Pisljar <peter.pisljar@elastic.co>
This commit is contained in:
Marco Liberati 2023-06-01 10:09:26 +02:00 committed by GitHub
parent 72fa06535b
commit eed0d01531
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 146 additions and 30 deletions

View file

@ -119,11 +119,18 @@ export const referenceLineFunction: ReferenceLineFn = {
? false
: args.textVisibility;
const valueMeta =
args.forAccessor && table
? table.columns.find(({ id }) => id === args.forAccessor)?.meta
: undefined;
return {
type: REFERENCE_LINE,
layerType: LayerTypes.REFERENCELINE,
lineLength: table?.rows.length ?? 0,
decorations: [{ ...args, textVisibility, type: EXTENDED_REFERENCE_LINE_DECORATION_CONFIG }],
decorations: [
{ ...args, textVisibility, type: EXTENDED_REFERENCE_LINE_DECORATION_CONFIG, valueMeta },
],
};
},
};

View file

@ -9,7 +9,11 @@
import { type AxisProps, HorizontalAlignment, Position, VerticalAlignment } from '@elastic/charts';
import type { $Values } from '@kbn/utility-types';
import type { PaletteOutput } from '@kbn/coloring';
import type { Datatable, ExpressionFunctionDefinition } from '@kbn/expressions-plugin/common';
import type {
Datatable,
DatatableColumnMeta,
ExpressionFunctionDefinition,
} from '@kbn/expressions-plugin/common';
import { LegendSize } from '@kbn/visualizations-plugin/common';
import { EventAnnotationOutput } from '@kbn/event-annotation-plugin/common';
import { ExpressionValueVisDimension } from '@kbn/visualizations-plugin/common';
@ -334,6 +338,7 @@ export interface ReferenceLineArgs extends Omit<ReferenceLineDecorationConfig, '
name?: string;
value: number;
fill: FillStyle;
valueMeta?: DatatableColumnMeta;
}
export interface ReferenceLineLayerArgs {

View file

@ -12,12 +12,13 @@ import { FieldFormat } from '@kbn/field-formats-plugin/common';
import { ReferenceLineConfig } from '../../../common/types';
import { ReferenceLineAnnotations } from './reference_line_annotations';
import { AxesMap, GroupsConfiguration } from '../../helpers';
import { getAxisGroupForReferenceLine } from './utils';
import { FormattersMap, getAxisGroupForReferenceLine } from './utils';
interface ReferenceLineProps {
layer: ReferenceLineConfig;
paddingMap: Partial<Record<Position, number>>;
xAxisFormatter: FieldFormat;
formatters: FormattersMap;
axesConfiguration: GroupsConfiguration;
isHorizontal: boolean;
nextValue?: number;
@ -28,6 +29,7 @@ export const ReferenceLine: FC<ReferenceLineProps> = ({
layer,
axesConfiguration,
xAxisFormatter,
formatters,
paddingMap,
isHorizontal,
nextValue,
@ -47,7 +49,8 @@ export const ReferenceLine: FC<ReferenceLineProps> = ({
const axisGroup = getAxisGroupForReferenceLine(axesConfiguration, decorationConfig, isHorizontal);
const formatter = axisGroup?.formatter || xAxisFormatter;
const formatter =
formatters[decorationConfig.forAccessor] || axisGroup?.formatter || xAxisFormatter;
const id = `${layer.layerId}-${value}`;
const name = decorationConfig.textVisibility
? columnToLabelMap[decorationConfig.forAccessor]

View file

@ -13,13 +13,14 @@ import { Position } from '@elastic/charts';
import { ReferenceLineLayerConfig } from '../../../common/types';
import { ReferenceLineAnnotations } from './reference_line_annotations';
import { LayerAccessorsTitles, GroupsConfiguration, AxesMap } from '../../helpers';
import { getAxisGroupForReferenceLine } from './utils';
import { FormattersMap, getAxisGroupForReferenceLine } from './utils';
interface ReferenceLineLayerProps {
layer: ReferenceLineLayerConfig;
paddingMap: Partial<Record<Position, number>>;
isHorizontal: boolean;
titles?: LayerAccessorsTitles;
formatters: FormattersMap;
xAxisFormatter: FieldFormat;
axesConfiguration: GroupsConfiguration;
yAxesMap: AxesMap;
@ -28,6 +29,7 @@ interface ReferenceLineLayerProps {
export const ReferenceLineLayer: FC<ReferenceLineLayerProps> = ({
layer,
axesConfiguration,
formatters,
xAxisFormatter,
paddingMap,
isHorizontal,
@ -59,7 +61,8 @@ export const ReferenceLineLayer: FC<ReferenceLineLayerProps> = ({
isHorizontal
);
const formatter = axisGroup?.formatter || xAxisFormatter;
const formatter =
formatters[decorationConfig.forAccessor] || axisGroup?.formatter || xAxisFormatter;
const name =
columnToLabelMap[decorationConfig.forAccessor] ??
titles?.yTitles?.[decorationConfig.forAccessor];

View file

@ -47,7 +47,8 @@ const data: Datatable = {
};
function createLayers(
decorations: ReferenceLineLayerArgs['decorations']
decorations: ReferenceLineLayerArgs['decorations'],
table?: Datatable
): ReferenceLineLayerConfig[] {
return [
{
@ -56,7 +57,7 @@ function createLayers(
decorations,
type: 'referenceLineLayer',
layerType: LayerTypes.REFERENCELINE,
table: data,
table: table || data,
},
];
}
@ -96,6 +97,7 @@ describe('ReferenceLines', () => {
beforeEach(() => {
defaultProps = {
formatters: {},
xAxisFormatter: { convert: jest.fn((x) => x) } as unknown as FieldFormat,
isHorizontal: false,
axesConfiguration: [
@ -163,6 +165,68 @@ describe('ReferenceLines', () => {
).not.toThrow();
});
it('should prefer column formatter over x axis default one', () => {
const convertLeft = jest.fn((x) => `left-${x}`);
const convertRight = jest.fn((x) => `right-${x}`);
const wrapper = shallow(
<ReferenceLines
{...defaultProps}
formatters={{
yAccessorLeftFirstId: { convert: convertLeft } as unknown as FieldFormat,
yAccessorRightFirstId: { convert: convertRight } as unknown as FieldFormat,
}}
layers={createLayers(
[
{
forAccessor: `yAccessorLeftFirstId`,
position: getAxisFromId('yAccessorLeft'),
lineStyle: 'solid',
fill: undefined,
type: 'referenceLineDecorationConfig',
},
{
forAccessor: `yAccessorRightFirstId`,
position: getAxisFromId('yAccessorRight'),
lineStyle: 'solid',
fill: 'above',
type: 'referenceLineDecorationConfig',
},
],
{
type: 'datatable',
rows: [row],
columns: Object.keys(row).map((id) => ({
id,
name: `Static value: ${row[id]}`,
meta: {
type: 'number',
params: { id: 'number', params: { formatOverride: true, pattern: '0.0' } },
},
})),
}
)}
/>
);
const referenceLineLayer = wrapper.find(ReferenceLineLayer).dive();
const annotations = referenceLineLayer.find(ReferenceLineAnnotations);
expect(annotations.first().dive().find(LineAnnotation).prop('dataValues')).toEqual(
expect.arrayContaining([{ dataValue: 5, details: `left-5`, header: undefined }])
);
expect(annotations.last().dive().find(RectAnnotation).prop('dataValues')).toEqual(
expect.arrayContaining([
{
coordinates: { x0: undefined, x1: undefined, y0: 5, y1: undefined },
details: `right-5`,
header: undefined,
},
])
);
expect(convertLeft).toHaveBeenCalled();
expect(convertRight).toHaveBeenCalled();
expect(defaultProps.xAxisFormatter.convert).not.toHaveBeenCalled();
});
it.each([
['yAccessorLeft', 'above'],
['yAccessorLeft', 'below'],
@ -482,6 +546,7 @@ describe('ReferenceLines', () => {
beforeEach(() => {
defaultProps = {
formatters: {},
xAxisFormatter: { convert: jest.fn((x) => x) } as unknown as FieldFormat,
isHorizontal: false,
axesConfiguration: [

View file

@ -20,7 +20,7 @@ import {
} from '../../helpers';
import { ReferenceLineLayer } from './reference_line_layer';
import { ReferenceLine } from './reference_line';
import { getNextValuesForReferenceLines } from './utils';
import { FormattersMap, getNextValuesForReferenceLines } from './utils';
export interface ReferenceLinesProps {
layers: CommonXYReferenceLineLayerConfig[];
@ -30,6 +30,7 @@ export interface ReferenceLinesProps {
paddingMap: Partial<Record<Position, number>>;
titles?: LayersAccessorsTitles;
yAxesMap: AxesMap;
formatters: FormattersMap;
}
export const ReferenceLines = ({ layers, titles = {}, ...rest }: ReferenceLinesProps) => {

View file

@ -9,7 +9,7 @@
import React from 'react';
import { Position } from '@elastic/charts';
import { euiLightVars } from '@kbn/ui-theme';
import { FieldFormat } from '@kbn/field-formats-plugin/common';
import { FieldFormat, FormatFactory } from '@kbn/field-formats-plugin/common';
import { groupBy, orderBy } from 'lodash';
import {
IconPosition,
@ -17,6 +17,7 @@ import {
FillStyle,
ExtendedReferenceLineDecorationConfig,
ReferenceLineDecorationConfig,
CommonXYReferenceLineLayerConfig,
} from '../../../common/types';
import { FillStyles } from '../../../common/constants';
import {
@ -27,6 +28,7 @@ import {
getAxisPosition,
getOriginalAxisPosition,
AxesMap,
isReferenceLine,
} from '../../helpers';
import type { ReferenceLineAnnotationConfig } from './reference_line_annotations';
@ -241,3 +243,29 @@ export function getAxisGroupForReferenceLine(
getAxisPosition(decorationConfig.position ?? Position.Left, shouldRotate) === axis.position
);
}
export type FormattersMap = Record<string, FieldFormat>;
export function getReferenceLinesFormattersMap(
referenceLinesLayers: CommonXYReferenceLineLayerConfig[],
formatFactory: FormatFactory
): FormattersMap {
const formattersMap: Record<string, FieldFormat> = {};
for (const layer of referenceLinesLayers) {
if (isReferenceLine(layer)) {
for (const { valueMeta, forAccessor } of layer.decorations) {
if (valueMeta?.params?.params?.formatOverride) {
formattersMap[forAccessor] = formatFactory(valueMeta.params);
}
}
} else {
for (const { forAccessor } of layer.decorations || []) {
const columnFormat = layer.table.columns.find(({ id }) => id === forAccessor)?.meta.params;
if (columnFormat?.params?.formatOverride) {
formattersMap[forAccessor] = formatFactory(columnFormat);
}
}
}
}
return formattersMap;
}

View file

@ -93,6 +93,7 @@ import {
ReferenceLines,
computeChartMargins,
getAxisGroupForReferenceLine,
getReferenceLinesFormattersMap,
} from './reference_lines';
import { visualizationDefinitions } from '../definitions';
import { CommonXYLayerConfig } from '../../common/types';
@ -452,7 +453,7 @@ export function XYChart({
: Position.Bottom,
})),
...groupedLineAnnotations,
].filter(Boolean);
].filter(nonNullable);
const shouldHideDetails =
annotations?.layers && annotations.layers.length > 0
@ -800,6 +801,11 @@ export function XYChart({
'settings'
) as Partial<SettingsProps>;
const referenceLinesFormatters = getReferenceLinesFormattersMap(
referenceLineLayers,
formatFactory
);
return (
<div css={chartContainerStyle}>
{showLegend !== undefined && uiState && (
@ -1073,6 +1079,7 @@ export function XYChart({
paddingMap={linesPaddings}
titles={titles}
yAxesMap={yAxesMap}
formatters={referenceLinesFormatters}
/>
) : null}
{(rangeAnnotations.length || lineAnnotations.length) && isTimeViz ? (

View file

@ -46,9 +46,7 @@ describe('format_column', () => {
const result = await fn(datatable, { columnId: 'test', format: 'number' });
expect(result.columns[0].meta.params).toEqual({
id: 'number',
params: {
pattern: '0,0.00',
},
params: { formatOverride: true, pattern: '0,0.00' },
});
});
@ -57,9 +55,7 @@ describe('format_column', () => {
const result = await fn(datatable, { columnId: 'test', format: 'number', decimals: 5 });
expect(result.columns[0].meta.params).toEqual({
id: 'number',
params: {
pattern: '0,0.00000',
},
params: { formatOverride: true, pattern: '0,0.00000' },
});
});
@ -76,9 +72,8 @@ describe('format_column', () => {
params: {
suffixString: 'ABC',
id: 'number',
params: {
pattern: '0,0.00000',
},
formatOverride: true,
params: { formatOverride: true, pattern: '0,0.00000' },
},
});
});
@ -88,9 +83,7 @@ describe('format_column', () => {
const result = await fn(datatable, { columnId: 'test', format: 'number', decimals: 0 });
expect(result.columns[0].meta.params).toEqual({
id: 'number',
params: {
pattern: '0,0',
},
params: { formatOverride: true, pattern: '0,0' },
});
});
@ -175,6 +168,7 @@ describe('format_column', () => {
id: 'suffix',
params: {
suffixString: 'abc',
formatOverride: true,
id: 'wrapper',
params: {
wrapperParam: 123,
@ -229,9 +223,8 @@ describe('format_column', () => {
params: {
wrapperParam: 123,
id: 'number',
params: {
pattern: '0,0.00000',
},
params: { formatOverride: true, pattern: '0,0.00000' },
formatOverride: true,
pattern: '0,0.00000',
},
});
@ -256,9 +249,8 @@ describe('format_column', () => {
paramsPerField: [
{
id: 'number',
params: {
pattern: '0,0.00000',
},
params: { formatOverride: true, pattern: '0,0.00000' },
formatOverride: true,
pattern: '0,0.00000',
},
],

View file

@ -33,7 +33,10 @@ export const formatColumnFn: FormatColumnExpressionFunction['fn'] = (
if (supportedFormats[format]) {
const serializedFormat: SerializedFieldFormat = {
id: supportedFormats[format].formatId,
params: { pattern: supportedFormats[format].decimalsToPattern(decimals) },
params: {
pattern: supportedFormats[format].decimalsToPattern(decimals),
formatOverride: true,
},
};
return withParams(col, serializedFormat as Record<string, unknown>);
} else if (format) {
@ -56,6 +59,7 @@ export const formatColumnFn: FormatColumnExpressionFunction['fn'] = (
if (format && supportedFormats[format]) {
const customParams = {
pattern: supportedFormats[format].decimalsToPattern(decimals),
formatOverride: true,
};
// Some parent formatters are multi-fields and wrap the custom format into a "paramsPerField"
// property. Here the format is passed to this property to make it work properly
@ -128,6 +132,7 @@ export const formatColumnFn: FormatColumnExpressionFunction['fn'] = (
params: {
...col.meta.params,
suffixString: suffix,
formatOverride: true,
},
},
},