Skip to content

Commit

Permalink
[Lens] Allow non-numeric metrics for metric vis (#169258)
Browse files Browse the repository at this point in the history
## Summary

Fixes #137756 
Allows to set non numeric metrics for metric visualization for primary
and secondary metric.

<img width="369" alt="Screenshot 2023-10-19 at 13 45 47"
src="https://github.com/elastic/kibana/assets/4283304/d6f00cd1-3be8-4c07-abe0-5bd15e2e9813">
<img width="350" alt="Screenshot 2023-10-19 at 13 46 37"
src="https://github.com/elastic/kibana/assets/4283304/01978149-ca40-44c2-ba73-9698335e819a">


Doesn't include coloring by terms.
When primary metric is non-numeric:
1. when maximum value is empty, we hide maximum value group
2. when maximum value has a value we set an error message on dimension
3. we don’t allow to use a palette for coloring
4. we don’t allow to set a trendline

<img width="681" alt="Screenshot 2023-10-19 at 13 30 16"
src="https://github.com/elastic/kibana/assets/4283304/7464f9cc-c09c-42cd-bd44-f55ffc1dfad9">
<img width="456" alt="Screenshot 2023-10-19 at 13 30 22"
src="https://github.com/elastic/kibana/assets/4283304/e5726ab9-a748-4417-9b66-5bf4d708d833">



### 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)
  • Loading branch information
mbondyra committed Oct 30, 2023
1 parent beae7b1 commit c7e7853
Show file tree
Hide file tree
Showing 13 changed files with 671 additions and 481 deletions.
Expand Up @@ -20,12 +20,14 @@ import {
MetricWTrend,
MetricWNumber,
SettingsProps,
MetricWText,
} from '@elastic/charts';
import { getColumnByAccessor, getFormatByAccessor } from '@kbn/visualizations-plugin/common/utils';
import { ExpressionValueVisDimension } from '@kbn/visualizations-plugin/common';
import type {
Datatable,
DatatableColumn,
DatatableRow,
IInterpreterRenderHandlers,
RenderMode,
} from '@kbn/expressions-plugin/common';
Expand Down Expand Up @@ -65,6 +67,28 @@ function enhanceFieldFormat(serializedFieldFormat: SerializedFieldFormat | undef
return serializedFieldFormat ?? { id: formatId };
}

const renderSecondaryMetric = (
columns: DatatableColumn[],
row: DatatableRow,
config: Pick<VisParams, 'metric' | 'dimensions'>
) => {
let secondaryMetricColumn: DatatableColumn | undefined;
let formatSecondaryMetric: ReturnType<typeof getMetricFormatter>;
if (config.dimensions.secondaryMetric) {
secondaryMetricColumn = getColumnByAccessor(config.dimensions.secondaryMetric, columns);
formatSecondaryMetric = getMetricFormatter(config.dimensions.secondaryMetric, columns);
}
const secondaryPrefix = config.metric.secondaryPrefix ?? secondaryMetricColumn?.name;
return (
<span>
{secondaryPrefix}
{secondaryMetricColumn
? `${secondaryPrefix ? ' ' : ''}${formatSecondaryMetric!(row[secondaryMetricColumn.id])}`
: undefined}
</span>
);
};

const getMetricFormatter = (
accessor: ExpressionValueVisDimension | string,
columns: Datatable['columns']
Expand Down Expand Up @@ -149,13 +173,6 @@ export const MetricVis = ({
const primaryMetricColumn = getColumnByAccessor(config.dimensions.metric, data.columns)!;
const formatPrimaryMetric = getMetricFormatter(config.dimensions.metric, data.columns);

let secondaryMetricColumn: DatatableColumn | undefined;
let formatSecondaryMetric: ReturnType<typeof getMetricFormatter>;
if (config.dimensions.secondaryMetric) {
secondaryMetricColumn = getColumnByAccessor(config.dimensions.secondaryMetric, data.columns);
formatSecondaryMetric = getMetricFormatter(config.dimensions.secondaryMetric, data.columns);
}

let breakdownByColumn: DatatableColumn | undefined;
let formatBreakdownValue: FieldFormatConvertFunction;
if (config.dimensions.breakdownBy) {
Expand All @@ -172,28 +189,32 @@ export const MetricVis = ({
const metricConfigs: MetricSpec['data'][number] = (
breakdownByColumn ? data.rows : data.rows.slice(0, 1)
).map((row, rowIdx) => {
const value: number = row[primaryMetricColumn.id] !== null ? row[primaryMetricColumn.id] : NaN;
const value: number | string =
row[primaryMetricColumn.id] !== null ? row[primaryMetricColumn.id] : NaN;
const title = breakdownByColumn
? formatBreakdownValue(row[breakdownByColumn.id])
: primaryMetricColumn.name;
const subtitle = breakdownByColumn ? primaryMetricColumn.name : config.metric.subtitle;
const secondaryPrefix = config.metric.secondaryPrefix ?? secondaryMetricColumn?.name;

if (typeof value !== 'number') {
const nonNumericMetric: MetricWText = {
value: formatPrimaryMetric(value),
title: String(title),
subtitle,
icon: config.metric?.icon ? getIcon(config.metric?.icon) : undefined,
extra: renderSecondaryMetric(data.columns, row, config),
color: config.metric.color ?? defaultColor,
};
return nonNumericMetric;
}

const baseMetric: MetricWNumber = {
value,
valueFormatter: formatPrimaryMetric,
title: String(title),
subtitle,
icon: config.metric?.icon ? getIcon(config.metric?.icon) : undefined,
extra: (
<span>
{secondaryPrefix}
{secondaryMetricColumn
? `${secondaryPrefix ? ' ' : ''}${formatSecondaryMetric!(
row[secondaryMetricColumn.id]
)}`
: undefined}
</span>
),
extra: renderSecondaryMetric(data.columns, row, config),
color:
config.metric.palette && value != null
? getColor(
Expand Down
Expand Up @@ -224,6 +224,33 @@ describe('LayerPanel', () => {
const group = instance.find('.lnsLayerPanel__dimensionContainer[data-test-subj="lnsGroup"]');
expect(group).toHaveLength(1);
});
it('does not render a hidden group', async () => {
mockVisualization.getConfiguration.mockReturnValue({
groups: [
{
groupLabel: 'A',
groupId: 'a',
accessors: [],
filterOperations: () => true,
supportsMoreColumns: true,
dataTestSubj: 'lnsGroup',
},
{
groupLabel: 'B',
groupId: 'b',
accessors: [],
filterOperations: () => true,
isHidden: true,
supportsMoreColumns: true,
dataTestSubj: 'lnsGroup',
},
],
});

const { instance } = await mountWithProvider(<LayerPanel {...getDefaultProps()} />);
const group = instance.find('.lnsLayerPanel__dimensionContainer[data-test-subj="lnsGroup"]');
expect(group).toHaveLength(1);
});

it('should render the required warning when only one group is configured', async () => {
mockVisualization.getConfiguration.mockReturnValue({
Expand Down

0 comments on commit c7e7853

Please sign in to comment.