Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ export const metricVisFunction = (): MetricVisExpressionFunctionDefinition => ({
...(args.bucket ? { bucket: args.bucket } : {}),
},
},
canNavigateToLens: Boolean(handlers?.variables?.canNavigateToLens),
},
};
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export interface MetricVisRenderConfig {
visType: typeof visType;
visData: Datatable;
visConfig: Pick<VisParams, 'metric' | 'dimensions'>;
canNavigateToLens: boolean;
}

export type MetricVisExpressionFunctionDefinition = ExpressionFunctionDefinition<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const style: MetricStyle = {
};

const config: MetricVisRenderConfig = {
canNavigateToLens: false,
visType,
visData: {
type: 'datatable',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const getMetricVisRenderer: (
name: EXPRESSION_METRIC_NAME,
displayName: 'metric visualization',
reuseDomNode: true,
render: async (domNode, { visData, visConfig }, handlers) => {
render: async (domNode, { visData, visConfig, canNavigateToLens }, handlers) => {
const { core, plugins } = getStartDeps();

handlers.onDestroy(() => {
Expand All @@ -82,9 +82,12 @@ export const getMetricVisRenderer: (
const visualizationType = extractVisualizationType(executionContext);

if (containerType && visualizationType) {
plugins.usageCollection?.reportUiCounter(containerType, METRIC_TYPE.COUNT, [
const events = [
`render_${visualizationType}_legacy_metric`,
]);
canNavigateToLens ? `render_${visualizationType}_legacy_metric_convertable` : undefined,
].filter<string>((event): event is string => Boolean(event));

plugins.usageCollection?.reportUiCounter(containerType, METRIC_TYPE.COUNT, events);
}

handlers.done();
Expand Down
15 changes: 12 additions & 3 deletions src/plugins/vis_types/metric/kibana.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,20 @@
"kibanaVersion": "kibana",
"server": true,
"ui": true,
"requiredPlugins": ["data", "visualizations", "charts", "expressions"],
"requiredBundles": ["visDefaultEditor"],
"requiredPlugins": [
"data",
"visualizations",
"charts",
"expressions",
"dataViews"
],
"requiredBundles": [
"visDefaultEditor",
"kibanaUtils"
],
"owner": {
"name": "Vis Editors",
"githubTeam": "kibana-vis-editors"
},
"description": "Registers the Metric aggregation-based visualization."
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { ColorSchemas } from '@kbn/charts-plugin/common';
import { getConfiguration, getPercentageModeConfig } from '.';
import { VisParams } from '../../types';

const mockGetPalette = jest.fn();

jest.mock('./palette', () => ({
getPalette: jest.fn(() => mockGetPalette()),
}));

const params: VisParams = {
addTooltip: false,
addLegend: false,
dimensions: {} as VisParams['dimensions'],
metric: {
percentageMode: false,
percentageFormatPattern: '',
useRanges: true,
colorSchema: ColorSchemas.Greys,
metricColorMode: 'Labels',
colorsRange: [
{ type: 'range', from: 0, to: 100 },
{ type: 'range', from: 100, to: 200 },
{ type: 'range', from: 200, to: 300 },
],
labels: {},
invertColors: false,
style: {} as VisParams['metric']['style'],
},
type: 'metric',
};

describe('getPercentageModeConfig', () => {
test('should return falsy percentage mode if percentage mode is off', () => {
expect(getPercentageModeConfig(params)).toEqual({ isPercentageMode: false });
});

test('should return percentage mode config', () => {
expect(
getPercentageModeConfig({ ...params, metric: { ...params.metric, percentageMode: true } })
).toEqual({ isPercentageMode: true, min: 0, max: 300 });
});
});

describe('getConfiguration', () => {
const palette = { name: 'custom', params: { name: 'custom' }, type: 'palette' };

beforeEach(() => {
jest.clearAllMocks();
mockGetPalette.mockReturnValue(palette);
});

test('shourd return correct configuration', () => {
const layerId = 'layer-id';
const metric = 'metric-id';
const bucket = 'bucket-id';
const collapseFn = 'sum';
expect(
getConfiguration(layerId, params, {
metrics: [metric],
buckets: [bucket],
columnsWithoutReferenced: [],
bucketCollapseFn: { [metric]: collapseFn },
})
).toEqual({
breakdownByAccessor: bucket,
collapseFn,
layerId,
layerType: 'data',
metricAccessor: metric,
palette,
});
expect(mockGetPalette).toBeCalledTimes(1);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { Column, MetricVisConfiguration } from '@kbn/visualizations-plugin/common';
import { PercentageModeConfig } from '@kbn/visualizations-plugin/common/convert_to_lens';
import { VisParams } from '../../types';
import { getPalette } from './palette';

export const getPercentageModeConfig = (params: VisParams): PercentageModeConfig => {
if (!params.metric.percentageMode) {
return { isPercentageMode: false };
}
const { colorsRange } = params.metric;
return {
isPercentageMode: true,
min: colorsRange[0].from,
max: colorsRange[colorsRange.length - 1].to,
};
};

export const getConfiguration = (
layerId: string,
params: VisParams,
{
metrics,
buckets,
columnsWithoutReferenced,
bucketCollapseFn,
}: {
metrics: string[];
buckets: string[];
columnsWithoutReferenced: Column[];
bucketCollapseFn?: Record<string, string | undefined>;
}
): MetricVisConfiguration => {
const [metricAccessor] = metrics;
const [breakdownByAccessor] = buckets;
return {
layerId,
layerType: 'data',
palette: getPalette(params),
metricAccessor,
breakdownByAccessor,
collapseFn: Object.values(bucketCollapseFn ?? {})[0],
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { ColorSchemas } from '@kbn/charts-plugin/common';
import { VisParams } from '../../types';
import { getPalette } from './palette';

describe('getPalette', () => {
const params: VisParams = {
addTooltip: false,
addLegend: false,
dimensions: {} as VisParams['dimensions'],
metric: {
percentageMode: false,
percentageFormatPattern: '',
useRanges: true,
colorSchema: ColorSchemas.Greys,
metricColorMode: 'Labels',
colorsRange: [
{ type: 'range', from: 0, to: 100 },
{ type: 'range', from: 100, to: 200 },
{ type: 'range', from: 200, to: 300 },
],
labels: {},
invertColors: false,
style: {} as VisParams['metric']['style'],
},
type: 'metric',
};

test('should return undefined if metricColorMode is `None`', () => {
const metricColorMode = 'None';
const paramsWithNoneMetricColorMode: VisParams = {
...params,
metric: { ...params.metric, metricColorMode },
};
expect(getPalette(paramsWithNoneMetricColorMode)).toBeUndefined();
});

test('should return undefined if empty color ranges were passed', () => {
const paramsWithNoneMetricColorMode: VisParams = {
...params,
metric: { ...params.metric, colorsRange: [] },
};
expect(getPalette(paramsWithNoneMetricColorMode)).toBeUndefined();
});

test('should return correct palette', () => {
expect(getPalette(params)).toEqual({
name: 'custom',
params: {
colorStops: [
{ color: '#FFFFFF', stop: 0 },
{ color: '#979797', stop: 100 },
{ color: '#000000', stop: 200 },
],
continuity: 'none',
maxSteps: 5,
name: 'custom',
progression: 'fixed',
rangeMax: 300,
rangeMin: 0,
rangeType: 'number',
reverse: false,
stops: [
{ color: '#FFFFFF', stop: 100 },
{ color: '#979797', stop: 200 },
{ color: '#000000', stop: 300 },
],
},
type: 'palette',
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import color from 'color';
import { CustomPaletteParams, PaletteOutput } from '@kbn/coloring';
import { VisParams } from '../../types';
import { getStopsWithColorsFromRanges } from '../../utils';
import { PaletteConfig } from '../../utils/palette';

type ColorStopsWithMinMax = Pick<
CustomPaletteParams,
'colorStops' | 'stops' | 'steps' | 'rangeMax' | 'rangeMin' | 'continuity'
>;

const buildPaletteParams = ({ color: colors, stop }: PaletteConfig): ColorStopsWithMinMax => {
const colorsWithoutStartColor = colors.slice(1, colors.length);
return {
rangeMin: stop[0],
rangeMax: stop[stop.length - 1],
continuity: 'none',
colorStops: colorsWithoutStartColor.map((c, index) => ({
color: color(c!).hex(),
stop: stop[index],
})),
stops: colorsWithoutStartColor.map((c, index) => ({
color: color(c!).hex(),
stop: stop[index + 1],
})),
};
};

const buildCustomPalette = (
colorStopsWithMinMax: ColorStopsWithMinMax
): PaletteOutput<CustomPaletteParams> => {
return {
name: 'custom',
params: {
maxSteps: 5,
name: 'custom',
progression: 'fixed',
rangeMax: Infinity,
rangeMin: -Infinity,
rangeType: 'number',
reverse: false,
...colorStopsWithMinMax,
},
type: 'palette',
};
};

export const getPalette = (params: VisParams): PaletteOutput<CustomPaletteParams> | undefined => {
const { colorSchema, colorsRange, invertColors, metricColorMode } = params.metric;

if (metricColorMode === 'None' || !(colorsRange && colorsRange.length)) {
return;
}

const stopsWithColors = getStopsWithColorsFromRanges(colorsRange, colorSchema, invertColors);
return buildCustomPalette(buildPaletteParams(stopsWithColors));
};
Loading